]> source.dussan.org Git - vaadin-framework.git/commitdiff
Portlet tools integrated into main src-tree
authorMarc Englund <marc.englund@itmill.com>
Tue, 29 Apr 2008 12:56:19 +0000 (12:56 +0000)
committerMarc Englund <marc.englund@itmill.com>
Tue, 29 Apr 2008 12:56:19 +0000 (12:56 +0000)
svn changeset:4286/svn branch:trunk

16 files changed:
portlet-src/com/itmill/toolkit/demo/portlet/PortletDemo.java [deleted file]
portlet-src/com/itmill/toolkit/demo/reservation/simple/AdminView.java [deleted file]
portlet-src/com/itmill/toolkit/demo/reservation/simple/SampleDB.java [deleted file]
portlet-src/com/itmill/toolkit/demo/reservation/simple/SimpleReserver.java [deleted file]
portlet-src/com/itmill/toolkit/demo/reservation/simple/StdView.java [deleted file]
portlet-src/com/itmill/toolkit/portlet/util/PortletConfigurationGenerator.java [deleted file]
portlet-src/com/itmill/toolkit/terminal/gwt/server/ApplicationPortlet.java [deleted file]
portlet-src/com/itmill/toolkit/terminal/gwt/server/PortletApplicationContext.java [deleted file]
src/com/itmill/toolkit/demo/PortletDemo.java [new file with mode: 0644]
src/com/itmill/toolkit/demo/reservation/simple/AdminView.java [new file with mode: 0644]
src/com/itmill/toolkit/demo/reservation/simple/SampleDB.java [new file with mode: 0644]
src/com/itmill/toolkit/demo/reservation/simple/SimpleReserver.java [new file with mode: 0644]
src/com/itmill/toolkit/demo/reservation/simple/StdView.java [new file with mode: 0644]
src/com/itmill/toolkit/terminal/gwt/server/ApplicationPortlet.java [new file with mode: 0644]
src/com/itmill/toolkit/terminal/gwt/server/PortletApplicationContext.java [new file with mode: 0644]
src/com/itmill/toolkit/util/PortletConfigurationGenerator.java [new file with mode: 0644]

diff --git a/portlet-src/com/itmill/toolkit/demo/portlet/PortletDemo.java b/portlet-src/com/itmill/toolkit/demo/portlet/PortletDemo.java
deleted file mode 100644 (file)
index 8645be2..0000000
+++ /dev/null
@@ -1,152 +0,0 @@
-/**\r
- * \r
- */\r
-package com.itmill.toolkit.demo.portlet;\r
-\r
-import java.util.Iterator;\r
-import java.util.Map;\r
-\r
-import javax.portlet.ActionRequest;\r
-import javax.portlet.ActionResponse;\r
-import javax.portlet.PortletMode;\r
-import javax.portlet.PortletRequest;\r
-import javax.portlet.PortletURL;\r
-import javax.portlet.RenderRequest;\r
-import javax.portlet.RenderResponse;\r
-import javax.portlet.WindowState;\r
-\r
-import com.itmill.toolkit.Application;\r
-import com.itmill.toolkit.terminal.ExternalResource;\r
-import com.itmill.toolkit.terminal.gwt.server.PortletApplicationContext;\r
-import com.itmill.toolkit.terminal.gwt.server.PortletApplicationContext.PortletListener;\r
-import com.itmill.toolkit.ui.Label;\r
-import com.itmill.toolkit.ui.Link;\r
-import com.itmill.toolkit.ui.TextField;\r
-import com.itmill.toolkit.ui.Window;\r
-import com.itmill.toolkit.ui.Window.Notification;\r
-\r
-/**\r
- * @author marc\r
- * \r
- */\r
-public class PortletDemo extends Application {\r
-\r
-    Window main = new Window();\r
-    TextField tf = new TextField("Some value");\r
-    Label userInfo = new Label();\r
-    Link portletEdit = new Link();\r
-    Link portletMax = new Link();\r
-    Link someAction = null;\r
-\r
-    public void init() {\r
-        main = new Window();\r
-        setMainWindow(main);\r
-\r
-        userInfo.setCaption("User info");\r
-        userInfo.setContentMode(Label.CONTENT_PREFORMATTED);\r
-        main.addComponent(userInfo);\r
-\r
-        tf.setEnabled(false);\r
-        tf.setImmediate(true);\r
-        main.addComponent(tf);\r
-\r
-        portletEdit.setEnabled(false);\r
-        main.addComponent(portletEdit);\r
-        portletMax.setEnabled(false);\r
-        main.addComponent(portletMax);\r
-\r
-        if (getContext() instanceof PortletApplicationContext) {\r
-            PortletApplicationContext ctx = (PortletApplicationContext) getContext();\r
-            ctx.addPortletListener(this, new DemoPortletListener());\r
-        } else {\r
-            getMainWindow().showNotification("Not inited via Portal!",\r
-                    Notification.TYPE_ERROR_MESSAGE);\r
-        }\r
-\r
-    }\r
-\r
-    private class DemoPortletListener implements PortletListener {\r
-\r
-        public void handleActionRequest(ActionRequest request,\r
-                ActionResponse response) {\r
-\r
-            main.addComponent(new Label("Action received"));\r
-\r
-        }\r
-\r
-        public void handleRenderRequest(RenderRequest request,\r
-                RenderResponse response) {\r
-            // Portlet up-and-running, enable stuff\r
-            portletEdit.setEnabled(true);\r
-            portletMax.setEnabled(true);\r
-\r
-            // Editable if we're in editmode\r
-            tf.setEnabled((request.getPortletMode() == PortletMode.EDIT));\r
-\r
-            // Show notification about current mode and state\r
-            getMainWindow().showNotification(\r
-                    "Portlet status",\r
-                    "Mode: " + request.getPortletMode() + " State: "\r
-                            + request.getWindowState(),\r
-                    Notification.TYPE_WARNING_MESSAGE);\r
-\r
-            // Display current user info\r
-            Map uinfo = (Map) request.getAttribute(PortletRequest.USER_INFO);\r
-            if (uinfo != null) {\r
-                String s = "";\r
-                for (Iterator it = uinfo.keySet().iterator(); it.hasNext();) {\r
-                    Object key = it.next();\r
-                    Object val = uinfo.get(key);\r
-                    s += key + ": " + val + "\n";\r
-                }\r
-                if (request.isUserInRole("administrator")) {\r
-                    s += "(administrator)";\r
-                }\r
-                userInfo.setValue(s);\r
-            } else {\r
-                userInfo.setValue("-");\r
-            }\r
-\r
-            // Create Edit/Done link (actionUrl)\r
-            PortletURL url = response.createActionURL();\r
-            try {\r
-                url\r
-                        .setPortletMode((request.getPortletMode() == PortletMode.VIEW ? PortletMode.EDIT\r
-                                : PortletMode.VIEW));\r
-                portletEdit.setResource(new ExternalResource(url.toString()));\r
-                portletEdit\r
-                        .setCaption((request.getPortletMode() == PortletMode.VIEW ? "Edit"\r
-                                : "Done"));\r
-            } catch (Exception e) {\r
-                portletEdit.setEnabled(false);\r
-            }\r
-            // Create Maximize/Normal link (actionUrl)\r
-            url = response.createActionURL();\r
-            try {\r
-                url\r
-                        .setWindowState((request.getWindowState() == WindowState.NORMAL ? WindowState.MAXIMIZED\r
-                                : WindowState.NORMAL));\r
-                portletMax.setResource(new ExternalResource(url.toString()));\r
-                portletMax\r
-                        .setCaption((request.getWindowState() == WindowState.NORMAL ? "Maximize"\r
-                                : "Back to normal"));\r
-            } catch (Exception e) {\r
-                portletMax.setEnabled(false);\r
-            }\r
-\r
-            if (someAction == null) {\r
-                url = response.createActionURL();\r
-                try {\r
-                    someAction = new Link("An action", new ExternalResource(url\r
-                            .toString()));\r
-                    main.addComponent(someAction);\r
-                } catch (Exception e) {\r
-                    // Oops\r
-                    System.err.println("Could not create someAction: " + e);\r
-                }\r
-\r
-            }\r
-\r
-        }\r
-    }\r
-}\r
diff --git a/portlet-src/com/itmill/toolkit/demo/reservation/simple/AdminView.java b/portlet-src/com/itmill/toolkit/demo/reservation/simple/AdminView.java
deleted file mode 100644 (file)
index ac9319c..0000000
+++ /dev/null
@@ -1,98 +0,0 @@
-package com.itmill.toolkit.demo.reservation.simple;
-
-import com.itmill.toolkit.data.Item;
-import com.itmill.toolkit.data.Property.ValueChangeEvent;
-import com.itmill.toolkit.ui.Button;
-import com.itmill.toolkit.ui.ComboBox;
-import com.itmill.toolkit.ui.OrderedLayout;
-import com.itmill.toolkit.ui.TextField;
-import com.itmill.toolkit.ui.AbstractSelect.NewItemHandler;
-import com.itmill.toolkit.ui.Button.ClickEvent;
-import com.itmill.toolkit.ui.Button.ClickListener;
-
-public class AdminView extends OrderedLayout {
-
-    private ComboBox resources = new ComboBox(
-            "Select for editing or type new resource");
-    private SimpleReserver application;
-    private OrderedLayout form = new OrderedLayout();
-    private Button save = new Button("Save resource");
-
-    private TextField name = new TextField("Name:");
-    private TextField desc = new TextField("Description:");
-    protected Item editedItem;
-
-    AdminView(SimpleReserver app) {
-        setWidth("250px");
-
-        application = app;
-
-        resources.setImmediate(true);
-        resources.setFilteringMode(ComboBox.FILTERINGMODE_CONTAINS);
-        refreshList();
-        resources.setItemCaptionMode(ComboBox.ITEM_CAPTION_MODE_PROPERTY);
-        resources.setItemCaptionPropertyId(SampleDB.Resource.PROPERTY_ID_NAME);
-        resources.setNewItemsAllowed(true);
-        resources.setNewItemHandler(new NewItemHandler() {
-            public void addNewItem(String newItemCaption) {
-                name.setValue(newItemCaption);
-                desc.setValue("");
-                form.setVisible(true);
-            }
-        });
-
-        resources.addListener(new ComboBox.ValueChangeListener() {
-            public void valueChange(ValueChangeEvent event) {
-                if (resources.getValue() != null) {
-                    editedItem = resources.getItem(resources.getValue());
-
-                    name
-                            .setPropertyDataSource(editedItem
-                                    .getItemProperty(SampleDB.Resource.PROPERTY_ID_NAME));
-                    desc
-                            .setPropertyDataSource(editedItem
-                                    .getItemProperty(SampleDB.Resource.PROPERTY_ID_DESCRIPTION));
-
-                    form.setVisible(true);
-
-                } else {
-                    form.setVisible(false);
-                    editedItem = null;
-                }
-
-            }
-        });
-        addComponent(resources);
-
-        form.setVisible(false);
-        addComponent(form);
-        form.addComponent(name);
-        form.addComponent(desc);
-        name.setWidth("100%");
-        desc.setWidth("100%");
-        form.addComponent(save);
-        save.addListener(new ClickListener() {
-            public void buttonClick(ClickEvent event) {
-                if (editedItem == null) {
-                    // save
-                    int addResource = application.getDb().addResource(
-                            name.getValue().toString(),
-                            desc.getValue().toString());
-                } else {
-                    // update
-                    application.getDb().updateResource(editedItem,
-                            name.getValue().toString(),
-                            desc.getValue().toString());
-                }
-                resources.setValue(null);
-                refreshList();
-            }
-        });
-
-    }
-
-    private void refreshList() {
-        resources
-                .setContainerDataSource(application.getDb().getResources(null));
-    }
-}
diff --git a/portlet-src/com/itmill/toolkit/demo/reservation/simple/SampleDB.java b/portlet-src/com/itmill/toolkit/demo/reservation/simple/SampleDB.java
deleted file mode 100644 (file)
index 86428db..0000000
+++ /dev/null
@@ -1,501 +0,0 @@
-/* 
-@ITMillApache2LicenseForJavaFiles@
- */
-
-package com.itmill.toolkit.demo.reservation.simple;
-
-import java.sql.Connection;
-import java.sql.DriverManager;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.util.Calendar;
-import java.util.Collection;
-import java.util.Date;
-import java.util.Iterator;
-import java.util.List;
-
-import com.itmill.toolkit.data.Container;
-import com.itmill.toolkit.data.Item;
-import com.itmill.toolkit.data.util.QueryContainer;
-import com.itmill.toolkit.demo.reservation.ResourceNotAvailableException;
-
-/**
- * Simplified version of Reservr's SampleDB
- * 
- * If you are going to use this application in production, make sure to modify
- * this to save data into real DB instead of in memory HSQLDB.
- */
-public class SampleDB {
-
-    public class Resource {
-        public static final String TABLE = "RESOURCE";
-        public static final String PROPERTY_ID_ID = TABLE + "_ID";
-        public static final String PROPERTY_ID_STYLENAME = TABLE + "_STYLENAME";
-        public static final String PROPERTY_ID_NAME = TABLE + "_NAME";
-        public static final String PROPERTY_ID_DESCRIPTION = TABLE
-                + "_DESCRIPTION";
-        public static final String PROPERTY_ID_LOCATIONX = TABLE
-                + "_LOCATION_X";
-        public static final String PROPERTY_ID_LOCATIONY = TABLE
-                + "_LOCATION_Y";
-        public static final String PROPERTY_ID_CATEGORY = TABLE + "_CATEGORY";
-        public static final String PROPERTY_ID_DELETED = TABLE + "_DELETED";
-    }
-
-    public class Reservation {
-        public static final String TABLE = "RESERVATION";
-        public static final String PROPERTY_ID_ID = TABLE + "_ID";
-        public static final String PROPERTY_ID_DESCRIPTION = TABLE
-                + "_DESCRIPTION";
-        public static final String PROPERTY_ID_RESOURCE_ID = TABLE
-                + "_RESOURCE_ID";
-        public static final String PROPERTY_ID_RESERVED_BY = TABLE
-                + "_RESERVED_BY_USER";
-        public static final String PROPERTY_ID_RESERVED_FROM = TABLE
-                + "_RESERVED_FROM";
-        public static final String PROPERTY_ID_RESERVED_TO = TABLE
-                + "_RESERVED_TO";
-    }
-
-    // TODO -> param
-    private static final String DB_URL = "jdbc:hsqldb:file:reservation.db";
-
-    private static final String CREATE_TABLE_RESOURCE = "CREATE TABLE "
-            + Resource.TABLE + " (" + " " + Resource.PROPERTY_ID_ID
-            + " INTEGER IDENTITY" + ", " + Resource.PROPERTY_ID_STYLENAME
-            + " VARCHAR(20) NOT NULL" + ", " + Resource.PROPERTY_ID_NAME
-            + " VARCHAR(30) NOT NULL" + ", " + Resource.PROPERTY_ID_DESCRIPTION
-            + " VARCHAR(100)" + ", " + Resource.PROPERTY_ID_LOCATIONX
-            + " DOUBLE" + ", " + Resource.PROPERTY_ID_LOCATIONY + " DOUBLE"
-            + ", " + Resource.PROPERTY_ID_CATEGORY + " VARCHAR(30)" + ", "
-            + Resource.PROPERTY_ID_DELETED + " BOOLEAN DEFAULT false NOT NULL"
-            + ", UNIQUE(" + Resource.PROPERTY_ID_NAME + "))";
-    private static final String CREATE_TABLE_RESERVATION = "CREATE TABLE "
-            + Reservation.TABLE + " (" + " " + Reservation.PROPERTY_ID_ID
-            + " INTEGER IDENTITY" + ", " + Reservation.PROPERTY_ID_RESOURCE_ID
-            + " INTEGER" + ", " + Reservation.PROPERTY_ID_RESERVED_FROM
-            + " TIMESTAMP NOT NULL" + ", "
-            + Reservation.PROPERTY_ID_RESERVED_TO + " TIMESTAMP NOT NULL"
-            + ", " + Reservation.PROPERTY_ID_DESCRIPTION + " VARCHAR(100)"
-            + ", " + Reservation.PROPERTY_ID_RESERVED_BY + " VARCHAR(100)"
-            + ", FOREIGN KEY (" + Reservation.PROPERTY_ID_RESOURCE_ID
-            + ") REFERENCES " + Resource.TABLE + "(" + Resource.PROPERTY_ID_ID
-            + "))";
-
-    private static Connection connection = null;
-
-    /**
-     * Create database.
-     */
-    public SampleDB() {
-        // connect to SQL database
-        connect();
-
-    }
-
-    private synchronized void dropTables() {
-        try {
-            update("DROP TABLE " + Reservation.TABLE);
-        } catch (final SQLException IGNORED) {
-            // IGNORED, assuming it was not there
-        }
-        try {
-            update("DROP TABLE " + Resource.TABLE);
-        } catch (final SQLException IGNORED) {
-            // IGNORED, assuming it was not there
-        }
-    }
-
-    /**
-     * Connect to SQL database. In this sample we use HSQLDB and an toolkit
-     * named database in implicitly created into system memory.
-     * 
-     */
-    private synchronized void connect() {
-        if (connection == null) {
-            try {
-                Class.forName("org.hsqldb.jdbcDriver").newInstance();
-                connection = DriverManager.getConnection(DB_URL);
-            } catch (final Exception e) {
-                throw new RuntimeException(e);
-            }
-
-            dropTables();
-            // initialize SQL database
-            createTables();
-
-            // test by executing sample JDBC query
-            testDatabase();
-
-            generateResources();
-            generateReservations();
-
-        }
-    }
-
-    /**
-     * use for SQL commands CREATE, DROP, INSERT and UPDATE
-     * 
-     * @param expression
-     * @throws SQLException
-     */
-    private synchronized void update(String expression) throws SQLException {
-        Statement st = null;
-        st = connection.createStatement();
-        final int i = st.executeUpdate(expression);
-        if (i == -1) {
-            System.out.println("SampleDatabase error : " + expression);
-        }
-        st.close();
-    }
-
-    /**
-     * Create test table and few rows. Issue note: using capitalized column
-     * names as HSQLDB returns column names in capitalized form with this demo.
-     * 
-     */
-    private synchronized void createTables() {
-        try {
-            String stmt = null;
-            stmt = CREATE_TABLE_RESOURCE;
-            update(stmt);
-        } catch (final SQLException e) {
-            if (e.toString().indexOf("Table already exists") == -1) {
-                throw new RuntimeException(e);
-            }
-        }
-        try {
-            String stmt = null;
-            stmt = CREATE_TABLE_RESERVATION;
-            update(stmt);
-        } catch (final SQLException e) {
-            if (e.toString().indexOf("Table already exists") == -1) {
-                throw new RuntimeException(e);
-            }
-        }
-    }
-
-    /**
-     * Test database connection with simple SELECT command.
-     * 
-     */
-    private synchronized String testDatabase() {
-        String result = null;
-        try {
-            final Statement stmt = connection.createStatement(
-                    ResultSet.TYPE_SCROLL_INSENSITIVE,
-                    ResultSet.CONCUR_UPDATABLE);
-            final ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM "
-                    + Resource.TABLE);
-            rs.next();
-            result = "rowcount for table test is " + rs.getObject(1).toString();
-            stmt.close();
-        } catch (final SQLException e) {
-            throw new RuntimeException(e);
-        }
-        return result;
-    }
-
-    public Connection getConnection() {
-        return connection;
-    }
-
-    public Container getCategories() {
-        // TODO where deleted=?
-        final String q = "SELECT DISTINCT(" + Resource.PROPERTY_ID_CATEGORY
-                + ") FROM " + Resource.TABLE + " ORDER BY "
-                + Resource.PROPERTY_ID_CATEGORY;
-        try {
-            return new QueryContainer(q, connection,
-                    ResultSet.TYPE_SCROLL_INSENSITIVE,
-                    ResultSet.CONCUR_READ_ONLY);
-        } catch (final SQLException e) {
-            throw new RuntimeException(e);
-        }
-
-    }
-
-    public Container getResources(String category) {
-        // TODO where deleted=?
-        String q = "SELECT * FROM " + Resource.TABLE;
-        if (category != null) {
-            q += " WHERE " + Resource.PROPERTY_ID_CATEGORY + "='" + category
-                    + "'"; // FIXME ->
-            // PreparedStatement!
-        }
-
-        try {
-            return new QueryContainer(q, connection,
-                    ResultSet.TYPE_SCROLL_INSENSITIVE,
-                    ResultSet.CONCUR_READ_ONLY);
-        } catch (final SQLException e) {
-            throw new RuntimeException(e);
-        }
-
-    }
-
-    public Container getReservations(List resources) {
-        // TODO where reserved_by=?
-        // TODO where from=?
-        // TODO where to=?
-        // TODO where deleted=?
-        String q = "SELECT * FROM " + Reservation.TABLE + "," + Resource.TABLE;
-        q += " WHERE " + Reservation.PROPERTY_ID_RESOURCE_ID + "="
-                + Resource.PROPERTY_ID_ID;
-        if (resources != null && resources.size() > 0) {
-            final StringBuffer s = new StringBuffer();
-            for (final Iterator it = resources.iterator(); it.hasNext();) {
-                if (s.length() > 0) {
-                    s.append(",");
-                }
-                s.append(((Item) it.next())
-                        .getItemProperty(Resource.PROPERTY_ID_ID));
-            }
-            q += " HAVING " + Reservation.PROPERTY_ID_RESOURCE_ID + " IN (" + s
-                    + ")";
-        }
-        q += " ORDER BY " + Reservation.PROPERTY_ID_RESERVED_FROM;
-        try {
-            final QueryContainer qc = new QueryContainer(q, connection,
-                    ResultSet.TYPE_SCROLL_INSENSITIVE,
-                    ResultSet.CONCUR_READ_ONLY);
-            if (qc.size() < 1) {
-                return null;
-            } else {
-                return qc;
-            }
-        } catch (final SQLException e) {
-            throw new RuntimeException(e);
-        }
-    }
-
-    public synchronized void addReservation(Item resource, String reservedBy,
-            Date reservedFrom, Date reservedTo, String description)
-            throws ResourceNotAvailableException {
-        if (reservedFrom.after(reservedTo)) {
-            final Date tmp = reservedTo;
-            reservedTo = reservedFrom;
-            reservedFrom = tmp;
-        }
-        final int resourceId = ((Integer) resource.getItemProperty(
-                Resource.PROPERTY_ID_ID).getValue()).intValue();
-        final String q = "INSERT INTO " + Reservation.TABLE + " ("
-                + Reservation.PROPERTY_ID_RESOURCE_ID + ","
-                + Reservation.PROPERTY_ID_RESERVED_BY + ","
-                + Reservation.PROPERTY_ID_RESERVED_FROM + ","
-                + Reservation.PROPERTY_ID_RESERVED_TO + ","
-                + Reservation.PROPERTY_ID_DESCRIPTION + ")"
-                + "VALUES (?,?,?,?,?)";
-        synchronized (DB_URL) {
-            if (!isAvailableResource(resourceId, reservedFrom, reservedTo)) {
-                throw new ResourceNotAvailableException(
-                        "The resource is not available at that time.");
-            }
-            try {
-                PreparedStatement p;
-                p = connection.prepareStatement(q);
-                p.setInt(1, resourceId);
-                p.setString(2, reservedBy);
-                p.setTimestamp(3,
-                        new java.sql.Timestamp(reservedFrom.getTime()));
-                p.setTimestamp(4, new java.sql.Timestamp(reservedTo.getTime()));
-                p.setString(5, description);
-                p.execute();
-            } catch (SQLException e) {
-                // TODO Auto-generated catch block
-                e.printStackTrace();
-            }
-        }
-    }
-
-    public boolean isAvailableResource(int resourceId, Date reservedFrom,
-            Date reservedTo) {
-        // TODO where deleted=?
-        if (reservedFrom.after(reservedTo)) {
-            final Date tmp = reservedTo;
-            reservedTo = reservedFrom;
-            reservedFrom = tmp;
-        }
-        final String checkQ = "SELECT count(*) FROM " + Reservation.TABLE
-                + " WHERE " + Reservation.PROPERTY_ID_RESOURCE_ID + "=? AND (("
-                + Reservation.PROPERTY_ID_RESERVED_FROM + ">=? AND "
-                + Reservation.PROPERTY_ID_RESERVED_FROM + "<?) OR ("
-                + Reservation.PROPERTY_ID_RESERVED_TO + ">? AND "
-                + Reservation.PROPERTY_ID_RESERVED_TO + "<=?) OR ("
-                + Reservation.PROPERTY_ID_RESERVED_FROM + "<=? AND "
-                + Reservation.PROPERTY_ID_RESERVED_TO + ">=?)" + ")";
-        try {
-            final PreparedStatement p = connection.prepareStatement(checkQ);
-            p.setInt(1, resourceId);
-            p.setTimestamp(2, new java.sql.Timestamp(reservedFrom.getTime()));
-            p.setTimestamp(3, new java.sql.Timestamp(reservedTo.getTime()));
-            p.setTimestamp(4, new java.sql.Timestamp(reservedFrom.getTime()));
-            p.setTimestamp(5, new java.sql.Timestamp(reservedTo.getTime()));
-            p.setTimestamp(6, new java.sql.Timestamp(reservedFrom.getTime()));
-            p.setTimestamp(7, new java.sql.Timestamp(reservedTo.getTime()));
-            p.execute();
-            final ResultSet rs = p.getResultSet();
-            if (rs.next() && rs.getInt(1) > 0) {
-                return false;
-            }
-        } catch (final Exception e) {
-            throw new RuntimeException(e);
-        }
-        return true;
-    }
-
-    public synchronized void generateReservations() {
-        final int days = 30;
-        final String descriptions[] = { "Picking up guests from airport",
-                "Sightseeing with the guests",
-                "Moving new servers from A to B", "Shopping",
-                "Customer meeting", "Guests arriving at harbour",
-                "Moving furniture", "Taking guests to see town" };
-        final Container cat = getCategories();
-        final Collection cIds = cat.getItemIds();
-        for (final Iterator it = cIds.iterator(); it.hasNext();) {
-            final Object id = it.next();
-            final Item ci = cat.getItem(id);
-            final String c = (String) ci.getItemProperty(
-                    Resource.PROPERTY_ID_CATEGORY).getValue();
-            final Container resources = getResources(c);
-            final Collection rIds = resources.getItemIds();
-            final Calendar cal = Calendar.getInstance();
-            cal.set(Calendar.MINUTE, 0);
-            cal.set(Calendar.SECOND, 0);
-            cal.set(Calendar.MILLISECOND, 0);
-            final int hourNow = new Date().getHours();
-            // cal.add(Calendar.DAY_OF_MONTH, -days);
-            for (int i = 0; i < days; i++) {
-                int r = 3;
-                for (final Iterator rit = rIds.iterator(); rit.hasNext()
-                        && r > 0; r--) {
-                    final Object rid = rit.next();
-                    final Item resource = resources.getItem(rid);
-                    final int s = hourNow - 6
-                            + (int) Math.round(Math.random() * 6.0);
-                    final int e = s + 1 + (int) Math.round(Math.random() * 4.0);
-                    final Date start = new Date(cal.getTimeInMillis());
-                    start.setHours(s);
-                    final Date end = new Date(cal.getTimeInMillis());
-                    end.setHours(e);
-                    try {
-                        addReservation(resource, "Demo User", start, end,
-                                descriptions[(int) Math.floor(Math.random()
-                                        * descriptions.length)]);
-                    } catch (ResourceNotAvailableException e1) {
-                        // TODO Auto-generated catch block
-                        e1.printStackTrace();
-                    }
-                }
-                cal.add(Calendar.DATE, 1);
-            }
-        }
-
-    }
-
-    public synchronized void generateResources() {
-
-        final Object[][] resources = {
-
-                { "01", "Portable Video projector 1", "Small,XGA resolution",
-                        "Turku", new Double(60.510857), new Double(22.275424) },
-                { "02", "Auditorio", "", "Turku", new Double(60.452171),
-                        new Double(22.2995) },
-                { "03", "Meeting room 1", "Projector, WiFi", "Turku",
-                        new Double(60.4507), new Double(22.295551) },
-                { "04", "Meeting room 2", "WiFi, Blackboard", "Turku",
-                        new Double(60.434722), new Double(22.224398) },
-                { "05", "AV Room", "Cabrio. Keys from infodesk.", "Turku",
-                        new Double(60.508970), new Double(22.264790) },
-                { "06", "Video projector",
-                        "Rather heavy, good luminance, WXGA", "Turku",
-                        new Double(60.434722), new Double(22.224398) },
-
-        };
-
-        final String q = "INSERT INTO " + Resource.TABLE + "("
-                + Resource.PROPERTY_ID_STYLENAME + ","
-                + Resource.PROPERTY_ID_NAME + ","
-                + Resource.PROPERTY_ID_DESCRIPTION + ","
-                + Resource.PROPERTY_ID_CATEGORY + ","
-                + Resource.PROPERTY_ID_LOCATIONX + ","
-                + Resource.PROPERTY_ID_LOCATIONY + ")"
-                + " VALUES (?,?,?,?,?,?)";
-        try {
-            final PreparedStatement stmt = connection.prepareStatement(q);
-            for (int i = 0; i < resources.length; i++) {
-                int j = 0;
-                stmt.setString(j + 1, (String) resources[i][j++]);
-                stmt.setString(j + 1, (String) resources[i][j++]);
-                stmt.setString(j + 1, (String) resources[i][j++]);
-                stmt.setString(j + 1, (String) resources[i][j++]);
-                stmt.setDouble(j + 1, ((Double) resources[i][j++])
-                        .doubleValue());
-                stmt.setDouble(j + 1, ((Double) resources[i][j++])
-                        .doubleValue());
-                stmt.execute();
-            }
-        } catch (final SQLException e) {
-            throw new RuntimeException(e);
-        }
-    }
-
-    public int addResource(String name, String desc) {
-        final String q = "INSERT INTO " + Resource.TABLE + " ("
-                + Resource.PROPERTY_ID_STYLENAME + ","
-                + Resource.PROPERTY_ID_NAME + ","
-                + Resource.PROPERTY_ID_DESCRIPTION + ","
-                + Resource.PROPERTY_ID_CATEGORY + ","
-                + Resource.PROPERTY_ID_LOCATIONX + ","
-                + Resource.PROPERTY_ID_LOCATIONY + ")"
-                + " VALUES (?,?,?,?,?,?)";
-        synchronized (DB_URL) {
-            try {
-                PreparedStatement p = connection.prepareStatement(q);
-                p.setString(1, "");
-                p.setString(2, name);
-                p.setString(3, desc);
-                p.setString(4, "default");
-                p.setDouble(5, 0);
-                p.setDouble(6, 0);
-                p.execute();
-
-                Statement createStatement = connection.createStatement();
-                ResultSet executeQuery = createStatement
-                        .executeQuery("CALL IDENTITY()");
-                executeQuery.next();
-                return executeQuery.getInt(1);
-
-            } catch (SQLException e) {
-                // TODO Auto-generated catch block
-                e.printStackTrace();
-            }
-        }
-        return -1;
-    }
-
-    public void updateResource(Item editedItem, String name, String desc) {
-        final String q = "UPDATE " + Resource.TABLE + " SET "
-                + Resource.PROPERTY_ID_NAME + " = ? ,"
-                + Resource.PROPERTY_ID_DESCRIPTION + " = ? " + "WHERE "
-                + Resource.PROPERTY_ID_ID + " = ?";
-        synchronized (DB_URL) {
-            try {
-                PreparedStatement p = connection.prepareStatement(q);
-                p.setString(1, name);
-                p.setString(2, desc);
-                p.setInt(3, ((Integer) editedItem.getItemProperty(
-                        Resource.PROPERTY_ID_ID).getValue()).intValue());
-                p.execute();
-
-            } catch (SQLException e) {
-                // TODO Auto-generated catch block
-                e.printStackTrace();
-            }
-        }
-
-    }
-}
diff --git a/portlet-src/com/itmill/toolkit/demo/reservation/simple/SimpleReserver.java b/portlet-src/com/itmill/toolkit/demo/reservation/simple/SimpleReserver.java
deleted file mode 100644 (file)
index c5e9f28..0000000
+++ /dev/null
@@ -1,132 +0,0 @@
-package com.itmill.toolkit.demo.reservation.simple;
-
-import java.security.Principal;
-
-import javax.portlet.ActionRequest;
-import javax.portlet.ActionResponse;
-import javax.portlet.PortletMode;
-import javax.portlet.RenderRequest;
-import javax.portlet.RenderResponse;
-
-import com.itmill.toolkit.Application;
-import com.itmill.toolkit.terminal.gwt.server.PortletApplicationContext;
-import com.itmill.toolkit.terminal.gwt.server.PortletApplicationContext.PortletListener;
-import com.itmill.toolkit.ui.Button;
-import com.itmill.toolkit.ui.OrderedLayout;
-import com.itmill.toolkit.ui.Window;
-import com.itmill.toolkit.ui.Button.ClickEvent;
-import com.itmill.toolkit.ui.Button.ClickListener;
-import com.liferay.portal.model.User;
-import com.liferay.portal.service.UserServiceUtil;
-
-/**
- * This is a stripped down version of Reservr example. Idea is to create simple,
- * but actually usable portal gadget. Example is Liferay spesific (in user
- * handling), so you need to add portal-kernel.jar and portal-service.jar files
- * to your classpath.
- * 
- */
-public class SimpleReserver extends Application {
-
-    private SampleDB db = new SampleDB();
-
-    private StdView stdView = new StdView(this);
-
-    private AdminView adminView = new AdminView(this);
-
-    private Button toggleMode = new Button("Switch mode");
-
-    private boolean isAdminView = false;
-
-    private boolean isPortlet;
-
-    protected User user;
-
-    public void init() {
-        final Window w = new Window("Simple Reserver");
-        w.addStyleName("simplereserver");
-
-        if (getContext() instanceof PortletApplicationContext) {
-            isPortlet = true;
-            PortletApplicationContext context = (PortletApplicationContext) getContext();
-            context.addPortletListener(this, new PortletListener() {
-
-                public void handleActionRequest(ActionRequest request,
-                        ActionResponse response) {
-
-                }
-
-                public void handleRenderRequest(RenderRequest request,
-                        RenderResponse response) {
-                    // react on mode changes
-                    if ((request.getPortletMode() == PortletMode.EDIT && !isAdminView)
-                            || (request.getPortletMode() == PortletMode.VIEW && isAdminView)) {
-                        toggleMode();
-                    }
-
-                    // save user object to application for later use
-                    Principal userPrincipal = request.getUserPrincipal();
-                    try {
-                        user = UserServiceUtil.getUserById(Long
-                                .parseLong(userPrincipal.toString()));
-                    } catch (Exception e) {
-                        e.printStackTrace();
-                    }
-
-                }
-            });
-            w.setTheme("liferay");
-            // portal will deal outer margins
-            w.getLayout().setMargin(false);
-        } else {
-            w.setTheme("reservr");
-        }
-
-        setMainWindow(w);
-        if (!isPortlet) {
-            // only use toggle mode button when not in portal
-            w.addComponent(toggleMode);
-            toggleMode.addListener(new ClickListener() {
-                public void buttonClick(ClickEvent event) {
-                    toggleMode();
-                }
-            });
-        }
-        w.addComponent(stdView);
-    }
-
-    protected void toggleMode() {
-        OrderedLayout main = (OrderedLayout) getMainWindow().getLayout();
-        isAdminView = !isAdminView;
-        if (isAdminView) {
-            main.replaceComponent(stdView, adminView);
-        } else {
-            main.replaceComponent(adminView, stdView);
-            stdView.refreshData();
-        }
-    }
-
-    public SampleDB getDb() {
-        return db;
-    }
-
-    public Object getUser() {
-        if (getContext() instanceof PortletApplicationContext) {
-            try {
-                return user.getFirstName() + " " + user.getLastName();
-            } catch (Exception e) {
-                // TODO: handle exception
-                e.printStackTrace();
-                return "Portlet Demouser";
-            }
-        } else {
-            Object user = super.getUser();
-            if (user == null) {
-                return "Demo User";
-            } else {
-                return user;
-            }
-        }
-
-    }
-}
diff --git a/portlet-src/com/itmill/toolkit/demo/reservation/simple/StdView.java b/portlet-src/com/itmill/toolkit/demo/reservation/simple/StdView.java
deleted file mode 100644 (file)
index bbb07aa..0000000
+++ /dev/null
@@ -1,194 +0,0 @@
-package com.itmill.toolkit.demo.reservation.simple;
-
-import java.util.Calendar;
-import java.util.Date;
-import java.util.LinkedList;
-import java.util.List;
-
-import com.itmill.toolkit.data.Container;
-import com.itmill.toolkit.data.Item;
-import com.itmill.toolkit.data.Property.ValueChangeEvent;
-import com.itmill.toolkit.data.Property.ValueChangeListener;
-import com.itmill.toolkit.demo.reservation.CalendarField;
-import com.itmill.toolkit.demo.reservation.ResourceNotAvailableException;
-import com.itmill.toolkit.ui.Button;
-import com.itmill.toolkit.ui.ComboBox;
-import com.itmill.toolkit.ui.DateField;
-import com.itmill.toolkit.ui.Label;
-import com.itmill.toolkit.ui.OrderedLayout;
-import com.itmill.toolkit.ui.TextField;
-import com.itmill.toolkit.ui.Window;
-import com.itmill.toolkit.ui.Button.ClickEvent;
-import com.itmill.toolkit.ui.Button.ClickListener;
-
-public class StdView extends OrderedLayout {
-
-    private ComboBox resources = new ComboBox("Select resource");
-    private CalendarField reservations = new CalendarField();
-    private Button add = new Button("Add reservation");
-    private SimpleReserver application;
-
-    private EditorWindow editor = new EditorWindow();
-
-    StdView(SimpleReserver app) {
-        setWidth("250px");
-        application = app;
-
-        resources.setImmediate(true);
-        resources.setFilteringMode(ComboBox.FILTERINGMODE_CONTAINS);
-        resources
-                .setContainerDataSource(application.getDb().getResources(null));
-        resources.setItemCaptionMode(ComboBox.ITEM_CAPTION_MODE_PROPERTY);
-        resources.setItemCaptionPropertyId(SampleDB.Resource.PROPERTY_ID_NAME);
-        resources.addListener(new ComboBox.ValueChangeListener() {
-            public void valueChange(ValueChangeEvent event) {
-                refreshReservations();
-            }
-        });
-        addComponent(resources);
-
-        initCalendarFieldPropertyIds(reservations);
-        Calendar c = Calendar.getInstance();
-        reservations.setValue(c.getTime());
-        reservations.setEnabled(false);
-        addComponent(reservations);
-        reservations.setImmediate(true);
-
-        add.setEnabled(false);
-        addComponent(add);
-
-        add.addListener(new Button.ClickListener() {
-            public void buttonClick(ClickEvent event) {
-                if (resources.getValue() != null) {
-                    Item i = resources.getItem(resources.getValue());
-                    editor.newReservationFor(i);
-                }
-            }
-        });
-
-        add.setDescription("Add new reservation for selected resource");
-
-    }
-
-    private static void initCalendarFieldPropertyIds(CalendarField cal) {
-        cal.setItemStyleNamePropertyId(SampleDB.Resource.PROPERTY_ID_STYLENAME);
-        cal
-                .setItemStartPropertyId(SampleDB.Reservation.PROPERTY_ID_RESERVED_FROM);
-        cal.setItemEndPropertyId(SampleDB.Reservation.PROPERTY_ID_RESERVED_TO);
-        cal
-                .setItemTitlePropertyId(SampleDB.Reservation.PROPERTY_ID_RESERVED_BY);
-        cal
-                .setItemDescriptionPropertyId(SampleDB.Reservation.PROPERTY_ID_DESCRIPTION);
-    }
-
-    private void refreshReservations() {
-        if (resources.getValue() == null) {
-            reservations.setContainerDataSource(null);
-            add.setEnabled(false);
-            reservations.setEnabled(false);
-        } else {
-            List resource = new LinkedList();
-            resource.add(resources.getItem(resources.getValue()));
-            final Container res = application.getDb().getReservations(resource);
-            reservations.setContainerDataSource(res);
-            add.setEnabled(true);
-            reservations.setEnabled(true);
-        }
-    }
-
-    public class EditorWindow extends Window {
-
-        Label resourceName = new Label();
-
-        DateField start = new DateField("From:");
-        DateField end = new DateField("To:");
-        TextField desc = new TextField("Description:");
-        Button save = new Button("Save");
-
-        private Item res;
-
-        private Calendar cal;
-
-        EditorWindow() {
-            super("Add reservation");
-
-            cal = Calendar.getInstance();
-
-            addComponent(resourceName);
-
-            start.setResolution(DateField.RESOLUTION_MIN);
-            start.setImmediate(true);
-            start.setValue(new Date());
-            start.addListener(new ValueChangeListener() {
-                public void valueChange(ValueChangeEvent event) {
-                    Date startTime = (Date) start.getValue();
-                    Date endTime = (Date) end.getValue();
-                    if (endTime.before(startTime)) {
-                        cal.setTime(startTime);
-                        cal.add(Calendar.HOUR_OF_DAY, 1);
-                        end.setValue(cal.getTime());
-                    }
-                }
-            });
-            addComponent(start);
-
-            end.setResolution(DateField.RESOLUTION_MIN);
-            end.setImmediate(true);
-            end.setValue(new Date());
-            end.addListener(new ValueChangeListener() {
-                public void valueChange(ValueChangeEvent event) {
-                    Date startTime = (Date) start.getValue();
-                    Date endTime = (Date) end.getValue();
-                    if (endTime.before(startTime)) {
-                        cal.setTime(endTime);
-                        cal.add(Calendar.HOUR, -1);
-                        start.setValue(cal.getTime());
-                    }
-                }
-            });
-            addComponent(end);
-            addComponent(desc);
-            addComponent(save);
-            save.addListener(new ClickListener() {
-                public void buttonClick(ClickEvent event) {
-                    try {
-                        application.getDb().addReservation(res,
-                                application.getUser().toString(),
-                                (Date) start.getValue(), (Date) end.getValue(),
-                                (String) desc.getValue());
-                        EditorWindow.this.close();
-                        refreshReservations();
-                    } catch (ResourceNotAvailableException e) {
-                        getWindow()
-                                .showNotification(
-                                        "Resource is not available at that time "
-                                                + "or is too close to another reservation.");
-                    }
-                }
-            });
-        }
-
-        public void newReservationFor(Item resource) {
-            res = resource;
-            resourceName.setValue("Resourse: "
-                    + res.getItemProperty(SampleDB.Resource.PROPERTY_ID_NAME)
-                            .getValue());
-
-            cal.setTime((Date) reservations.getValue());
-            cal.set(Calendar.MINUTE, 0);
-            cal.set(Calendar.MILLISECOND, 0);
-            cal.set(Calendar.SECOND, 0);
-            start.setValue(cal.getTime());
-            cal.add(Calendar.HOUR_OF_DAY, 1);
-            end.setValue(cal.getTime());
-            StdView.this.getWindow().addWindow(this);
-        }
-    }
-
-    public void refreshData() {
-        resources
-                .setContainerDataSource(application.getDb().getResources(null));
-        refreshReservations();
-
-    }
-}
diff --git a/portlet-src/com/itmill/toolkit/portlet/util/PortletConfigurationGenerator.java b/portlet-src/com/itmill/toolkit/portlet/util/PortletConfigurationGenerator.java
deleted file mode 100644 (file)
index 403e181..0000000
+++ /dev/null
@@ -1,297 +0,0 @@
-/**\r
- * \r
- */\r
-package com.itmill.toolkit.portlet.util;\r
-\r
-import java.io.BufferedReader;\r
-import java.io.File;\r
-import java.io.FileNotFoundException;\r
-import java.io.FileOutputStream;\r
-import java.io.FileReader;\r
-import java.io.IOException;\r
-import java.io.OutputStreamWriter;\r
-import java.nio.charset.Charset;\r
-import java.util.regex.Matcher;\r
-import java.util.regex.Pattern;\r
-\r
-/**\r
- * Generates portlet.xml, liferay-portlet.xml, liferay-display.xml from web.xml.\r
- * Currently uses regular expressions to avoid dependencies; does not strictly\r
- * adhere to xml rules, but should work with a 'normal' web.xml.\r
- * \r
- * To be included, the servlet-mapping must include a special comment: <!--\r
- * portlet --> If the portlet requires some special styles (i.e height): <!--\r
- * portlet style=height:400px -->\r
- * \r
- * @author marc\r
- */\r
-public class PortletConfigurationGenerator {\r
-    // can be changed for debugging:\r
-    private static final String WEB_XML_FILE = "web.xml";\r
-    private static final String PORTLET_XML_FILE = "portlet.xml";\r
-    private static final String LIFERAY_PORTLET_XML_FILE = "liferay-portlet.xml";\r
-    private static final String LIFERAY_DISPLAY_XML_FILE = "liferay-display.xml";\r
-\r
-    // "templates" follow;\r
-    private static final String PORTLET_XML_HEAD = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"\r
-            + "<portlet-app\n"\r
-            + "        xmlns=\"http://java.sun.com/xml/ns/portlet/portlet-app_1_0.xsd\"\n"\r
-            + "        version=\"1.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"\r
-            + "        xsi:schemaLocation=\"http://java.sun.com/xml/ns/portlet/portlet-app_1_0.xsd http://java.sun.com/xml/ns/portlet/portlet-app_1_0.xsd\">\n";\r
-    private static final String PORTLET_XML_SECTION = "        <portlet>\n"\r
-            + "                <portlet-name>%PORTLETNAME%</portlet-name>\n"\r
-            + "                <display-name>IT Mill Toolkit %NAME%</display-name>\n"\r
-            + "                <portlet-class>com.itmill.toolkit.terminal.gwt.server.ApplicationPortlet</portlet-class>\n"\r
-            + "                <init-param>\n"\r
-            + "                        <name>application</name>\n"\r
-            + "                        <value>%URL%</value>\n"\r
-            + "                </init-param>\n"\r
-            + "                %EXTRAPARAMS%\n"\r
-            + "                <supports>\n"\r
-            + "                        <mime-type>text/html</mime-type>\n"\r
-            + "                        <portlet-mode>view</portlet-mode>\n"\r
-            + "                        <portlet-mode>edit</portlet-mode>\n"\r
-            + "                        <portlet-mode>help</portlet-mode>\n"\r
-            + "                </supports>\n"\r
-            + "                <portlet-info>\n"\r
-            + "                        <title>%NAME%</title>\n"\r
-            + "                        <short-title>%NAME%</short-title>\n"\r
-            + "                </portlet-info>\n" + "                \n"\r
-            + "                <security-role-ref>\n"\r
-            + "                        <role-name>administrator</role-name>\n"\r
-            + "                </security-role-ref>\n"\r
-            + "                <security-role-ref>\n"\r
-            + "                        <role-name>guest</role-name>\n"\r
-            + "                </security-role-ref>\n"\r
-            + "                <security-role-ref>\n"\r
-            + "                        <role-name>power-user</role-name>\n"\r
-            + "                </security-role-ref>\n"\r
-            + "                <security-role-ref>\n"\r
-            + "                        <role-name>user</role-name>\n"\r
-            + "                </security-role-ref>\n" + "        </portlet>\n";\r
-    private static final String PORTLET_XML_FOOT = "        %CONTEXTPARAMS%\n"\r
-            + "        <container-runtime-option>\n"\r
-            + "                <name>javax.portlet.escapeXml</name>\n"\r
-            + "                <value>false</value>\n"\r
-            + "        </container-runtime-option>\n" + "</portlet-app>";\r
-\r
-    private static final String LIFERAY_PORTLET_XML_HEAD = "<?xml version=\"1.0\"?>\n"\r
-            + "<!DOCTYPE liferay-portlet-app PUBLIC \"-//Liferay//DTD Portlet Application 4.3.0//EN\" \"http://www.liferay.com/dtd/liferay-portlet-app_4_3_0.dtd\">\n"\r
-            + "\n" + "<liferay-portlet-app>\n" + "";\r
-    private static final String LIFERAY_PORTLET_XML_SECTION = "        <portlet>\n"\r
-            + "                <portlet-name>%PORTLETNAME%</portlet-name>\n"\r
-            + "                <instanceable>true</instanceable>       \n"\r
-            + "                <ajaxable>false</ajaxable>\n"\r
-            + "        </portlet>\n" + "";\r
-    private static final String LIFERAY_PORTLET_XML_FOOT = "    \n"\r
-            + "        <role-mapper>\n"\r
-            + "                <role-name>administrator</role-name>\n"\r
-            + "                <role-link>Administrator</role-link>\n"\r
-            + "        </role-mapper>\n" + "        <role-mapper>\n"\r
-            + "                <role-name>guest</role-name>\n"\r
-            + "                <role-link>Guest</role-link>\n"\r
-            + "        </role-mapper>\n" + "        <role-mapper>\n"\r
-            + "                <role-name>power-user</role-name>\n"\r
-            + "                <role-link>Power User</role-link>\n"\r
-            + "        </role-mapper>\n" + "        <role-mapper>\n"\r
-            + "                <role-name>user</role-name>\n"\r
-            + "                <role-link>User</role-link>\n"\r
-            + "        </role-mapper>\n" + "        \n"\r
-            + "</liferay-portlet-app>";\r
-    private static final String LIFERAY_DISPLAY_XML_HEAD = "<?xml version=\"1.0\"?>\n"\r
-            + "<!DOCTYPE display PUBLIC \"-//Liferay//DTD Display 4.0.0//EN\" \"http://www.liferay.com/dtd/liferay-display_4_0_0.dtd\">\n"\r
-            + "\n"\r
-            + "<display>\n"\r
-            + "        <category name=\"IT Mill Toolkit\">\n" + "";\r
-    private static final String LIFERAY_DISPLAY_XML_SECTION = "                <portlet id=\"%PORTLETNAME%\" />\n";\r
-    private static final String LIFERAY_DISPLAY_XML_FOOT = "\n"\r
-            + "        </category>\n" + "</display>";\r
-\r
-    /**\r
-     * @param args\r
-     *                <path to directory with web.xml>\r
-     */\r
-    public static void main(String[] args) {\r
-        if (args.length < 1 || !new File(args[0]).isDirectory()) {\r
-            System.err\r
-                    .println("Usage: PortletConfigurationGenerator <directory> [widgetset]");\r
-            return;\r
-        }\r
-\r
-        String widgetset = "";\r
-        if (args.length > 1) {\r
-            widgetset = "<context-param><name>widgetset</name><value>"\r
-                    + args[1] + "</value></context-param>";\r
-        }\r
-\r
-        /*\r
-         * Read web.xml\r
-         */\r
-        File dir = new File(args[0]);\r
-        File webxmlFile = new File(dir.getAbsolutePath() + File.separatorChar\r
-                + WEB_XML_FILE);\r
-        String webXml = "";\r
-        BufferedReader in = null;\r
-        try {\r
-            in = new BufferedReader(new FileReader(webxmlFile));\r
-            String line = in.readLine();\r
-            while (line != null) {\r
-                webXml += line;\r
-                line = in.readLine();\r
-            }\r
-        } catch (FileNotFoundException e1) {\r
-            System.out.println(webxmlFile + " not found!");\r
-            return;\r
-        } catch (IOException e2) {\r
-            System.out.println("IOException while reading " + webxmlFile);\r
-            webXml = null;\r
-        }\r
-        try {\r
-            if (in != null) {\r
-                in.close();\r
-            }\r
-        } catch (IOException e1) {\r
-            System.out.println("IOException while closing " + webxmlFile);\r
-        }\r
-        if (webXml == null) {\r
-            System.out.println("Could not read web.xml!");\r
-            return;\r
-        }\r
-\r
-        /*\r
-         * Open outputs\r
-         */\r
-\r
-        // Open portlet.xml\r
-        File portletXmlFile = new File(args[0] + File.separatorChar\r
-                + PORTLET_XML_FILE);\r
-        OutputStreamWriter pout = null;\r
-        try {\r
-            pout = new OutputStreamWriter(new FileOutputStream(portletXmlFile),\r
-                    Charset.forName("UTF-8"));\r
-        } catch (FileNotFoundException e) {\r
-            System.out.println(portletXmlFile + " not found!");\r
-        }\r
-        // open liferay-portlet.xml\r
-        File liferayPortletXmlFile = new File(args[0] + File.separatorChar\r
-                + LIFERAY_PORTLET_XML_FILE);\r
-        OutputStreamWriter lpout = null;\r
-        try {\r
-            lpout = new OutputStreamWriter(new FileOutputStream(\r
-                    liferayPortletXmlFile), Charset.forName("UTF-8"));\r
-        } catch (FileNotFoundException e) {\r
-            System.out.println(liferayPortletXmlFile + " not found!");\r
-        }\r
-        // open liferay-display.xml\r
-        File liferayDisplayXmlFile = new File(args[0] + File.separatorChar\r
-                + LIFERAY_DISPLAY_XML_FILE);\r
-        OutputStreamWriter ldout = null;\r
-        try {\r
-            ldout = new OutputStreamWriter(new FileOutputStream(\r
-                    liferayDisplayXmlFile), Charset.forName("UTF-8"));\r
-        } catch (FileNotFoundException e) {\r
-            System.out.println(liferayDisplayXmlFile + " not found!");\r
-        }\r
-\r
-        if (pout != null && lpout != null && ldout != null) {\r
-\r
-            String pstring = PORTLET_XML_HEAD;\r
-            String lpstring = LIFERAY_PORTLET_XML_HEAD;\r
-            String ldstring = LIFERAY_DISPLAY_XML_HEAD;\r
-\r
-            Pattern p1 = Pattern\r
-                    .compile("<servlet-mapping>.*?<servlet-name>(.*?)<\\/servlet-name>.*?<url-pattern>(.*?)<\\/url-pattern>(.*?)<\\/servlet-mapping>");\r
-            Pattern p2 = Pattern\r
-                    .compile(".*?<!--\\s+portlet\\s?(style=\\S+)?\\s+-->.*?");\r
-            Matcher m = p1.matcher(webXml);\r
-            while (m.find()) {\r
-                if (m.groupCount() < 3) {\r
-                    // don't include\r
-                    continue;\r
-                }\r
-                Matcher m2 = p2.matcher(m.group(3));\r
-                if (!m2.find()) {\r
-                    // don't include\r
-                    continue;\r
-                }\r
-\r
-                String style = "";\r
-                if (m2.groupCount() == 1 && m2.group(1) != null) {\r
-                    style = "<init-param><name>style</name><value>"\r
-                            + m2.group(1) + "</value></init-param>";\r
-                }\r
-\r
-                String name = m.group(1);\r
-                // remove leading- and trailing whitespace\r
-                name = name.replaceAll("^\\s*", "");\r
-                name = name.replaceAll("\\s*$", "");\r
-                String pname = name + "Portlet";\r
-                String url = m.group(2);\r
-                // remove leading- and trailing whitespace\r
-                url = url.replaceAll("^\\s*", "");\r
-                url = url.replaceAll("\\s*$", "");\r
-                if (url.startsWith("/")) {\r
-                    url = url.substring(1);\r
-                }\r
-                if (url.endsWith("*")) {\r
-                    url = url.substring(0, url.length() - 1);\r
-                }\r
-                if (url.endsWith("/")) {\r
-                    url = url.substring(0, url.length() - 1);\r
-                }\r
-\r
-                System.out.println("Mapping " + pname + " to " + url);\r
-\r
-                String s = PORTLET_XML_SECTION;\r
-                s = s.replaceAll("%NAME%", name);\r
-                s = s.replaceAll("%PORTLETNAME%", pname);\r
-                s = s.replaceAll("%URL%", url);\r
-                s = s.replaceAll("%EXTRAPARAMS%", style);\r
-\r
-                pstring += s;\r
-\r
-                s = LIFERAY_PORTLET_XML_SECTION;\r
-                s = s.replaceAll("%NAME%", name);\r
-                s = s.replaceAll("%PORTLETNAME%", pname);\r
-                s = s.replaceAll("%URL%", url);\r
-                lpstring += s;\r
-\r
-                s = LIFERAY_DISPLAY_XML_SECTION;\r
-                s = s.replaceAll("%NAME%", name);\r
-                s = s.replaceAll("%PORTLETNAME%", pname);\r
-                s = s.replaceAll("%URL%", url);\r
-                ldstring += s;\r
-\r
-            }\r
-\r
-            pstring += PORTLET_XML_FOOT\r
-                    .replaceAll("%CONTEXTPARAMS%", widgetset);\r
-            lpstring += LIFERAY_PORTLET_XML_FOOT;\r
-            ldstring += LIFERAY_DISPLAY_XML_FOOT;\r
-\r
-            try {\r
-                pout.write(pstring);\r
-                lpout.write(lpstring);\r
-                ldout.write(ldstring);\r
-            } catch (IOException e) {\r
-                System.out.println("Write FAILED:" + e);\r
-            }\r
-\r
-        }\r
-\r
-        try {\r
-            if (pout != null) {\r
-                pout.close();\r
-            }\r
-            if (lpout != null) {\r
-                lpout.close();\r
-            }\r
-            if (ldout != null) {\r
-                ldout.close();\r
-            }\r
-        } catch (IOException e) {\r
-            System.out.println("Close FAILED: " + e);\r
-        }\r
-        System.out.println("Done.");\r
-    }\r
-}\r
diff --git a/portlet-src/com/itmill/toolkit/terminal/gwt/server/ApplicationPortlet.java b/portlet-src/com/itmill/toolkit/terminal/gwt/server/ApplicationPortlet.java
deleted file mode 100644 (file)
index 77cca2a..0000000
+++ /dev/null
@@ -1,91 +0,0 @@
-package com.itmill.toolkit.terminal.gwt.server;\r
-\r
-import java.io.IOException;\r
-import java.io.PrintWriter;\r
-\r
-import javax.portlet.ActionRequest;\r
-import javax.portlet.ActionResponse;\r
-import javax.portlet.Portlet;\r
-import javax.portlet.PortletConfig;\r
-import javax.portlet.PortletException;\r
-import javax.portlet.PortletRequestDispatcher;\r
-import javax.portlet.PortletSession;\r
-import javax.portlet.RenderRequest;\r
-import javax.portlet.RenderResponse;\r
-\r
-import com.itmill.toolkit.Application;\r
-\r
-public class ApplicationPortlet implements Portlet {\r
-    // The application to show\r
-    protected String app = null;\r
-    // some applications might require forced height (and, more seldom, width)\r
-    protected String style = null; // e.g "height:500px;"\r
-    protected String widgetset = null;\r
-\r
-    public void destroy() {\r
-\r
-    }\r
-\r
-    public void init(PortletConfig config) throws PortletException {\r
-        app = config.getInitParameter("application");\r
-        if (app == null) {\r
-            app = "PortletDemo";\r
-        }\r
-        style = config.getInitParameter("style");\r
-        widgetset = config.getInitParameter("widgetset");\r
-    }\r
-\r
-    public void processAction(ActionRequest request, ActionResponse response)\r
-            throws PortletException, IOException {\r
-        PortletApplicationContext.dispatchRequest(this, request, response);\r
-    }\r
-\r
-    public void render(RenderRequest request, RenderResponse response)\r
-            throws PortletException, IOException {\r
-\r
-        // display the IT Mill Toolkit application\r
-        writeAjaxWindow(request, response);\r
-    }\r
-\r
-    protected void writeAjaxWindow(RenderRequest request,\r
-            RenderResponse response) throws IOException {\r
-\r
-        if (app != null) {\r
-            PortletSession sess = request.getPortletSession();\r
-            PortletApplicationContext ctx = PortletApplicationContext\r
-                    .getApplicationContext(sess);\r
-\r
-            PortletRequestDispatcher dispatcher = sess.getPortletContext()\r
-                    .getRequestDispatcher("/" + app);\r
-\r
-            try {\r
-                request.setAttribute(ApplicationServlet.REQUEST_FRAGMENT,\r
-                        "true");\r
-                if (widgetset != null) {\r
-                    request.setAttribute(ApplicationServlet.REQUEST_WIDGETSET,\r
-                            widgetset);\r
-                }\r
-                if (style != null) {\r
-                    request.setAttribute(ApplicationServlet.REQUEST_APPSTYLE,\r
-                            style);\r
-                }\r
-                dispatcher.include(request, response);\r
-\r
-            } catch (PortletException e) {\r
-                response.setContentType("text/html");\r
-                PrintWriter out = response.getWriter();\r
-                out.print("<h1>Servlet include failed!</h1>");\r
-                out.print("<div>" + e + "</div>");\r
-                ctx.setPortletApplication(this, null);\r
-                return;\r
-            }\r
-\r
-            Application app = (Application) request\r
-                    .getAttribute(Application.class.getName());\r
-            ctx.setPortletApplication(this, app);\r
-            ctx.firePortletRenderRequest(this, request, response);\r
-\r
-        }\r
-    }\r
-\r
-}\r
diff --git a/portlet-src/com/itmill/toolkit/terminal/gwt/server/PortletApplicationContext.java b/portlet-src/com/itmill/toolkit/terminal/gwt/server/PortletApplicationContext.java
deleted file mode 100644 (file)
index 4ddbabd..0000000
+++ /dev/null
@@ -1,283 +0,0 @@
-/**\r
- * \r
- */\r
-package com.itmill.toolkit.terminal.gwt.server;\r
-\r
-import java.io.IOException;\r
-import java.io.OutputStream;\r
-import java.io.PrintWriter;\r
-import java.util.HashMap;\r
-import java.util.Iterator;\r
-import java.util.LinkedHashSet;\r
-import java.util.Locale;\r
-import java.util.Map;\r
-import java.util.Set;\r
-\r
-import javax.portlet.ActionRequest;\r
-import javax.portlet.ActionResponse;\r
-import javax.portlet.Portlet;\r
-import javax.portlet.PortletSession;\r
-import javax.portlet.PortletURL;\r
-import javax.portlet.RenderRequest;\r
-import javax.portlet.RenderResponse;\r
-import javax.servlet.http.HttpSession;\r
-\r
-import com.itmill.toolkit.Application;\r
-\r
-/**\r
- * @author marc\r
- * \r
- */\r
-public class PortletApplicationContext extends WebApplicationContext {\r
-\r
-    protected PortletSession portletSession;\r
-\r
-    protected Map portletListeners = new HashMap();\r
-\r
-    protected Map portletToApplication = new HashMap();\r
-\r
-    PortletApplicationContext() {\r
-\r
-    }\r
-\r
-    static public PortletApplicationContext getApplicationContext(\r
-            PortletSession session) {\r
-        WebApplicationContext cx = (WebApplicationContext) session\r
-                .getAttribute(WebApplicationContext.class.getName(),\r
-                        PortletSession.APPLICATION_SCOPE);\r
-        if (cx == null) {\r
-            cx = new PortletApplicationContext();\r
-        }\r
-        if (!(cx instanceof PortletApplicationContext)) {\r
-            // TODO Should we even try this? And should we leave original as-is?\r
-            PortletApplicationContext pcx = new PortletApplicationContext();\r
-            pcx.applications.addAll(cx.applications);\r
-            cx.applications.clear();\r
-            pcx.browser = cx.browser;\r
-            cx.browser = null;\r
-            pcx.listeners = cx.listeners;\r
-            cx.listeners = null;\r
-            pcx.session = cx.session;\r
-            cx = pcx;\r
-        }\r
-        if (((PortletApplicationContext) cx).portletSession == null) {\r
-            ((PortletApplicationContext) cx).portletSession = session;\r
-        }\r
-        session.setAttribute(WebApplicationContext.class.getName(), cx,\r
-                PortletSession.APPLICATION_SCOPE);\r
-        return (PortletApplicationContext) cx;\r
-    }\r
-\r
-    static public WebApplicationContext getApplicationContext(\r
-            HttpSession session) {\r
-        WebApplicationContext cx = (WebApplicationContext) session\r
-                .getAttribute(WebApplicationContext.class.getName());\r
-        if (cx == null) {\r
-            cx = new PortletApplicationContext();\r
-        }\r
-        if (cx.session == null) {\r
-            cx.session = session;\r
-        }\r
-        session.setAttribute(WebApplicationContext.class.getName(), cx);\r
-        return cx;\r
-    }\r
-\r
-    protected void removeApplication(Application application) {\r
-        portletListeners.remove(application);\r
-        for (Iterator it = portletToApplication.keySet().iterator(); it\r
-                .hasNext();) {\r
-            Object key = it.next();\r
-            if (key == application) {\r
-                portletToApplication.remove(key);\r
-            }\r
-        }\r
-        super.removeApplication(application);\r
-    }\r
-\r
-    public boolean equals(Object obj) {\r
-        if (portletSession == null) {\r
-            return super.equals(obj);\r
-        }\r
-        return portletSession.equals(obj);\r
-    }\r
-\r
-    public int hashCode() {\r
-        if (portletSession == null) {\r
-            return super.hashCode();\r
-        }\r
-        return portletSession.hashCode();\r
-    }\r
-\r
-    public void setPortletApplication(Portlet portlet, Application app) {\r
-        portletToApplication.put(portlet, app);\r
-    }\r
-\r
-    public Application getPortletApplication(Portlet portlet) {\r
-        return (Application) portletToApplication.get(portlet);\r
-    }\r
-\r
-    public PortletSession getPortletSession() {\r
-        return portletSession;\r
-    }\r
-\r
-    public void addPortletListener(Application app, PortletListener listener) {\r
-        Set l = (Set) portletListeners.get(app);\r
-        if (l == null) {\r
-            l = new LinkedHashSet();\r
-            portletListeners.put(app, l);\r
-        }\r
-        l.add(listener);\r
-    }\r
-\r
-    public void removePortletListener(Application app, PortletListener listener) {\r
-        Set l = (Set) portletListeners.get(app);\r
-        if (l != null) {\r
-            l.remove(listener);\r
-        }\r
-    }\r
-\r
-    public static void dispatchRequest(Portlet portlet, RenderRequest request,\r
-            RenderResponse response) {\r
-        PortletApplicationContext ctx = getApplicationContext(request\r
-                .getPortletSession());\r
-        if (ctx != null) {\r
-            ctx.firePortletRenderRequest(portlet, request, response);\r
-        }\r
-    }\r
-\r
-    public static void dispatchRequest(Portlet portlet, ActionRequest request,\r
-            ActionResponse response) {\r
-        PortletApplicationContext ctx = getApplicationContext(request\r
-                .getPortletSession());\r
-        if (ctx != null) {\r
-            ctx.firePortletActionRequest(portlet, request, response);\r
-        }\r
-    }\r
-\r
-    public void firePortletRenderRequest(Portlet portlet,\r
-            RenderRequest request, RenderResponse response) {\r
-        Application app = getPortletApplication(portlet);\r
-        Set listeners = (Set) portletListeners.get(app);\r
-        if (listeners != null) {\r
-            for (Iterator it = listeners.iterator(); it.hasNext();) {\r
-                PortletListener l = (PortletListener) it.next();\r
-                l.handleRenderRequest(request, new RestrictedRenderResponse(\r
-                        response));\r
-            }\r
-        }\r
-    }\r
-\r
-    public void firePortletActionRequest(Portlet portlet,\r
-            ActionRequest request, ActionResponse response) {\r
-        Application app = getPortletApplication(portlet);\r
-        Set listeners = (Set) portletListeners.get(app);\r
-        if (listeners != null) {\r
-            for (Iterator it = listeners.iterator(); it.hasNext();) {\r
-                PortletListener l = (PortletListener) it.next();\r
-                l.handleActionRequest(request, response);\r
-            }\r
-        }\r
-    }\r
-\r
-    public interface PortletListener {\r
-        public void handleRenderRequest(RenderRequest request,\r
-                RenderResponse response);\r
-\r
-        public void handleActionRequest(ActionRequest request,\r
-                ActionResponse response);\r
-    }\r
-\r
-    private class RestrictedRenderResponse implements RenderResponse {\r
-\r
-        private RenderResponse response;\r
-\r
-        private RestrictedRenderResponse(RenderResponse response) {\r
-            this.response = response;\r
-        }\r
-\r
-        public void addProperty(String key, String value) {\r
-            response.addProperty(key, value);\r
-        }\r
-\r
-        public PortletURL createActionURL() {\r
-            return response.createActionURL();\r
-        }\r
-\r
-        public PortletURL createRenderURL() {\r
-            return response.createRenderURL();\r
-        }\r
-\r
-        public String encodeURL(String path) {\r
-            return response.encodeURL(path);\r
-        }\r
-\r
-        public void flushBuffer() throws IOException {\r
-            // NOP\r
-            // TODO throw?\r
-        }\r
-\r
-        public int getBufferSize() {\r
-            return response.getBufferSize();\r
-        }\r
-\r
-        public String getCharacterEncoding() {\r
-            return response.getCharacterEncoding();\r
-        }\r
-\r
-        public String getContentType() {\r
-            return response.getContentType();\r
-        }\r
-\r
-        public Locale getLocale() {\r
-            return response.getLocale();\r
-        }\r
-\r
-        public String getNamespace() {\r
-            return response.getNamespace();\r
-        }\r
-\r
-        public OutputStream getPortletOutputStream() throws IOException {\r
-            // write forbidden\r
-            return null;\r
-        }\r
-\r
-        public PrintWriter getWriter() throws IOException {\r
-            // write forbidden\r
-            return null;\r
-        }\r
-\r
-        public boolean isCommitted() {\r
-            return response.isCommitted();\r
-        }\r
-\r
-        public void reset() {\r
-            // NOP\r
-            // TODO throw?\r
-        }\r
-\r
-        public void resetBuffer() {\r
-            // NOP\r
-            // TODO throw?\r
-        }\r
-\r
-        public void setBufferSize(int size) {\r
-            // NOP\r
-            // TODO throw?\r
-        }\r
-\r
-        public void setContentType(String type) {\r
-            // NOP\r
-            // TODO throw?\r
-        }\r
-\r
-        public void setProperty(String key, String value) {\r
-            response.setProperty(key, value);\r
-        }\r
-\r
-        public void setTitle(String title) {\r
-            response.setTitle(title);\r
-        }\r
-\r
-    }\r
-\r
-}\r
diff --git a/src/com/itmill/toolkit/demo/PortletDemo.java b/src/com/itmill/toolkit/demo/PortletDemo.java
new file mode 100644 (file)
index 0000000..e408961
--- /dev/null
@@ -0,0 +1,152 @@
+/**\r
+ * \r
+ */\r
+package com.itmill.toolkit.demo;\r
+\r
+import java.util.Iterator;\r
+import java.util.Map;\r
+\r
+import javax.portlet.ActionRequest;\r
+import javax.portlet.ActionResponse;\r
+import javax.portlet.PortletMode;\r
+import javax.portlet.PortletRequest;\r
+import javax.portlet.PortletURL;\r
+import javax.portlet.RenderRequest;\r
+import javax.portlet.RenderResponse;\r
+import javax.portlet.WindowState;\r
+\r
+import com.itmill.toolkit.Application;\r
+import com.itmill.toolkit.terminal.ExternalResource;\r
+import com.itmill.toolkit.terminal.gwt.server.PortletApplicationContext;\r
+import com.itmill.toolkit.terminal.gwt.server.PortletApplicationContext.PortletListener;\r
+import com.itmill.toolkit.ui.Label;\r
+import com.itmill.toolkit.ui.Link;\r
+import com.itmill.toolkit.ui.TextField;\r
+import com.itmill.toolkit.ui.Window;\r
+import com.itmill.toolkit.ui.Window.Notification;\r
+\r
+/**\r
+ * @author marc\r
+ * \r
+ */\r
+public class PortletDemo extends Application {\r
+\r
+    Window main = new Window();\r
+    TextField tf = new TextField("Some value");\r
+    Label userInfo = new Label();\r
+    Link portletEdit = new Link();\r
+    Link portletMax = new Link();\r
+    Link someAction = null;\r
+\r
+    public void init() {\r
+        main = new Window();\r
+        setMainWindow(main);\r
+\r
+        userInfo.setCaption("User info");\r
+        userInfo.setContentMode(Label.CONTENT_PREFORMATTED);\r
+        main.addComponent(userInfo);\r
+\r
+        tf.setEnabled(false);\r
+        tf.setImmediate(true);\r
+        main.addComponent(tf);\r
+\r
+        portletEdit.setEnabled(false);\r
+        main.addComponent(portletEdit);\r
+        portletMax.setEnabled(false);\r
+        main.addComponent(portletMax);\r
+\r
+        if (getContext() instanceof PortletApplicationContext) {\r
+            PortletApplicationContext ctx = (PortletApplicationContext) getContext();\r
+            ctx.addPortletListener(this, new DemoPortletListener());\r
+        } else {\r
+            getMainWindow().showNotification("Not inited via Portal!",\r
+                    Notification.TYPE_ERROR_MESSAGE);\r
+        }\r
+\r
+    }\r
+\r
+    private class DemoPortletListener implements PortletListener {\r
+\r
+        public void handleActionRequest(ActionRequest request,\r
+                ActionResponse response) {\r
+\r
+            main.addComponent(new Label("Action received"));\r
+\r
+        }\r
+\r
+        public void handleRenderRequest(RenderRequest request,\r
+                RenderResponse response) {\r
+            // Portlet up-and-running, enable stuff\r
+            portletEdit.setEnabled(true);\r
+            portletMax.setEnabled(true);\r
+\r
+            // Editable if we're in editmode\r
+            tf.setEnabled((request.getPortletMode() == PortletMode.EDIT));\r
+\r
+            // Show notification about current mode and state\r
+            getMainWindow().showNotification(\r
+                    "Portlet status",\r
+                    "Mode: " + request.getPortletMode() + " State: "\r
+                            + request.getWindowState(),\r
+                    Notification.TYPE_WARNING_MESSAGE);\r
+\r
+            // Display current user info\r
+            Map uinfo = (Map) request.getAttribute(PortletRequest.USER_INFO);\r
+            if (uinfo != null) {\r
+                String s = "";\r
+                for (Iterator it = uinfo.keySet().iterator(); it.hasNext();) {\r
+                    Object key = it.next();\r
+                    Object val = uinfo.get(key);\r
+                    s += key + ": " + val + "\n";\r
+                }\r
+                if (request.isUserInRole("administrator")) {\r
+                    s += "(administrator)";\r
+                }\r
+                userInfo.setValue(s);\r
+            } else {\r
+                userInfo.setValue("-");\r
+            }\r
+\r
+            // Create Edit/Done link (actionUrl)\r
+            PortletURL url = response.createActionURL();\r
+            try {\r
+                url\r
+                        .setPortletMode((request.getPortletMode() == PortletMode.VIEW ? PortletMode.EDIT\r
+                                : PortletMode.VIEW));\r
+                portletEdit.setResource(new ExternalResource(url.toString()));\r
+                portletEdit\r
+                        .setCaption((request.getPortletMode() == PortletMode.VIEW ? "Edit"\r
+                                : "Done"));\r
+            } catch (Exception e) {\r
+                portletEdit.setEnabled(false);\r
+            }\r
+            // Create Maximize/Normal link (actionUrl)\r
+            url = response.createActionURL();\r
+            try {\r
+                url\r
+                        .setWindowState((request.getWindowState() == WindowState.NORMAL ? WindowState.MAXIMIZED\r
+                                : WindowState.NORMAL));\r
+                portletMax.setResource(new ExternalResource(url.toString()));\r
+                portletMax\r
+                        .setCaption((request.getWindowState() == WindowState.NORMAL ? "Maximize"\r
+                                : "Back to normal"));\r
+            } catch (Exception e) {\r
+                portletMax.setEnabled(false);\r
+            }\r
+\r
+            if (someAction == null) {\r
+                url = response.createActionURL();\r
+                try {\r
+                    someAction = new Link("An action", new ExternalResource(url\r
+                            .toString()));\r
+                    main.addComponent(someAction);\r
+                } catch (Exception e) {\r
+                    // Oops\r
+                    System.err.println("Could not create someAction: " + e);\r
+                }\r
+\r
+            }\r
+\r
+        }\r
+    }\r
+}\r
diff --git a/src/com/itmill/toolkit/demo/reservation/simple/AdminView.java b/src/com/itmill/toolkit/demo/reservation/simple/AdminView.java
new file mode 100644 (file)
index 0000000..ac9319c
--- /dev/null
@@ -0,0 +1,98 @@
+package com.itmill.toolkit.demo.reservation.simple;
+
+import com.itmill.toolkit.data.Item;
+import com.itmill.toolkit.data.Property.ValueChangeEvent;
+import com.itmill.toolkit.ui.Button;
+import com.itmill.toolkit.ui.ComboBox;
+import com.itmill.toolkit.ui.OrderedLayout;
+import com.itmill.toolkit.ui.TextField;
+import com.itmill.toolkit.ui.AbstractSelect.NewItemHandler;
+import com.itmill.toolkit.ui.Button.ClickEvent;
+import com.itmill.toolkit.ui.Button.ClickListener;
+
+public class AdminView extends OrderedLayout {
+
+    private ComboBox resources = new ComboBox(
+            "Select for editing or type new resource");
+    private SimpleReserver application;
+    private OrderedLayout form = new OrderedLayout();
+    private Button save = new Button("Save resource");
+
+    private TextField name = new TextField("Name:");
+    private TextField desc = new TextField("Description:");
+    protected Item editedItem;
+
+    AdminView(SimpleReserver app) {
+        setWidth("250px");
+
+        application = app;
+
+        resources.setImmediate(true);
+        resources.setFilteringMode(ComboBox.FILTERINGMODE_CONTAINS);
+        refreshList();
+        resources.setItemCaptionMode(ComboBox.ITEM_CAPTION_MODE_PROPERTY);
+        resources.setItemCaptionPropertyId(SampleDB.Resource.PROPERTY_ID_NAME);
+        resources.setNewItemsAllowed(true);
+        resources.setNewItemHandler(new NewItemHandler() {
+            public void addNewItem(String newItemCaption) {
+                name.setValue(newItemCaption);
+                desc.setValue("");
+                form.setVisible(true);
+            }
+        });
+
+        resources.addListener(new ComboBox.ValueChangeListener() {
+            public void valueChange(ValueChangeEvent event) {
+                if (resources.getValue() != null) {
+                    editedItem = resources.getItem(resources.getValue());
+
+                    name
+                            .setPropertyDataSource(editedItem
+                                    .getItemProperty(SampleDB.Resource.PROPERTY_ID_NAME));
+                    desc
+                            .setPropertyDataSource(editedItem
+                                    .getItemProperty(SampleDB.Resource.PROPERTY_ID_DESCRIPTION));
+
+                    form.setVisible(true);
+
+                } else {
+                    form.setVisible(false);
+                    editedItem = null;
+                }
+
+            }
+        });
+        addComponent(resources);
+
+        form.setVisible(false);
+        addComponent(form);
+        form.addComponent(name);
+        form.addComponent(desc);
+        name.setWidth("100%");
+        desc.setWidth("100%");
+        form.addComponent(save);
+        save.addListener(new ClickListener() {
+            public void buttonClick(ClickEvent event) {
+                if (editedItem == null) {
+                    // save
+                    int addResource = application.getDb().addResource(
+                            name.getValue().toString(),
+                            desc.getValue().toString());
+                } else {
+                    // update
+                    application.getDb().updateResource(editedItem,
+                            name.getValue().toString(),
+                            desc.getValue().toString());
+                }
+                resources.setValue(null);
+                refreshList();
+            }
+        });
+
+    }
+
+    private void refreshList() {
+        resources
+                .setContainerDataSource(application.getDb().getResources(null));
+    }
+}
diff --git a/src/com/itmill/toolkit/demo/reservation/simple/SampleDB.java b/src/com/itmill/toolkit/demo/reservation/simple/SampleDB.java
new file mode 100644 (file)
index 0000000..86428db
--- /dev/null
@@ -0,0 +1,501 @@
+/* 
+@ITMillApache2LicenseForJavaFiles@
+ */
+
+package com.itmill.toolkit.demo.reservation.simple;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.Calendar;
+import java.util.Collection;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.List;
+
+import com.itmill.toolkit.data.Container;
+import com.itmill.toolkit.data.Item;
+import com.itmill.toolkit.data.util.QueryContainer;
+import com.itmill.toolkit.demo.reservation.ResourceNotAvailableException;
+
+/**
+ * Simplified version of Reservr's SampleDB
+ * 
+ * If you are going to use this application in production, make sure to modify
+ * this to save data into real DB instead of in memory HSQLDB.
+ */
+public class SampleDB {
+
+    public class Resource {
+        public static final String TABLE = "RESOURCE";
+        public static final String PROPERTY_ID_ID = TABLE + "_ID";
+        public static final String PROPERTY_ID_STYLENAME = TABLE + "_STYLENAME";
+        public static final String PROPERTY_ID_NAME = TABLE + "_NAME";
+        public static final String PROPERTY_ID_DESCRIPTION = TABLE
+                + "_DESCRIPTION";
+        public static final String PROPERTY_ID_LOCATIONX = TABLE
+                + "_LOCATION_X";
+        public static final String PROPERTY_ID_LOCATIONY = TABLE
+                + "_LOCATION_Y";
+        public static final String PROPERTY_ID_CATEGORY = TABLE + "_CATEGORY";
+        public static final String PROPERTY_ID_DELETED = TABLE + "_DELETED";
+    }
+
+    public class Reservation {
+        public static final String TABLE = "RESERVATION";
+        public static final String PROPERTY_ID_ID = TABLE + "_ID";
+        public static final String PROPERTY_ID_DESCRIPTION = TABLE
+                + "_DESCRIPTION";
+        public static final String PROPERTY_ID_RESOURCE_ID = TABLE
+                + "_RESOURCE_ID";
+        public static final String PROPERTY_ID_RESERVED_BY = TABLE
+                + "_RESERVED_BY_USER";
+        public static final String PROPERTY_ID_RESERVED_FROM = TABLE
+                + "_RESERVED_FROM";
+        public static final String PROPERTY_ID_RESERVED_TO = TABLE
+                + "_RESERVED_TO";
+    }
+
+    // TODO -> param
+    private static final String DB_URL = "jdbc:hsqldb:file:reservation.db";
+
+    private static final String CREATE_TABLE_RESOURCE = "CREATE TABLE "
+            + Resource.TABLE + " (" + " " + Resource.PROPERTY_ID_ID
+            + " INTEGER IDENTITY" + ", " + Resource.PROPERTY_ID_STYLENAME
+            + " VARCHAR(20) NOT NULL" + ", " + Resource.PROPERTY_ID_NAME
+            + " VARCHAR(30) NOT NULL" + ", " + Resource.PROPERTY_ID_DESCRIPTION
+            + " VARCHAR(100)" + ", " + Resource.PROPERTY_ID_LOCATIONX
+            + " DOUBLE" + ", " + Resource.PROPERTY_ID_LOCATIONY + " DOUBLE"
+            + ", " + Resource.PROPERTY_ID_CATEGORY + " VARCHAR(30)" + ", "
+            + Resource.PROPERTY_ID_DELETED + " BOOLEAN DEFAULT false NOT NULL"
+            + ", UNIQUE(" + Resource.PROPERTY_ID_NAME + "))";
+    private static final String CREATE_TABLE_RESERVATION = "CREATE TABLE "
+            + Reservation.TABLE + " (" + " " + Reservation.PROPERTY_ID_ID
+            + " INTEGER IDENTITY" + ", " + Reservation.PROPERTY_ID_RESOURCE_ID
+            + " INTEGER" + ", " + Reservation.PROPERTY_ID_RESERVED_FROM
+            + " TIMESTAMP NOT NULL" + ", "
+            + Reservation.PROPERTY_ID_RESERVED_TO + " TIMESTAMP NOT NULL"
+            + ", " + Reservation.PROPERTY_ID_DESCRIPTION + " VARCHAR(100)"
+            + ", " + Reservation.PROPERTY_ID_RESERVED_BY + " VARCHAR(100)"
+            + ", FOREIGN KEY (" + Reservation.PROPERTY_ID_RESOURCE_ID
+            + ") REFERENCES " + Resource.TABLE + "(" + Resource.PROPERTY_ID_ID
+            + "))";
+
+    private static Connection connection = null;
+
+    /**
+     * Create database.
+     */
+    public SampleDB() {
+        // connect to SQL database
+        connect();
+
+    }
+
+    private synchronized void dropTables() {
+        try {
+            update("DROP TABLE " + Reservation.TABLE);
+        } catch (final SQLException IGNORED) {
+            // IGNORED, assuming it was not there
+        }
+        try {
+            update("DROP TABLE " + Resource.TABLE);
+        } catch (final SQLException IGNORED) {
+            // IGNORED, assuming it was not there
+        }
+    }
+
+    /**
+     * Connect to SQL database. In this sample we use HSQLDB and an toolkit
+     * named database in implicitly created into system memory.
+     * 
+     */
+    private synchronized void connect() {
+        if (connection == null) {
+            try {
+                Class.forName("org.hsqldb.jdbcDriver").newInstance();
+                connection = DriverManager.getConnection(DB_URL);
+            } catch (final Exception e) {
+                throw new RuntimeException(e);
+            }
+
+            dropTables();
+            // initialize SQL database
+            createTables();
+
+            // test by executing sample JDBC query
+            testDatabase();
+
+            generateResources();
+            generateReservations();
+
+        }
+    }
+
+    /**
+     * use for SQL commands CREATE, DROP, INSERT and UPDATE
+     * 
+     * @param expression
+     * @throws SQLException
+     */
+    private synchronized void update(String expression) throws SQLException {
+        Statement st = null;
+        st = connection.createStatement();
+        final int i = st.executeUpdate(expression);
+        if (i == -1) {
+            System.out.println("SampleDatabase error : " + expression);
+        }
+        st.close();
+    }
+
+    /**
+     * Create test table and few rows. Issue note: using capitalized column
+     * names as HSQLDB returns column names in capitalized form with this demo.
+     * 
+     */
+    private synchronized void createTables() {
+        try {
+            String stmt = null;
+            stmt = CREATE_TABLE_RESOURCE;
+            update(stmt);
+        } catch (final SQLException e) {
+            if (e.toString().indexOf("Table already exists") == -1) {
+                throw new RuntimeException(e);
+            }
+        }
+        try {
+            String stmt = null;
+            stmt = CREATE_TABLE_RESERVATION;
+            update(stmt);
+        } catch (final SQLException e) {
+            if (e.toString().indexOf("Table already exists") == -1) {
+                throw new RuntimeException(e);
+            }
+        }
+    }
+
+    /**
+     * Test database connection with simple SELECT command.
+     * 
+     */
+    private synchronized String testDatabase() {
+        String result = null;
+        try {
+            final Statement stmt = connection.createStatement(
+                    ResultSet.TYPE_SCROLL_INSENSITIVE,
+                    ResultSet.CONCUR_UPDATABLE);
+            final ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM "
+                    + Resource.TABLE);
+            rs.next();
+            result = "rowcount for table test is " + rs.getObject(1).toString();
+            stmt.close();
+        } catch (final SQLException e) {
+            throw new RuntimeException(e);
+        }
+        return result;
+    }
+
+    public Connection getConnection() {
+        return connection;
+    }
+
+    public Container getCategories() {
+        // TODO where deleted=?
+        final String q = "SELECT DISTINCT(" + Resource.PROPERTY_ID_CATEGORY
+                + ") FROM " + Resource.TABLE + " ORDER BY "
+                + Resource.PROPERTY_ID_CATEGORY;
+        try {
+            return new QueryContainer(q, connection,
+                    ResultSet.TYPE_SCROLL_INSENSITIVE,
+                    ResultSet.CONCUR_READ_ONLY);
+        } catch (final SQLException e) {
+            throw new RuntimeException(e);
+        }
+
+    }
+
+    public Container getResources(String category) {
+        // TODO where deleted=?
+        String q = "SELECT * FROM " + Resource.TABLE;
+        if (category != null) {
+            q += " WHERE " + Resource.PROPERTY_ID_CATEGORY + "='" + category
+                    + "'"; // FIXME ->
+            // PreparedStatement!
+        }
+
+        try {
+            return new QueryContainer(q, connection,
+                    ResultSet.TYPE_SCROLL_INSENSITIVE,
+                    ResultSet.CONCUR_READ_ONLY);
+        } catch (final SQLException e) {
+            throw new RuntimeException(e);
+        }
+
+    }
+
+    public Container getReservations(List resources) {
+        // TODO where reserved_by=?
+        // TODO where from=?
+        // TODO where to=?
+        // TODO where deleted=?
+        String q = "SELECT * FROM " + Reservation.TABLE + "," + Resource.TABLE;
+        q += " WHERE " + Reservation.PROPERTY_ID_RESOURCE_ID + "="
+                + Resource.PROPERTY_ID_ID;
+        if (resources != null && resources.size() > 0) {
+            final StringBuffer s = new StringBuffer();
+            for (final Iterator it = resources.iterator(); it.hasNext();) {
+                if (s.length() > 0) {
+                    s.append(",");
+                }
+                s.append(((Item) it.next())
+                        .getItemProperty(Resource.PROPERTY_ID_ID));
+            }
+            q += " HAVING " + Reservation.PROPERTY_ID_RESOURCE_ID + " IN (" + s
+                    + ")";
+        }
+        q += " ORDER BY " + Reservation.PROPERTY_ID_RESERVED_FROM;
+        try {
+            final QueryContainer qc = new QueryContainer(q, connection,
+                    ResultSet.TYPE_SCROLL_INSENSITIVE,
+                    ResultSet.CONCUR_READ_ONLY);
+            if (qc.size() < 1) {
+                return null;
+            } else {
+                return qc;
+            }
+        } catch (final SQLException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    public synchronized void addReservation(Item resource, String reservedBy,
+            Date reservedFrom, Date reservedTo, String description)
+            throws ResourceNotAvailableException {
+        if (reservedFrom.after(reservedTo)) {
+            final Date tmp = reservedTo;
+            reservedTo = reservedFrom;
+            reservedFrom = tmp;
+        }
+        final int resourceId = ((Integer) resource.getItemProperty(
+                Resource.PROPERTY_ID_ID).getValue()).intValue();
+        final String q = "INSERT INTO " + Reservation.TABLE + " ("
+                + Reservation.PROPERTY_ID_RESOURCE_ID + ","
+                + Reservation.PROPERTY_ID_RESERVED_BY + ","
+                + Reservation.PROPERTY_ID_RESERVED_FROM + ","
+                + Reservation.PROPERTY_ID_RESERVED_TO + ","
+                + Reservation.PROPERTY_ID_DESCRIPTION + ")"
+                + "VALUES (?,?,?,?,?)";
+        synchronized (DB_URL) {
+            if (!isAvailableResource(resourceId, reservedFrom, reservedTo)) {
+                throw new ResourceNotAvailableException(
+                        "The resource is not available at that time.");
+            }
+            try {
+                PreparedStatement p;
+                p = connection.prepareStatement(q);
+                p.setInt(1, resourceId);
+                p.setString(2, reservedBy);
+                p.setTimestamp(3,
+                        new java.sql.Timestamp(reservedFrom.getTime()));
+                p.setTimestamp(4, new java.sql.Timestamp(reservedTo.getTime()));
+                p.setString(5, description);
+                p.execute();
+            } catch (SQLException e) {
+                // TODO Auto-generated catch block
+                e.printStackTrace();
+            }
+        }
+    }
+
+    public boolean isAvailableResource(int resourceId, Date reservedFrom,
+            Date reservedTo) {
+        // TODO where deleted=?
+        if (reservedFrom.after(reservedTo)) {
+            final Date tmp = reservedTo;
+            reservedTo = reservedFrom;
+            reservedFrom = tmp;
+        }
+        final String checkQ = "SELECT count(*) FROM " + Reservation.TABLE
+                + " WHERE " + Reservation.PROPERTY_ID_RESOURCE_ID + "=? AND (("
+                + Reservation.PROPERTY_ID_RESERVED_FROM + ">=? AND "
+                + Reservation.PROPERTY_ID_RESERVED_FROM + "<?) OR ("
+                + Reservation.PROPERTY_ID_RESERVED_TO + ">? AND "
+                + Reservation.PROPERTY_ID_RESERVED_TO + "<=?) OR ("
+                + Reservation.PROPERTY_ID_RESERVED_FROM + "<=? AND "
+                + Reservation.PROPERTY_ID_RESERVED_TO + ">=?)" + ")";
+        try {
+            final PreparedStatement p = connection.prepareStatement(checkQ);
+            p.setInt(1, resourceId);
+            p.setTimestamp(2, new java.sql.Timestamp(reservedFrom.getTime()));
+            p.setTimestamp(3, new java.sql.Timestamp(reservedTo.getTime()));
+            p.setTimestamp(4, new java.sql.Timestamp(reservedFrom.getTime()));
+            p.setTimestamp(5, new java.sql.Timestamp(reservedTo.getTime()));
+            p.setTimestamp(6, new java.sql.Timestamp(reservedFrom.getTime()));
+            p.setTimestamp(7, new java.sql.Timestamp(reservedTo.getTime()));
+            p.execute();
+            final ResultSet rs = p.getResultSet();
+            if (rs.next() && rs.getInt(1) > 0) {
+                return false;
+            }
+        } catch (final Exception e) {
+            throw new RuntimeException(e);
+        }
+        return true;
+    }
+
+    public synchronized void generateReservations() {
+        final int days = 30;
+        final String descriptions[] = { "Picking up guests from airport",
+                "Sightseeing with the guests",
+                "Moving new servers from A to B", "Shopping",
+                "Customer meeting", "Guests arriving at harbour",
+                "Moving furniture", "Taking guests to see town" };
+        final Container cat = getCategories();
+        final Collection cIds = cat.getItemIds();
+        for (final Iterator it = cIds.iterator(); it.hasNext();) {
+            final Object id = it.next();
+            final Item ci = cat.getItem(id);
+            final String c = (String) ci.getItemProperty(
+                    Resource.PROPERTY_ID_CATEGORY).getValue();
+            final Container resources = getResources(c);
+            final Collection rIds = resources.getItemIds();
+            final Calendar cal = Calendar.getInstance();
+            cal.set(Calendar.MINUTE, 0);
+            cal.set(Calendar.SECOND, 0);
+            cal.set(Calendar.MILLISECOND, 0);
+            final int hourNow = new Date().getHours();
+            // cal.add(Calendar.DAY_OF_MONTH, -days);
+            for (int i = 0; i < days; i++) {
+                int r = 3;
+                for (final Iterator rit = rIds.iterator(); rit.hasNext()
+                        && r > 0; r--) {
+                    final Object rid = rit.next();
+                    final Item resource = resources.getItem(rid);
+                    final int s = hourNow - 6
+                            + (int) Math.round(Math.random() * 6.0);
+                    final int e = s + 1 + (int) Math.round(Math.random() * 4.0);
+                    final Date start = new Date(cal.getTimeInMillis());
+                    start.setHours(s);
+                    final Date end = new Date(cal.getTimeInMillis());
+                    end.setHours(e);
+                    try {
+                        addReservation(resource, "Demo User", start, end,
+                                descriptions[(int) Math.floor(Math.random()
+                                        * descriptions.length)]);
+                    } catch (ResourceNotAvailableException e1) {
+                        // TODO Auto-generated catch block
+                        e1.printStackTrace();
+                    }
+                }
+                cal.add(Calendar.DATE, 1);
+            }
+        }
+
+    }
+
+    public synchronized void generateResources() {
+
+        final Object[][] resources = {
+
+                { "01", "Portable Video projector 1", "Small,XGA resolution",
+                        "Turku", new Double(60.510857), new Double(22.275424) },
+                { "02", "Auditorio", "", "Turku", new Double(60.452171),
+                        new Double(22.2995) },
+                { "03", "Meeting room 1", "Projector, WiFi", "Turku",
+                        new Double(60.4507), new Double(22.295551) },
+                { "04", "Meeting room 2", "WiFi, Blackboard", "Turku",
+                        new Double(60.434722), new Double(22.224398) },
+                { "05", "AV Room", "Cabrio. Keys from infodesk.", "Turku",
+                        new Double(60.508970), new Double(22.264790) },
+                { "06", "Video projector",
+                        "Rather heavy, good luminance, WXGA", "Turku",
+                        new Double(60.434722), new Double(22.224398) },
+
+        };
+
+        final String q = "INSERT INTO " + Resource.TABLE + "("
+                + Resource.PROPERTY_ID_STYLENAME + ","
+                + Resource.PROPERTY_ID_NAME + ","
+                + Resource.PROPERTY_ID_DESCRIPTION + ","
+                + Resource.PROPERTY_ID_CATEGORY + ","
+                + Resource.PROPERTY_ID_LOCATIONX + ","
+                + Resource.PROPERTY_ID_LOCATIONY + ")"
+                + " VALUES (?,?,?,?,?,?)";
+        try {
+            final PreparedStatement stmt = connection.prepareStatement(q);
+            for (int i = 0; i < resources.length; i++) {
+                int j = 0;
+                stmt.setString(j + 1, (String) resources[i][j++]);
+                stmt.setString(j + 1, (String) resources[i][j++]);
+                stmt.setString(j + 1, (String) resources[i][j++]);
+                stmt.setString(j + 1, (String) resources[i][j++]);
+                stmt.setDouble(j + 1, ((Double) resources[i][j++])
+                        .doubleValue());
+                stmt.setDouble(j + 1, ((Double) resources[i][j++])
+                        .doubleValue());
+                stmt.execute();
+            }
+        } catch (final SQLException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    public int addResource(String name, String desc) {
+        final String q = "INSERT INTO " + Resource.TABLE + " ("
+                + Resource.PROPERTY_ID_STYLENAME + ","
+                + Resource.PROPERTY_ID_NAME + ","
+                + Resource.PROPERTY_ID_DESCRIPTION + ","
+                + Resource.PROPERTY_ID_CATEGORY + ","
+                + Resource.PROPERTY_ID_LOCATIONX + ","
+                + Resource.PROPERTY_ID_LOCATIONY + ")"
+                + " VALUES (?,?,?,?,?,?)";
+        synchronized (DB_URL) {
+            try {
+                PreparedStatement p = connection.prepareStatement(q);
+                p.setString(1, "");
+                p.setString(2, name);
+                p.setString(3, desc);
+                p.setString(4, "default");
+                p.setDouble(5, 0);
+                p.setDouble(6, 0);
+                p.execute();
+
+                Statement createStatement = connection.createStatement();
+                ResultSet executeQuery = createStatement
+                        .executeQuery("CALL IDENTITY()");
+                executeQuery.next();
+                return executeQuery.getInt(1);
+
+            } catch (SQLException e) {
+                // TODO Auto-generated catch block
+                e.printStackTrace();
+            }
+        }
+        return -1;
+    }
+
+    public void updateResource(Item editedItem, String name, String desc) {
+        final String q = "UPDATE " + Resource.TABLE + " SET "
+                + Resource.PROPERTY_ID_NAME + " = ? ,"
+                + Resource.PROPERTY_ID_DESCRIPTION + " = ? " + "WHERE "
+                + Resource.PROPERTY_ID_ID + " = ?";
+        synchronized (DB_URL) {
+            try {
+                PreparedStatement p = connection.prepareStatement(q);
+                p.setString(1, name);
+                p.setString(2, desc);
+                p.setInt(3, ((Integer) editedItem.getItemProperty(
+                        Resource.PROPERTY_ID_ID).getValue()).intValue());
+                p.execute();
+
+            } catch (SQLException e) {
+                // TODO Auto-generated catch block
+                e.printStackTrace();
+            }
+        }
+
+    }
+}
diff --git a/src/com/itmill/toolkit/demo/reservation/simple/SimpleReserver.java b/src/com/itmill/toolkit/demo/reservation/simple/SimpleReserver.java
new file mode 100644 (file)
index 0000000..c5e9f28
--- /dev/null
@@ -0,0 +1,132 @@
+package com.itmill.toolkit.demo.reservation.simple;
+
+import java.security.Principal;
+
+import javax.portlet.ActionRequest;
+import javax.portlet.ActionResponse;
+import javax.portlet.PortletMode;
+import javax.portlet.RenderRequest;
+import javax.portlet.RenderResponse;
+
+import com.itmill.toolkit.Application;
+import com.itmill.toolkit.terminal.gwt.server.PortletApplicationContext;
+import com.itmill.toolkit.terminal.gwt.server.PortletApplicationContext.PortletListener;
+import com.itmill.toolkit.ui.Button;
+import com.itmill.toolkit.ui.OrderedLayout;
+import com.itmill.toolkit.ui.Window;
+import com.itmill.toolkit.ui.Button.ClickEvent;
+import com.itmill.toolkit.ui.Button.ClickListener;
+import com.liferay.portal.model.User;
+import com.liferay.portal.service.UserServiceUtil;
+
+/**
+ * This is a stripped down version of Reservr example. Idea is to create simple,
+ * but actually usable portal gadget. Example is Liferay spesific (in user
+ * handling), so you need to add portal-kernel.jar and portal-service.jar files
+ * to your classpath.
+ * 
+ */
+public class SimpleReserver extends Application {
+
+    private SampleDB db = new SampleDB();
+
+    private StdView stdView = new StdView(this);
+
+    private AdminView adminView = new AdminView(this);
+
+    private Button toggleMode = new Button("Switch mode");
+
+    private boolean isAdminView = false;
+
+    private boolean isPortlet;
+
+    protected User user;
+
+    public void init() {
+        final Window w = new Window("Simple Reserver");
+        w.addStyleName("simplereserver");
+
+        if (getContext() instanceof PortletApplicationContext) {
+            isPortlet = true;
+            PortletApplicationContext context = (PortletApplicationContext) getContext();
+            context.addPortletListener(this, new PortletListener() {
+
+                public void handleActionRequest(ActionRequest request,
+                        ActionResponse response) {
+
+                }
+
+                public void handleRenderRequest(RenderRequest request,
+                        RenderResponse response) {
+                    // react on mode changes
+                    if ((request.getPortletMode() == PortletMode.EDIT && !isAdminView)
+                            || (request.getPortletMode() == PortletMode.VIEW && isAdminView)) {
+                        toggleMode();
+                    }
+
+                    // save user object to application for later use
+                    Principal userPrincipal = request.getUserPrincipal();
+                    try {
+                        user = UserServiceUtil.getUserById(Long
+                                .parseLong(userPrincipal.toString()));
+                    } catch (Exception e) {
+                        e.printStackTrace();
+                    }
+
+                }
+            });
+            w.setTheme("liferay");
+            // portal will deal outer margins
+            w.getLayout().setMargin(false);
+        } else {
+            w.setTheme("reservr");
+        }
+
+        setMainWindow(w);
+        if (!isPortlet) {
+            // only use toggle mode button when not in portal
+            w.addComponent(toggleMode);
+            toggleMode.addListener(new ClickListener() {
+                public void buttonClick(ClickEvent event) {
+                    toggleMode();
+                }
+            });
+        }
+        w.addComponent(stdView);
+    }
+
+    protected void toggleMode() {
+        OrderedLayout main = (OrderedLayout) getMainWindow().getLayout();
+        isAdminView = !isAdminView;
+        if (isAdminView) {
+            main.replaceComponent(stdView, adminView);
+        } else {
+            main.replaceComponent(adminView, stdView);
+            stdView.refreshData();
+        }
+    }
+
+    public SampleDB getDb() {
+        return db;
+    }
+
+    public Object getUser() {
+        if (getContext() instanceof PortletApplicationContext) {
+            try {
+                return user.getFirstName() + " " + user.getLastName();
+            } catch (Exception e) {
+                // TODO: handle exception
+                e.printStackTrace();
+                return "Portlet Demouser";
+            }
+        } else {
+            Object user = super.getUser();
+            if (user == null) {
+                return "Demo User";
+            } else {
+                return user;
+            }
+        }
+
+    }
+}
diff --git a/src/com/itmill/toolkit/demo/reservation/simple/StdView.java b/src/com/itmill/toolkit/demo/reservation/simple/StdView.java
new file mode 100644 (file)
index 0000000..bbb07aa
--- /dev/null
@@ -0,0 +1,194 @@
+package com.itmill.toolkit.demo.reservation.simple;
+
+import java.util.Calendar;
+import java.util.Date;
+import java.util.LinkedList;
+import java.util.List;
+
+import com.itmill.toolkit.data.Container;
+import com.itmill.toolkit.data.Item;
+import com.itmill.toolkit.data.Property.ValueChangeEvent;
+import com.itmill.toolkit.data.Property.ValueChangeListener;
+import com.itmill.toolkit.demo.reservation.CalendarField;
+import com.itmill.toolkit.demo.reservation.ResourceNotAvailableException;
+import com.itmill.toolkit.ui.Button;
+import com.itmill.toolkit.ui.ComboBox;
+import com.itmill.toolkit.ui.DateField;
+import com.itmill.toolkit.ui.Label;
+import com.itmill.toolkit.ui.OrderedLayout;
+import com.itmill.toolkit.ui.TextField;
+import com.itmill.toolkit.ui.Window;
+import com.itmill.toolkit.ui.Button.ClickEvent;
+import com.itmill.toolkit.ui.Button.ClickListener;
+
+public class StdView extends OrderedLayout {
+
+    private ComboBox resources = new ComboBox("Select resource");
+    private CalendarField reservations = new CalendarField();
+    private Button add = new Button("Add reservation");
+    private SimpleReserver application;
+
+    private EditorWindow editor = new EditorWindow();
+
+    StdView(SimpleReserver app) {
+        setWidth("250px");
+        application = app;
+
+        resources.setImmediate(true);
+        resources.setFilteringMode(ComboBox.FILTERINGMODE_CONTAINS);
+        resources
+                .setContainerDataSource(application.getDb().getResources(null));
+        resources.setItemCaptionMode(ComboBox.ITEM_CAPTION_MODE_PROPERTY);
+        resources.setItemCaptionPropertyId(SampleDB.Resource.PROPERTY_ID_NAME);
+        resources.addListener(new ComboBox.ValueChangeListener() {
+            public void valueChange(ValueChangeEvent event) {
+                refreshReservations();
+            }
+        });
+        addComponent(resources);
+
+        initCalendarFieldPropertyIds(reservations);
+        Calendar c = Calendar.getInstance();
+        reservations.setValue(c.getTime());
+        reservations.setEnabled(false);
+        addComponent(reservations);
+        reservations.setImmediate(true);
+
+        add.setEnabled(false);
+        addComponent(add);
+
+        add.addListener(new Button.ClickListener() {
+            public void buttonClick(ClickEvent event) {
+                if (resources.getValue() != null) {
+                    Item i = resources.getItem(resources.getValue());
+                    editor.newReservationFor(i);
+                }
+            }
+        });
+
+        add.setDescription("Add new reservation for selected resource");
+
+    }
+
+    private static void initCalendarFieldPropertyIds(CalendarField cal) {
+        cal.setItemStyleNamePropertyId(SampleDB.Resource.PROPERTY_ID_STYLENAME);
+        cal
+                .setItemStartPropertyId(SampleDB.Reservation.PROPERTY_ID_RESERVED_FROM);
+        cal.setItemEndPropertyId(SampleDB.Reservation.PROPERTY_ID_RESERVED_TO);
+        cal
+                .setItemTitlePropertyId(SampleDB.Reservation.PROPERTY_ID_RESERVED_BY);
+        cal
+                .setItemDescriptionPropertyId(SampleDB.Reservation.PROPERTY_ID_DESCRIPTION);
+    }
+
+    private void refreshReservations() {
+        if (resources.getValue() == null) {
+            reservations.setContainerDataSource(null);
+            add.setEnabled(false);
+            reservations.setEnabled(false);
+        } else {
+            List resource = new LinkedList();
+            resource.add(resources.getItem(resources.getValue()));
+            final Container res = application.getDb().getReservations(resource);
+            reservations.setContainerDataSource(res);
+            add.setEnabled(true);
+            reservations.setEnabled(true);
+        }
+    }
+
+    public class EditorWindow extends Window {
+
+        Label resourceName = new Label();
+
+        DateField start = new DateField("From:");
+        DateField end = new DateField("To:");
+        TextField desc = new TextField("Description:");
+        Button save = new Button("Save");
+
+        private Item res;
+
+        private Calendar cal;
+
+        EditorWindow() {
+            super("Add reservation");
+
+            cal = Calendar.getInstance();
+
+            addComponent(resourceName);
+
+            start.setResolution(DateField.RESOLUTION_MIN);
+            start.setImmediate(true);
+            start.setValue(new Date());
+            start.addListener(new ValueChangeListener() {
+                public void valueChange(ValueChangeEvent event) {
+                    Date startTime = (Date) start.getValue();
+                    Date endTime = (Date) end.getValue();
+                    if (endTime.before(startTime)) {
+                        cal.setTime(startTime);
+                        cal.add(Calendar.HOUR_OF_DAY, 1);
+                        end.setValue(cal.getTime());
+                    }
+                }
+            });
+            addComponent(start);
+
+            end.setResolution(DateField.RESOLUTION_MIN);
+            end.setImmediate(true);
+            end.setValue(new Date());
+            end.addListener(new ValueChangeListener() {
+                public void valueChange(ValueChangeEvent event) {
+                    Date startTime = (Date) start.getValue();
+                    Date endTime = (Date) end.getValue();
+                    if (endTime.before(startTime)) {
+                        cal.setTime(endTime);
+                        cal.add(Calendar.HOUR, -1);
+                        start.setValue(cal.getTime());
+                    }
+                }
+            });
+            addComponent(end);
+            addComponent(desc);
+            addComponent(save);
+            save.addListener(new ClickListener() {
+                public void buttonClick(ClickEvent event) {
+                    try {
+                        application.getDb().addReservation(res,
+                                application.getUser().toString(),
+                                (Date) start.getValue(), (Date) end.getValue(),
+                                (String) desc.getValue());
+                        EditorWindow.this.close();
+                        refreshReservations();
+                    } catch (ResourceNotAvailableException e) {
+                        getWindow()
+                                .showNotification(
+                                        "Resource is not available at that time "
+                                                + "or is too close to another reservation.");
+                    }
+                }
+            });
+        }
+
+        public void newReservationFor(Item resource) {
+            res = resource;
+            resourceName.setValue("Resourse: "
+                    + res.getItemProperty(SampleDB.Resource.PROPERTY_ID_NAME)
+                            .getValue());
+
+            cal.setTime((Date) reservations.getValue());
+            cal.set(Calendar.MINUTE, 0);
+            cal.set(Calendar.MILLISECOND, 0);
+            cal.set(Calendar.SECOND, 0);
+            start.setValue(cal.getTime());
+            cal.add(Calendar.HOUR_OF_DAY, 1);
+            end.setValue(cal.getTime());
+            StdView.this.getWindow().addWindow(this);
+        }
+    }
+
+    public void refreshData() {
+        resources
+                .setContainerDataSource(application.getDb().getResources(null));
+        refreshReservations();
+
+    }
+}
diff --git a/src/com/itmill/toolkit/terminal/gwt/server/ApplicationPortlet.java b/src/com/itmill/toolkit/terminal/gwt/server/ApplicationPortlet.java
new file mode 100644 (file)
index 0000000..77cca2a
--- /dev/null
@@ -0,0 +1,91 @@
+package com.itmill.toolkit.terminal.gwt.server;\r
+\r
+import java.io.IOException;\r
+import java.io.PrintWriter;\r
+\r
+import javax.portlet.ActionRequest;\r
+import javax.portlet.ActionResponse;\r
+import javax.portlet.Portlet;\r
+import javax.portlet.PortletConfig;\r
+import javax.portlet.PortletException;\r
+import javax.portlet.PortletRequestDispatcher;\r
+import javax.portlet.PortletSession;\r
+import javax.portlet.RenderRequest;\r
+import javax.portlet.RenderResponse;\r
+\r
+import com.itmill.toolkit.Application;\r
+\r
+public class ApplicationPortlet implements Portlet {\r
+    // The application to show\r
+    protected String app = null;\r
+    // some applications might require forced height (and, more seldom, width)\r
+    protected String style = null; // e.g "height:500px;"\r
+    protected String widgetset = null;\r
+\r
+    public void destroy() {\r
+\r
+    }\r
+\r
+    public void init(PortletConfig config) throws PortletException {\r
+        app = config.getInitParameter("application");\r
+        if (app == null) {\r
+            app = "PortletDemo";\r
+        }\r
+        style = config.getInitParameter("style");\r
+        widgetset = config.getInitParameter("widgetset");\r
+    }\r
+\r
+    public void processAction(ActionRequest request, ActionResponse response)\r
+            throws PortletException, IOException {\r
+        PortletApplicationContext.dispatchRequest(this, request, response);\r
+    }\r
+\r
+    public void render(RenderRequest request, RenderResponse response)\r
+            throws PortletException, IOException {\r
+\r
+        // display the IT Mill Toolkit application\r
+        writeAjaxWindow(request, response);\r
+    }\r
+\r
+    protected void writeAjaxWindow(RenderRequest request,\r
+            RenderResponse response) throws IOException {\r
+\r
+        if (app != null) {\r
+            PortletSession sess = request.getPortletSession();\r
+            PortletApplicationContext ctx = PortletApplicationContext\r
+                    .getApplicationContext(sess);\r
+\r
+            PortletRequestDispatcher dispatcher = sess.getPortletContext()\r
+                    .getRequestDispatcher("/" + app);\r
+\r
+            try {\r
+                request.setAttribute(ApplicationServlet.REQUEST_FRAGMENT,\r
+                        "true");\r
+                if (widgetset != null) {\r
+                    request.setAttribute(ApplicationServlet.REQUEST_WIDGETSET,\r
+                            widgetset);\r
+                }\r
+                if (style != null) {\r
+                    request.setAttribute(ApplicationServlet.REQUEST_APPSTYLE,\r
+                            style);\r
+                }\r
+                dispatcher.include(request, response);\r
+\r
+            } catch (PortletException e) {\r
+                response.setContentType("text/html");\r
+                PrintWriter out = response.getWriter();\r
+                out.print("<h1>Servlet include failed!</h1>");\r
+                out.print("<div>" + e + "</div>");\r
+                ctx.setPortletApplication(this, null);\r
+                return;\r
+            }\r
+\r
+            Application app = (Application) request\r
+                    .getAttribute(Application.class.getName());\r
+            ctx.setPortletApplication(this, app);\r
+            ctx.firePortletRenderRequest(this, request, response);\r
+\r
+        }\r
+    }\r
+\r
+}\r
diff --git a/src/com/itmill/toolkit/terminal/gwt/server/PortletApplicationContext.java b/src/com/itmill/toolkit/terminal/gwt/server/PortletApplicationContext.java
new file mode 100644 (file)
index 0000000..4ddbabd
--- /dev/null
@@ -0,0 +1,283 @@
+/**\r
+ * \r
+ */\r
+package com.itmill.toolkit.terminal.gwt.server;\r
+\r
+import java.io.IOException;\r
+import java.io.OutputStream;\r
+import java.io.PrintWriter;\r
+import java.util.HashMap;\r
+import java.util.Iterator;\r
+import java.util.LinkedHashSet;\r
+import java.util.Locale;\r
+import java.util.Map;\r
+import java.util.Set;\r
+\r
+import javax.portlet.ActionRequest;\r
+import javax.portlet.ActionResponse;\r
+import javax.portlet.Portlet;\r
+import javax.portlet.PortletSession;\r
+import javax.portlet.PortletURL;\r
+import javax.portlet.RenderRequest;\r
+import javax.portlet.RenderResponse;\r
+import javax.servlet.http.HttpSession;\r
+\r
+import com.itmill.toolkit.Application;\r
+\r
+/**\r
+ * @author marc\r
+ * \r
+ */\r
+public class PortletApplicationContext extends WebApplicationContext {\r
+\r
+    protected PortletSession portletSession;\r
+\r
+    protected Map portletListeners = new HashMap();\r
+\r
+    protected Map portletToApplication = new HashMap();\r
+\r
+    PortletApplicationContext() {\r
+\r
+    }\r
+\r
+    static public PortletApplicationContext getApplicationContext(\r
+            PortletSession session) {\r
+        WebApplicationContext cx = (WebApplicationContext) session\r
+                .getAttribute(WebApplicationContext.class.getName(),\r
+                        PortletSession.APPLICATION_SCOPE);\r
+        if (cx == null) {\r
+            cx = new PortletApplicationContext();\r
+        }\r
+        if (!(cx instanceof PortletApplicationContext)) {\r
+            // TODO Should we even try this? And should we leave original as-is?\r
+            PortletApplicationContext pcx = new PortletApplicationContext();\r
+            pcx.applications.addAll(cx.applications);\r
+            cx.applications.clear();\r
+            pcx.browser = cx.browser;\r
+            cx.browser = null;\r
+            pcx.listeners = cx.listeners;\r
+            cx.listeners = null;\r
+            pcx.session = cx.session;\r
+            cx = pcx;\r
+        }\r
+        if (((PortletApplicationContext) cx).portletSession == null) {\r
+            ((PortletApplicationContext) cx).portletSession = session;\r
+        }\r
+        session.setAttribute(WebApplicationContext.class.getName(), cx,\r
+                PortletSession.APPLICATION_SCOPE);\r
+        return (PortletApplicationContext) cx;\r
+    }\r
+\r
+    static public WebApplicationContext getApplicationContext(\r
+            HttpSession session) {\r
+        WebApplicationContext cx = (WebApplicationContext) session\r
+                .getAttribute(WebApplicationContext.class.getName());\r
+        if (cx == null) {\r
+            cx = new PortletApplicationContext();\r
+        }\r
+        if (cx.session == null) {\r
+            cx.session = session;\r
+        }\r
+        session.setAttribute(WebApplicationContext.class.getName(), cx);\r
+        return cx;\r
+    }\r
+\r
+    protected void removeApplication(Application application) {\r
+        portletListeners.remove(application);\r
+        for (Iterator it = portletToApplication.keySet().iterator(); it\r
+                .hasNext();) {\r
+            Object key = it.next();\r
+            if (key == application) {\r
+                portletToApplication.remove(key);\r
+            }\r
+        }\r
+        super.removeApplication(application);\r
+    }\r
+\r
+    public boolean equals(Object obj) {\r
+        if (portletSession == null) {\r
+            return super.equals(obj);\r
+        }\r
+        return portletSession.equals(obj);\r
+    }\r
+\r
+    public int hashCode() {\r
+        if (portletSession == null) {\r
+            return super.hashCode();\r
+        }\r
+        return portletSession.hashCode();\r
+    }\r
+\r
+    public void setPortletApplication(Portlet portlet, Application app) {\r
+        portletToApplication.put(portlet, app);\r
+    }\r
+\r
+    public Application getPortletApplication(Portlet portlet) {\r
+        return (Application) portletToApplication.get(portlet);\r
+    }\r
+\r
+    public PortletSession getPortletSession() {\r
+        return portletSession;\r
+    }\r
+\r
+    public void addPortletListener(Application app, PortletListener listener) {\r
+        Set l = (Set) portletListeners.get(app);\r
+        if (l == null) {\r
+            l = new LinkedHashSet();\r
+            portletListeners.put(app, l);\r
+        }\r
+        l.add(listener);\r
+    }\r
+\r
+    public void removePortletListener(Application app, PortletListener listener) {\r
+        Set l = (Set) portletListeners.get(app);\r
+        if (l != null) {\r
+            l.remove(listener);\r
+        }\r
+    }\r
+\r
+    public static void dispatchRequest(Portlet portlet, RenderRequest request,\r
+            RenderResponse response) {\r
+        PortletApplicationContext ctx = getApplicationContext(request\r
+                .getPortletSession());\r
+        if (ctx != null) {\r
+            ctx.firePortletRenderRequest(portlet, request, response);\r
+        }\r
+    }\r
+\r
+    public static void dispatchRequest(Portlet portlet, ActionRequest request,\r
+            ActionResponse response) {\r
+        PortletApplicationContext ctx = getApplicationContext(request\r
+                .getPortletSession());\r
+        if (ctx != null) {\r
+            ctx.firePortletActionRequest(portlet, request, response);\r
+        }\r
+    }\r
+\r
+    public void firePortletRenderRequest(Portlet portlet,\r
+            RenderRequest request, RenderResponse response) {\r
+        Application app = getPortletApplication(portlet);\r
+        Set listeners = (Set) portletListeners.get(app);\r
+        if (listeners != null) {\r
+            for (Iterator it = listeners.iterator(); it.hasNext();) {\r
+                PortletListener l = (PortletListener) it.next();\r
+                l.handleRenderRequest(request, new RestrictedRenderResponse(\r
+                        response));\r
+            }\r
+        }\r
+    }\r
+\r
+    public void firePortletActionRequest(Portlet portlet,\r
+            ActionRequest request, ActionResponse response) {\r
+        Application app = getPortletApplication(portlet);\r
+        Set listeners = (Set) portletListeners.get(app);\r
+        if (listeners != null) {\r
+            for (Iterator it = listeners.iterator(); it.hasNext();) {\r
+                PortletListener l = (PortletListener) it.next();\r
+                l.handleActionRequest(request, response);\r
+            }\r
+        }\r
+    }\r
+\r
+    public interface PortletListener {\r
+        public void handleRenderRequest(RenderRequest request,\r
+                RenderResponse response);\r
+\r
+        public void handleActionRequest(ActionRequest request,\r
+                ActionResponse response);\r
+    }\r
+\r
+    private class RestrictedRenderResponse implements RenderResponse {\r
+\r
+        private RenderResponse response;\r
+\r
+        private RestrictedRenderResponse(RenderResponse response) {\r
+            this.response = response;\r
+        }\r
+\r
+        public void addProperty(String key, String value) {\r
+            response.addProperty(key, value);\r
+        }\r
+\r
+        public PortletURL createActionURL() {\r
+            return response.createActionURL();\r
+        }\r
+\r
+        public PortletURL createRenderURL() {\r
+            return response.createRenderURL();\r
+        }\r
+\r
+        public String encodeURL(String path) {\r
+            return response.encodeURL(path);\r
+        }\r
+\r
+        public void flushBuffer() throws IOException {\r
+            // NOP\r
+            // TODO throw?\r
+        }\r
+\r
+        public int getBufferSize() {\r
+            return response.getBufferSize();\r
+        }\r
+\r
+        public String getCharacterEncoding() {\r
+            return response.getCharacterEncoding();\r
+        }\r
+\r
+        public String getContentType() {\r
+            return response.getContentType();\r
+        }\r
+\r
+        public Locale getLocale() {\r
+            return response.getLocale();\r
+        }\r
+\r
+        public String getNamespace() {\r
+            return response.getNamespace();\r
+        }\r
+\r
+        public OutputStream getPortletOutputStream() throws IOException {\r
+            // write forbidden\r
+            return null;\r
+        }\r
+\r
+        public PrintWriter getWriter() throws IOException {\r
+            // write forbidden\r
+            return null;\r
+        }\r
+\r
+        public boolean isCommitted() {\r
+            return response.isCommitted();\r
+        }\r
+\r
+        public void reset() {\r
+            // NOP\r
+            // TODO throw?\r
+        }\r
+\r
+        public void resetBuffer() {\r
+            // NOP\r
+            // TODO throw?\r
+        }\r
+\r
+        public void setBufferSize(int size) {\r
+            // NOP\r
+            // TODO throw?\r
+        }\r
+\r
+        public void setContentType(String type) {\r
+            // NOP\r
+            // TODO throw?\r
+        }\r
+\r
+        public void setProperty(String key, String value) {\r
+            response.setProperty(key, value);\r
+        }\r
+\r
+        public void setTitle(String title) {\r
+            response.setTitle(title);\r
+        }\r
+\r
+    }\r
+\r
+}\r
diff --git a/src/com/itmill/toolkit/util/PortletConfigurationGenerator.java b/src/com/itmill/toolkit/util/PortletConfigurationGenerator.java
new file mode 100644 (file)
index 0000000..2513558
--- /dev/null
@@ -0,0 +1,297 @@
+/**\r
+ * \r
+ */\r
+package com.itmill.toolkit.util;\r
+\r
+import java.io.BufferedReader;\r
+import java.io.File;\r
+import java.io.FileNotFoundException;\r
+import java.io.FileOutputStream;\r
+import java.io.FileReader;\r
+import java.io.IOException;\r
+import java.io.OutputStreamWriter;\r
+import java.nio.charset.Charset;\r
+import java.util.regex.Matcher;\r
+import java.util.regex.Pattern;\r
+\r
+/**\r
+ * Generates portlet.xml, liferay-portlet.xml, liferay-display.xml from web.xml.\r
+ * Currently uses regular expressions to avoid dependencies; does not strictly\r
+ * adhere to xml rules, but should work with a 'normal' web.xml.\r
+ * \r
+ * To be included, the servlet-mapping must include a special comment: <!--\r
+ * portlet --> If the portlet requires some special styles (i.e height): <!--\r
+ * portlet style=height:400px -->\r
+ * \r
+ * @author marc\r
+ */\r
+public class PortletConfigurationGenerator {\r
+    // can be changed for debugging:\r
+    private static final String WEB_XML_FILE = "web.xml";\r
+    private static final String PORTLET_XML_FILE = "portlet.xml";\r
+    private static final String LIFERAY_PORTLET_XML_FILE = "liferay-portlet.xml";\r
+    private static final String LIFERAY_DISPLAY_XML_FILE = "liferay-display.xml";\r
+\r
+    // "templates" follow;\r
+    private static final String PORTLET_XML_HEAD = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"\r
+            + "<portlet-app\n"\r
+            + "        xmlns=\"http://java.sun.com/xml/ns/portlet/portlet-app_1_0.xsd\"\n"\r
+            + "        version=\"1.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"\r
+            + "        xsi:schemaLocation=\"http://java.sun.com/xml/ns/portlet/portlet-app_1_0.xsd http://java.sun.com/xml/ns/portlet/portlet-app_1_0.xsd\">\n";\r
+    private static final String PORTLET_XML_SECTION = "        <portlet>\n"\r
+            + "                <portlet-name>%PORTLETNAME%</portlet-name>\n"\r
+            + "                <display-name>IT Mill Toolkit %NAME%</display-name>\n"\r
+            + "                <portlet-class>com.itmill.toolkit.terminal.gwt.server.ApplicationPortlet</portlet-class>\n"\r
+            + "                <init-param>\n"\r
+            + "                        <name>application</name>\n"\r
+            + "                        <value>%URL%</value>\n"\r
+            + "                </init-param>\n"\r
+            + "                %EXTRAPARAMS%\n"\r
+            + "                <supports>\n"\r
+            + "                        <mime-type>text/html</mime-type>\n"\r
+            + "                        <portlet-mode>view</portlet-mode>\n"\r
+            + "                        <portlet-mode>edit</portlet-mode>\n"\r
+            + "                        <portlet-mode>help</portlet-mode>\n"\r
+            + "                </supports>\n"\r
+            + "                <portlet-info>\n"\r
+            + "                        <title>%NAME%</title>\n"\r
+            + "                        <short-title>%NAME%</short-title>\n"\r
+            + "                </portlet-info>\n" + "                \n"\r
+            + "                <security-role-ref>\n"\r
+            + "                        <role-name>administrator</role-name>\n"\r
+            + "                </security-role-ref>\n"\r
+            + "                <security-role-ref>\n"\r
+            + "                        <role-name>guest</role-name>\n"\r
+            + "                </security-role-ref>\n"\r
+            + "                <security-role-ref>\n"\r
+            + "                        <role-name>power-user</role-name>\n"\r
+            + "                </security-role-ref>\n"\r
+            + "                <security-role-ref>\n"\r
+            + "                        <role-name>user</role-name>\n"\r
+            + "                </security-role-ref>\n" + "        </portlet>\n";\r
+    private static final String PORTLET_XML_FOOT = "        %CONTEXTPARAMS%\n"\r
+            + "        <container-runtime-option>\n"\r
+            + "                <name>javax.portlet.escapeXml</name>\n"\r
+            + "                <value>false</value>\n"\r
+            + "        </container-runtime-option>\n" + "</portlet-app>";\r
+\r
+    private static final String LIFERAY_PORTLET_XML_HEAD = "<?xml version=\"1.0\"?>\n"\r
+            + "<!DOCTYPE liferay-portlet-app PUBLIC \"-//Liferay//DTD Portlet Application 4.3.0//EN\" \"http://www.liferay.com/dtd/liferay-portlet-app_4_3_0.dtd\">\n"\r
+            + "\n" + "<liferay-portlet-app>\n" + "";\r
+    private static final String LIFERAY_PORTLET_XML_SECTION = "        <portlet>\n"\r
+            + "                <portlet-name>%PORTLETNAME%</portlet-name>\n"\r
+            + "                <instanceable>true</instanceable>       \n"\r
+            + "                <ajaxable>false</ajaxable>\n"\r
+            + "        </portlet>\n" + "";\r
+    private static final String LIFERAY_PORTLET_XML_FOOT = "    \n"\r
+            + "        <role-mapper>\n"\r
+            + "                <role-name>administrator</role-name>\n"\r
+            + "                <role-link>Administrator</role-link>\n"\r
+            + "        </role-mapper>\n" + "        <role-mapper>\n"\r
+            + "                <role-name>guest</role-name>\n"\r
+            + "                <role-link>Guest</role-link>\n"\r
+            + "        </role-mapper>\n" + "        <role-mapper>\n"\r
+            + "                <role-name>power-user</role-name>\n"\r
+            + "                <role-link>Power User</role-link>\n"\r
+            + "        </role-mapper>\n" + "        <role-mapper>\n"\r
+            + "                <role-name>user</role-name>\n"\r
+            + "                <role-link>User</role-link>\n"\r
+            + "        </role-mapper>\n" + "        \n"\r
+            + "</liferay-portlet-app>";\r
+    private static final String LIFERAY_DISPLAY_XML_HEAD = "<?xml version=\"1.0\"?>\n"\r
+            + "<!DOCTYPE display PUBLIC \"-//Liferay//DTD Display 4.0.0//EN\" \"http://www.liferay.com/dtd/liferay-display_4_0_0.dtd\">\n"\r
+            + "\n"\r
+            + "<display>\n"\r
+            + "        <category name=\"IT Mill Toolkit\">\n" + "";\r
+    private static final String LIFERAY_DISPLAY_XML_SECTION = "                <portlet id=\"%PORTLETNAME%\" />\n";\r
+    private static final String LIFERAY_DISPLAY_XML_FOOT = "\n"\r
+            + "        </category>\n" + "</display>";\r
+\r
+    /**\r
+     * @param args\r
+     *                <path to directory with web.xml>\r
+     */\r
+    public static void main(String[] args) {\r
+        if (args.length < 1 || !new File(args[0]).isDirectory()) {\r
+            System.err\r
+                    .println("Usage: PortletConfigurationGenerator <directory> [widgetset]");\r
+            return;\r
+        }\r
+\r
+        String widgetset = "";\r
+        if (args.length > 1) {\r
+            widgetset = "<context-param><name>widgetset</name><value>"\r
+                    + args[1] + "</value></context-param>";\r
+        }\r
+\r
+        /*\r
+         * Read web.xml\r
+         */\r
+        File dir = new File(args[0]);\r
+        File webxmlFile = new File(dir.getAbsolutePath() + File.separatorChar\r
+                + WEB_XML_FILE);\r
+        String webXml = "";\r
+        BufferedReader in = null;\r
+        try {\r
+            in = new BufferedReader(new FileReader(webxmlFile));\r
+            String line = in.readLine();\r
+            while (line != null) {\r
+                webXml += line;\r
+                line = in.readLine();\r
+            }\r
+        } catch (FileNotFoundException e1) {\r
+            System.out.println(webxmlFile + " not found!");\r
+            return;\r
+        } catch (IOException e2) {\r
+            System.out.println("IOException while reading " + webxmlFile);\r
+            webXml = null;\r
+        }\r
+        try {\r
+            if (in != null) {\r
+                in.close();\r
+            }\r
+        } catch (IOException e1) {\r
+            System.out.println("IOException while closing " + webxmlFile);\r
+        }\r
+        if (webXml == null) {\r
+            System.out.println("Could not read web.xml!");\r
+            return;\r
+        }\r
+\r
+        /*\r
+         * Open outputs\r
+         */\r
+\r
+        // Open portlet.xml\r
+        File portletXmlFile = new File(args[0] + File.separatorChar\r
+                + PORTLET_XML_FILE);\r
+        OutputStreamWriter pout = null;\r
+        try {\r
+            pout = new OutputStreamWriter(new FileOutputStream(portletXmlFile),\r
+                    Charset.forName("UTF-8"));\r
+        } catch (FileNotFoundException e) {\r
+            System.out.println(portletXmlFile + " not found!");\r
+        }\r
+        // open liferay-portlet.xml\r
+        File liferayPortletXmlFile = new File(args[0] + File.separatorChar\r
+                + LIFERAY_PORTLET_XML_FILE);\r
+        OutputStreamWriter lpout = null;\r
+        try {\r
+            lpout = new OutputStreamWriter(new FileOutputStream(\r
+                    liferayPortletXmlFile), Charset.forName("UTF-8"));\r
+        } catch (FileNotFoundException e) {\r
+            System.out.println(liferayPortletXmlFile + " not found!");\r
+        }\r
+        // open liferay-display.xml\r
+        File liferayDisplayXmlFile = new File(args[0] + File.separatorChar\r
+                + LIFERAY_DISPLAY_XML_FILE);\r
+        OutputStreamWriter ldout = null;\r
+        try {\r
+            ldout = new OutputStreamWriter(new FileOutputStream(\r
+                    liferayDisplayXmlFile), Charset.forName("UTF-8"));\r
+        } catch (FileNotFoundException e) {\r
+            System.out.println(liferayDisplayXmlFile + " not found!");\r
+        }\r
+\r
+        if (pout != null && lpout != null && ldout != null) {\r
+\r
+            String pstring = PORTLET_XML_HEAD;\r
+            String lpstring = LIFERAY_PORTLET_XML_HEAD;\r
+            String ldstring = LIFERAY_DISPLAY_XML_HEAD;\r
+\r
+            Pattern p1 = Pattern\r
+                    .compile("<servlet-mapping>.*?<servlet-name>(.*?)<\\/servlet-name>.*?<url-pattern>(.*?)<\\/url-pattern>(.*?)<\\/servlet-mapping>");\r
+            Pattern p2 = Pattern\r
+                    .compile(".*?<!--\\s+portlet\\s?(style=\\S+)?\\s+-->.*?");\r
+            Matcher m = p1.matcher(webXml);\r
+            while (m.find()) {\r
+                if (m.groupCount() < 3) {\r
+                    // don't include\r
+                    continue;\r
+                }\r
+                Matcher m2 = p2.matcher(m.group(3));\r
+                if (!m2.find()) {\r
+                    // don't include\r
+                    continue;\r
+                }\r
+\r
+                String style = "";\r
+                if (m2.groupCount() == 1 && m2.group(1) != null) {\r
+                    style = "<init-param><name>style</name><value>"\r
+                            + m2.group(1) + "</value></init-param>";\r
+                }\r
+\r
+                String name = m.group(1);\r
+                // remove leading- and trailing whitespace\r
+                name = name.replaceAll("^\\s*", "");\r
+                name = name.replaceAll("\\s*$", "");\r
+                String pname = name + "Portlet";\r
+                String url = m.group(2);\r
+                // remove leading- and trailing whitespace\r
+                url = url.replaceAll("^\\s*", "");\r
+                url = url.replaceAll("\\s*$", "");\r
+                if (url.startsWith("/")) {\r
+                    url = url.substring(1);\r
+                }\r
+                if (url.endsWith("*")) {\r
+                    url = url.substring(0, url.length() - 1);\r
+                }\r
+                if (url.endsWith("/")) {\r
+                    url = url.substring(0, url.length() - 1);\r
+                }\r
+\r
+                System.out.println("Mapping " + pname + " to " + url);\r
+\r
+                String s = PORTLET_XML_SECTION;\r
+                s = s.replaceAll("%NAME%", name);\r
+                s = s.replaceAll("%PORTLETNAME%", pname);\r
+                s = s.replaceAll("%URL%", url);\r
+                s = s.replaceAll("%EXTRAPARAMS%", style);\r
+\r
+                pstring += s;\r
+\r
+                s = LIFERAY_PORTLET_XML_SECTION;\r
+                s = s.replaceAll("%NAME%", name);\r
+                s = s.replaceAll("%PORTLETNAME%", pname);\r
+                s = s.replaceAll("%URL%", url);\r
+                lpstring += s;\r
+\r
+                s = LIFERAY_DISPLAY_XML_SECTION;\r
+                s = s.replaceAll("%NAME%", name);\r
+                s = s.replaceAll("%PORTLETNAME%", pname);\r
+                s = s.replaceAll("%URL%", url);\r
+                ldstring += s;\r
+\r
+            }\r
+\r
+            pstring += PORTLET_XML_FOOT\r
+                    .replaceAll("%CONTEXTPARAMS%", widgetset);\r
+            lpstring += LIFERAY_PORTLET_XML_FOOT;\r
+            ldstring += LIFERAY_DISPLAY_XML_FOOT;\r
+\r
+            try {\r
+                pout.write(pstring);\r
+                lpout.write(lpstring);\r
+                ldout.write(ldstring);\r
+            } catch (IOException e) {\r
+                System.out.println("Write FAILED:" + e);\r
+            }\r
+\r
+        }\r
+\r
+        try {\r
+            if (pout != null) {\r
+                pout.close();\r
+            }\r
+            if (lpout != null) {\r
+                lpout.close();\r
+            }\r
+            if (ldout != null) {\r
+                ldout.close();\r
+            }\r
+        } catch (IOException e) {\r
+            System.out.println("Close FAILED: " + e);\r
+        }\r
+        System.out.println("Done.");\r
+    }\r
+}\r