From: Marc Englund Date: Tue, 29 Apr 2008 12:56:19 +0000 (+0000) Subject: Portlet tools integrated into main src-tree X-Git-Tag: 6.7.0.beta1~4848 X-Git-Url: https://source.dussan.org/?a=commitdiff_plain;h=c8699106d9ede048eb81584e4138e79993bc3f67;p=vaadin-framework.git Portlet tools integrated into main src-tree svn changeset:4286/svn branch:trunk --- 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 index 8645be21b7..0000000000 --- a/portlet-src/com/itmill/toolkit/demo/portlet/PortletDemo.java +++ /dev/null @@ -1,152 +0,0 @@ -/** - * - */ -package com.itmill.toolkit.demo.portlet; - -import java.util.Iterator; -import java.util.Map; - -import javax.portlet.ActionRequest; -import javax.portlet.ActionResponse; -import javax.portlet.PortletMode; -import javax.portlet.PortletRequest; -import javax.portlet.PortletURL; -import javax.portlet.RenderRequest; -import javax.portlet.RenderResponse; -import javax.portlet.WindowState; - -import com.itmill.toolkit.Application; -import com.itmill.toolkit.terminal.ExternalResource; -import com.itmill.toolkit.terminal.gwt.server.PortletApplicationContext; -import com.itmill.toolkit.terminal.gwt.server.PortletApplicationContext.PortletListener; -import com.itmill.toolkit.ui.Label; -import com.itmill.toolkit.ui.Link; -import com.itmill.toolkit.ui.TextField; -import com.itmill.toolkit.ui.Window; -import com.itmill.toolkit.ui.Window.Notification; - -/** - * @author marc - * - */ -public class PortletDemo extends Application { - - Window main = new Window(); - TextField tf = new TextField("Some value"); - Label userInfo = new Label(); - Link portletEdit = new Link(); - Link portletMax = new Link(); - Link someAction = null; - - public void init() { - main = new Window(); - setMainWindow(main); - - userInfo.setCaption("User info"); - userInfo.setContentMode(Label.CONTENT_PREFORMATTED); - main.addComponent(userInfo); - - tf.setEnabled(false); - tf.setImmediate(true); - main.addComponent(tf); - - portletEdit.setEnabled(false); - main.addComponent(portletEdit); - portletMax.setEnabled(false); - main.addComponent(portletMax); - - if (getContext() instanceof PortletApplicationContext) { - PortletApplicationContext ctx = (PortletApplicationContext) getContext(); - ctx.addPortletListener(this, new DemoPortletListener()); - } else { - getMainWindow().showNotification("Not inited via Portal!", - Notification.TYPE_ERROR_MESSAGE); - } - - } - - private class DemoPortletListener implements PortletListener { - - public void handleActionRequest(ActionRequest request, - ActionResponse response) { - - main.addComponent(new Label("Action received")); - - } - - public void handleRenderRequest(RenderRequest request, - RenderResponse response) { - // Portlet up-and-running, enable stuff - portletEdit.setEnabled(true); - portletMax.setEnabled(true); - - // Editable if we're in editmode - tf.setEnabled((request.getPortletMode() == PortletMode.EDIT)); - - // Show notification about current mode and state - getMainWindow().showNotification( - "Portlet status", - "Mode: " + request.getPortletMode() + " State: " - + request.getWindowState(), - Notification.TYPE_WARNING_MESSAGE); - - // Display current user info - Map uinfo = (Map) request.getAttribute(PortletRequest.USER_INFO); - if (uinfo != null) { - String s = ""; - for (Iterator it = uinfo.keySet().iterator(); it.hasNext();) { - Object key = it.next(); - Object val = uinfo.get(key); - s += key + ": " + val + "\n"; - } - if (request.isUserInRole("administrator")) { - s += "(administrator)"; - } - userInfo.setValue(s); - } else { - userInfo.setValue("-"); - } - - // Create Edit/Done link (actionUrl) - PortletURL url = response.createActionURL(); - try { - url - .setPortletMode((request.getPortletMode() == PortletMode.VIEW ? PortletMode.EDIT - : PortletMode.VIEW)); - portletEdit.setResource(new ExternalResource(url.toString())); - portletEdit - .setCaption((request.getPortletMode() == PortletMode.VIEW ? "Edit" - : "Done")); - } catch (Exception e) { - portletEdit.setEnabled(false); - } - // Create Maximize/Normal link (actionUrl) - url = response.createActionURL(); - try { - url - .setWindowState((request.getWindowState() == WindowState.NORMAL ? WindowState.MAXIMIZED - : WindowState.NORMAL)); - portletMax.setResource(new ExternalResource(url.toString())); - portletMax - .setCaption((request.getWindowState() == WindowState.NORMAL ? "Maximize" - : "Back to normal")); - } catch (Exception e) { - portletMax.setEnabled(false); - } - - if (someAction == null) { - url = response.createActionURL(); - try { - someAction = new Link("An action", new ExternalResource(url - .toString())); - main.addComponent(someAction); - } catch (Exception e) { - // Oops - System.err.println("Could not create someAction: " + e); - } - - } - - } - } -} 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 index ac9319c3f6..0000000000 --- a/portlet-src/com/itmill/toolkit/demo/reservation/simple/AdminView.java +++ /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 index 86428dba56..0000000000 --- a/portlet-src/com/itmill/toolkit/demo/reservation/simple/SampleDB.java +++ /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 + "? 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 index c5e9f28428..0000000000 --- a/portlet-src/com/itmill/toolkit/demo/reservation/simple/SimpleReserver.java +++ /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 index bbb07aa853..0000000000 --- a/portlet-src/com/itmill/toolkit/demo/reservation/simple/StdView.java +++ /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 index 403e181f20..0000000000 --- a/portlet-src/com/itmill/toolkit/portlet/util/PortletConfigurationGenerator.java +++ /dev/null @@ -1,297 +0,0 @@ -/** - * - */ -package com.itmill.toolkit.portlet.util; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.FileReader; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.nio.charset.Charset; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Generates portlet.xml, liferay-portlet.xml, liferay-display.xml from web.xml. - * Currently uses regular expressions to avoid dependencies; does not strictly - * adhere to xml rules, but should work with a 'normal' web.xml. - * - * To be included, the servlet-mapping must include a special comment: If the portlet requires some special styles (i.e height): - * - * @author marc - */ -public class PortletConfigurationGenerator { - // can be changed for debugging: - private static final String WEB_XML_FILE = "web.xml"; - private static final String PORTLET_XML_FILE = "portlet.xml"; - private static final String LIFERAY_PORTLET_XML_FILE = "liferay-portlet.xml"; - private static final String LIFERAY_DISPLAY_XML_FILE = "liferay-display.xml"; - - // "templates" follow; - private static final String PORTLET_XML_HEAD = "\n" - + "\n"; - private static final String PORTLET_XML_SECTION = " \n" - + " %PORTLETNAME%\n" - + " IT Mill Toolkit %NAME%\n" - + " com.itmill.toolkit.terminal.gwt.server.ApplicationPortlet\n" - + " \n" - + " application\n" - + " %URL%\n" - + " \n" - + " %EXTRAPARAMS%\n" - + " \n" - + " text/html\n" - + " view\n" - + " edit\n" - + " help\n" - + " \n" - + " \n" - + " %NAME%\n" - + " %NAME%\n" - + " \n" + " \n" - + " \n" - + " administrator\n" - + " \n" - + " \n" - + " guest\n" - + " \n" - + " \n" - + " power-user\n" - + " \n" - + " \n" - + " user\n" - + " \n" + " \n"; - private static final String PORTLET_XML_FOOT = " %CONTEXTPARAMS%\n" - + " \n" - + " javax.portlet.escapeXml\n" - + " false\n" - + " \n" + ""; - - private static final String LIFERAY_PORTLET_XML_HEAD = "\n" - + "\n" - + "\n" + "\n" + ""; - private static final String LIFERAY_PORTLET_XML_SECTION = " \n" - + " %PORTLETNAME%\n" - + " true \n" - + " false\n" - + " \n" + ""; - private static final String LIFERAY_PORTLET_XML_FOOT = " \n" - + " \n" - + " administrator\n" - + " Administrator\n" - + " \n" + " \n" - + " guest\n" - + " Guest\n" - + " \n" + " \n" - + " power-user\n" - + " Power User\n" - + " \n" + " \n" - + " user\n" - + " User\n" - + " \n" + " \n" - + ""; - private static final String LIFERAY_DISPLAY_XML_HEAD = "\n" - + "\n" - + "\n" - + "\n" - + " \n" + ""; - private static final String LIFERAY_DISPLAY_XML_SECTION = " \n"; - private static final String LIFERAY_DISPLAY_XML_FOOT = "\n" - + " \n" + ""; - - /** - * @param args - * - */ - public static void main(String[] args) { - if (args.length < 1 || !new File(args[0]).isDirectory()) { - System.err - .println("Usage: PortletConfigurationGenerator [widgetset]"); - return; - } - - String widgetset = ""; - if (args.length > 1) { - widgetset = "widgetset" - + args[1] + ""; - } - - /* - * Read web.xml - */ - File dir = new File(args[0]); - File webxmlFile = new File(dir.getAbsolutePath() + File.separatorChar - + WEB_XML_FILE); - String webXml = ""; - BufferedReader in = null; - try { - in = new BufferedReader(new FileReader(webxmlFile)); - String line = in.readLine(); - while (line != null) { - webXml += line; - line = in.readLine(); - } - } catch (FileNotFoundException e1) { - System.out.println(webxmlFile + " not found!"); - return; - } catch (IOException e2) { - System.out.println("IOException while reading " + webxmlFile); - webXml = null; - } - try { - if (in != null) { - in.close(); - } - } catch (IOException e1) { - System.out.println("IOException while closing " + webxmlFile); - } - if (webXml == null) { - System.out.println("Could not read web.xml!"); - return; - } - - /* - * Open outputs - */ - - // Open portlet.xml - File portletXmlFile = new File(args[0] + File.separatorChar - + PORTLET_XML_FILE); - OutputStreamWriter pout = null; - try { - pout = new OutputStreamWriter(new FileOutputStream(portletXmlFile), - Charset.forName("UTF-8")); - } catch (FileNotFoundException e) { - System.out.println(portletXmlFile + " not found!"); - } - // open liferay-portlet.xml - File liferayPortletXmlFile = new File(args[0] + File.separatorChar - + LIFERAY_PORTLET_XML_FILE); - OutputStreamWriter lpout = null; - try { - lpout = new OutputStreamWriter(new FileOutputStream( - liferayPortletXmlFile), Charset.forName("UTF-8")); - } catch (FileNotFoundException e) { - System.out.println(liferayPortletXmlFile + " not found!"); - } - // open liferay-display.xml - File liferayDisplayXmlFile = new File(args[0] + File.separatorChar - + LIFERAY_DISPLAY_XML_FILE); - OutputStreamWriter ldout = null; - try { - ldout = new OutputStreamWriter(new FileOutputStream( - liferayDisplayXmlFile), Charset.forName("UTF-8")); - } catch (FileNotFoundException e) { - System.out.println(liferayDisplayXmlFile + " not found!"); - } - - if (pout != null && lpout != null && ldout != null) { - - String pstring = PORTLET_XML_HEAD; - String lpstring = LIFERAY_PORTLET_XML_HEAD; - String ldstring = LIFERAY_DISPLAY_XML_HEAD; - - Pattern p1 = Pattern - .compile(".*?(.*?)<\\/servlet-name>.*?(.*?)<\\/url-pattern>(.*?)<\\/servlet-mapping>"); - Pattern p2 = Pattern - .compile(".*?.*?"); - Matcher m = p1.matcher(webXml); - while (m.find()) { - if (m.groupCount() < 3) { - // don't include - continue; - } - Matcher m2 = p2.matcher(m.group(3)); - if (!m2.find()) { - // don't include - continue; - } - - String style = ""; - if (m2.groupCount() == 1 && m2.group(1) != null) { - style = "style" - + m2.group(1) + ""; - } - - String name = m.group(1); - // remove leading- and trailing whitespace - name = name.replaceAll("^\\s*", ""); - name = name.replaceAll("\\s*$", ""); - String pname = name + "Portlet"; - String url = m.group(2); - // remove leading- and trailing whitespace - url = url.replaceAll("^\\s*", ""); - url = url.replaceAll("\\s*$", ""); - if (url.startsWith("/")) { - url = url.substring(1); - } - if (url.endsWith("*")) { - url = url.substring(0, url.length() - 1); - } - if (url.endsWith("/")) { - url = url.substring(0, url.length() - 1); - } - - System.out.println("Mapping " + pname + " to " + url); - - String s = PORTLET_XML_SECTION; - s = s.replaceAll("%NAME%", name); - s = s.replaceAll("%PORTLETNAME%", pname); - s = s.replaceAll("%URL%", url); - s = s.replaceAll("%EXTRAPARAMS%", style); - - pstring += s; - - s = LIFERAY_PORTLET_XML_SECTION; - s = s.replaceAll("%NAME%", name); - s = s.replaceAll("%PORTLETNAME%", pname); - s = s.replaceAll("%URL%", url); - lpstring += s; - - s = LIFERAY_DISPLAY_XML_SECTION; - s = s.replaceAll("%NAME%", name); - s = s.replaceAll("%PORTLETNAME%", pname); - s = s.replaceAll("%URL%", url); - ldstring += s; - - } - - pstring += PORTLET_XML_FOOT - .replaceAll("%CONTEXTPARAMS%", widgetset); - lpstring += LIFERAY_PORTLET_XML_FOOT; - ldstring += LIFERAY_DISPLAY_XML_FOOT; - - try { - pout.write(pstring); - lpout.write(lpstring); - ldout.write(ldstring); - } catch (IOException e) { - System.out.println("Write FAILED:" + e); - } - - } - - try { - if (pout != null) { - pout.close(); - } - if (lpout != null) { - lpout.close(); - } - if (ldout != null) { - ldout.close(); - } - } catch (IOException e) { - System.out.println("Close FAILED: " + e); - } - System.out.println("Done."); - } -} 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 index 77cca2ac1b..0000000000 --- a/portlet-src/com/itmill/toolkit/terminal/gwt/server/ApplicationPortlet.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.itmill.toolkit.terminal.gwt.server; - -import java.io.IOException; -import java.io.PrintWriter; - -import javax.portlet.ActionRequest; -import javax.portlet.ActionResponse; -import javax.portlet.Portlet; -import javax.portlet.PortletConfig; -import javax.portlet.PortletException; -import javax.portlet.PortletRequestDispatcher; -import javax.portlet.PortletSession; -import javax.portlet.RenderRequest; -import javax.portlet.RenderResponse; - -import com.itmill.toolkit.Application; - -public class ApplicationPortlet implements Portlet { - // The application to show - protected String app = null; - // some applications might require forced height (and, more seldom, width) - protected String style = null; // e.g "height:500px;" - protected String widgetset = null; - - public void destroy() { - - } - - public void init(PortletConfig config) throws PortletException { - app = config.getInitParameter("application"); - if (app == null) { - app = "PortletDemo"; - } - style = config.getInitParameter("style"); - widgetset = config.getInitParameter("widgetset"); - } - - public void processAction(ActionRequest request, ActionResponse response) - throws PortletException, IOException { - PortletApplicationContext.dispatchRequest(this, request, response); - } - - public void render(RenderRequest request, RenderResponse response) - throws PortletException, IOException { - - // display the IT Mill Toolkit application - writeAjaxWindow(request, response); - } - - protected void writeAjaxWindow(RenderRequest request, - RenderResponse response) throws IOException { - - if (app != null) { - PortletSession sess = request.getPortletSession(); - PortletApplicationContext ctx = PortletApplicationContext - .getApplicationContext(sess); - - PortletRequestDispatcher dispatcher = sess.getPortletContext() - .getRequestDispatcher("/" + app); - - try { - request.setAttribute(ApplicationServlet.REQUEST_FRAGMENT, - "true"); - if (widgetset != null) { - request.setAttribute(ApplicationServlet.REQUEST_WIDGETSET, - widgetset); - } - if (style != null) { - request.setAttribute(ApplicationServlet.REQUEST_APPSTYLE, - style); - } - dispatcher.include(request, response); - - } catch (PortletException e) { - response.setContentType("text/html"); - PrintWriter out = response.getWriter(); - out.print("

Servlet include failed!

"); - out.print("
" + e + "
"); - ctx.setPortletApplication(this, null); - return; - } - - Application app = (Application) request - .getAttribute(Application.class.getName()); - ctx.setPortletApplication(this, app); - ctx.firePortletRenderRequest(this, request, response); - - } - } - -} 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 index 4ddbabdb96..0000000000 --- a/portlet-src/com/itmill/toolkit/terminal/gwt/server/PortletApplicationContext.java +++ /dev/null @@ -1,283 +0,0 @@ -/** - * - */ -package com.itmill.toolkit.terminal.gwt.server; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.PrintWriter; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.Locale; -import java.util.Map; -import java.util.Set; - -import javax.portlet.ActionRequest; -import javax.portlet.ActionResponse; -import javax.portlet.Portlet; -import javax.portlet.PortletSession; -import javax.portlet.PortletURL; -import javax.portlet.RenderRequest; -import javax.portlet.RenderResponse; -import javax.servlet.http.HttpSession; - -import com.itmill.toolkit.Application; - -/** - * @author marc - * - */ -public class PortletApplicationContext extends WebApplicationContext { - - protected PortletSession portletSession; - - protected Map portletListeners = new HashMap(); - - protected Map portletToApplication = new HashMap(); - - PortletApplicationContext() { - - } - - static public PortletApplicationContext getApplicationContext( - PortletSession session) { - WebApplicationContext cx = (WebApplicationContext) session - .getAttribute(WebApplicationContext.class.getName(), - PortletSession.APPLICATION_SCOPE); - if (cx == null) { - cx = new PortletApplicationContext(); - } - if (!(cx instanceof PortletApplicationContext)) { - // TODO Should we even try this? And should we leave original as-is? - PortletApplicationContext pcx = new PortletApplicationContext(); - pcx.applications.addAll(cx.applications); - cx.applications.clear(); - pcx.browser = cx.browser; - cx.browser = null; - pcx.listeners = cx.listeners; - cx.listeners = null; - pcx.session = cx.session; - cx = pcx; - } - if (((PortletApplicationContext) cx).portletSession == null) { - ((PortletApplicationContext) cx).portletSession = session; - } - session.setAttribute(WebApplicationContext.class.getName(), cx, - PortletSession.APPLICATION_SCOPE); - return (PortletApplicationContext) cx; - } - - static public WebApplicationContext getApplicationContext( - HttpSession session) { - WebApplicationContext cx = (WebApplicationContext) session - .getAttribute(WebApplicationContext.class.getName()); - if (cx == null) { - cx = new PortletApplicationContext(); - } - if (cx.session == null) { - cx.session = session; - } - session.setAttribute(WebApplicationContext.class.getName(), cx); - return cx; - } - - protected void removeApplication(Application application) { - portletListeners.remove(application); - for (Iterator it = portletToApplication.keySet().iterator(); it - .hasNext();) { - Object key = it.next(); - if (key == application) { - portletToApplication.remove(key); - } - } - super.removeApplication(application); - } - - public boolean equals(Object obj) { - if (portletSession == null) { - return super.equals(obj); - } - return portletSession.equals(obj); - } - - public int hashCode() { - if (portletSession == null) { - return super.hashCode(); - } - return portletSession.hashCode(); - } - - public void setPortletApplication(Portlet portlet, Application app) { - portletToApplication.put(portlet, app); - } - - public Application getPortletApplication(Portlet portlet) { - return (Application) portletToApplication.get(portlet); - } - - public PortletSession getPortletSession() { - return portletSession; - } - - public void addPortletListener(Application app, PortletListener listener) { - Set l = (Set) portletListeners.get(app); - if (l == null) { - l = new LinkedHashSet(); - portletListeners.put(app, l); - } - l.add(listener); - } - - public void removePortletListener(Application app, PortletListener listener) { - Set l = (Set) portletListeners.get(app); - if (l != null) { - l.remove(listener); - } - } - - public static void dispatchRequest(Portlet portlet, RenderRequest request, - RenderResponse response) { - PortletApplicationContext ctx = getApplicationContext(request - .getPortletSession()); - if (ctx != null) { - ctx.firePortletRenderRequest(portlet, request, response); - } - } - - public static void dispatchRequest(Portlet portlet, ActionRequest request, - ActionResponse response) { - PortletApplicationContext ctx = getApplicationContext(request - .getPortletSession()); - if (ctx != null) { - ctx.firePortletActionRequest(portlet, request, response); - } - } - - public void firePortletRenderRequest(Portlet portlet, - RenderRequest request, RenderResponse response) { - Application app = getPortletApplication(portlet); - Set listeners = (Set) portletListeners.get(app); - if (listeners != null) { - for (Iterator it = listeners.iterator(); it.hasNext();) { - PortletListener l = (PortletListener) it.next(); - l.handleRenderRequest(request, new RestrictedRenderResponse( - response)); - } - } - } - - public void firePortletActionRequest(Portlet portlet, - ActionRequest request, ActionResponse response) { - Application app = getPortletApplication(portlet); - Set listeners = (Set) portletListeners.get(app); - if (listeners != null) { - for (Iterator it = listeners.iterator(); it.hasNext();) { - PortletListener l = (PortletListener) it.next(); - l.handleActionRequest(request, response); - } - } - } - - public interface PortletListener { - public void handleRenderRequest(RenderRequest request, - RenderResponse response); - - public void handleActionRequest(ActionRequest request, - ActionResponse response); - } - - private class RestrictedRenderResponse implements RenderResponse { - - private RenderResponse response; - - private RestrictedRenderResponse(RenderResponse response) { - this.response = response; - } - - public void addProperty(String key, String value) { - response.addProperty(key, value); - } - - public PortletURL createActionURL() { - return response.createActionURL(); - } - - public PortletURL createRenderURL() { - return response.createRenderURL(); - } - - public String encodeURL(String path) { - return response.encodeURL(path); - } - - public void flushBuffer() throws IOException { - // NOP - // TODO throw? - } - - public int getBufferSize() { - return response.getBufferSize(); - } - - public String getCharacterEncoding() { - return response.getCharacterEncoding(); - } - - public String getContentType() { - return response.getContentType(); - } - - public Locale getLocale() { - return response.getLocale(); - } - - public String getNamespace() { - return response.getNamespace(); - } - - public OutputStream getPortletOutputStream() throws IOException { - // write forbidden - return null; - } - - public PrintWriter getWriter() throws IOException { - // write forbidden - return null; - } - - public boolean isCommitted() { - return response.isCommitted(); - } - - public void reset() { - // NOP - // TODO throw? - } - - public void resetBuffer() { - // NOP - // TODO throw? - } - - public void setBufferSize(int size) { - // NOP - // TODO throw? - } - - public void setContentType(String type) { - // NOP - // TODO throw? - } - - public void setProperty(String key, String value) { - response.setProperty(key, value); - } - - public void setTitle(String title) { - response.setTitle(title); - } - - } - -} diff --git a/src/com/itmill/toolkit/demo/PortletDemo.java b/src/com/itmill/toolkit/demo/PortletDemo.java new file mode 100644 index 0000000000..e4089612f3 --- /dev/null +++ b/src/com/itmill/toolkit/demo/PortletDemo.java @@ -0,0 +1,152 @@ +/** + * + */ +package com.itmill.toolkit.demo; + +import java.util.Iterator; +import java.util.Map; + +import javax.portlet.ActionRequest; +import javax.portlet.ActionResponse; +import javax.portlet.PortletMode; +import javax.portlet.PortletRequest; +import javax.portlet.PortletURL; +import javax.portlet.RenderRequest; +import javax.portlet.RenderResponse; +import javax.portlet.WindowState; + +import com.itmill.toolkit.Application; +import com.itmill.toolkit.terminal.ExternalResource; +import com.itmill.toolkit.terminal.gwt.server.PortletApplicationContext; +import com.itmill.toolkit.terminal.gwt.server.PortletApplicationContext.PortletListener; +import com.itmill.toolkit.ui.Label; +import com.itmill.toolkit.ui.Link; +import com.itmill.toolkit.ui.TextField; +import com.itmill.toolkit.ui.Window; +import com.itmill.toolkit.ui.Window.Notification; + +/** + * @author marc + * + */ +public class PortletDemo extends Application { + + Window main = new Window(); + TextField tf = new TextField("Some value"); + Label userInfo = new Label(); + Link portletEdit = new Link(); + Link portletMax = new Link(); + Link someAction = null; + + public void init() { + main = new Window(); + setMainWindow(main); + + userInfo.setCaption("User info"); + userInfo.setContentMode(Label.CONTENT_PREFORMATTED); + main.addComponent(userInfo); + + tf.setEnabled(false); + tf.setImmediate(true); + main.addComponent(tf); + + portletEdit.setEnabled(false); + main.addComponent(portletEdit); + portletMax.setEnabled(false); + main.addComponent(portletMax); + + if (getContext() instanceof PortletApplicationContext) { + PortletApplicationContext ctx = (PortletApplicationContext) getContext(); + ctx.addPortletListener(this, new DemoPortletListener()); + } else { + getMainWindow().showNotification("Not inited via Portal!", + Notification.TYPE_ERROR_MESSAGE); + } + + } + + private class DemoPortletListener implements PortletListener { + + public void handleActionRequest(ActionRequest request, + ActionResponse response) { + + main.addComponent(new Label("Action received")); + + } + + public void handleRenderRequest(RenderRequest request, + RenderResponse response) { + // Portlet up-and-running, enable stuff + portletEdit.setEnabled(true); + portletMax.setEnabled(true); + + // Editable if we're in editmode + tf.setEnabled((request.getPortletMode() == PortletMode.EDIT)); + + // Show notification about current mode and state + getMainWindow().showNotification( + "Portlet status", + "Mode: " + request.getPortletMode() + " State: " + + request.getWindowState(), + Notification.TYPE_WARNING_MESSAGE); + + // Display current user info + Map uinfo = (Map) request.getAttribute(PortletRequest.USER_INFO); + if (uinfo != null) { + String s = ""; + for (Iterator it = uinfo.keySet().iterator(); it.hasNext();) { + Object key = it.next(); + Object val = uinfo.get(key); + s += key + ": " + val + "\n"; + } + if (request.isUserInRole("administrator")) { + s += "(administrator)"; + } + userInfo.setValue(s); + } else { + userInfo.setValue("-"); + } + + // Create Edit/Done link (actionUrl) + PortletURL url = response.createActionURL(); + try { + url + .setPortletMode((request.getPortletMode() == PortletMode.VIEW ? PortletMode.EDIT + : PortletMode.VIEW)); + portletEdit.setResource(new ExternalResource(url.toString())); + portletEdit + .setCaption((request.getPortletMode() == PortletMode.VIEW ? "Edit" + : "Done")); + } catch (Exception e) { + portletEdit.setEnabled(false); + } + // Create Maximize/Normal link (actionUrl) + url = response.createActionURL(); + try { + url + .setWindowState((request.getWindowState() == WindowState.NORMAL ? WindowState.MAXIMIZED + : WindowState.NORMAL)); + portletMax.setResource(new ExternalResource(url.toString())); + portletMax + .setCaption((request.getWindowState() == WindowState.NORMAL ? "Maximize" + : "Back to normal")); + } catch (Exception e) { + portletMax.setEnabled(false); + } + + if (someAction == null) { + url = response.createActionURL(); + try { + someAction = new Link("An action", new ExternalResource(url + .toString())); + main.addComponent(someAction); + } catch (Exception e) { + // Oops + System.err.println("Could not create someAction: " + e); + } + + } + + } + } +} 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 index 0000000000..ac9319c3f6 --- /dev/null +++ b/src/com/itmill/toolkit/demo/reservation/simple/AdminView.java @@ -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 index 0000000000..86428dba56 --- /dev/null +++ b/src/com/itmill/toolkit/demo/reservation/simple/SampleDB.java @@ -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 + "? 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 index 0000000000..c5e9f28428 --- /dev/null +++ b/src/com/itmill/toolkit/demo/reservation/simple/SimpleReserver.java @@ -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 index 0000000000..bbb07aa853 --- /dev/null +++ b/src/com/itmill/toolkit/demo/reservation/simple/StdView.java @@ -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 index 0000000000..77cca2ac1b --- /dev/null +++ b/src/com/itmill/toolkit/terminal/gwt/server/ApplicationPortlet.java @@ -0,0 +1,91 @@ +package com.itmill.toolkit.terminal.gwt.server; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.portlet.ActionRequest; +import javax.portlet.ActionResponse; +import javax.portlet.Portlet; +import javax.portlet.PortletConfig; +import javax.portlet.PortletException; +import javax.portlet.PortletRequestDispatcher; +import javax.portlet.PortletSession; +import javax.portlet.RenderRequest; +import javax.portlet.RenderResponse; + +import com.itmill.toolkit.Application; + +public class ApplicationPortlet implements Portlet { + // The application to show + protected String app = null; + // some applications might require forced height (and, more seldom, width) + protected String style = null; // e.g "height:500px;" + protected String widgetset = null; + + public void destroy() { + + } + + public void init(PortletConfig config) throws PortletException { + app = config.getInitParameter("application"); + if (app == null) { + app = "PortletDemo"; + } + style = config.getInitParameter("style"); + widgetset = config.getInitParameter("widgetset"); + } + + public void processAction(ActionRequest request, ActionResponse response) + throws PortletException, IOException { + PortletApplicationContext.dispatchRequest(this, request, response); + } + + public void render(RenderRequest request, RenderResponse response) + throws PortletException, IOException { + + // display the IT Mill Toolkit application + writeAjaxWindow(request, response); + } + + protected void writeAjaxWindow(RenderRequest request, + RenderResponse response) throws IOException { + + if (app != null) { + PortletSession sess = request.getPortletSession(); + PortletApplicationContext ctx = PortletApplicationContext + .getApplicationContext(sess); + + PortletRequestDispatcher dispatcher = sess.getPortletContext() + .getRequestDispatcher("/" + app); + + try { + request.setAttribute(ApplicationServlet.REQUEST_FRAGMENT, + "true"); + if (widgetset != null) { + request.setAttribute(ApplicationServlet.REQUEST_WIDGETSET, + widgetset); + } + if (style != null) { + request.setAttribute(ApplicationServlet.REQUEST_APPSTYLE, + style); + } + dispatcher.include(request, response); + + } catch (PortletException e) { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + out.print("

Servlet include failed!

"); + out.print("
" + e + "
"); + ctx.setPortletApplication(this, null); + return; + } + + Application app = (Application) request + .getAttribute(Application.class.getName()); + ctx.setPortletApplication(this, app); + ctx.firePortletRenderRequest(this, request, response); + + } + } + +} 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 index 0000000000..4ddbabdb96 --- /dev/null +++ b/src/com/itmill/toolkit/terminal/gwt/server/PortletApplicationContext.java @@ -0,0 +1,283 @@ +/** + * + */ +package com.itmill.toolkit.terminal.gwt.server; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.PrintWriter; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +import javax.portlet.ActionRequest; +import javax.portlet.ActionResponse; +import javax.portlet.Portlet; +import javax.portlet.PortletSession; +import javax.portlet.PortletURL; +import javax.portlet.RenderRequest; +import javax.portlet.RenderResponse; +import javax.servlet.http.HttpSession; + +import com.itmill.toolkit.Application; + +/** + * @author marc + * + */ +public class PortletApplicationContext extends WebApplicationContext { + + protected PortletSession portletSession; + + protected Map portletListeners = new HashMap(); + + protected Map portletToApplication = new HashMap(); + + PortletApplicationContext() { + + } + + static public PortletApplicationContext getApplicationContext( + PortletSession session) { + WebApplicationContext cx = (WebApplicationContext) session + .getAttribute(WebApplicationContext.class.getName(), + PortletSession.APPLICATION_SCOPE); + if (cx == null) { + cx = new PortletApplicationContext(); + } + if (!(cx instanceof PortletApplicationContext)) { + // TODO Should we even try this? And should we leave original as-is? + PortletApplicationContext pcx = new PortletApplicationContext(); + pcx.applications.addAll(cx.applications); + cx.applications.clear(); + pcx.browser = cx.browser; + cx.browser = null; + pcx.listeners = cx.listeners; + cx.listeners = null; + pcx.session = cx.session; + cx = pcx; + } + if (((PortletApplicationContext) cx).portletSession == null) { + ((PortletApplicationContext) cx).portletSession = session; + } + session.setAttribute(WebApplicationContext.class.getName(), cx, + PortletSession.APPLICATION_SCOPE); + return (PortletApplicationContext) cx; + } + + static public WebApplicationContext getApplicationContext( + HttpSession session) { + WebApplicationContext cx = (WebApplicationContext) session + .getAttribute(WebApplicationContext.class.getName()); + if (cx == null) { + cx = new PortletApplicationContext(); + } + if (cx.session == null) { + cx.session = session; + } + session.setAttribute(WebApplicationContext.class.getName(), cx); + return cx; + } + + protected void removeApplication(Application application) { + portletListeners.remove(application); + for (Iterator it = portletToApplication.keySet().iterator(); it + .hasNext();) { + Object key = it.next(); + if (key == application) { + portletToApplication.remove(key); + } + } + super.removeApplication(application); + } + + public boolean equals(Object obj) { + if (portletSession == null) { + return super.equals(obj); + } + return portletSession.equals(obj); + } + + public int hashCode() { + if (portletSession == null) { + return super.hashCode(); + } + return portletSession.hashCode(); + } + + public void setPortletApplication(Portlet portlet, Application app) { + portletToApplication.put(portlet, app); + } + + public Application getPortletApplication(Portlet portlet) { + return (Application) portletToApplication.get(portlet); + } + + public PortletSession getPortletSession() { + return portletSession; + } + + public void addPortletListener(Application app, PortletListener listener) { + Set l = (Set) portletListeners.get(app); + if (l == null) { + l = new LinkedHashSet(); + portletListeners.put(app, l); + } + l.add(listener); + } + + public void removePortletListener(Application app, PortletListener listener) { + Set l = (Set) portletListeners.get(app); + if (l != null) { + l.remove(listener); + } + } + + public static void dispatchRequest(Portlet portlet, RenderRequest request, + RenderResponse response) { + PortletApplicationContext ctx = getApplicationContext(request + .getPortletSession()); + if (ctx != null) { + ctx.firePortletRenderRequest(portlet, request, response); + } + } + + public static void dispatchRequest(Portlet portlet, ActionRequest request, + ActionResponse response) { + PortletApplicationContext ctx = getApplicationContext(request + .getPortletSession()); + if (ctx != null) { + ctx.firePortletActionRequest(portlet, request, response); + } + } + + public void firePortletRenderRequest(Portlet portlet, + RenderRequest request, RenderResponse response) { + Application app = getPortletApplication(portlet); + Set listeners = (Set) portletListeners.get(app); + if (listeners != null) { + for (Iterator it = listeners.iterator(); it.hasNext();) { + PortletListener l = (PortletListener) it.next(); + l.handleRenderRequest(request, new RestrictedRenderResponse( + response)); + } + } + } + + public void firePortletActionRequest(Portlet portlet, + ActionRequest request, ActionResponse response) { + Application app = getPortletApplication(portlet); + Set listeners = (Set) portletListeners.get(app); + if (listeners != null) { + for (Iterator it = listeners.iterator(); it.hasNext();) { + PortletListener l = (PortletListener) it.next(); + l.handleActionRequest(request, response); + } + } + } + + public interface PortletListener { + public void handleRenderRequest(RenderRequest request, + RenderResponse response); + + public void handleActionRequest(ActionRequest request, + ActionResponse response); + } + + private class RestrictedRenderResponse implements RenderResponse { + + private RenderResponse response; + + private RestrictedRenderResponse(RenderResponse response) { + this.response = response; + } + + public void addProperty(String key, String value) { + response.addProperty(key, value); + } + + public PortletURL createActionURL() { + return response.createActionURL(); + } + + public PortletURL createRenderURL() { + return response.createRenderURL(); + } + + public String encodeURL(String path) { + return response.encodeURL(path); + } + + public void flushBuffer() throws IOException { + // NOP + // TODO throw? + } + + public int getBufferSize() { + return response.getBufferSize(); + } + + public String getCharacterEncoding() { + return response.getCharacterEncoding(); + } + + public String getContentType() { + return response.getContentType(); + } + + public Locale getLocale() { + return response.getLocale(); + } + + public String getNamespace() { + return response.getNamespace(); + } + + public OutputStream getPortletOutputStream() throws IOException { + // write forbidden + return null; + } + + public PrintWriter getWriter() throws IOException { + // write forbidden + return null; + } + + public boolean isCommitted() { + return response.isCommitted(); + } + + public void reset() { + // NOP + // TODO throw? + } + + public void resetBuffer() { + // NOP + // TODO throw? + } + + public void setBufferSize(int size) { + // NOP + // TODO throw? + } + + public void setContentType(String type) { + // NOP + // TODO throw? + } + + public void setProperty(String key, String value) { + response.setProperty(key, value); + } + + public void setTitle(String title) { + response.setTitle(title); + } + + } + +} diff --git a/src/com/itmill/toolkit/util/PortletConfigurationGenerator.java b/src/com/itmill/toolkit/util/PortletConfigurationGenerator.java new file mode 100644 index 0000000000..2513558719 --- /dev/null +++ b/src/com/itmill/toolkit/util/PortletConfigurationGenerator.java @@ -0,0 +1,297 @@ +/** + * + */ +package com.itmill.toolkit.util; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.nio.charset.Charset; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Generates portlet.xml, liferay-portlet.xml, liferay-display.xml from web.xml. + * Currently uses regular expressions to avoid dependencies; does not strictly + * adhere to xml rules, but should work with a 'normal' web.xml. + * + * To be included, the servlet-mapping must include a special comment: If the portlet requires some special styles (i.e height): + * + * @author marc + */ +public class PortletConfigurationGenerator { + // can be changed for debugging: + private static final String WEB_XML_FILE = "web.xml"; + private static final String PORTLET_XML_FILE = "portlet.xml"; + private static final String LIFERAY_PORTLET_XML_FILE = "liferay-portlet.xml"; + private static final String LIFERAY_DISPLAY_XML_FILE = "liferay-display.xml"; + + // "templates" follow; + private static final String PORTLET_XML_HEAD = "\n" + + "\n"; + private static final String PORTLET_XML_SECTION = " \n" + + " %PORTLETNAME%\n" + + " IT Mill Toolkit %NAME%\n" + + " com.itmill.toolkit.terminal.gwt.server.ApplicationPortlet\n" + + " \n" + + " application\n" + + " %URL%\n" + + " \n" + + " %EXTRAPARAMS%\n" + + " \n" + + " text/html\n" + + " view\n" + + " edit\n" + + " help\n" + + " \n" + + " \n" + + " %NAME%\n" + + " %NAME%\n" + + " \n" + " \n" + + " \n" + + " administrator\n" + + " \n" + + " \n" + + " guest\n" + + " \n" + + " \n" + + " power-user\n" + + " \n" + + " \n" + + " user\n" + + " \n" + " \n"; + private static final String PORTLET_XML_FOOT = " %CONTEXTPARAMS%\n" + + " \n" + + " javax.portlet.escapeXml\n" + + " false\n" + + " \n" + ""; + + private static final String LIFERAY_PORTLET_XML_HEAD = "\n" + + "\n" + + "\n" + "\n" + ""; + private static final String LIFERAY_PORTLET_XML_SECTION = " \n" + + " %PORTLETNAME%\n" + + " true \n" + + " false\n" + + " \n" + ""; + private static final String LIFERAY_PORTLET_XML_FOOT = " \n" + + " \n" + + " administrator\n" + + " Administrator\n" + + " \n" + " \n" + + " guest\n" + + " Guest\n" + + " \n" + " \n" + + " power-user\n" + + " Power User\n" + + " \n" + " \n" + + " user\n" + + " User\n" + + " \n" + " \n" + + ""; + private static final String LIFERAY_DISPLAY_XML_HEAD = "\n" + + "\n" + + "\n" + + "\n" + + " \n" + ""; + private static final String LIFERAY_DISPLAY_XML_SECTION = " \n"; + private static final String LIFERAY_DISPLAY_XML_FOOT = "\n" + + " \n" + ""; + + /** + * @param args + * + */ + public static void main(String[] args) { + if (args.length < 1 || !new File(args[0]).isDirectory()) { + System.err + .println("Usage: PortletConfigurationGenerator [widgetset]"); + return; + } + + String widgetset = ""; + if (args.length > 1) { + widgetset = "widgetset" + + args[1] + ""; + } + + /* + * Read web.xml + */ + File dir = new File(args[0]); + File webxmlFile = new File(dir.getAbsolutePath() + File.separatorChar + + WEB_XML_FILE); + String webXml = ""; + BufferedReader in = null; + try { + in = new BufferedReader(new FileReader(webxmlFile)); + String line = in.readLine(); + while (line != null) { + webXml += line; + line = in.readLine(); + } + } catch (FileNotFoundException e1) { + System.out.println(webxmlFile + " not found!"); + return; + } catch (IOException e2) { + System.out.println("IOException while reading " + webxmlFile); + webXml = null; + } + try { + if (in != null) { + in.close(); + } + } catch (IOException e1) { + System.out.println("IOException while closing " + webxmlFile); + } + if (webXml == null) { + System.out.println("Could not read web.xml!"); + return; + } + + /* + * Open outputs + */ + + // Open portlet.xml + File portletXmlFile = new File(args[0] + File.separatorChar + + PORTLET_XML_FILE); + OutputStreamWriter pout = null; + try { + pout = new OutputStreamWriter(new FileOutputStream(portletXmlFile), + Charset.forName("UTF-8")); + } catch (FileNotFoundException e) { + System.out.println(portletXmlFile + " not found!"); + } + // open liferay-portlet.xml + File liferayPortletXmlFile = new File(args[0] + File.separatorChar + + LIFERAY_PORTLET_XML_FILE); + OutputStreamWriter lpout = null; + try { + lpout = new OutputStreamWriter(new FileOutputStream( + liferayPortletXmlFile), Charset.forName("UTF-8")); + } catch (FileNotFoundException e) { + System.out.println(liferayPortletXmlFile + " not found!"); + } + // open liferay-display.xml + File liferayDisplayXmlFile = new File(args[0] + File.separatorChar + + LIFERAY_DISPLAY_XML_FILE); + OutputStreamWriter ldout = null; + try { + ldout = new OutputStreamWriter(new FileOutputStream( + liferayDisplayXmlFile), Charset.forName("UTF-8")); + } catch (FileNotFoundException e) { + System.out.println(liferayDisplayXmlFile + " not found!"); + } + + if (pout != null && lpout != null && ldout != null) { + + String pstring = PORTLET_XML_HEAD; + String lpstring = LIFERAY_PORTLET_XML_HEAD; + String ldstring = LIFERAY_DISPLAY_XML_HEAD; + + Pattern p1 = Pattern + .compile(".*?(.*?)<\\/servlet-name>.*?(.*?)<\\/url-pattern>(.*?)<\\/servlet-mapping>"); + Pattern p2 = Pattern + .compile(".*?.*?"); + Matcher m = p1.matcher(webXml); + while (m.find()) { + if (m.groupCount() < 3) { + // don't include + continue; + } + Matcher m2 = p2.matcher(m.group(3)); + if (!m2.find()) { + // don't include + continue; + } + + String style = ""; + if (m2.groupCount() == 1 && m2.group(1) != null) { + style = "style" + + m2.group(1) + ""; + } + + String name = m.group(1); + // remove leading- and trailing whitespace + name = name.replaceAll("^\\s*", ""); + name = name.replaceAll("\\s*$", ""); + String pname = name + "Portlet"; + String url = m.group(2); + // remove leading- and trailing whitespace + url = url.replaceAll("^\\s*", ""); + url = url.replaceAll("\\s*$", ""); + if (url.startsWith("/")) { + url = url.substring(1); + } + if (url.endsWith("*")) { + url = url.substring(0, url.length() - 1); + } + if (url.endsWith("/")) { + url = url.substring(0, url.length() - 1); + } + + System.out.println("Mapping " + pname + " to " + url); + + String s = PORTLET_XML_SECTION; + s = s.replaceAll("%NAME%", name); + s = s.replaceAll("%PORTLETNAME%", pname); + s = s.replaceAll("%URL%", url); + s = s.replaceAll("%EXTRAPARAMS%", style); + + pstring += s; + + s = LIFERAY_PORTLET_XML_SECTION; + s = s.replaceAll("%NAME%", name); + s = s.replaceAll("%PORTLETNAME%", pname); + s = s.replaceAll("%URL%", url); + lpstring += s; + + s = LIFERAY_DISPLAY_XML_SECTION; + s = s.replaceAll("%NAME%", name); + s = s.replaceAll("%PORTLETNAME%", pname); + s = s.replaceAll("%URL%", url); + ldstring += s; + + } + + pstring += PORTLET_XML_FOOT + .replaceAll("%CONTEXTPARAMS%", widgetset); + lpstring += LIFERAY_PORTLET_XML_FOOT; + ldstring += LIFERAY_DISPLAY_XML_FOOT; + + try { + pout.write(pstring); + lpout.write(lpstring); + ldout.write(ldstring); + } catch (IOException e) { + System.out.println("Write FAILED:" + e); + } + + } + + try { + if (pout != null) { + pout.close(); + } + if (lpout != null) { + lpout.close(); + } + if (ldout != null) { + ldout.close(); + } + } catch (IOException e) { + System.out.println("Close FAILED: " + e); + } + System.out.println("Done."); + } +}