From f2e3722df9676436680afc0f1991e91e1696fb99 Mon Sep 17 00:00:00 2001
From: Marc Englund
@@ -105,972 +112,996 @@ import java.net.URL;
*/
public abstract class Application implements URIHandler, Terminal.ErrorListener {
- /**
- * Random window name generator.
- */
- private static Random nameGenerator = new Random();
-
- /**
- * Application context the application is running in.
- */
- private ApplicationContext context;
-
- /**
- * The current user or
- * Gets a window by name. Returns
- * Since version 5.0 all windows can be referenced by their names in url
- *
- * One should note that this method can, as a side effect create new windows
- * if needed by the application. This can be achieved by overriding the
- * default implementation.
- *
- * The method should return null if the window does not exists (and is not
- * created as a side-effect) or if the application is not running anymore
- *
- * This implicitly invokes the
- * {@link com.itmill.toolkit.ui.Window#setApplication(Application)} method.
- *
- * Note that all application-level windows can be accessed by their names in
- * url
- * Sets the user of the application instance. An application instance may
- * have a user associated to it. This can be set in login procedure or
- * application initialization.
- *
- * A component performing the user login procedure can assign the user
- * property of the application and make the user object available to other
- * components of the application.
- *
- * Main initializer of the application. The
- * Note that this theme can be overridden by the windows.
- * Sets the mainWindow. If the main window is not explicitly set, the main
- * window defaults to first created window. Setting window as a main window
- * of this application also adds the window to this application.
- *
- * An event that characterizes a change in the current selection.
- *
- * Desktop application just closes the application window and
- * web-application redirects the browser to application main URL.
- *
- * Invoked by the terminal on any exception that occurs in application and
- * is thrown by the
- * You can safely override this method in your application in order to
- * direct the errors to some other destination (for example log).
- *
- * The application context is the environment where the application is
- * running in.
- *
+ * Gets a window by name. Returns
+ * Since version 5.0 all windows can be referenced by their names in url
+ *
+ * One should note that this method can, as a side effect create new windows
+ * if needed by the application. This can be achieved by overriding the
+ * default implementation.
+ *
+ * The method should return null if the window does not exists (and is not
+ * created as a side-effect) or if the application is not running anymore
+ *
+ * This implicitly invokes the
+ * {@link com.itmill.toolkit.ui.Window#setApplication(Application)} method.
+ *
+ * Note that all application-level windows can be accessed by their names in
+ * url
+ * Sets the user of the application instance. An application instance may
+ * have a user associated to it. This can be set in login procedure or
+ * application initialization.
+ *
+ * A component performing the user login procedure can assign the user
+ * property of the application and make the user object available to other
+ * components of the application.
+ *
+ * Main initializer of the application. The
+ * Note that this theme can be overridden by the windows.
+ * Sets the mainWindow. If the main window is not explicitly set, the main
+ * window defaults to first created window. Setting window as a main window
+ * of this application also adds the window to this application.
+ *
+ * An event that characterizes a change in the current selection.
+ *
+ * Desktop application just closes the application window and
+ * web-application redirects the browser to application main URL.
+ *
+ * Invoked by the terminal on any exception that occurs in application and
+ * is thrown by the
+ * You can safely override this method in your application in order to
+ * direct the errors to some other destination (for example log).
+ *
+ * The application context is the environment where the application is
+ * running in.
+ *
- * The only exception to this rule is that when the object is not in
- * write-through mode and it's buffer contains a modified value, the value
- * retrieved from the object will be the locally modified value in the
- * buffer which may differ from the value in the data source.
- *
- * The causes that do not specify error level default to
- *
+ * The only exception to this rule is that when the object is not in
+ * write-through mode and it's buffer contains a modified value, the value
+ * retrieved from the object will be the locally modified value in the
+ * buffer which may differ from the value in the data source.
+ *
+ * The causes that do not specify error level default to
+ *
- * Item is returned, and it is ready to have its Properties modified.
- * Returns
- * This functionality is optional.
- *
- * The new ID is returned, or
- * This functionality is optional.
- *
- * Note that Property ID and type information is preserved. This
- * functionality is optional.
- *
- * Adding an item after null item adds the item as first item of the
- * ordered container.
- *
- * Adding an item after null item adds the item as first item of the
- * ordered container.
- *
- * The indexes of the item currently in the given position and all the
- * following items are incremented.
- *
- * The indexes of the item currently in the given position and all the
- * following items are incremented.
- *
- * Interface for
- * Sets the parent of an Item. The new parent item must exist and be
- * able to have children. (
- *
- * This operation is optional.
- *
- * Sets the given Item's capability to have children. If the Item
- * identified with
- * The children must be first explicitly removed with
- * {@link #setParent(Object itemId, Object newParentId)}or
- * {@link com.itmill.toolkit.data.Container#removeItem(Object itemId)}.
- *
- * This operation is optional. If it is not implemented, the method
- * always returns
- * Tests if the Item specified with
- * Note that being a leaf does not imply whether or not an Item is
- * allowed to have children.
- *
- * Interface implemented by the editor classes supporting editing the
- * Container. Implementing this interface means that the Container serving
- * as the data source of the editor can be modified through it.
- *
- * Note that not implementing the
- * Note: The general Java convention is not to explicitly declare that a
- * class generates events, but to directly define the
- *
- * Note: These events are triggered only through succesful calls to the
- *
- * The interface for adding and removing
- * Note that the general Java convention is not to explicitly declare that a
- * class generates events, but to directly define the
- *
+ * Item is returned, and it is ready to have its Properties modified.
+ * Returns
+ * This functionality is optional.
+ *
+ * The new ID is returned, or
+ * This functionality is optional.
+ *
+ * Note that Property ID and type information is preserved. This
+ * functionality is optional.
+ *
+ * Adding an item after null item adds the item as first item of the
+ * ordered container.
+ *
+ * Adding an item after null item adds the item as first item of the
+ * ordered container.
+ *
+ * The indexes of the item currently in the given position and all the
+ * following items are incremented.
+ *
+ * The indexes of the item currently in the given position and all the
+ * following items are incremented.
+ *
+ * Interface for
+ * Sets the parent of an Item. The new parent item must exist and be
+ * able to have children. (
+ *
+ * This operation is optional.
+ *
+ * Sets the given Item's capability to have children. If the Item
+ * identified with
+ * The children must be first explicitly removed with
+ * {@link #setParent(Object itemId, Object newParentId)}or
+ * {@link com.itmill.toolkit.data.Container#removeItem(Object itemId)}.
+ *
+ * This operation is optional. If it is not implemented, the method
+ * always returns
+ * Tests if the Item specified with
+ * Note that being a leaf does not imply whether or not an Item is
+ * allowed to have children.
+ *
+ * Interface implemented by the editor classes supporting editing the
+ * Container. Implementing this interface means that the Container serving
+ * as the data source of the editor can be modified through it.
+ *
+ * Note that not implementing the
+ * Note: The general Java convention is not to explicitly declare that a
+ * class generates events, but to directly define the
+ *
+ * Note: These events are triggered only through succesful calls to the
+ *
+ * The interface for adding and removing
+ * Note that the general Java convention is not to explicitly declare that a
+ * class generates events, but to directly define the
+ *
- * This functionality is optional.
- *
- * This functionality is optional.
- *
- * Note : Not implementing the
- * Note: The values stored in the Properties may change without triggering
- * this event.
- *
- * Note : The general Java convention is not to explicitly declare that a
- * class generates events, but to directly define the
- *
+ * This functionality is optional.
+ *
+ * This functionality is optional.
+ *
+ * Note : Not implementing the
+ * Note: The values stored in the Properties may change without triggering
+ * this event.
+ *
+ * Note : The general Java convention is not to explicitly declare that a
+ * class generates events, but to directly define the
+ *
- * Implementing this functionality is optional. If the functionality is
- * missing, one should declare the Property to be in read-only mode and
- * throw
- * Implementing this interface means that the Property serving as the data
- * source of the editor can be modified through the editor. It does not
- * restrict the editor from editing the Property internally, though if the
- * Property is in a read-only mode, attempts to modify it will result in the
- *
- * Note : The general Java convention is not to explicitly declare that a
- * class generates events, but to directly define the
- *
- * Note : The general Java convention is not to explicitly declare that a
- * class generates events, but to directly define the
- *
+ * Implementing this functionality is optional. If the functionality is
+ * missing, one should declare the Property to be in read-only mode and
+ * throw
+ * Implementing this interface means that the Property serving as the data
+ * source of the editor can be modified through the editor. It does not
+ * restrict the editor from editing the Property internally, though if the
+ * Property is in a read-only mode, attempts to modify it will result in the
+ *
+ * Note : The general Java convention is not to explicitly declare that a
+ * class generates events, but to directly define the
+ *
+ * Note : The general Java convention is not to explicitly declare that a
+ * class generates events, but to directly define the
+ *
- * Adds a new validator for this object. The validator's
- * {@link Validator#validate(Object)} method is activated every time the
- * object's value needs to be verified, that is, when the {@link #isValid()}
- * method is called. This usually happens when the object's value changes.
- *
- * Removes a previously registered validator from the object. The specified
- * validator is removed from the object and its
- * Lists all validators currently registered for the object. If no
- * validators are registered, returns
- * Tests the current value of the object against all registered validators.
- * The registered validators are iterated and for each the
- * {@link Validator#validate(Object)} method is called. If any validator
- * throws the {@link Validator.InvalidValueException} this method returns
- *
- * Checks the validity of the validatable. If the validatable is valid this
- * method should do nothing, and if it's not valid, it should throw
- *
- * Checks the validabtable object accept invalid values.The default value is
- *
- * Should the validabtable object accept invalid values. Supporting this
- * configuration possibility is optional. By default invalid values are
- * allowed.
- *
+ * Adds a new validator for this object. The validator's
+ * {@link Validator#validate(Object)} method is activated every time the
+ * object's value needs to be verified, that is, when the {@link #isValid()}
+ * method is called. This usually happens when the object's value changes.
+ *
+ * Removes a previously registered validator from the object. The specified
+ * validator is removed from the object and its
+ * Lists all validators currently registered for the object. If no
+ * validators are registered, returns
+ * Tests the current value of the object against all registered validators.
+ * The registered validators are iterated and for each the
+ * {@link Validator#validate(Object)} method is called. If any validator
+ * throws the {@link Validator.InvalidValueException} this method returns
+ *
+ * Checks the validity of the validatable. If the validatable is valid this
+ * method should do nothing, and if it's not valid, it should throw
+ *
+ * Checks the validabtable object accept invalid values.The default value is
+ *
+ * Should the validabtable object accept invalid values. Supporting this
+ * configuration possibility is optional. By default invalid values are
+ * allowed.
+ *
- * Creates a new instance of
- * Note : This version only supports introspectable bean properties and
- * their getter and setter methods. Stand-alone
- * Creates a new instance of
- * Note : This version only supports introspectable bean properties and
- * their getter and setter methods. Stand-alone
+ * Creates a new instance of
+ * Note : This version only supports introspectable bean properties and
+ * their getter and setter methods. Stand-alone
+ * Creates a new instance of
+ * Note : This version only supports introspectable bean properties and
+ * their getter and setter methods. Stand-alone
- * Note : The Item is not removed from the underlying Container.
- *
- * Sets the given Item's capability to have children. If the Item identified
- * with the itemId already has children and the areChildrenAllowed is false
- * this method fails and
- * Sets the parent of an Item. The new parent item must exist and be able to
- * have children. (
- * Note : The Property will be removed from all Items in the Container.
- *
+ * Note : The Item is not removed from the underlying Container.
+ *
+ * Sets the given Item's capability to have children. If the Item identified
+ * with the itemId already has children and the areChildrenAllowed is false
+ * this method fails and
+ * Sets the parent of an Item. The new parent item must exist and be able to
+ * have children. (
+ * Note : The Property will be removed from all Items in the Container.
+ *
- * Note : The Item is not removed from the underlying Container.
- *
- * Note : If the contents of the wrapped container change without the
- * wrapper's knowledge, this method needs to be called to update the
- * ordering information of the Items.
- *
- * Note : The Property will be removed from all the Items in the Container.
- *
+ * Note : The Item is not removed from the underlying Container.
+ *
+ * Note : If the contents of the wrapped container change without the
+ * wrapper's knowledge, this method needs to be called to update the
+ * ordering information of the Items.
+ *
+ * Note : The Property will be removed from all the Items in the Container.
+ *
- * Note : This is meaningful only if the root really is a directory.
- *
+ * Note : This is meaningful only if the root really is a directory.
+ *
- * Sets the given Item's capability to have children. If the Item identified
- * with the itemId already has children and the areChildrenAllowed is false
- * this method fails and
- * Sets the parent of an Item. The new parent item must exist and be able to
- * have children. (
+ * Sets the given Item's capability to have children. If the Item identified
+ * with the itemId already has children and the areChildrenAllowed is false
+ * this method fails and
+ * Sets the parent of an Item. The new parent item must exist and be able to
+ * have children. (
- * Note : The Property ID and type information is preserved.
- * null
if no user has logged in.
- */
- private Object user;
-
- /**
- * Mapping from window name to window instance.
- */
- private Hashtable windows = new Hashtable();
-
- /**
- * Main window of the application.
- */
- private Window mainWindow = null;
-
- /**
- * The application's URL.
- */
- private URL applicationUrl;
-
- /**
- * Name of the theme currently used by the application.
- */
- private String theme = null;
-
- /**
- * Application status.
- */
- private boolean applicationIsRunning = false;
-
- /**
- * Application properties.
- */
- private Properties properties;
-
- /**
- * Default locale of the application.
- */
- private Locale locale;
-
- /**
- * List of listeners listening user changes.
- */
- private LinkedList userChangeListeners = null;
-
- /**
- * Window attach listeners.
- */
- private LinkedList windowAttachListeners = null;
-
- /**
- * Window detach listeners.
- */
- private LinkedList windowDetachListeners = null;
-
-
- /**
- * Application resource mapping: key <-> resource.
- */
- private Hashtable resourceKeyMap = new Hashtable();
-
- private Hashtable keyResourceMap = new Hashtable();
-
- private long lastResourceKeyNumber = 0;
-
- /**
- * URL the user is redirected to on application close or null if application
- * is just closed
- */
- private String logoutURL = null;
-
- private Focusable pendingFocus;
-
- /**
- * null
if the application is
- * not running or it does not contain a window corresponding to the name.
- * http://host:port/foo/bar/
where
- * http://host:port/foo/
is the application url as returned
- * by getURL() and bar
is the name of the window.
- * null
- */
- public Window getWindow(String name) {
-
- // For closed app, do not give any windows
- if (!isRunning())
- return null;
-
- // Gets the window by name
- Window window = (Window) windows.get(name);
-
- return window;
- }
-
- /**
- * Adds a new window to the application.
- *
- * http://host:port/foo/bar/
where
- * http://host:port/foo/
is the application url as returned
- * by getURL() and bar
is the name of the window. Also note
- * that not all windows should be added to application - one can also add
- * windows inside other windows - these windows show as smaller windows
- * inside those windows.
- * Window
to add. If the name of the
- * window is null
, an unique name is
- * automatically given for the window.
- * @throws IllegalArgumentException
- * if a window with the same name as the new window already
- * exists in the application.
- * @throws NullPointerException
- * if the given Window
is null
.
- */
- public void addWindow(Window window) throws IllegalArgumentException,
- NullPointerException {
-
- // Nulls can not be added to application
- if (window == null)
- return;
-
- // Gets the naming proposal from window
- String name = window.getName();
-
- // Checks that the application does not already contain
- // window having the same name
- if (name != null && windows.containsKey(name)) {
-
- // If the window is already added
- if (window == windows.get(name))
- return;
-
- // Otherwise complain
- throw new IllegalArgumentException("Window with name '"
- + window.getName()
- + "' is already present in the application");
- }
-
- // If the name of the window is null, the window is automatically named
- if (name == null) {
- boolean accepted = false;
- while (!accepted) {
-
- // Try another name
- name = String.valueOf(Math.abs(nameGenerator.nextInt()));
- if (!windows.containsKey(name))
- accepted = true;
- }
- window.setName(name);
- }
-
- // Adds the window to application
- windows.put(name, window);
- window.setApplication(this);
-
- fireWindowAttachEvent(window);
-
- // If no main window is set, declare the window to be main window
- if (getMainWindow() == null)
- setMainWindow(window);
- }
-
- /**
- * Send information to all listeners about new Windows associated with this
- * application.
- *
- * @param window
- */
- private void fireWindowAttachEvent(Window window) {
- // Fires the window attach event
- if (windowAttachListeners != null) {
- Object[] listeners = windowAttachListeners.toArray();
- WindowAttachEvent event = new WindowAttachEvent(window);
- for (int i = 0; i < listeners.length; i++) {
- ((WindowAttachListener) listeners[i]).windowAttached(event);
- }
- }
- }
-
- /**
- * Removes the specified window from the application.
- *
- * @param window
- * the window to be removed.
- */
- public void removeWindow(Window window) {
- if (window != null && windows.contains(window)) {
-
- // Removes the window from application
- windows.remove(window.getName());
-
- // If the window was main window, clear it
- if (getMainWindow() == window)
- setMainWindow(null);
-
- // Removes the application from window
- if (window.getApplication() == this)
- window.setApplication(null);
-
- fireWindowDetachEvent(window);
- }
- }
-
- private void fireWindowDetachEvent(Window window) {
- // Fires the window detach event
- if (windowDetachListeners != null) {
- Object[] listeners = windowDetachListeners.toArray();
- WindowDetachEvent event = new WindowDetachEvent(window);
- for (int i = 0; i < listeners.length; i++) {
- ((WindowDetachListener) listeners[i]).windowDetached(event);
- }
- }
- }
-
- /**
- * Gets the user of the application.
- *
- * @return the User of the application.
- */
- public Object getUser() {
- return user;
- }
-
- /**
- * true
if the application is running,
- * false
if not.
- */
- public boolean isRunning() {
- return applicationIsRunning;
- }
-
- /**
- * Gets the set of windows contained by the application.
- *
- * @return the Unmodifiable collection of windows.
- */
- public Collection getWindows() {
- return Collections.unmodifiableCollection(windows.values());
- }
-
- /**
- * init
method is
- * called by the framework when the application is started, and it should
- * perform whatever initialization operations the application needs, such as
- * creating windows and adding components to them.
- * null
is returned.
- *
- * @return the name of the application's theme.
- */
- public String getTheme() {
- return theme;
- }
-
- /**
- * Sets the application's theme.
- * null
- * implies the default terminal theme.
- * null
if the property is not found.
- *
- * @param name
- * the name of the property.
- * @return the value in this property list with the specified key value.
- */
- public String getProperty(String name) {
- return this.properties.getProperty(name);
- }
-
- /**
- * Adds new resource to the application. The resource can be accessed by the
- * user of the application.
- *
- * @param resource
- * the resource to add.
- */
- public void addResource(ApplicationResource resource) {
-
- // Check if the resource is already mapped
- if (resourceKeyMap.containsKey(resource))
- return;
-
- // Generate key
- String key = String.valueOf(++lastResourceKeyNumber);
-
- // Add the resource to mappings
- resourceKeyMap.put(resource, key);
- keyResourceMap.put(key, resource);
- }
-
- /**
- * Removes the resource from the application.
- *
- * @param resource
- * the resource to remove.
- */
- public void removeResource(ApplicationResource resource) {
- Object key = resourceKeyMap.get(resource);
- if (key != null) {
- resourceKeyMap.remove(resource);
- keyResourceMap.remove(key);
- }
- }
-
- /**
- * Gets the relative uri of the resource.
- *
- * @param resource
- * the resource to get relative location.
- * @return the relative uri of the resource.
- */
- public String getRelativeLocation(ApplicationResource resource) {
-
- // Gets the key
- String key = (String) resourceKeyMap.get(resource);
-
- // If the resource is not registered, return null
- if (key == null)
- return null;
-
- String filename = resource.getFilename();
- if (filename == null)
- return "APP/" + key + "/";
- else
- return "APP/" + key + "/" + filename;
- }
-
- /*
- * @see com.itmill.toolkit.terminal.URIHandler#handleURI(URL, String)
- */
- public DownloadStream handleURI(URL context, String relativeUri) {
-
- // If the relative uri is null, we are ready
- if (relativeUri == null)
- return null;
-
- // Resolves the prefix
- String prefix = relativeUri;
- int index = relativeUri.indexOf('/');
- if (index >= 0)
- prefix = relativeUri.substring(0, index);
-
- // Handles the resource requests
- if (prefix.equals("APP")) {
-
- // Handles the resource request
- int next = relativeUri.indexOf('/', index + 1);
- if (next < 0)
- return null;
- String key = relativeUri.substring(index + 1, next);
- ApplicationResource resource = (ApplicationResource) keyResourceMap
- .get(key);
- if (resource != null)
- return resource.getStream();
-
- // Resource requests override uri handling
- return null;
- }
-
- // If the uri is in some window, handle the window uri
- Window window = getWindow(prefix);
- if (window != null) {
- URL windowContext;
- try {
- windowContext = new URL(context, prefix + "/");
- String windowUri = relativeUri.length() > prefix.length() + 1 ? relativeUri
- .substring(prefix.length() + 1)
- : "";
- return window.handleURI(windowContext, windowUri);
- } catch (MalformedURLException e) {
- return null;
- }
- }
-
- // If the uri was not pointing to a window, handle the
- // uri in main window
- window = getMainWindow();
- if (window != null)
- return window.handleURI(context, relativeUri);
-
- return null;
- }
-
- /**
- * Gets the default locale for this application.
- *
- * @return the locale of this application.
- */
- public Locale getLocale() {
- if (this.locale != null)
- return this.locale;
- return Locale.getDefault();
- }
-
- /**
- * Sets the default locale for this application.
- *
- * @param locale
- * the Locale object.
- *
- */
- public void setLocale(Locale locale) {
- this.locale = locale;
- }
-
- /**
- * null
- */
- public Object getPreviousUser() {
- return prevUser;
- }
-
- /**
- * Gets the application where the user change occurred.
- *
- * @return the Application.
- */
- public Application getApplication() {
- return (Application) getSource();
- }
- }
-
- /**
- * The UserChangeListener
interface for listening application
- * user changes.
- *
- * @version
- * @VERSION@
- * @since 3.0
- */
- public interface UserChangeListener extends EventListener {
-
- /**
- * The applicationUserChanged
method Invoked when the
- * application user has changed.
- *
- * @param event
- * the change event.
- */
- public void applicationUserChanged(Application.UserChangeEvent event);
- }
-
- /**
- * Adds the user change listener.
- *
- * @param listener
- * the user change listener to add.
- */
- public void addListener(UserChangeListener listener) {
- if (userChangeListeners == null)
- userChangeListeners = new LinkedList();
- userChangeListeners.add(listener);
- }
-
- /**
- * Removes the user change listener.
- *
- * @param listener
- * the user change listener to remove.
- */
- public void removeListener(UserChangeListener listener) {
- if (userChangeListeners == null)
- return;
- userChangeListeners.remove(listener);
- if (userChangeListeners.isEmpty())
- userChangeListeners = null;
- }
-
- /**
- * Window detach event.
- */
- public class WindowDetachEvent extends EventObject {
-
- /**
- * Serial generated by eclipse.
- */
- private static final long serialVersionUID = 3544669568644691769L;
-
- private Window window;
-
- /**
- * Creates a event.
- *
- * @param window
- * the Detached window.
- */
- public WindowDetachEvent(Window window) {
- super(Application.this);
- this.window = window;
- }
-
- /**
- * Gets the detached window.
- *
- * @return the detached window.
- */
- public Window getWindow() {
- return window;
- }
-
- /**
- * Gets the application from which the window was detached.
- *
- * @return the Application.
- */
- public Application getApplication() {
- return (Application) getSource();
- }
- }
-
- /**
- * Window attach event.
- */
- public class WindowAttachEvent extends EventObject {
-
- /**
- * Serial generated by eclipse.
- */
- private static final long serialVersionUID = 3977578104367822392L;
-
- private Window window;
-
- /**
- * Creates a event.
- *
- * @param window
- * the Attached window.
- */
- public WindowAttachEvent(Window window) {
- super(Application.this);
- this.window = window;
- }
-
- /**
- * Gets the attached window.
- *
- * @return the attached window.
- */
- public Window getWindow() {
- return window;
- }
-
- /**
- * Gets the application to which the window was attached.
- *
- * @return the Application.
- */
- public Application getApplication() {
- return (Application) getSource();
- }
- }
-
- /**
- * Window attach listener interface.
- */
- public interface WindowAttachListener {
-
- /**
- * Window attached
- *
- * @param event
- * the window attach event.
- */
- public void windowAttached(WindowAttachEvent event);
- }
-
- /**
- * Window detach listener interface.
- */
- public interface WindowDetachListener {
-
- /**
- * Window detached.
- *
- * @param event
- * the window detach event.
- */
- public void windowDetached(WindowDetachEvent event);
- }
-
- /**
- * Adds the window attach listener.
- *
- * @param listener
- * the window attach listener to add.
- */
- public void addListener(WindowAttachListener listener) {
- if (windowAttachListeners == null)
- windowAttachListeners = new LinkedList();
- windowAttachListeners.add(listener);
- }
-
- /**
- * Adds the window detach listener.
- *
- * @param listener
- * the window detach listener to add.
- */
- public void addListener(WindowDetachListener listener) {
- if (windowDetachListeners == null)
- windowDetachListeners = new LinkedList();
- windowDetachListeners.add(listener);
- }
-
- /**
- * Removes the window attach listener.
- *
- * @param listener
- * the window attach listener to remove.
- */
- public void removeListener(WindowAttachListener listener) {
- if (windowAttachListeners != null) {
- windowAttachListeners.remove(listener);
- if (windowAttachListeners.isEmpty())
- windowAttachListeners = null;
- }
- }
-
- /**
- * Removes the window detach listener.
- *
- * @param listener
- * the window detach listener to remove.
- */
- public void removeListener(WindowDetachListener listener) {
- if (windowDetachListeners != null) {
- windowDetachListeners.remove(listener);
- if (windowDetachListeners.isEmpty())
- windowDetachListeners = null;
- }
- }
-
- /**
- * Returns the URL user is redirected to on application close.If the URL is
- * null
, the application is closed normally as defined by
- * the application running environment.
- * null
, the application is closed normally as defined by
- * the application running environment: Desktop application just closes the
- * application window and web-application redirects the browser to
- * application main URL.
- *
- * @param logoutURL
- * the logoutURL to set.
- */
- public void setLogoutURL(String logoutURL) {
- this.logoutURL = logoutURL;
- }
-
- /**
- * setVariable
to the terminal. The default
- * implementation sets the exceptions as ComponentErrors
to
- * the component that initiated the exception.
- * null
if no user has logged in.
+ */
+ private Object user;
+
+ /**
+ * Mapping from window name to window instance.
+ */
+ private Hashtable windows = new Hashtable();
+
+ /**
+ * Main window of the application.
+ */
+ private Window mainWindow = null;
+
+ /**
+ * The application's URL.
+ */
+ private URL applicationUrl;
+
+ /**
+ * Name of the theme currently used by the application.
+ */
+ private String theme = null;
+
+ /**
+ * Application status.
+ */
+ private boolean applicationIsRunning = false;
+
+ /**
+ * Application properties.
+ */
+ private Properties properties;
+
+ /**
+ * Default locale of the application.
+ */
+ private Locale locale;
+
+ /**
+ * List of listeners listening user changes.
+ */
+ private LinkedList userChangeListeners = null;
+
+ /**
+ * Window attach listeners.
+ */
+ private LinkedList windowAttachListeners = null;
+
+ /**
+ * Window detach listeners.
+ */
+ private LinkedList windowDetachListeners = null;
+
+ /**
+ * Application resource mapping: key <-> resource.
+ */
+ private Hashtable resourceKeyMap = new Hashtable();
+
+ private Hashtable keyResourceMap = new Hashtable();
+
+ private long lastResourceKeyNumber = 0;
+
+ /**
+ * URL the user is redirected to on application close or null if application
+ * is just closed
+ */
+ private String logoutURL = null;
+
+ private Focusable pendingFocus;
+
+ /**
+ * null
if the application is
+ * not running or it does not contain a window corresponding to the name.
+ * http://host:port/foo/bar/
where
+ * http://host:port/foo/
is the application url as returned
+ * by getURL() and bar
is the name of the window.
+ * null
+ */
+ public Window getWindow(String name) {
+
+ // For closed app, do not give any windows
+ if (!isRunning()) {
+ return null;
+ }
+
+ // Gets the window by name
+ Window window = (Window) windows.get(name);
+
+ return window;
+ }
+
+ /**
+ * Adds a new window to the application.
+ *
+ * http://host:port/foo/bar/
where
+ * http://host:port/foo/
is the application url as returned
+ * by getURL() and bar
is the name of the window. Also note
+ * that not all windows should be added to application - one can also add
+ * windows inside other windows - these windows show as smaller windows
+ * inside those windows.
+ * Window
to add. If the name of the
+ * window is null
, an unique name is
+ * automatically given for the window.
+ * @throws IllegalArgumentException
+ * if a window with the same name as the new window already
+ * exists in the application.
+ * @throws NullPointerException
+ * if the given Window
is null
.
+ */
+ public void addWindow(Window window) throws IllegalArgumentException,
+ NullPointerException {
+
+ // Nulls can not be added to application
+ if (window == null) {
+ return;
+ }
+
+ // Gets the naming proposal from window
+ String name = window.getName();
+
+ // Checks that the application does not already contain
+ // window having the same name
+ if (name != null && windows.containsKey(name)) {
+
+ // If the window is already added
+ if (window == windows.get(name)) {
+ return;
+ }
+
+ // Otherwise complain
+ throw new IllegalArgumentException("Window with name '"
+ + window.getName()
+ + "' is already present in the application");
+ }
+
+ // If the name of the window is null, the window is automatically named
+ if (name == null) {
+ boolean accepted = false;
+ while (!accepted) {
+
+ // Try another name
+ name = String.valueOf(Math.abs(nameGenerator.nextInt()));
+ if (!windows.containsKey(name)) {
+ accepted = true;
+ }
+ }
+ window.setName(name);
+ }
+
+ // Adds the window to application
+ windows.put(name, window);
+ window.setApplication(this);
+
+ fireWindowAttachEvent(window);
+
+ // If no main window is set, declare the window to be main window
+ if (getMainWindow() == null) {
+ setMainWindow(window);
+ }
+ }
+
+ /**
+ * Send information to all listeners about new Windows associated with this
+ * application.
+ *
+ * @param window
+ */
+ private void fireWindowAttachEvent(Window window) {
+ // Fires the window attach event
+ if (windowAttachListeners != null) {
+ Object[] listeners = windowAttachListeners.toArray();
+ WindowAttachEvent event = new WindowAttachEvent(window);
+ for (int i = 0; i < listeners.length; i++) {
+ ((WindowAttachListener) listeners[i]).windowAttached(event);
+ }
+ }
+ }
+
+ /**
+ * Removes the specified window from the application.
+ *
+ * @param window
+ * the window to be removed.
+ */
+ public void removeWindow(Window window) {
+ if (window != null && windows.contains(window)) {
+
+ // Removes the window from application
+ windows.remove(window.getName());
+
+ // If the window was main window, clear it
+ if (getMainWindow() == window) {
+ setMainWindow(null);
+ }
+
+ // Removes the application from window
+ if (window.getApplication() == this) {
+ window.setApplication(null);
+ }
+
+ fireWindowDetachEvent(window);
+ }
+ }
+
+ private void fireWindowDetachEvent(Window window) {
+ // Fires the window detach event
+ if (windowDetachListeners != null) {
+ Object[] listeners = windowDetachListeners.toArray();
+ WindowDetachEvent event = new WindowDetachEvent(window);
+ for (int i = 0; i < listeners.length; i++) {
+ ((WindowDetachListener) listeners[i]).windowDetached(event);
+ }
+ }
+ }
+
+ /**
+ * Gets the user of the application.
+ *
+ * @return the User of the application.
+ */
+ public Object getUser() {
+ return user;
+ }
+
+ /**
+ * true
if the application is running,
+ * false
if not.
+ */
+ public boolean isRunning() {
+ return applicationIsRunning;
+ }
+
+ /**
+ * Gets the set of windows contained by the application.
+ *
+ * @return the Unmodifiable collection of windows.
+ */
+ public Collection getWindows() {
+ return Collections.unmodifiableCollection(windows.values());
+ }
+
+ /**
+ * init
method is
+ * called by the framework when the application is started, and it should
+ * perform whatever initialization operations the application needs, such as
+ * creating windows and adding components to them.
+ * null
is returned.
+ *
+ * @return the name of the application's theme.
+ */
+ public String getTheme() {
+ return theme;
+ }
+
+ /**
+ * Sets the application's theme.
+ * null
+ * implies the default terminal theme.
+ * null
if the property is not found.
+ *
+ * @param name
+ * the name of the property.
+ * @return the value in this property list with the specified key value.
+ */
+ public String getProperty(String name) {
+ return properties.getProperty(name);
+ }
+
+ /**
+ * Adds new resource to the application. The resource can be accessed by the
+ * user of the application.
+ *
+ * @param resource
+ * the resource to add.
+ */
+ public void addResource(ApplicationResource resource) {
+
+ // Check if the resource is already mapped
+ if (resourceKeyMap.containsKey(resource)) {
+ return;
+ }
+
+ // Generate key
+ String key = String.valueOf(++lastResourceKeyNumber);
+
+ // Add the resource to mappings
+ resourceKeyMap.put(resource, key);
+ keyResourceMap.put(key, resource);
+ }
+
+ /**
+ * Removes the resource from the application.
+ *
+ * @param resource
+ * the resource to remove.
+ */
+ public void removeResource(ApplicationResource resource) {
+ Object key = resourceKeyMap.get(resource);
+ if (key != null) {
+ resourceKeyMap.remove(resource);
+ keyResourceMap.remove(key);
+ }
+ }
+
+ /**
+ * Gets the relative uri of the resource.
+ *
+ * @param resource
+ * the resource to get relative location.
+ * @return the relative uri of the resource.
+ */
+ public String getRelativeLocation(ApplicationResource resource) {
+
+ // Gets the key
+ String key = (String) resourceKeyMap.get(resource);
+
+ // If the resource is not registered, return null
+ if (key == null) {
+ return null;
+ }
+
+ String filename = resource.getFilename();
+ if (filename == null) {
+ return "APP/" + key + "/";
+ } else {
+ return "APP/" + key + "/" + filename;
+ }
+ }
+
+ /*
+ * @see com.itmill.toolkit.terminal.URIHandler#handleURI(URL, String)
+ */
+ public DownloadStream handleURI(URL context, String relativeUri) {
+
+ // If the relative uri is null, we are ready
+ if (relativeUri == null) {
+ return null;
+ }
+
+ // Resolves the prefix
+ String prefix = relativeUri;
+ int index = relativeUri.indexOf('/');
+ if (index >= 0) {
+ prefix = relativeUri.substring(0, index);
+ }
+
+ // Handles the resource requests
+ if (prefix.equals("APP")) {
+
+ // Handles the resource request
+ int next = relativeUri.indexOf('/', index + 1);
+ if (next < 0) {
+ return null;
+ }
+ String key = relativeUri.substring(index + 1, next);
+ ApplicationResource resource = (ApplicationResource) keyResourceMap
+ .get(key);
+ if (resource != null) {
+ return resource.getStream();
+ }
+
+ // Resource requests override uri handling
+ return null;
+ }
+
+ // If the uri is in some window, handle the window uri
+ Window window = getWindow(prefix);
+ if (window != null) {
+ URL windowContext;
+ try {
+ windowContext = new URL(context, prefix + "/");
+ String windowUri = relativeUri.length() > prefix.length() + 1 ? relativeUri
+ .substring(prefix.length() + 1)
+ : "";
+ return window.handleURI(windowContext, windowUri);
+ } catch (MalformedURLException e) {
+ return null;
+ }
+ }
+
+ // If the uri was not pointing to a window, handle the
+ // uri in main window
+ window = getMainWindow();
+ if (window != null) {
+ return window.handleURI(context, relativeUri);
+ }
+
+ return null;
+ }
+
+ /**
+ * Gets the default locale for this application.
+ *
+ * @return the locale of this application.
+ */
+ public Locale getLocale() {
+ if (locale != null) {
+ return locale;
+ }
+ return Locale.getDefault();
+ }
+
+ /**
+ * Sets the default locale for this application.
+ *
+ * @param locale
+ * the Locale object.
+ *
+ */
+ public void setLocale(Locale locale) {
+ this.locale = locale;
+ }
+
+ /**
+ * null
+ */
+ public Object getPreviousUser() {
+ return prevUser;
+ }
+
+ /**
+ * Gets the application where the user change occurred.
+ *
+ * @return the Application.
+ */
+ public Application getApplication() {
+ return (Application) getSource();
+ }
+ }
+
+ /**
+ * The UserChangeListener
interface for listening application
+ * user changes.
+ *
+ * @version
+ * @VERSION@
+ * @since 3.0
+ */
+ public interface UserChangeListener extends EventListener {
+
+ /**
+ * The applicationUserChanged
method Invoked when the
+ * application user has changed.
+ *
+ * @param event
+ * the change event.
+ */
+ public void applicationUserChanged(Application.UserChangeEvent event);
+ }
+
+ /**
+ * Adds the user change listener.
+ *
+ * @param listener
+ * the user change listener to add.
+ */
+ public void addListener(UserChangeListener listener) {
+ if (userChangeListeners == null) {
+ userChangeListeners = new LinkedList();
+ }
+ userChangeListeners.add(listener);
+ }
+
+ /**
+ * Removes the user change listener.
+ *
+ * @param listener
+ * the user change listener to remove.
+ */
+ public void removeListener(UserChangeListener listener) {
+ if (userChangeListeners == null) {
+ return;
+ }
+ userChangeListeners.remove(listener);
+ if (userChangeListeners.isEmpty()) {
+ userChangeListeners = null;
+ }
+ }
+
+ /**
+ * Window detach event.
+ */
+ public class WindowDetachEvent extends EventObject {
+
+ /**
+ * Serial generated by eclipse.
+ */
+ private static final long serialVersionUID = 3544669568644691769L;
+
+ private Window window;
+
+ /**
+ * Creates a event.
+ *
+ * @param window
+ * the Detached window.
+ */
+ public WindowDetachEvent(Window window) {
+ super(Application.this);
+ this.window = window;
+ }
+
+ /**
+ * Gets the detached window.
+ *
+ * @return the detached window.
+ */
+ public Window getWindow() {
+ return window;
+ }
+
+ /**
+ * Gets the application from which the window was detached.
+ *
+ * @return the Application.
+ */
+ public Application getApplication() {
+ return (Application) getSource();
+ }
+ }
+
+ /**
+ * Window attach event.
+ */
+ public class WindowAttachEvent extends EventObject {
+
+ /**
+ * Serial generated by eclipse.
+ */
+ private static final long serialVersionUID = 3977578104367822392L;
+
+ private Window window;
+
+ /**
+ * Creates a event.
+ *
+ * @param window
+ * the Attached window.
+ */
+ public WindowAttachEvent(Window window) {
+ super(Application.this);
+ this.window = window;
+ }
+
+ /**
+ * Gets the attached window.
+ *
+ * @return the attached window.
+ */
+ public Window getWindow() {
+ return window;
+ }
+
+ /**
+ * Gets the application to which the window was attached.
+ *
+ * @return the Application.
+ */
+ public Application getApplication() {
+ return (Application) getSource();
+ }
+ }
+
+ /**
+ * Window attach listener interface.
+ */
+ public interface WindowAttachListener {
+
+ /**
+ * Window attached
+ *
+ * @param event
+ * the window attach event.
+ */
+ public void windowAttached(WindowAttachEvent event);
+ }
+
+ /**
+ * Window detach listener interface.
+ */
+ public interface WindowDetachListener {
+
+ /**
+ * Window detached.
+ *
+ * @param event
+ * the window detach event.
+ */
+ public void windowDetached(WindowDetachEvent event);
+ }
+
+ /**
+ * Adds the window attach listener.
+ *
+ * @param listener
+ * the window attach listener to add.
+ */
+ public void addListener(WindowAttachListener listener) {
+ if (windowAttachListeners == null) {
+ windowAttachListeners = new LinkedList();
+ }
+ windowAttachListeners.add(listener);
+ }
+
+ /**
+ * Adds the window detach listener.
+ *
+ * @param listener
+ * the window detach listener to add.
+ */
+ public void addListener(WindowDetachListener listener) {
+ if (windowDetachListeners == null) {
+ windowDetachListeners = new LinkedList();
+ }
+ windowDetachListeners.add(listener);
+ }
+
+ /**
+ * Removes the window attach listener.
+ *
+ * @param listener
+ * the window attach listener to remove.
+ */
+ public void removeListener(WindowAttachListener listener) {
+ if (windowAttachListeners != null) {
+ windowAttachListeners.remove(listener);
+ if (windowAttachListeners.isEmpty()) {
+ windowAttachListeners = null;
+ }
+ }
+ }
+
+ /**
+ * Removes the window detach listener.
+ *
+ * @param listener
+ * the window detach listener to remove.
+ */
+ public void removeListener(WindowDetachListener listener) {
+ if (windowDetachListeners != null) {
+ windowDetachListeners.remove(listener);
+ if (windowDetachListeners.isEmpty()) {
+ windowDetachListeners = null;
+ }
+ }
+ }
+
+ /**
+ * Returns the URL user is redirected to on application close.If the URL is
+ * null
, the application is closed normally as defined by
+ * the application running environment.
+ * null
, the application is closed normally as defined by
+ * the application running environment: Desktop application just closes the
+ * application window and web-application redirects the browser to
+ * application main URL.
+ *
+ * @param logoutURL
+ * the logoutURL to set.
+ */
+ public void setLogoutURL(String logoutURL) {
+ this.logoutURL = logoutURL;
+ }
+
+ /**
+ * setVariable
to the terminal. The default
+ * implementation sets the exceptions as ComponentErrors
to
+ * the component that initiated the exception.
+ * commit
is called.
- *
- * @throws SourceException
- * if the operation fails because of an exception is thrown by
- * the data source. The cause is included in the exception.
- */
- public void commit() throws SourceException;
-
- /**
- * Discards all changes since last commit. The object updates its value from
- * the data source.
- *
- * @throws SourceException
- * if the operation fails because of an exception is thrown by
- * the data source. The cause is included in the exception.
- */
- public void discard() throws SourceException;
-
- /**
- * Tests if the object is in write-through mode. If the object is in
- * write-through mode, all modifications to it will result in
- * commit
being called after the modification.
- *
- * @return true
if the object is in write-through mode,
- * false
if it's not.
- */
- public boolean isWriteThrough();
-
- /**
- * Sets the object's write-through mode to the specified status. When
- * switching the write-through mode on, the commit
operation
- * will be performed.
- *
- * @param writeThrough
- * Boolean value to indicate if the object should be in
- * write-through mode after the call.
- * @throws SourceException
- * If the operation fails because of an exception is thrown by
- * the data source.
- *
- */
- public void setWriteThrough(boolean writeThrough) throws SourceException;
-
- /**
- * Tests if the object is in read-through mode. If the object is in
- * read-through mode, retrieving its value will result in the value being
- * first updated from the data source to the object.
- * true
if the object is in read-through mode,
- * false
if it's not.
- */
- public boolean isReadThrough();
-
- /**
- * Sets the object's read-through mode to the specified status. When
- * switching read-through mode on, the object's value is updated from the
- * data source.
- *
- * @param readThrough
- * Boolean value to indicate if the object should be in
- * read-through mode after the call.
- *
- * @throws SourceException
- * If the operation fails because of an exception is thrown by
- * the data source. The cause is included in the exception.
- */
- public void setReadThrough(boolean readThrough) throws SourceException;
-
- /**
- * Tests if the value stored in the object has been modified since it was
- * last updated from the data source.
- *
- * @return true
if the value in the object has been modified
- * since the last data source update, false
if not.
- */
- public boolean isModified();
-
- /**
- * An exception that signals that one or more exceptions occurred while a
- * buffered object tried to access its data source or if there is a problem
- * in processing a data source.
- *
- * @author IT Mill Ltd.
- * @version
- * @VERSION@
- * @since 3.0
- */
- public class SourceException extends RuntimeException implements
- ErrorMessage {
-
- /**
- * Serial generated by eclipse.
- */
- private static final long serialVersionUID = 3256720671781630518L;
-
- /** Source class implementing the buffered interface */
- private Buffered source;
-
- /** Original cause of the source exception */
- private Throwable[] causes = {};
-
- /**
- * Creates a source exception that does not include a cause.
- *
- * @param source
- * the source object implementing the Buffered interface.
- */
- public SourceException(Buffered source) {
- this.source = source;
- }
-
- /**
- * Creates a source exception from a cause exception.
- *
- * @param source
- * the source object implementing the Buffered interface.
- * @param cause
- * the original cause for this exception.
- */
- public SourceException(Buffered source, Throwable cause) {
- this.source = source;
- causes = new Throwable[] { cause };
- }
-
- /**
- * Creates a source exception from multiple causes.
- *
- * @param source
- * the source object implementing the Buffered interface.
- * @param causes
- * the original causes for this exception.
- */
- public SourceException(Buffered source, Throwable[] causes) {
- this.source = source;
- this.causes = causes;
- }
-
- /**
- * Gets the cause of the exception.
- *
- * @return The cause for the exception.
- * @throws MoreThanOneCauseException
- * if there is more than one cause for the exception. This
- * is possible if the commit operation triggers more than
- * one error at the same time.
- */
- public final Throwable getCause() {
- if (causes.length == 0)
- return null;
- return causes[0];
- }
-
- /**
- * Gets all the causes for this exception.
- *
- * @return throwables that caused this exception
- */
- public final Throwable[] getCauses() {
- return causes;
- }
-
- /**
- * Gets a source of the exception.
- *
- * @return the Buffered object which generated this exception.
- */
- public Buffered getSource() {
- return source;
- }
-
- /**
- * Gets the error level of this buffered source exception. The level of
- * the exception is maximum error level of all the contained causes.
- * ERROR
level. Also source exception without any causes
- * are of level ERROR
.
- * commit
is called.
+ *
+ * @throws SourceException
+ * if the operation fails because of an exception is thrown
+ * by the data source. The cause is included in the
+ * exception.
+ */
+ public void commit() throws SourceException;
+
+ /**
+ * Discards all changes since last commit. The object updates its value from
+ * the data source.
+ *
+ * @throws SourceException
+ * if the operation fails because of an exception is thrown
+ * by the data source. The cause is included in the
+ * exception.
+ */
+ public void discard() throws SourceException;
+
+ /**
+ * Tests if the object is in write-through mode. If the object is in
+ * write-through mode, all modifications to it will result in
+ * commit
being called after the modification.
+ *
+ * @return true
if the object is in write-through mode,
+ * false
if it's not.
+ */
+ public boolean isWriteThrough();
+
+ /**
+ * Sets the object's write-through mode to the specified status. When
+ * switching the write-through mode on, the commit
operation
+ * will be performed.
+ *
+ * @param writeThrough
+ * Boolean value to indicate if the object should be in
+ * write-through mode after the call.
+ * @throws SourceException
+ * If the operation fails because of an exception is thrown
+ * by the data source.
+ *
+ */
+ public void setWriteThrough(boolean writeThrough) throws SourceException;
+
+ /**
+ * Tests if the object is in read-through mode. If the object is in
+ * read-through mode, retrieving its value will result in the value being
+ * first updated from the data source to the object.
+ * true
if the object is in read-through mode,
+ * false
if it's not.
+ */
+ public boolean isReadThrough();
+
+ /**
+ * Sets the object's read-through mode to the specified status. When
+ * switching read-through mode on, the object's value is updated from the
+ * data source.
+ *
+ * @param readThrough
+ * Boolean value to indicate if the object should be in
+ * read-through mode after the call.
+ *
+ * @throws SourceException
+ * If the operation fails because of an exception is thrown
+ * by the data source. The cause is included in the
+ * exception.
+ */
+ public void setReadThrough(boolean readThrough) throws SourceException;
+
+ /**
+ * Tests if the value stored in the object has been modified since it was
+ * last updated from the data source.
+ *
+ * @return true
if the value in the object has been modified
+ * since the last data source update, false
if not.
+ */
+ public boolean isModified();
+
+ /**
+ * An exception that signals that one or more exceptions occurred while a
+ * buffered object tried to access its data source or if there is a problem
+ * in processing a data source.
+ *
+ * @author IT Mill Ltd.
+ * @version
+ * @VERSION@
+ * @since 3.0
+ */
+ public class SourceException extends RuntimeException implements
+ ErrorMessage {
+
+ /**
+ * Serial generated by eclipse.
+ */
+ private static final long serialVersionUID = 3256720671781630518L;
+
+ /** Source class implementing the buffered interface */
+ private Buffered source;
+
+ /** Original cause of the source exception */
+ private Throwable[] causes = {};
+
+ /**
+ * Creates a source exception that does not include a cause.
+ *
+ * @param source
+ * the source object implementing the Buffered interface.
+ */
+ public SourceException(Buffered source) {
+ this.source = source;
+ }
+
+ /**
+ * Creates a source exception from a cause exception.
+ *
+ * @param source
+ * the source object implementing the Buffered interface.
+ * @param cause
+ * the original cause for this exception.
+ */
+ public SourceException(Buffered source, Throwable cause) {
+ this.source = source;
+ causes = new Throwable[] { cause };
+ }
+
+ /**
+ * Creates a source exception from multiple causes.
+ *
+ * @param source
+ * the source object implementing the Buffered interface.
+ * @param causes
+ * the original causes for this exception.
+ */
+ public SourceException(Buffered source, Throwable[] causes) {
+ this.source = source;
+ this.causes = causes;
+ }
+
+ /**
+ * Gets the cause of the exception.
+ *
+ * @return The cause for the exception.
+ * @throws MoreThanOneCauseException
+ * if there is more than one cause for the exception.
+ * This is possible if the commit operation triggers
+ * more than one error at the same time.
+ */
+ public final Throwable getCause() {
+ if (causes.length == 0) {
+ return null;
+ }
+ return causes[0];
+ }
+
+ /**
+ * Gets all the causes for this exception.
+ *
+ * @return throwables that caused this exception
+ */
+ public final Throwable[] getCauses() {
+ return causes;
+ }
+
+ /**
+ * Gets a source of the exception.
+ *
+ * @return the Buffered object which generated this exception.
+ */
+ public Buffered getSource() {
+ return source;
+ }
+
+ /**
+ * Gets the error level of this buffered source exception. The level of
+ * the exception is maximum error level of all the contained causes.
+ * ERROR
level. Also source exception without any causes
+ * are of level ERROR
.
+ * false
.
- */
- public boolean isInvalidCommitted();
-
- /**
- * Sets if the invalid data should be committed to datasource. The default
- * is false
.
- */
- public void setInvalidCommitted(boolean isCommitted);
+ /**
+ * Tests if the invalid data is committed to datasource. The default is
+ * false
.
+ */
+ public boolean isInvalidCommitted();
+
+ /**
+ * Sets if the invalid data should be committed to datasource. The default
+ * is false
.
+ */
+ public void setInvalidCommitted(boolean isCommitted);
}
diff --git a/src/com/itmill/toolkit/data/Container.java b/src/com/itmill/toolkit/data/Container.java
index 5d2ff27b57..d57ae6af30 100644
--- a/src/com/itmill/toolkit/data/Container.java
+++ b/src/com/itmill/toolkit/data/Container.java
@@ -75,704 +75,714 @@ import java.util.Collection;
*/
public interface Container {
- /**
- * Gets the Item with the given Item ID from the Container. If the Container
- * does not contain the requested Item, null
is returned.
- *
- * @param itemId
- * ID of the Item to retrieve
- * @return the Item with the given ID or null
if the Item is
- * not found in the Container
- */
- public Item getItem(Object itemId);
-
- /**
- * Gets the ID's of all Properties stored in the Container. The ID's are
- * returned as a unmodifiable collection.
- *
- * @return unmodifiable collection of Property IDs
- */
- public Collection getContainerPropertyIds();
-
- /**
- * Gets the ID's of all Items stored in the Container. The ID's are returned
- * as a unmodifiable collection.
- *
- * @return unmodifiable collection of Item IDs
- */
- public Collection getItemIds();
-
- /**
- * Gets the Property identified by the given itemId and propertyId from the
- * Container. If the Container does not contain the Property,
- * null
is returned.
- *
- * @param itemId
- * ID of the Item which contains the Property
- * @param propertyId
- * ID of the Property to retrieve
- * @return Property with the given ID or null
- */
- public Property getContainerProperty(Object itemId, Object propertyId);
-
- /**
- * Gets the data type of all Properties identified by the given Property ID.
- *
- * @param propertyId
- * ID identifying the Properties
- * @return data type of the Properties
- */
- public Class getType(Object propertyId);
-
- /**
- * Gets the number of Items in the Container.
- *
- * @return number of Items in the Container
- */
- public int size();
-
- /**
- * Tests if the Container contains the specified Item
- *
- * @param itemId
- * ID the of Item to be tested
- * @return boolean indicating if the Container holds the specified Item
- */
- public boolean containsId(Object itemId);
-
- /**
- * Creates a new Item with the given ID into the Container. The new
- * null
if the operation fails or the Container
- * already contains a Item with the given ID.
- * null
in case of a failure
- */
- public Item addItem(Object itemId) throws UnsupportedOperationException;
-
- /**
- * Creates a new Item into the Container, and assign it an automatic ID.
- *
- * null
if the operation fails.
- * After a successful call you can use the
- * {@link #getItem(Object ItemId) getItem
}method to fetch the
- * Item.
- * null
in case of a
- * failure
- */
- public Object addItem() throws UnsupportedOperationException;
-
- /**
- * Removes the Item identified by ItemId
from the Container.
- * This functionality is optional.
- *
- * @param itemId
- * ID of the Item to remove
- * @return true
if the operation succeeded,
- * false
if not
- */
- public boolean removeItem(Object itemId)
- throws UnsupportedOperationException;
-
- /**
- * Adds a new Property to all Items in the Container. The Property ID, data
- * type and default value of the new Property are given as parameters.
- *
- * This functionality is optional.
- *
- * @param propertyId
- * ID of the Property
- * @param type
- * Data type of the new Property
- * @param defaultValue
- * The value all created Properties are initialized to
- * @return true
if the operation succeeded,
- * false
if not
- */
- public boolean addContainerProperty(Object propertyId, Class type,
- Object defaultValue) throws UnsupportedOperationException;
-
- /**
- * Removes a Property specified by the given Property ID from the Container.
- * Note that the Property will be removed from all Items in the Container.
- *
- * This functionality is optional.
- *
- * @param propertyId
- * ID of the Property to remove
- * @return true
if the operation succeeded,
- * false
if not
- */
- public boolean removeContainerProperty(Object propertyId)
- throws UnsupportedOperationException;
-
- /**
- * Removes all Items from the Container.
- *
- * true
if the operation succeeded,
- * false
if not
- */
- public boolean removeAllItems() throws UnsupportedOperationException;
-
- /**
- * Interface for Container classes whose Items can be traversed in order.
- */
- public interface Ordered extends Container {
-
- /**
- * Gets the ID of the Item following the Item that corresponds to
- * itemId
. If the given Item is the last or not found in
- * the Container, null
is returned.
- *
- * @param itemId
- * ID of an Item in the Container
- * @return ID of the next Item or null
- */
- public Object nextItemId(Object itemId);
-
- /**
- * Gets the ID of the Item preceding the Item that corresponds to
- * itemId
. If the given Item is the first or not found
- * in the Container, null
is returned.
- *
- * @param itemId
- * ID of an Item in the Container
- * @return ID of the previous Item or null
- */
- public Object prevItemId(Object itemId);
-
- /**
- * Gets the ID of the first Item in the Container.
- *
- * @return ID of the first Item in the Container
- */
- public Object firstItemId();
-
- /**
- * Gets the ID of the last Item in the Container..
- *
- * @return ID of the last Item in the Container
- */
- public Object lastItemId();
-
- /**
- * Tests if the Item corresponding to the given Item ID is the first
- * Item in the Container.
- *
- * @param itemId
- * ID of an Item in the Container
- * @return true
if the Item is first in the Container,
- * false
if not
- */
- public boolean isFirstId(Object itemId);
-
- /**
- * Tests if the Item corresponding to the given Item ID is the last Item
- * in the Container.
- *
- * @return true
if the Item is last in the Container,
- * false
if not
- */
- public boolean isLastId(Object itemId);
-
- /**
- * Adds new item after the given item.
- * getSortableContainerPropertyIds
- * @param ascending
- * Array of sorting order flags corresponding to each
- * property ID used in sorting. If this array is shorter than
- * propertyId array, ascending order is assumed for items
- * where the order is not specified. Use true
- * to sort in ascending order, false
to use
- * descending order.
- */
- void sort(Object[] propertyId, boolean[] ascending);
-
- /**
- * Gets the container property IDs, which can be used to sort the item.
- *
- * @return The sortable field ids.
- */
- Collection getSortableContainerPropertyIds();
-
- }
-
- /** Interface for Container classes whose Items can be indexed. */
- public interface Indexed extends Ordered {
-
- /**
- * Gets the index of the Item corresponding to the itemId. The following
- * is true
for the returned index: 0 <= index < size().
- *
- * @param itemId
- * ID of an Item in the Container
- * @return index of the Item, or -1 if the Container does not include
- * the Item
- */
- public int indexOfId(Object itemId);
-
- /**
- * Gets the ID of an Item by an index number.
- *
- * @param index
- * Index of the requested id in the Container
- * @return ID of the Item in the given index
- */
- public Object getIdByIndex(int index);
-
- /**
- * Adds new item at given index.
- * Container
classes whose Items can be
- * arranged hierarchically. This means that the Items in the container
- * belong in a tree-like structure, with the following quirks:
- *
- *
- */
- public interface Hierarchical extends Container {
-
- /**
- * Gets the IDs of all Items that are children of the specified Item.
- * The returned collection is unmodifiable.
- *
- * @param itemId
- * ID of the Item whose children the caller is interested in
- * @return An unmodifiable {@link java.util.Collection collection}
- * containing the IDs of all other Items that are children in
- * the container hierarchy
- */
- public Collection getChildren(Object itemId);
-
- /**
- * Gets the ID of the parent Item of the specified Item.
- *
- * @param itemId
- * ID of the Item whose parent the caller wishes to find out.
- * @return the ID of the parent Item. Will be null
if the
- * specified Item is a root element.
- */
- public Object getParent(Object itemId);
-
- /**
- * Gets the IDs of all Items in the container that don't have a parent.
- * Such items are called root
Items. The returned
- * collection is unmodifiable.
- *
- * @return An unmodifiable {@link java.util.Collection collection}
- * containing IDs of all root elements of the container
- */
- public Collection rootItemIds();
-
- /**
- * canHaveChildren(newParentId) == true
). It is also
- * possible to detach a node from the hierarchy (and thus make it root)
- * by setting the parent null
.
- * newParentId
- * @param newParentId
- * ID of the Item that's to be the new parent of the Item
- * identified with itemId
- * @return true
if the operation succeeded,
- * false
if not
- */
- public boolean setParent(Object itemId, Object newParentId)
- throws UnsupportedOperationException;
-
- /**
- * Tests if the Item with given ID can have any children. If the
- * Container also implements the Managed
interface, the
- * items created with newItem
can have children by
- * default.
- *
- * @param itemId
- * ID of the Item in the container whose child capability is
- * to be tested
- * @return true
if the specified Item exists in the
- * Container and it can have children, false
if
- * it's not found from the container or it can't have children.
- */
- public boolean areChildrenAllowed(Object itemId);
-
- /**
- * itemId
already has children and
- * areChildrenAllowed
is false this method fails and
- * false
is returned.
- * false
.
- * true
if the operation succeeded,
- * false
if not
- */
- public boolean setChildrenAllowed(Object itemId,
- boolean areChildrenAllowed)
- throws UnsupportedOperationException;
-
- /**
- * Tests if the Item specified with itemId
is a root
- * Item. The hierarchical container can have more than one root and must
- * have at least one unless it is empty. The
- * {@link #getParent(Object itemId)}method always returns
- * null
for root Items.
- *
- * @param itemId
- * ID of the Item whose root status is to be tested
- * @return true
if the specified Item is a root,
- * false
if not
- */
- public boolean isRoot(Object itemId);
-
- /**
- * itemId
has any child
- * Items, that is, is it a leaf Item. The
- * {@link #getChildren(Object itemId)}method always returns
- * null
for leaf Items.
- * true
if the specified Item is a leaf,
- * false
if not
- */
- public boolean hasChildren(Object itemId);
- }
-
- /** Interface is implemented by containers that allow reducing their visiblecontents with
- * set of filters.
- *
- * When a set of filters are set, only items that match the filters are included in the
- * visible contents of the container. Still new items that do not match filters can be
- * added to the container. Multiple filters can be added and the container remembers the
- * state of the filters. When multiple filters are added, all filters must match for
- * an item to be visible in the container.
- *
- * @since 5.0
- */
- public interface Filterable extends Container {
-
- /** Add a filter for given property.
- *
- * Only items where given property for which toString() contains or starts
- * with given filterString are visible in the container.
- *
- * @param propertyId Property for which the filter is applied to.
- * @param filterString String that must match contents of the property
- * @param ignoreCase Determine if the casing can be ignored when comparing strings.
- * @param onlyMatchPrefix Only match prefixes; no other matches are included.
- */
- public void addContainerFilter(Object propertyId, String filterString, boolean ignoreCase, boolean onlyMatchPrefix);
-
- /** Remove all filters from all properties. */
- public void removeAllContainerFilters();
-
- /** Remove all filters from given property. */
- public void removeContainerFilters(Object propertyId);
- }
-
-
- /**
- * Interface implemented by viewer classes capable of using a Container as a
- * data source.
- */
- public interface Viewer {
-
- /**
- * Sets the Container that serves as the data source of the viewer.
- *
- * @param newDataSource
- * The new data source Item
- */
- public void setContainerDataSource(Container newDataSource);
-
- /**
- * Gets the Container serving as the data source of the viewer.
- *
- * @return data source Container
- */
- public Container getContainerDataSource();
-
- }
-
- /**
- * Container.Editor
interface
- * does not restrict the class from editing the Container contents
- * internally.
- * Event
object specifying the Container whose Item set
- * has changed. Note that these events are triggered only through succesful
- * calls to the newItem
and removeAllItems
- * methods in the Container.Managed interface.
- */
- public interface ItemSetChangeEvent {
-
- /**
- * Gets the Property where the event occurred.
- *
- * @return source of the event
- */
- public Container getContainer();
- }
-
- /** Container Item set change listener interface. */
- public interface ItemSetChangeListener {
-
- /**
- * Lets the listener know a Containers Item set has changed.
- *
- * @param event
- * change event text
- */
- public void containerItemSetChange(Container.ItemSetChangeEvent event);
- }
-
- /**
- * The interface for adding and removing ItemSetChangeEvent
- * listeners. By implementing this interface a class explicitly announces
- * that it will generate a ItemSetChangeEvent
when its
- * contents are modified.
- * addListener
and removeListener
methods.
- * That way the caller of these methods has no real way of finding out if
- * the class really will send the events, or if it just defines the methods
- * to be able to implement an interface.
- * Event
object specifying the Container whose Property
- * set has changed.
- * addProperty
and removeProperty
methods in
- * the Container.Managed interface.
- * PropertySetChangeEvent
- * objects.
- */
- public interface PropertySetChangeListener {
-
- /**
- * Notifies this listener that the Containers contents has changed.
- *
- * @param event
- * Change event.
- */
- public void containerPropertySetChange(
- Container.PropertySetChangeEvent event);
- }
-
- /**
- * PropertySetChangeEvent
- * listeners. By implementing this interface a class explicitly announces
- * that it will generate a PropertySetChangeEvent
when its
- * contents are modified.
- * addListener
and removeListener
methods.
- * That way the caller of these methods has no real way of finding out if
- * the class really will send the events, or if it just defines the methods
- * to be able to implement an interface.
- * null
is returned.
+ *
+ * @param itemId
+ * ID of the Item to retrieve
+ * @return the Item with the given ID or null
if the Item is
+ * not found in the Container
+ */
+ public Item getItem(Object itemId);
+
+ /**
+ * Gets the ID's of all Properties stored in the Container. The ID's are
+ * returned as a unmodifiable collection.
+ *
+ * @return unmodifiable collection of Property IDs
+ */
+ public Collection getContainerPropertyIds();
+
+ /**
+ * Gets the ID's of all Items stored in the Container. The ID's are returned
+ * as a unmodifiable collection.
+ *
+ * @return unmodifiable collection of Item IDs
+ */
+ public Collection getItemIds();
+
+ /**
+ * Gets the Property identified by the given itemId and propertyId from the
+ * Container. If the Container does not contain the Property,
+ * null
is returned.
+ *
+ * @param itemId
+ * ID of the Item which contains the Property
+ * @param propertyId
+ * ID of the Property to retrieve
+ * @return Property with the given ID or null
+ */
+ public Property getContainerProperty(Object itemId, Object propertyId);
+
+ /**
+ * Gets the data type of all Properties identified by the given Property ID.
+ *
+ * @param propertyId
+ * ID identifying the Properties
+ * @return data type of the Properties
+ */
+ public Class getType(Object propertyId);
+
+ /**
+ * Gets the number of Items in the Container.
+ *
+ * @return number of Items in the Container
+ */
+ public int size();
+
+ /**
+ * Tests if the Container contains the specified Item
+ *
+ * @param itemId
+ * ID the of Item to be tested
+ * @return boolean indicating if the Container holds the specified Item
+ */
+ public boolean containsId(Object itemId);
+
+ /**
+ * Creates a new Item with the given ID into the Container. The new
+ * null
if the operation fails or the Container
+ * already contains a Item with the given ID.
+ * null
in case of a failure
+ */
+ public Item addItem(Object itemId) throws UnsupportedOperationException;
+
+ /**
+ * Creates a new Item into the Container, and assign it an automatic ID.
+ *
+ * null
if the operation fails.
+ * After a successful call you can use the
+ * {@link #getItem(Object ItemId) getItem
}method to fetch the
+ * Item.
+ * null
in case of a
+ * failure
+ */
+ public Object addItem() throws UnsupportedOperationException;
+
+ /**
+ * Removes the Item identified by ItemId
from the Container.
+ * This functionality is optional.
+ *
+ * @param itemId
+ * ID of the Item to remove
+ * @return true
if the operation succeeded,
+ * false
if not
+ */
+ public boolean removeItem(Object itemId)
+ throws UnsupportedOperationException;
+
+ /**
+ * Adds a new Property to all Items in the Container. The Property ID, data
+ * type and default value of the new Property are given as parameters.
+ *
+ * This functionality is optional.
+ *
+ * @param propertyId
+ * ID of the Property
+ * @param type
+ * Data type of the new Property
+ * @param defaultValue
+ * The value all created Properties are initialized to
+ * @return true
if the operation succeeded,
+ * false
if not
+ */
+ public boolean addContainerProperty(Object propertyId, Class type,
+ Object defaultValue) throws UnsupportedOperationException;
+
+ /**
+ * Removes a Property specified by the given Property ID from the Container.
+ * Note that the Property will be removed from all Items in the Container.
+ *
+ * This functionality is optional.
+ *
+ * @param propertyId
+ * ID of the Property to remove
+ * @return true
if the operation succeeded,
+ * false
if not
+ */
+ public boolean removeContainerProperty(Object propertyId)
+ throws UnsupportedOperationException;
+
+ /**
+ * Removes all Items from the Container.
+ *
+ * true
if the operation succeeded,
+ * false
if not
+ */
+ public boolean removeAllItems() throws UnsupportedOperationException;
+
+ /**
+ * Interface for Container classes whose Items can be traversed in order.
+ */
+ public interface Ordered extends Container {
+
+ /**
+ * Gets the ID of the Item following the Item that corresponds to
+ * itemId
. If the given Item is the last or not found in
+ * the Container, null
is returned.
+ *
+ * @param itemId
+ * ID of an Item in the Container
+ * @return ID of the next Item or null
+ */
+ public Object nextItemId(Object itemId);
+
+ /**
+ * Gets the ID of the Item preceding the Item that corresponds to
+ * itemId
. If the given Item is the first or not found
+ * in the Container, null
is returned.
+ *
+ * @param itemId
+ * ID of an Item in the Container
+ * @return ID of the previous Item or null
+ */
+ public Object prevItemId(Object itemId);
+
+ /**
+ * Gets the ID of the first Item in the Container.
+ *
+ * @return ID of the first Item in the Container
+ */
+ public Object firstItemId();
+
+ /**
+ * Gets the ID of the last Item in the Container..
+ *
+ * @return ID of the last Item in the Container
+ */
+ public Object lastItemId();
+
+ /**
+ * Tests if the Item corresponding to the given Item ID is the first
+ * Item in the Container.
+ *
+ * @param itemId
+ * ID of an Item in the Container
+ * @return true
if the Item is first in the Container,
+ * false
if not
+ */
+ public boolean isFirstId(Object itemId);
+
+ /**
+ * Tests if the Item corresponding to the given Item ID is the last Item
+ * in the Container.
+ *
+ * @return true
if the Item is last in the Container,
+ * false
if not
+ */
+ public boolean isLastId(Object itemId);
+
+ /**
+ * Adds new item after the given item.
+ * getSortableContainerPropertyIds
+ * @param ascending
+ * Array of sorting order flags corresponding to each
+ * property ID used in sorting. If this array is shorter
+ * than propertyId array, ascending order is assumed for
+ * items where the order is not specified. Use
+ * true
to sort in ascending order,
+ * false
to use descending order.
+ */
+ void sort(Object[] propertyId, boolean[] ascending);
+
+ /**
+ * Gets the container property IDs, which can be used to sort the item.
+ *
+ * @return The sortable field ids.
+ */
+ Collection getSortableContainerPropertyIds();
+
+ }
+
+ /** Interface for Container classes whose Items can be indexed. */
+ public interface Indexed extends Ordered {
+
+ /**
+ * Gets the index of the Item corresponding to the itemId. The following
+ * is true
for the returned index: 0 <= index < size().
+ *
+ * @param itemId
+ * ID of an Item in the Container
+ * @return index of the Item, or -1 if the Container does not include
+ * the Item
+ */
+ public int indexOfId(Object itemId);
+
+ /**
+ * Gets the ID of an Item by an index number.
+ *
+ * @param index
+ * Index of the requested id in the Container
+ * @return ID of the Item in the given index
+ */
+ public Object getIdByIndex(int index);
+
+ /**
+ * Adds new item at given index.
+ * Container
classes whose Items can be
+ * arranged hierarchically. This means that the Items in the container
+ * belong in a tree-like structure, with the following quirks:
+ *
+ *
+ */
+ public interface Hierarchical extends Container {
+
+ /**
+ * Gets the IDs of all Items that are children of the specified Item.
+ * The returned collection is unmodifiable.
+ *
+ * @param itemId
+ * ID of the Item whose children the caller is interested
+ * in
+ * @return An unmodifiable {@link java.util.Collection collection}
+ * containing the IDs of all other Items that are children in
+ * the container hierarchy
+ */
+ public Collection getChildren(Object itemId);
+
+ /**
+ * Gets the ID of the parent Item of the specified Item.
+ *
+ * @param itemId
+ * ID of the Item whose parent the caller wishes to find
+ * out.
+ * @return the ID of the parent Item. Will be null
if the
+ * specified Item is a root element.
+ */
+ public Object getParent(Object itemId);
+
+ /**
+ * Gets the IDs of all Items in the container that don't have a parent.
+ * Such items are called root
Items. The returned
+ * collection is unmodifiable.
+ *
+ * @return An unmodifiable {@link java.util.Collection collection}
+ * containing IDs of all root elements of the container
+ */
+ public Collection rootItemIds();
+
+ /**
+ * canHaveChildren(newParentId) == true
). It is also
+ * possible to detach a node from the hierarchy (and thus make it root)
+ * by setting the parent null
.
+ * newParentId
+ * @param newParentId
+ * ID of the Item that's to be the new parent of the Item
+ * identified with itemId
+ * @return true
if the operation succeeded,
+ * false
if not
+ */
+ public boolean setParent(Object itemId, Object newParentId)
+ throws UnsupportedOperationException;
+
+ /**
+ * Tests if the Item with given ID can have any children. If the
+ * Container also implements the Managed
interface, the
+ * items created with newItem
can have children by
+ * default.
+ *
+ * @param itemId
+ * ID of the Item in the container whose child capability
+ * is to be tested
+ * @return true
if the specified Item exists in the
+ * Container and it can have children, false
if
+ * it's not found from the container or it can't have children.
+ */
+ public boolean areChildrenAllowed(Object itemId);
+
+ /**
+ * itemId
already has children and
+ * areChildrenAllowed
is false this method fails and
+ * false
is returned.
+ * false
.
+ * true
if the operation succeeded,
+ * false
if not
+ */
+ public boolean setChildrenAllowed(Object itemId,
+ boolean areChildrenAllowed)
+ throws UnsupportedOperationException;
+
+ /**
+ * Tests if the Item specified with itemId
is a root
+ * Item. The hierarchical container can have more than one root and must
+ * have at least one unless it is empty. The
+ * {@link #getParent(Object itemId)}method always returns
+ * null
for root Items.
+ *
+ * @param itemId
+ * ID of the Item whose root status is to be tested
+ * @return true
if the specified Item is a root,
+ * false
if not
+ */
+ public boolean isRoot(Object itemId);
+
+ /**
+ * itemId
has any child
+ * Items, that is, is it a leaf Item. The
+ * {@link #getChildren(Object itemId)}method always returns
+ * null
for leaf Items.
+ * true
if the specified Item is a leaf,
+ * false
if not
+ */
+ public boolean hasChildren(Object itemId);
+ }
+
+ /**
+ * Interface is implemented by containers that allow reducing their
+ * visiblecontents with set of filters.
+ *
+ * When a set of filters are set, only items that match the filters are
+ * included in the visible contents of the container. Still new items that
+ * do not match filters can be added to the container. Multiple filters can
+ * be added and the container remembers the state of the filters. When
+ * multiple filters are added, all filters must match for an item to be
+ * visible in the container.
+ *
+ * @since 5.0
+ */
+ public interface Filterable extends Container {
+
+ /**
+ * Add a filter for given property.
+ *
+ * Only items where given property for which toString() contains or
+ * starts with given filterString are visible in the container.
+ *
+ * @param propertyId
+ * Property for which the filter is applied to.
+ * @param filterString
+ * String that must match contents of the property
+ * @param ignoreCase
+ * Determine if the casing can be ignored when comparing
+ * strings.
+ * @param onlyMatchPrefix
+ * Only match prefixes; no other matches are included.
+ */
+ public void addContainerFilter(Object propertyId, String filterString,
+ boolean ignoreCase, boolean onlyMatchPrefix);
+
+ /** Remove all filters from all properties. */
+ public void removeAllContainerFilters();
+
+ /** Remove all filters from given property. */
+ public void removeContainerFilters(Object propertyId);
+ }
+
+ /**
+ * Interface implemented by viewer classes capable of using a Container as a
+ * data source.
+ */
+ public interface Viewer {
+
+ /**
+ * Sets the Container that serves as the data source of the viewer.
+ *
+ * @param newDataSource
+ * The new data source Item
+ */
+ public void setContainerDataSource(Container newDataSource);
+
+ /**
+ * Gets the Container serving as the data source of the viewer.
+ *
+ * @return data source Container
+ */
+ public Container getContainerDataSource();
+
+ }
+
+ /**
+ * Container.Editor
interface
+ * does not restrict the class from editing the Container contents
+ * internally.
+ * Event
object specifying the Container whose Item set
+ * has changed. Note that these events are triggered only through succesful
+ * calls to the newItem
and removeAllItems
+ * methods in the Container.Managed interface.
+ */
+ public interface ItemSetChangeEvent {
+
+ /**
+ * Gets the Property where the event occurred.
+ *
+ * @return source of the event
+ */
+ public Container getContainer();
+ }
+
+ /** Container Item set change listener interface. */
+ public interface ItemSetChangeListener {
+
+ /**
+ * Lets the listener know a Containers Item set has changed.
+ *
+ * @param event
+ * change event text
+ */
+ public void containerItemSetChange(Container.ItemSetChangeEvent event);
+ }
+
+ /**
+ * The interface for adding and removing ItemSetChangeEvent
+ * listeners. By implementing this interface a class explicitly announces
+ * that it will generate a ItemSetChangeEvent
when its
+ * contents are modified.
+ * addListener
and removeListener
methods.
+ * That way the caller of these methods has no real way of finding out if
+ * the class really will send the events, or if it just defines the methods
+ * to be able to implement an interface.
+ * Event
object specifying the Container whose Property
+ * set has changed.
+ * addProperty
and removeProperty
methods in
+ * the Container.Managed interface.
+ * PropertySetChangeEvent
+ * objects.
+ */
+ public interface PropertySetChangeListener {
+
+ /**
+ * Notifies this listener that the Containers contents has changed.
+ *
+ * @param event
+ * Change event.
+ */
+ public void containerPropertySetChange(
+ Container.PropertySetChangeEvent event);
+ }
+
+ /**
+ * PropertySetChangeEvent
+ * listeners. By implementing this interface a class explicitly announces
+ * that it will generate a PropertySetChangeEvent
when its
+ * contents are modified.
+ * addListener
and removeListener
methods.
+ * That way the caller of these methods has no real way of finding out if
+ * the class really will send the events, or if it just defines the methods
+ * to be able to implement an interface.
+ * null
is
- * returned.
- *
- * @param id
- * identifier of the Property to get
- * @return the Property with the given ID or null
- */
- public Property getItemProperty(Object id);
-
- /**
- * Gets the collection of IDs of all Properties stored in the Item.
- *
- * @return unmodifiable collection containing IDs of the Properties stored
- * the Item
- */
- public Collection getItemPropertyIds();
-
- /**
- * Tries to add a new Property into the Item.
- *
- * true
if the operation succeeded,
- * false
if not
- * @throws UnsupportedOperationException
- * if the operation is not supported.
- */
- public boolean addItemProperty(Object id, Property property)
- throws UnsupportedOperationException;
-
- /**
- * Removes the Property identified by ID from the Item.
- *
- * true
if the operation succeeded
- * @throws UnsupportedOperationException
- * if the operation is not supported. false
if
- * not
- */
- public boolean removeItemProperty(Object id)
- throws UnsupportedOperationException;
-
- /**
- * Interface implemented by viewer classes capable of using an Item as a
- * data source.
- */
- public interface Viewer {
-
- /**
- * Sets the Item that serves as the data source of the viewer.
- *
- * @param newDataSource
- * The new data source Item
- */
- public void setItemDataSource(Item newDataSource);
-
- /**
- * Gets the Item serving as the data source of the viewer.
- *
- * @return data source Item
- */
- public Item getItemDataSource();
- }
-
- /**
- * Interface implemented by the Editor
classes capable of
- * editing the Item. Implementing this interface means that the Item serving
- * as the data source of the editor can be modified through it.
- * Item.Editor
interface does not
- * restrict the class from editing the contents of an internally.
- * Event
object specifying the Item whose contents has
- * been changed through the Property
interface.
- * PropertySetChangeEvent
- * objects.
- */
- public interface PropertySetChangeListener {
-
- /**
- * Notifies this listener that the Item's property set has changed.
- *
- * @param event
- * Property set change event object
- */
- public void itemPropertySetChange(Item.PropertySetChangeEvent event);
- }
-
- /**
- * The interface for adding and removing PropertySetChangeEvent
- * listeners. By implementing this interface a class explicitly announces
- * that it will generate a PropertySetChangeEvent
when its
- * Property set is modified.
- * addListener
and removeListener
methods.
- * That way the caller of these methods has no real way of finding out if
- * the class really will send the events, or if it just defines the methods
- * to be able to implement an interface.
- * null
is
+ * returned.
+ *
+ * @param id
+ * identifier of the Property to get
+ * @return the Property with the given ID or null
+ */
+ public Property getItemProperty(Object id);
+
+ /**
+ * Gets the collection of IDs of all Properties stored in the Item.
+ *
+ * @return unmodifiable collection containing IDs of the Properties stored
+ * the Item
+ */
+ public Collection getItemPropertyIds();
+
+ /**
+ * Tries to add a new Property into the Item.
+ *
+ * true
if the operation succeeded,
+ * false
if not
+ * @throws UnsupportedOperationException
+ * if the operation is not supported.
+ */
+ public boolean addItemProperty(Object id, Property property)
+ throws UnsupportedOperationException;
+
+ /**
+ * Removes the Property identified by ID from the Item.
+ *
+ * true
if the operation succeeded
+ * @throws UnsupportedOperationException
+ * if the operation is not supported. false
+ * if not
+ */
+ public boolean removeItemProperty(Object id)
+ throws UnsupportedOperationException;
+
+ /**
+ * Interface implemented by viewer classes capable of using an Item as a
+ * data source.
+ */
+ public interface Viewer {
+
+ /**
+ * Sets the Item that serves as the data source of the viewer.
+ *
+ * @param newDataSource
+ * The new data source Item
+ */
+ public void setItemDataSource(Item newDataSource);
+
+ /**
+ * Gets the Item serving as the data source of the viewer.
+ *
+ * @return data source Item
+ */
+ public Item getItemDataSource();
+ }
+
+ /**
+ * Interface implemented by the Editor
classes capable of
+ * editing the Item. Implementing this interface means that the Item serving
+ * as the data source of the editor can be modified through it.
+ * Item.Editor
interface does not
+ * restrict the class from editing the contents of an internally.
+ * Event
object specifying the Item whose contents has
+ * been changed through the Property
interface.
+ * PropertySetChangeEvent
+ * objects.
+ */
+ public interface PropertySetChangeListener {
+
+ /**
+ * Notifies this listener that the Item's property set has changed.
+ *
+ * @param event
+ * Property set change event object
+ */
+ public void itemPropertySetChange(Item.PropertySetChangeEvent event);
+ }
+
+ /**
+ * The interface for adding and removing PropertySetChangeEvent
+ * listeners. By implementing this interface a class explicitly announces
+ * that it will generate a PropertySetChangeEvent
when its
+ * Property set is modified.
+ * addListener
and removeListener
methods.
+ * That way the caller of these methods has no real way of finding out if
+ * the class really will send the events, or if it just defines the methods
+ * to be able to implement an interface.
+ * Property.ReadOnlyException
in this function.
- * String
in addition to the native type of
- * the Property (as given by the getType
method). If the
- * String
conversion fails or is unsupported, the method
- * should throw Property.ConversionException
. The string
- * conversion should at least understand the format returned by the
- * toString
method of the Property.
- *
- * @param newValue
- * New value of the Property. This should be assignable to the
- * type returned by getType, but also String type should be
- * supported
- *
- * @throws Property.ReadOnlyException
- * if the object is in read-only mode
- * @throws Property.ConversionException
- * if newValue can't be converted into the Property's native
- * type directly or through String
- */
- public void setValue(Object newValue) throws Property.ReadOnlyException,
- Property.ConversionException;
-
- /**
- * Returns the value of the Property in human readable textual format. The
- * return value should be assignable to the setValue
method
- * if the Property is not in read-only mode.
- *
- * @return String
representation of the value stored in the
- * Property
- */
- public String toString();
-
- /**
- * Returns the type of the Property. The methods getValue
and
- * setValue
must be compatible with this type: one must be
- * able to safely cast the value returned from getValue
to
- * the given type and pass any variable assignable to this type as an
- * argument to setValue
.
- *
- * @return type of the Property
- */
- public Class getType();
-
- /**
- * Tests if the Property is in read-only mode. In read-only mode calls to
- * the method setValue
will throw
- * ReadOnlyException
and will not modify the value of the
- * Property.
- *
- * @return true
if the Property is in read-only mode,
- * false
if it's not
- */
- public boolean isReadOnly();
-
- /**
- * Sets the Property's read-only mode to the specified status.
- *
- * This functionality is optional, but all properties must implement the
- * isReadOnly
mode query correctly.
- *
- * @param newStatus
- * new read-only status of the Property
- */
- public void setReadOnly(boolean newStatus);
-
- /**
- * Exception
object that signals that a requested Property
- * modification failed because it's in read-only mode.
- *
- * @author IT Mill Ltd.
- * @version
- * @VERSION@
- * @since 3.0
- */
- public class ReadOnlyException extends RuntimeException {
-
- /**
- * Serial generated by eclipse.
- */
- private static final long serialVersionUID = 3257571702287119410L;
-
- /**
- * Constructs a new ReadOnlyException
without a detail
- * message.
- */
- public ReadOnlyException() {
- }
-
- /**
- * Constructs a new ReadOnlyException
with the specified
- * detail message.
- *
- * @param msg
- * the detail message
- */
- public ReadOnlyException(String msg) {
- super(msg);
- }
- }
-
- /**
- * An exception that signals that the value passed to the
- * setValue
method couldn't be converted to the native type
- * of the Property.
- *
- * @author IT Mill Ltd
- * @version
- * @VERSION@
- * @since 3.0
- */
- public class ConversionException extends RuntimeException {
-
- /**
- * Serial generated by eclipse.
- */
- private static final long serialVersionUID = 3257571706666366008L;
-
- /**
- * Constructs a new ConversionException
without a detail
- * message.
- */
- public ConversionException() {
- }
-
- /**
- * Constructs a new ConversionException
with the
- * specified detail message.
- *
- * @param msg
- * the detail message
- */
- public ConversionException(String msg) {
- super(msg);
- }
-
- /**
- * Constructs a new ConversionException
from another
- * exception.
- *
- * @param cause
- * The cause of the the conversion failure
- */
- public ConversionException(Throwable cause) {
- super(cause.toString());
- }
- }
-
- /**
- * Interface implemented by the viewer classes capable of using a Property
- * as a data source.
- *
- * @author IT Mill Ltd.
- * @version
- * @VERSION@
- * @since 3.0
- */
- public interface Viewer {
-
- /**
- * Sets the Property that serves as the data source of the viewer.
- *
- * @param newDataSource
- * the new data source Property
- */
- public void setPropertyDataSource(Property newDataSource);
-
- /**
- * Gets the Property serving as the data source of the viewer.
- *
- * @return the Property serving as the viewers data source
- */
- public Property getPropertyDataSource();
- }
-
- /**
- * Interface implemented by the editor classes capable of editing the
- * Property.
- * ReadOnlyException
being thrown.
- * Event
object specifying the Property whose value has
- * been changed.
- *
- * @author IT Mill Ltd.
- * @version
- * @VERSION@
- * @since 3.0
- */
- public interface ValueChangeEvent {
-
- /**
- * Retrieves the Property that has been modified.
- *
- * @return source Property of the event
- */
- public Property getProperty();
- }
-
- /**
- * The listener
interface for receiving
- * ValueChangeEvent
objects.
- *
- * @author IT Mill Ltd.
- * @version
- * @VERSION@
- * @since 3.0
- */
- public interface ValueChangeListener {
-
- /**
- * Notifies this listener that the Property's value has changed.
- *
- * @param event
- * value change event object
- */
- public void valueChange(Property.ValueChangeEvent event);
- }
-
- /**
- * The interface for adding and removing ValueChangeEvent
- * listeners. If a Property wishes to allow other objects to receive
- * ValueChangeEvent
generated by it, it must implement this
- * interface.
- * addListener
and removeListener
methods.
- * That way the caller of these methods has no real way of finding out if
- * the class really will send the events, or if it just defines the methods
- * to be able to implement an interface.
- * Event
object specifying the Property whose read-only
- * status has been changed.
- *
- * @author IT Mill Ltd.
- * @version
- * @VERSION@
- * @since 3.0
- */
- public interface ReadOnlyStatusChangeEvent {
-
- /**
- * Property whose read-only state has changed.
- *
- * @return source Property of the event.
- */
- public Property getProperty();
- }
-
- /**
- * The listener interface for receiving
- * ReadOnlyStatusChangeEvent
objects.
- *
- * @author IT Mill Ltd.
- * @version
- * @VERSION@
- * @since 3.0
- */
- public interface ReadOnlyStatusChangeListener {
-
- /**
- * Notifies this listener that a Property's read-only status has
- * changed.
- *
- * @param event
- * Read-only status change event object
- */
- public void readOnlyStatusChange(
- Property.ReadOnlyStatusChangeEvent event);
- }
-
- /**
- * The interface for adding and removing
- * ReadOnlyStatusChangeEvent
listeners. If a Property wishes
- * to allow other objects to receive ReadOnlyStatusChangeEvent
- * generated by it, it must implement this interface.
- * addListener
and removeListener
methods.
- * That way the caller of these methods has no real way of finding out if
- * the class really will send the events, or if it just defines the methods
- * to be able to implement an interface.
- * Property.ReadOnlyException
in this function.
+ * String
in addition to the native type of
+ * the Property (as given by the getType
method). If the
+ * String
conversion fails or is unsupported, the method
+ * should throw Property.ConversionException
. The string
+ * conversion should at least understand the format returned by the
+ * toString
method of the Property.
+ *
+ * @param newValue
+ * New value of the Property. This should be assignable to
+ * the type returned by getType, but also String type should
+ * be supported
+ *
+ * @throws Property.ReadOnlyException
+ * if the object is in read-only mode
+ * @throws Property.ConversionException
+ * if newValue can't be converted into the Property's native
+ * type directly or through String
+ */
+ public void setValue(Object newValue) throws Property.ReadOnlyException,
+ Property.ConversionException;
+
+ /**
+ * Returns the value of the Property in human readable textual format. The
+ * return value should be assignable to the setValue
method
+ * if the Property is not in read-only mode.
+ *
+ * @return String
representation of the value stored in the
+ * Property
+ */
+ public String toString();
+
+ /**
+ * Returns the type of the Property. The methods getValue
and
+ * setValue
must be compatible with this type: one must be
+ * able to safely cast the value returned from getValue
to
+ * the given type and pass any variable assignable to this type as an
+ * argument to setValue
.
+ *
+ * @return type of the Property
+ */
+ public Class getType();
+
+ /**
+ * Tests if the Property is in read-only mode. In read-only mode calls to
+ * the method setValue
will throw
+ * ReadOnlyException
and will not modify the value of the
+ * Property.
+ *
+ * @return true
if the Property is in read-only mode,
+ * false
if it's not
+ */
+ public boolean isReadOnly();
+
+ /**
+ * Sets the Property's read-only mode to the specified status.
+ *
+ * This functionality is optional, but all properties must implement the
+ * isReadOnly
mode query correctly.
+ *
+ * @param newStatus
+ * new read-only status of the Property
+ */
+ public void setReadOnly(boolean newStatus);
+
+ /**
+ * Exception
object that signals that a requested Property
+ * modification failed because it's in read-only mode.
+ *
+ * @author IT Mill Ltd.
+ * @version
+ * @VERSION@
+ * @since 3.0
+ */
+ public class ReadOnlyException extends RuntimeException {
+
+ /**
+ * Serial generated by eclipse.
+ */
+ private static final long serialVersionUID = 3257571702287119410L;
+
+ /**
+ * Constructs a new ReadOnlyException
without a detail
+ * message.
+ */
+ public ReadOnlyException() {
+ }
+
+ /**
+ * Constructs a new ReadOnlyException
with the specified
+ * detail message.
+ *
+ * @param msg
+ * the detail message
+ */
+ public ReadOnlyException(String msg) {
+ super(msg);
+ }
+ }
+
+ /**
+ * An exception that signals that the value passed to the
+ * setValue
method couldn't be converted to the native type
+ * of the Property.
+ *
+ * @author IT Mill Ltd
+ * @version
+ * @VERSION@
+ * @since 3.0
+ */
+ public class ConversionException extends RuntimeException {
+
+ /**
+ * Serial generated by eclipse.
+ */
+ private static final long serialVersionUID = 3257571706666366008L;
+
+ /**
+ * Constructs a new ConversionException
without a detail
+ * message.
+ */
+ public ConversionException() {
+ }
+
+ /**
+ * Constructs a new ConversionException
with the
+ * specified detail message.
+ *
+ * @param msg
+ * the detail message
+ */
+ public ConversionException(String msg) {
+ super(msg);
+ }
+
+ /**
+ * Constructs a new ConversionException
from another
+ * exception.
+ *
+ * @param cause
+ * The cause of the the conversion failure
+ */
+ public ConversionException(Throwable cause) {
+ super(cause.toString());
+ }
+ }
+
+ /**
+ * Interface implemented by the viewer classes capable of using a Property
+ * as a data source.
+ *
+ * @author IT Mill Ltd.
+ * @version
+ * @VERSION@
+ * @since 3.0
+ */
+ public interface Viewer {
+
+ /**
+ * Sets the Property that serves as the data source of the viewer.
+ *
+ * @param newDataSource
+ * the new data source Property
+ */
+ public void setPropertyDataSource(Property newDataSource);
+
+ /**
+ * Gets the Property serving as the data source of the viewer.
+ *
+ * @return the Property serving as the viewers data source
+ */
+ public Property getPropertyDataSource();
+ }
+
+ /**
+ * Interface implemented by the editor classes capable of editing the
+ * Property.
+ * ReadOnlyException
being thrown.
+ * Event
object specifying the Property whose value has
+ * been changed.
+ *
+ * @author IT Mill Ltd.
+ * @version
+ * @VERSION@
+ * @since 3.0
+ */
+ public interface ValueChangeEvent {
+
+ /**
+ * Retrieves the Property that has been modified.
+ *
+ * @return source Property of the event
+ */
+ public Property getProperty();
+ }
+
+ /**
+ * The listener
interface for receiving
+ * ValueChangeEvent
objects.
+ *
+ * @author IT Mill Ltd.
+ * @version
+ * @VERSION@
+ * @since 3.0
+ */
+ public interface ValueChangeListener {
+
+ /**
+ * Notifies this listener that the Property's value has changed.
+ *
+ * @param event
+ * value change event object
+ */
+ public void valueChange(Property.ValueChangeEvent event);
+ }
+
+ /**
+ * The interface for adding and removing ValueChangeEvent
+ * listeners. If a Property wishes to allow other objects to receive
+ * ValueChangeEvent
generated by it, it must implement this
+ * interface.
+ * addListener
and removeListener
methods.
+ * That way the caller of these methods has no real way of finding out if
+ * the class really will send the events, or if it just defines the methods
+ * to be able to implement an interface.
+ * Event
object specifying the Property whose read-only
+ * status has been changed.
+ *
+ * @author IT Mill Ltd.
+ * @version
+ * @VERSION@
+ * @since 3.0
+ */
+ public interface ReadOnlyStatusChangeEvent {
+
+ /**
+ * Property whose read-only state has changed.
+ *
+ * @return source Property of the event.
+ */
+ public Property getProperty();
+ }
+
+ /**
+ * The listener interface for receiving
+ * ReadOnlyStatusChangeEvent
objects.
+ *
+ * @author IT Mill Ltd.
+ * @version
+ * @VERSION@
+ * @since 3.0
+ */
+ public interface ReadOnlyStatusChangeListener {
+
+ /**
+ * Notifies this listener that a Property's read-only status has
+ * changed.
+ *
+ * @param event
+ * Read-only status change event object
+ */
+ public void readOnlyStatusChange(
+ Property.ReadOnlyStatusChangeEvent event);
+ }
+
+ /**
+ * The interface for adding and removing
+ * ReadOnlyStatusChangeEvent
listeners. If a Property wishes
+ * to allow other objects to receive ReadOnlyStatusChangeEvent
+ * generated by it, it must implement this interface.
+ * addListener
and removeListener
methods.
+ * That way the caller of these methods has no real way of finding out if
+ * the class really will send the events, or if it just defines the methods
+ * to be able to implement an interface.
+ * validate
- * method is no longer called in {@link #isValid()}.
- * null
.
- * null
- */
- public Collection getValidators();
-
- /**
- * false
.
- * true
if the registered validators concur that the
- * value is valid, false
otherwise
- */
- public boolean isValid();
-
- /**
- * Validator.InvalidValueException
- * true
.
- * validate
+ * method is no longer called in {@link #isValid()}.
+ * null
.
+ * null
+ */
+ public Collection getValidators();
+
+ /**
+ * false
.
+ * true
if the registered validators concur that the
+ * value is valid, false
otherwise
+ */
+ public boolean isValid();
+
+ /**
+ * Validator.InvalidValueException
+ * true
.
+ * Validator.InvalidValueException
- *
- * @param value
- * the value to check
- * @throws Validator.InvalidValueException
- * if the value is not valid
- */
- public void validate(Object value) throws Validator.InvalidValueException;
-
- /**
- * Tests if the given value is valid.
- *
- * @param value
- * the value to check
- * @return true
for valid value, otherwise false
.
- */
- public boolean isValid(Object value);
-
- /**
- * Adds the proposing functionality to a {@link Validator}. A
- * Suggestive
validator can propose a valid value for the
- * object it is attached to validate. This way the {@link Validatable}
- * object may avoid situations where it contains a value that could lead to
- * a error.
- *
- * @author IT Mill Ltd.
- * @version
- * @VERSION@
- * @since 3.0
- */
- public interface Suggestive extends Validator {
-
- /**
- * Suggests another value that can be used instead of the proposedValue
- * if it is invalid. If it is valid in the opinion of this validator,
- * however, it is returned as is.
- *
- * @param proposedValue
- * Originally proposed value that could be invalid.
- * @return Suggested value that's not invalid against this validator
- */
- public Object suggestValidValue(Object proposedValue);
- }
-
- /**
- * Invalid value exception can be thrown by {@link Validator} when a given
- * value is not valid.
- *
- * @author IT Mill Ltd.
- * @version
- * @VERSION@
- * @since 3.0
- */
- public class InvalidValueException extends RuntimeException implements
- ErrorMessage {
-
- /**
- * Serial generated by eclipse.
- */
- private static final long serialVersionUID = 3689073941163422257L;
-
- /** Array of validation errors that are causing the problem. */
- private InvalidValueException[] causes = null;
-
- /**
- * Constructs a new InvalidValueException
with the
- * specified detail message.
- *
- * @param message
- * The detail message of the problem.
- */
- public InvalidValueException(String message) {
- this(message, new InvalidValueException[] {});
- }
-
- /**
- * Constructs a new InvalidValueException
with a set of
- * causing validation exceptions. The error message contains first the
- * given message and then a list of validation errors in the given
- * validatables.
- *
- * @param message
- * The detail message of the problem.
- * @param causes
- * Array of validatables whos invalidities are possiblity
- * causing the invalidity.
- */
- public InvalidValueException(String message,
- InvalidValueException[] causes) {
- super(message);
- if (causes == null)
- throw new NullPointerException(
- "Possible causes array must not be null");
- this.causes = causes;
- }
-
- public final int getErrorLevel() {
- return ErrorMessage.ERROR;
- }
-
- public void paint(PaintTarget target) throws PaintException {
- target.startTag("error");
- target.addAttribute("level", "error");
-
- // Error message
- String message = getLocalizedMessage();
- if (message != null)
- target.addText(message);
-
- // Paint all the causes
- for (int i = 0; i < causes.length; i++) {
- causes[i].paint(target);
- }
-
- target.endTag("error");
- }
-
- /* Documented in super interface */
- public void addListener(RepaintRequestListener listener) {
- }
-
- /* Documented in super interface */
- public void removeListener(RepaintRequestListener listener) {
- }
-
- /* Documented in super interface */
- public void requestRepaint() {
- }
-
- /* Documented in super interface */
- public void requestRepaintRequests() {
- }
-
- }
+ /**
+ * Checks the given value against this validator. If the value is valid this
+ * method should do nothing, and if it's not valid, it should throw
+ * Validator.InvalidValueException
+ *
+ * @param value
+ * the value to check
+ * @throws Validator.InvalidValueException
+ * if the value is not valid
+ */
+ public void validate(Object value) throws Validator.InvalidValueException;
+
+ /**
+ * Tests if the given value is valid.
+ *
+ * @param value
+ * the value to check
+ * @return true
for valid value, otherwise false
.
+ */
+ public boolean isValid(Object value);
+
+ /**
+ * Adds the proposing functionality to a {@link Validator}. A
+ * Suggestive
validator can propose a valid value for the
+ * object it is attached to validate. This way the {@link Validatable}
+ * object may avoid situations where it contains a value that could lead to
+ * a error.
+ *
+ * @author IT Mill Ltd.
+ * @version
+ * @VERSION@
+ * @since 3.0
+ */
+ public interface Suggestive extends Validator {
+
+ /**
+ * Suggests another value that can be used instead of the proposedValue
+ * if it is invalid. If it is valid in the opinion of this validator,
+ * however, it is returned as is.
+ *
+ * @param proposedValue
+ * Originally proposed value that could be invalid.
+ * @return Suggested value that's not invalid against this validator
+ */
+ public Object suggestValidValue(Object proposedValue);
+ }
+
+ /**
+ * Invalid value exception can be thrown by {@link Validator} when a given
+ * value is not valid.
+ *
+ * @author IT Mill Ltd.
+ * @version
+ * @VERSION@
+ * @since 3.0
+ */
+ public class InvalidValueException extends RuntimeException implements
+ ErrorMessage {
+
+ /**
+ * Serial generated by eclipse.
+ */
+ private static final long serialVersionUID = 3689073941163422257L;
+
+ /** Array of validation errors that are causing the problem. */
+ private InvalidValueException[] causes = null;
+
+ /**
+ * Constructs a new InvalidValueException
with the
+ * specified detail message.
+ *
+ * @param message
+ * The detail message of the problem.
+ */
+ public InvalidValueException(String message) {
+ this(message, new InvalidValueException[] {});
+ }
+
+ /**
+ * Constructs a new InvalidValueException
with a set of
+ * causing validation exceptions. The error message contains first the
+ * given message and then a list of validation errors in the given
+ * validatables.
+ *
+ * @param message
+ * The detail message of the problem.
+ * @param causes
+ * Array of validatables whos invalidities are possiblity
+ * causing the invalidity.
+ */
+ public InvalidValueException(String message,
+ InvalidValueException[] causes) {
+ super(message);
+ if (causes == null) {
+ throw new NullPointerException(
+ "Possible causes array must not be null");
+ }
+ this.causes = causes;
+ }
+
+ public final int getErrorLevel() {
+ return ErrorMessage.ERROR;
+ }
+
+ public void paint(PaintTarget target) throws PaintException {
+ target.startTag("error");
+ target.addAttribute("level", "error");
+
+ // Error message
+ String message = getLocalizedMessage();
+ if (message != null) {
+ target.addText(message);
+ }
+
+ // Paint all the causes
+ for (int i = 0; i < causes.length; i++) {
+ causes[i].paint(target);
+ }
+
+ target.endTag("error");
+ }
+
+ /* Documented in super interface */
+ public void addListener(RepaintRequestListener listener) {
+ }
+
+ /* Documented in super interface */
+ public void removeListener(RepaintRequestListener listener) {
+ }
+
+ /* Documented in super interface */
+ public void requestRepaint() {
+ }
+
+ /* Documented in super interface */
+ public void requestRepaintRequests() {
+ }
+
+ }
}
diff --git a/src/com/itmill/toolkit/data/util/BeanItem.java b/src/com/itmill/toolkit/data/util/BeanItem.java
index a6c50c4339..d5cb263274 100644
--- a/src/com/itmill/toolkit/data/util/BeanItem.java
+++ b/src/com/itmill/toolkit/data/util/BeanItem.java
@@ -28,8 +28,8 @@
package com.itmill.toolkit.data.util;
-import java.beans.Introspector;
import java.beans.BeanInfo;
+import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Collection;
@@ -47,112 +47,112 @@ import com.itmill.toolkit.data.Property;
*/
public class BeanItem extends PropertysetItem {
- /**
- * The bean which this Item is based on.
- */
- private Object bean;
-
- /**
- * BeanItem
and adds all properties
- * of a Java Bean to it. The properties are identified by their respective
- * bean names.
- * is
and
- * are
methods are not supported.
- * BeanItem
and adds all listed
- * properties of a Java Bean to it - in specified order. The properties are
- * identified by their respective bean names.
- * is
and
- * are
methods are not supported.
- * BeanItem
and adds all properties
+ * of a Java Bean to it. The properties are identified by their respective
+ * bean names.
+ * is
and
+ * are
methods are not supported.
+ * BeanItem
and adds all listed
+ * properties of a Java Bean to it - in specified order. The properties are
+ * identified by their respective bean names.
+ * is
and
+ * are
methods are not supported.
+ * Container.Hierarchical
interface.
- *
- * @param toBeWrapped
- * the container that needs to be accessed hierarchically
- * @see #updateHierarchicalWrapper()
- */
- public ContainerHierarchicalWrapper(Container toBeWrapped) {
-
- container = toBeWrapped;
- hierarchical = container instanceof Container.Hierarchical;
-
- // Check arguments
- if (container == null)
- throw new NullPointerException("Null can not be wrapped");
-
- // Create initial order if needed
- if (!hierarchical) {
- noChildrenAllowed = new HashSet();
- parent = new Hashtable();
- children = new Hashtable();
- roots = new LinkedList(container.getItemIds());
- }
-
- updateHierarchicalWrapper();
- }
-
- /**
- * Updates the wrapper's internal hierarchy data to include all Items in the
- * underlying container. If the contents of the wrapped container change
- * without the wrapper's knowledge, this method needs to be called to update
- * the hierarchy information of the Items.
- */
- public void updateHierarchicalWrapper() {
-
- if (!hierarchical) {
-
- // Recreate hierarchy and datasrtuctures if missing
- if (noChildrenAllowed == null || parent == null || children == null
- || roots == null) {
- noChildrenAllowed = new HashSet();
- parent = new Hashtable();
- children = new Hashtable();
- roots = new LinkedList(container.getItemIds());
- }
-
- // Check that the hierarchy is up-to-date
- else {
-
- // Calculate the set of all items in the hierarchy
- HashSet s = new HashSet();
- s.add(parent.keySet());
- s.add(children.keySet());
- s.addAll(roots);
-
- // Remove unnecessary items
- for (Iterator i = s.iterator(); i.hasNext();) {
- Object id = i.next();
- if (!container.containsId(id))
- removeFromHierarchyWrapper(id);
- }
-
- // Add all the missing items
- Collection ids = container.getItemIds();
- for (Iterator i = ids.iterator(); i.hasNext();) {
- Object id = i.next();
- if (!s.contains(id)) {
- addToHierarchyWrapper(id);
- s.add(id);
- }
- }
- }
- }
- }
-
- /**
- * Removes the specified Item from the wrapper's internal hierarchy
- * structure.
- * false
is returned; the children must
- * be first explicitly removed with
- * {@link #setParent(Object itemId, Object newParentId)} or
- * {@link com.itmill.toolkit.data.Container#removeItem(Object itemId)}.
- * true
if the operation succeeded,
- * false
if not
- */
- public boolean setChildrenAllowed(Object itemId, boolean childrenAllowed) {
-
- // If the wrapped container implements the method directly, use it
- if (hierarchical)
- return ((Container.Hierarchical) container).setChildrenAllowed(
- itemId, childrenAllowed);
-
- // Check that the item is in the container
- if (!containsId(itemId))
- return false;
-
- // Update status
- if (childrenAllowed)
- noChildrenAllowed.remove(itemId);
- else
- noChildrenAllowed.add(itemId);
-
- return true;
- }
-
- /**
- * canHaveChildren(newParentId) == true
).
- * It is also possible to detach a node from the hierarchy (and thus make it
- * root) by setting the parent null
.
- * true
if the operation succeeded,
- * false
if not
- */
- public boolean setParent(Object itemId, Object newParentId) {
-
- // If the wrapped container implements the method directly, use it
- if (hierarchical)
- return ((Container.Hierarchical) container).setParent(itemId,
- newParentId);
-
- // Check that the item is in the container
- if (!containsId(itemId))
- return false;
-
- // Get the old parent
- Object oldParentId = parent.get(itemId);
-
- // Check if no change is necessary
- if ((newParentId == null && oldParentId == null)
- || (newParentId != null && newParentId.equals(oldParentId)))
- return true;
-
- // Making root
- if (newParentId == null) {
-
- // Remove from old parents children list
- LinkedList l = (LinkedList) children.get(itemId);
- if (l != null) {
- l.remove(itemId);
- if (l.isEmpty())
- children.remove(itemId);
- }
-
- // Add to be a root
- roots.add(itemId);
-
- // Update parent
- parent.remove(itemId);
-
- return true;
- }
-
- // Check that the new parent exists in container and can have
- // children
- if (!containsId(newParentId) || noChildrenAllowed.contains(newParentId))
- return false;
-
- // Check that setting parent doesn't result to a loop
- Object o = newParentId;
- while (o != null && !o.equals(itemId))
- o = parent.get(o);
- if (o != null)
- return false;
-
- // Update parent
- parent.put(itemId, newParentId);
- LinkedList pcl = (LinkedList) children.get(newParentId);
- if (pcl == null) {
- pcl = new LinkedList();
- children.put(newParentId, pcl);
- }
- pcl.add(itemId);
-
- // Remove from old parent or root
- if (oldParentId == null)
- roots.remove(itemId);
- else {
- LinkedList l = (LinkedList) children.get(oldParentId);
- if (l != null) {
- l.remove(itemId);
- if (l.isEmpty())
- children.remove(oldParentId);
- }
- }
-
- return true;
- }
-
- /**
- * Creates a new Item into the Container, assigns it an automatic ID, and
- * adds it to the hierarchy.
- *
- * @return the autogenerated ID of the new Item or null
if
- * the operation failed
- * @throws UnsupportedOperationException
- * if the addItem is not supported.
- */
- public Object addItem() throws UnsupportedOperationException {
-
- Object id = container.addItem();
- if (id != null)
- addToHierarchyWrapper(id);
- return id;
- }
-
- /**
- * Adds a new Item by its ID to the underlying container and to the
- * hierarchy.
- *
- * @param itemId
- * the ID of the Item to be created.
- * @return the added Item or null
if the operation failed.
- * @throws UnsupportedOperationException
- * if the addItem is not supported.
- */
- public Item addItem(Object itemId) throws UnsupportedOperationException {
-
- Item item = container.addItem(itemId);
- if (item != null)
- addToHierarchyWrapper(itemId);
- return item;
- }
-
- /**
- * Removes all items from the underlying container and from the hierarcy.
- *
- * @return true
if the operation succeeded,
- * false
if not
- * @throws UnsupportedOperationException
- * if the removeAllItems is not supported.
- */
- public boolean removeAllItems() throws UnsupportedOperationException {
-
- boolean success = container.removeAllItems();
-
- if (success) {
- roots.clear();
- parent.clear();
- children.clear();
- noChildrenAllowed.clear();
- }
- return success;
- }
-
- /**
- * Removes an Item specified by the itemId from the underlying container and
- * from the hierarcy.
- *
- * @param itemId
- * the ID of the Item to be removed.
- * @return true
if the operation succeeded,
- * false
if not
- * @throws UnsupportedOperationException
- * if the removeItem is not supported.
- */
- public boolean removeItem(Object itemId)
- throws UnsupportedOperationException {
-
- boolean success = container.removeItem(itemId);
-
- if (success)
- removeFromHierarchyWrapper(itemId);
-
- return success;
- }
-
- /**
- * Adds a new Property to all Items in the Container.
- *
- * @param propertyId
- * the ID of the new Property.
- * @param type
- * the Data type of the new Property.
- * @param defaultValue
- * the value all created Properties are initialized to.
- * @return true
if the operation succeeded,
- * false
if not
- * @throws UnsupportedOperationException
- * if the addContainerProperty is not supported.
- */
- public boolean addContainerProperty(Object propertyId, Class type,
- Object defaultValue) throws UnsupportedOperationException {
-
- return container.addContainerProperty(propertyId, type, defaultValue);
- }
-
- /**
- * Removes the specified Property from the underlying container and from the
- * hierarchy.
- * true
if the operation succeeded,
- * false
if not
- * @throws UnsupportedOperationException
- * if the removeContainerProperty is not supported.
- */
- public boolean removeContainerProperty(Object propertyId)
- throws UnsupportedOperationException {
- return container.removeContainerProperty(propertyId);
- }
-
- /*
- * Does the container contain the specified Item? Don't add a JavaDoc
- * comment here, we use the default documentation from implemented
- * interface.
- */
- public boolean containsId(Object itemId) {
- return container.containsId(itemId);
- }
-
- /*
- * Gets the specified Item from the container. Don't add a JavaDoc comment
- * here, we use the default documentation from implemented interface.
- */
- public Item getItem(Object itemId) {
- return container.getItem(itemId);
- }
-
- /*
- * Gets the ID's of all Items stored in the Container Don't add a JavaDoc
- * comment here, we use the default documentation from implemented
- * interface.
- */
- public Collection getItemIds() {
- return container.getItemIds();
- }
-
- /*
- * Gets the Property identified by the given itemId and propertyId from the
- * Container Don't add a JavaDoc comment here, we use the default
- * documentation from implemented interface.
- */
- public Property getContainerProperty(Object itemId, Object propertyId) {
- return container.getContainerProperty(itemId, propertyId);
- }
-
- /*
- * Gets the ID's of all Properties stored in the Container Don't add a
- * JavaDoc comment here, we use the default documentation from implemented
- * interface.
- */
- public Collection getContainerPropertyIds() {
- return container.getContainerPropertyIds();
- }
-
- /*
- * Gets the data type of all Properties identified by the given Property ID.
- * Don't add a JavaDoc comment here, we use the default documentation from
- * implemented interface.
- */
- public Class getType(Object propertyId) {
- return container.getType(propertyId);
- }
-
- /*
- * Gets the number of Items in the Container. Don't add a JavaDoc comment
- * here, we use the default documentation from implemented interface.
- */
- public int size() {
- return container.size();
- }
-
- /*
- * Registers a new Item set change listener for this Container. Don't add a
- * JavaDoc comment here, we use the default documentation from implemented
- * interface.
- */
- public void addListener(Container.ItemSetChangeListener listener) {
- if (container instanceof Container.ItemSetChangeNotifier)
- ((Container.ItemSetChangeNotifier) container).addListener(listener);
- }
-
- /*
- * Removes a Item set change listener from the object. Don't add a JavaDoc
- * comment here, we use the default documentation from implemented
- * interface.
- */
- public void removeListener(Container.ItemSetChangeListener listener) {
- if (container instanceof Container.ItemSetChangeNotifier)
- ((Container.ItemSetChangeNotifier) container)
- .removeListener(listener);
- }
-
- /*
- * Registers a new Property set change listener for this Container. Don't
- * add a JavaDoc comment here, we use the default documentation from
- * implemented interface.
- */
- public void addListener(Container.PropertySetChangeListener listener) {
- if (container instanceof Container.PropertySetChangeNotifier)
- ((Container.PropertySetChangeNotifier) container)
- .addListener(listener);
- }
-
- /*
- * Removes a Property set change listener from the object. Don't add a
- * JavaDoc comment here, we use the default documentation from implemented
- * interface.
- */
- public void removeListener(Container.PropertySetChangeListener listener) {
- if (container instanceof Container.PropertySetChangeNotifier)
- ((Container.PropertySetChangeNotifier) container)
- .removeListener(listener);
- }
+ Container.ItemSetChangeNotifier, Container.PropertySetChangeNotifier {
+
+ /** The wrapped container */
+ private Container container;
+
+ /** Set of IDs of those contained Items that can't have children. */
+ private HashSet noChildrenAllowed = null;
+
+ /** Mapping from Item ID to parent Item */
+ private Hashtable parent = null;
+
+ /** Mapping from Item ID to a list of child IDs */
+ private Hashtable children = null;
+
+ /** List that contains all root elements of the container. */
+ private LinkedList roots = null;
+
+ /** Is the wrapped container hierarchical by itself ? */
+ private boolean hierarchical;
+
+ /**
+ * Constructs a new hierarchical wrapper for an existing Container. Works
+ * even if the to-be-wrapped container already implements the
+ * Container.Hierarchical
interface.
+ *
+ * @param toBeWrapped
+ * the container that needs to be accessed hierarchically
+ * @see #updateHierarchicalWrapper()
+ */
+ public ContainerHierarchicalWrapper(Container toBeWrapped) {
+
+ container = toBeWrapped;
+ hierarchical = container instanceof Container.Hierarchical;
+
+ // Check arguments
+ if (container == null) {
+ throw new NullPointerException("Null can not be wrapped");
+ }
+
+ // Create initial order if needed
+ if (!hierarchical) {
+ noChildrenAllowed = new HashSet();
+ parent = new Hashtable();
+ children = new Hashtable();
+ roots = new LinkedList(container.getItemIds());
+ }
+
+ updateHierarchicalWrapper();
+ }
+
+ /**
+ * Updates the wrapper's internal hierarchy data to include all Items in the
+ * underlying container. If the contents of the wrapped container change
+ * without the wrapper's knowledge, this method needs to be called to update
+ * the hierarchy information of the Items.
+ */
+ public void updateHierarchicalWrapper() {
+
+ if (!hierarchical) {
+
+ // Recreate hierarchy and datasrtuctures if missing
+ if (noChildrenAllowed == null || parent == null || children == null
+ || roots == null) {
+ noChildrenAllowed = new HashSet();
+ parent = new Hashtable();
+ children = new Hashtable();
+ roots = new LinkedList(container.getItemIds());
+ }
+
+ // Check that the hierarchy is up-to-date
+ else {
+
+ // Calculate the set of all items in the hierarchy
+ HashSet s = new HashSet();
+ s.add(parent.keySet());
+ s.add(children.keySet());
+ s.addAll(roots);
+
+ // Remove unnecessary items
+ for (Iterator i = s.iterator(); i.hasNext();) {
+ Object id = i.next();
+ if (!container.containsId(id)) {
+ removeFromHierarchyWrapper(id);
+ }
+ }
+
+ // Add all the missing items
+ Collection ids = container.getItemIds();
+ for (Iterator i = ids.iterator(); i.hasNext();) {
+ Object id = i.next();
+ if (!s.contains(id)) {
+ addToHierarchyWrapper(id);
+ s.add(id);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Removes the specified Item from the wrapper's internal hierarchy
+ * structure.
+ * false
is returned; the children must
+ * be first explicitly removed with
+ * {@link #setParent(Object itemId, Object newParentId)} or
+ * {@link com.itmill.toolkit.data.Container#removeItem(Object itemId)}.
+ * true
if the operation succeeded,
+ * false
if not
+ */
+ public boolean setChildrenAllowed(Object itemId, boolean childrenAllowed) {
+
+ // If the wrapped container implements the method directly, use it
+ if (hierarchical) {
+ return ((Container.Hierarchical) container).setChildrenAllowed(
+ itemId, childrenAllowed);
+ }
+
+ // Check that the item is in the container
+ if (!containsId(itemId)) {
+ return false;
+ }
+
+ // Update status
+ if (childrenAllowed) {
+ noChildrenAllowed.remove(itemId);
+ } else {
+ noChildrenAllowed.add(itemId);
+ }
+
+ return true;
+ }
+
+ /**
+ * canHaveChildren(newParentId) == true
).
+ * It is also possible to detach a node from the hierarchy (and thus make it
+ * root) by setting the parent null
.
+ * true
if the operation succeeded,
+ * false
if not
+ */
+ public boolean setParent(Object itemId, Object newParentId) {
+
+ // If the wrapped container implements the method directly, use it
+ if (hierarchical) {
+ return ((Container.Hierarchical) container).setParent(itemId,
+ newParentId);
+ }
+
+ // Check that the item is in the container
+ if (!containsId(itemId)) {
+ return false;
+ }
+
+ // Get the old parent
+ Object oldParentId = parent.get(itemId);
+
+ // Check if no change is necessary
+ if ((newParentId == null && oldParentId == null)
+ || (newParentId != null && newParentId.equals(oldParentId))) {
+ return true;
+ }
+
+ // Making root
+ if (newParentId == null) {
+
+ // Remove from old parents children list
+ LinkedList l = (LinkedList) children.get(itemId);
+ if (l != null) {
+ l.remove(itemId);
+ if (l.isEmpty()) {
+ children.remove(itemId);
+ }
+ }
+
+ // Add to be a root
+ roots.add(itemId);
+
+ // Update parent
+ parent.remove(itemId);
+
+ return true;
+ }
+
+ // Check that the new parent exists in container and can have
+ // children
+ if (!containsId(newParentId) || noChildrenAllowed.contains(newParentId)) {
+ return false;
+ }
+
+ // Check that setting parent doesn't result to a loop
+ Object o = newParentId;
+ while (o != null && !o.equals(itemId)) {
+ o = parent.get(o);
+ }
+ if (o != null) {
+ return false;
+ }
+
+ // Update parent
+ parent.put(itemId, newParentId);
+ LinkedList pcl = (LinkedList) children.get(newParentId);
+ if (pcl == null) {
+ pcl = new LinkedList();
+ children.put(newParentId, pcl);
+ }
+ pcl.add(itemId);
+
+ // Remove from old parent or root
+ if (oldParentId == null) {
+ roots.remove(itemId);
+ } else {
+ LinkedList l = (LinkedList) children.get(oldParentId);
+ if (l != null) {
+ l.remove(itemId);
+ if (l.isEmpty()) {
+ children.remove(oldParentId);
+ }
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * Creates a new Item into the Container, assigns it an automatic ID, and
+ * adds it to the hierarchy.
+ *
+ * @return the autogenerated ID of the new Item or null
if
+ * the operation failed
+ * @throws UnsupportedOperationException
+ * if the addItem is not supported.
+ */
+ public Object addItem() throws UnsupportedOperationException {
+
+ Object id = container.addItem();
+ if (id != null) {
+ addToHierarchyWrapper(id);
+ }
+ return id;
+ }
+
+ /**
+ * Adds a new Item by its ID to the underlying container and to the
+ * hierarchy.
+ *
+ * @param itemId
+ * the ID of the Item to be created.
+ * @return the added Item or null
if the operation failed.
+ * @throws UnsupportedOperationException
+ * if the addItem is not supported.
+ */
+ public Item addItem(Object itemId) throws UnsupportedOperationException {
+
+ Item item = container.addItem(itemId);
+ if (item != null) {
+ addToHierarchyWrapper(itemId);
+ }
+ return item;
+ }
+
+ /**
+ * Removes all items from the underlying container and from the hierarcy.
+ *
+ * @return true
if the operation succeeded,
+ * false
if not
+ * @throws UnsupportedOperationException
+ * if the removeAllItems is not supported.
+ */
+ public boolean removeAllItems() throws UnsupportedOperationException {
+
+ boolean success = container.removeAllItems();
+
+ if (success) {
+ roots.clear();
+ parent.clear();
+ children.clear();
+ noChildrenAllowed.clear();
+ }
+ return success;
+ }
+
+ /**
+ * Removes an Item specified by the itemId from the underlying container and
+ * from the hierarcy.
+ *
+ * @param itemId
+ * the ID of the Item to be removed.
+ * @return true
if the operation succeeded,
+ * false
if not
+ * @throws UnsupportedOperationException
+ * if the removeItem is not supported.
+ */
+ public boolean removeItem(Object itemId)
+ throws UnsupportedOperationException {
+
+ boolean success = container.removeItem(itemId);
+
+ if (success) {
+ removeFromHierarchyWrapper(itemId);
+ }
+
+ return success;
+ }
+
+ /**
+ * Adds a new Property to all Items in the Container.
+ *
+ * @param propertyId
+ * the ID of the new Property.
+ * @param type
+ * the Data type of the new Property.
+ * @param defaultValue
+ * the value all created Properties are initialized to.
+ * @return true
if the operation succeeded,
+ * false
if not
+ * @throws UnsupportedOperationException
+ * if the addContainerProperty is not supported.
+ */
+ public boolean addContainerProperty(Object propertyId, Class type,
+ Object defaultValue) throws UnsupportedOperationException {
+
+ return container.addContainerProperty(propertyId, type, defaultValue);
+ }
+
+ /**
+ * Removes the specified Property from the underlying container and from the
+ * hierarchy.
+ * true
if the operation succeeded,
+ * false
if not
+ * @throws UnsupportedOperationException
+ * if the removeContainerProperty is not supported.
+ */
+ public boolean removeContainerProperty(Object propertyId)
+ throws UnsupportedOperationException {
+ return container.removeContainerProperty(propertyId);
+ }
+
+ /*
+ * Does the container contain the specified Item? Don't add a JavaDoc
+ * comment here, we use the default documentation from implemented
+ * interface.
+ */
+ public boolean containsId(Object itemId) {
+ return container.containsId(itemId);
+ }
+
+ /*
+ * Gets the specified Item from the container. Don't add a JavaDoc comment
+ * here, we use the default documentation from implemented interface.
+ */
+ public Item getItem(Object itemId) {
+ return container.getItem(itemId);
+ }
+
+ /*
+ * Gets the ID's of all Items stored in the Container Don't add a JavaDoc
+ * comment here, we use the default documentation from implemented
+ * interface.
+ */
+ public Collection getItemIds() {
+ return container.getItemIds();
+ }
+
+ /*
+ * Gets the Property identified by the given itemId and propertyId from the
+ * Container Don't add a JavaDoc comment here, we use the default
+ * documentation from implemented interface.
+ */
+ public Property getContainerProperty(Object itemId, Object propertyId) {
+ return container.getContainerProperty(itemId, propertyId);
+ }
+
+ /*
+ * Gets the ID's of all Properties stored in the Container Don't add a
+ * JavaDoc comment here, we use the default documentation from implemented
+ * interface.
+ */
+ public Collection getContainerPropertyIds() {
+ return container.getContainerPropertyIds();
+ }
+
+ /*
+ * Gets the data type of all Properties identified by the given Property ID.
+ * Don't add a JavaDoc comment here, we use the default documentation from
+ * implemented interface.
+ */
+ public Class getType(Object propertyId) {
+ return container.getType(propertyId);
+ }
+
+ /*
+ * Gets the number of Items in the Container. Don't add a JavaDoc comment
+ * here, we use the default documentation from implemented interface.
+ */
+ public int size() {
+ return container.size();
+ }
+
+ /*
+ * Registers a new Item set change listener for this Container. Don't add a
+ * JavaDoc comment here, we use the default documentation from implemented
+ * interface.
+ */
+ public void addListener(Container.ItemSetChangeListener listener) {
+ if (container instanceof Container.ItemSetChangeNotifier) {
+ ((Container.ItemSetChangeNotifier) container).addListener(listener);
+ }
+ }
+
+ /*
+ * Removes a Item set change listener from the object. Don't add a JavaDoc
+ * comment here, we use the default documentation from implemented
+ * interface.
+ */
+ public void removeListener(Container.ItemSetChangeListener listener) {
+ if (container instanceof Container.ItemSetChangeNotifier) {
+ ((Container.ItemSetChangeNotifier) container)
+ .removeListener(listener);
+ }
+ }
+
+ /*
+ * Registers a new Property set change listener for this Container. Don't
+ * add a JavaDoc comment here, we use the default documentation from
+ * implemented interface.
+ */
+ public void addListener(Container.PropertySetChangeListener listener) {
+ if (container instanceof Container.PropertySetChangeNotifier) {
+ ((Container.PropertySetChangeNotifier) container)
+ .addListener(listener);
+ }
+ }
+
+ /*
+ * Removes a Property set change listener from the object. Don't add a
+ * JavaDoc comment here, we use the default documentation from implemented
+ * interface.
+ */
+ public void removeListener(Container.PropertySetChangeListener listener) {
+ if (container instanceof Container.PropertySetChangeNotifier) {
+ ((Container.PropertySetChangeNotifier) container)
+ .removeListener(listener);
+ }
+ }
}
diff --git a/src/com/itmill/toolkit/data/util/ContainerOrderedWrapper.java b/src/com/itmill/toolkit/data/util/ContainerOrderedWrapper.java
index 02f0813db4..b2fc22e8f8 100644
--- a/src/com/itmill/toolkit/data/util/ContainerOrderedWrapper.java
+++ b/src/com/itmill/toolkit/data/util/ContainerOrderedWrapper.java
@@ -29,9 +29,9 @@
package com.itmill.toolkit.data.util;
import java.util.Collection;
+import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
-import java.util.Hashtable;
import com.itmill.toolkit.data.Container;
import com.itmill.toolkit.data.Item;
@@ -55,493 +55,517 @@ import com.itmill.toolkit.data.Property;
* @since 3.0
*/
public class ContainerOrderedWrapper implements Container.Ordered,
- Container.ItemSetChangeNotifier, Container.PropertySetChangeNotifier {
-
- /**
- * The wrapped container
- */
- private Container container;
-
- /**
- * Ordering information, ie. the mapping from Item ID to the next item ID
- */
- private Hashtable next;
-
- /**
- * Reverse ordering information for convenience and performance reasons.
- */
- private Hashtable prev;
-
- /**
- * ID of the first Item in the container.
- */
- private Object first;
-
- /**
- * ID of the last Item in the container.
- */
- private Object last;
-
- /**
- * Is the wrapped container ordered by itself, ie. does it implement the
- * Container.Ordered interface by itself? If it does, this class will use
- * the methods of the underlying container directly.
- */
- private boolean ordered = false;
-
- /**
- * Constructs a new ordered wrapper for an existing Container. Works even if
- * the to-be-wrapped container already implements the Container.Ordered
- * interface.
- *
- * @param toBeWrapped
- * the container whose contents need to be ordered.
- */
- public ContainerOrderedWrapper(Container toBeWrapped) {
-
- container = toBeWrapped;
- ordered = container instanceof Container.Ordered;
-
- // Checks arguments
- if (container == null)
- throw new NullPointerException("Null can not be wrapped");
-
- // Creates initial order if needed
- updateOrderWrapper();
- }
-
- /**
- * Removes the specified Item from the wrapper's internal hierarchy
- * structure.
- * true
if the operation succeeded,
- * false
if not
- */
- public boolean addContainerProperty(Object propertyId, Class type,
- Object defaultValue) throws UnsupportedOperationException {
-
- return container.addContainerProperty(propertyId, type, defaultValue);
- }
-
- /**
- * Creates a new Item into the Container, assigns it an automatic ID, and
- * adds it to the ordering.
- *
- * @return the autogenerated ID of the new Item or null
if
- * the operation failed
- * @throws UnsupportedOperationException
- * if the addItem is not supported.
- */
- public Object addItem() throws UnsupportedOperationException {
-
- Object id = container.addItem();
- if (id != null)
- addToOrderWrapper(id);
- return id;
- }
-
- /**
- * Registers a new Item by its ID to the underlying container and to the
- * ordering.
- *
- * @param itemId
- * the ID of the Item to be created.
- * @return the added Item or null
if the operation failed
- * @throws UnsupportedOperationException
- * if the addItem is not supported.
- */
- public Item addItem(Object itemId) throws UnsupportedOperationException {
- Item item = container.addItem(itemId);
- if (item != null)
- addToOrderWrapper(itemId);
- return item;
- }
-
- /**
- * Removes all items from the underlying container and from the ordering.
- *
- * @return true
if the operation succeeded, otherwise
- * false
- * @throws UnsupportedOperationException
- * if the removeAllItems is not supported.
- */
- public boolean removeAllItems() throws UnsupportedOperationException {
- boolean success = container.removeAllItems();
- if (success) {
- first = last = null;
- next.clear();
- prev.clear();
- }
- return success;
- }
-
- /**
- * Removes an Item specified by the itemId from the underlying container and
- * from the ordering.
- *
- * @param itemId
- * the ID of the Item to be removed.
- * @return true
if the operation succeeded,
- * false
if not
- * @throws UnsupportedOperationException
- * if the removeItem is not supported.
- */
- public boolean removeItem(Object itemId)
- throws UnsupportedOperationException {
-
- boolean success = container.removeItem(itemId);
- if (success)
- removeFromOrderWrapper(itemId);
- return success;
- }
-
- /**
- * Removes the specified Property from the underlying container and from the
- * ordering.
- * true
if the operation succeeded,
- * false
if not
- * @throws UnsupportedOperationException
- * if the removeContainerProperty is not supported.
- */
- public boolean removeContainerProperty(Object propertyId)
- throws UnsupportedOperationException {
- return container.removeContainerProperty(propertyId);
- }
-
- /*
- * Does the container contain the specified Item? Don't add a JavaDoc
- * comment here, we use the default documentation from implemented
- * interface.
- */
- public boolean containsId(Object itemId) {
- return container.containsId(itemId);
- }
-
- /*
- * Gets the specified Item from the container. Don't add a JavaDoc comment
- * here, we use the default documentation from implemented interface.
- */
- public Item getItem(Object itemId) {
- return container.getItem(itemId);
- }
-
- /*
- * Gets the ID's of all Items stored in the Container Don't add a JavaDoc
- * comment here, we use the default documentation from implemented
- * interface.
- */
- public Collection getItemIds() {
- return container.getItemIds();
- }
-
- /*
- * Gets the Property identified by the given itemId and propertyId from the
- * Container Don't add a JavaDoc comment here, we use the default
- * documentation from implemented interface.
- */
- public Property getContainerProperty(Object itemId, Object propertyId) {
- return container.getContainerProperty(itemId, propertyId);
- }
-
- /*
- * Gets the ID's of all Properties stored in the Container Don't add a
- * JavaDoc comment here, we use the default documentation from implemented
- * interface.
- */
- public Collection getContainerPropertyIds() {
- return container.getContainerPropertyIds();
- }
-
- /*
- * Gets the data type of all Properties identified by the given Property ID.
- * Don't add a JavaDoc comment here, we use the default documentation from
- * implemented interface.
- */
- public Class getType(Object propertyId) {
- return container.getType(propertyId);
- }
-
- /*
- * Gets the number of Items in the Container. Don't add a JavaDoc comment
- * here, we use the default documentation from implemented interface.
- */
- public int size() {
- return container.size();
- }
-
- /*
- * Registers a new Item set change listener for this Container. Don't add a
- * JavaDoc comment here, we use the default documentation from implemented
- * interface.
- */
- public void addListener(Container.ItemSetChangeListener listener) {
- if (container instanceof Container.ItemSetChangeNotifier)
- ((Container.ItemSetChangeNotifier) container).addListener(listener);
- }
-
- /*
- * Removes a Item set change listener from the object. Don't add a JavaDoc
- * comment here, we use the default documentation from implemented
- * interface.
- */
- public void removeListener(Container.ItemSetChangeListener listener) {
- if (container instanceof Container.ItemSetChangeNotifier)
- ((Container.ItemSetChangeNotifier) container)
- .removeListener(listener);
- }
-
- /*
- * Registers a new Property set change listener for this Container. Don't
- * add a JavaDoc comment here, we use the default documentation from
- * implemented interface.
- */
- public void addListener(Container.PropertySetChangeListener listener) {
- if (container instanceof Container.PropertySetChangeNotifier)
- ((Container.PropertySetChangeNotifier) container)
- .addListener(listener);
- }
-
- /*
- * Removes a Property set change listener from the object. Don't add a
- * JavaDoc comment here, we use the default documentation from implemented
- * interface.
- */
- public void removeListener(Container.PropertySetChangeListener listener) {
- if (container instanceof Container.PropertySetChangeNotifier)
- ((Container.PropertySetChangeNotifier) container)
- .removeListener(listener);
- }
-
- /**
- * @see com.itmill.toolkit.data.Container.Ordered#addItemAfter(Object,
- * Object)
- */
- public Item addItemAfter(Object previousItemId, Object newItemId)
- throws UnsupportedOperationException {
-
- // If the previous item is not in the container, fail
- if (previousItemId != null && !containsId(previousItemId))
- return null;
-
- // Adds the item to container
- Item item = container.addItem(newItemId);
-
- // Puts the new item to its correct place
- if (item != null)
- addToOrderWrapper(newItemId, previousItemId);
-
- return item;
- }
-
- /**
- * @see com.itmill.toolkit.data.Container.Ordered#addItemAfter(Object)
- */
- public Object addItemAfter(Object previousItemId)
- throws UnsupportedOperationException {
-
- // If the previous item is not in the container, fail
- if (previousItemId != null && !containsId(previousItemId))
- return null;
-
- // Adds the item to container
- Object id = container.addItem();
-
- // Puts the new item to its correct place
- if (id != null)
- addToOrderWrapper(id, previousItemId);
-
- return id;
- }
+ Container.ItemSetChangeNotifier, Container.PropertySetChangeNotifier {
+
+ /**
+ * The wrapped container
+ */
+ private Container container;
+
+ /**
+ * Ordering information, ie. the mapping from Item ID to the next item ID
+ */
+ private Hashtable next;
+
+ /**
+ * Reverse ordering information for convenience and performance reasons.
+ */
+ private Hashtable prev;
+
+ /**
+ * ID of the first Item in the container.
+ */
+ private Object first;
+
+ /**
+ * ID of the last Item in the container.
+ */
+ private Object last;
+
+ /**
+ * Is the wrapped container ordered by itself, ie. does it implement the
+ * Container.Ordered interface by itself? If it does, this class will use
+ * the methods of the underlying container directly.
+ */
+ private boolean ordered = false;
+
+ /**
+ * Constructs a new ordered wrapper for an existing Container. Works even if
+ * the to-be-wrapped container already implements the Container.Ordered
+ * interface.
+ *
+ * @param toBeWrapped
+ * the container whose contents need to be ordered.
+ */
+ public ContainerOrderedWrapper(Container toBeWrapped) {
+
+ container = toBeWrapped;
+ ordered = container instanceof Container.Ordered;
+
+ // Checks arguments
+ if (container == null) {
+ throw new NullPointerException("Null can not be wrapped");
+ }
+
+ // Creates initial order if needed
+ updateOrderWrapper();
+ }
+
+ /**
+ * Removes the specified Item from the wrapper's internal hierarchy
+ * structure.
+ * true
if the operation succeeded,
+ * false
if not
+ */
+ public boolean addContainerProperty(Object propertyId, Class type,
+ Object defaultValue) throws UnsupportedOperationException {
+
+ return container.addContainerProperty(propertyId, type, defaultValue);
+ }
+
+ /**
+ * Creates a new Item into the Container, assigns it an automatic ID, and
+ * adds it to the ordering.
+ *
+ * @return the autogenerated ID of the new Item or null
if
+ * the operation failed
+ * @throws UnsupportedOperationException
+ * if the addItem is not supported.
+ */
+ public Object addItem() throws UnsupportedOperationException {
+
+ Object id = container.addItem();
+ if (id != null) {
+ addToOrderWrapper(id);
+ }
+ return id;
+ }
+
+ /**
+ * Registers a new Item by its ID to the underlying container and to the
+ * ordering.
+ *
+ * @param itemId
+ * the ID of the Item to be created.
+ * @return the added Item or null
if the operation failed
+ * @throws UnsupportedOperationException
+ * if the addItem is not supported.
+ */
+ public Item addItem(Object itemId) throws UnsupportedOperationException {
+ Item item = container.addItem(itemId);
+ if (item != null) {
+ addToOrderWrapper(itemId);
+ }
+ return item;
+ }
+
+ /**
+ * Removes all items from the underlying container and from the ordering.
+ *
+ * @return true
if the operation succeeded, otherwise
+ * false
+ * @throws UnsupportedOperationException
+ * if the removeAllItems is not supported.
+ */
+ public boolean removeAllItems() throws UnsupportedOperationException {
+ boolean success = container.removeAllItems();
+ if (success) {
+ first = last = null;
+ next.clear();
+ prev.clear();
+ }
+ return success;
+ }
+
+ /**
+ * Removes an Item specified by the itemId from the underlying container and
+ * from the ordering.
+ *
+ * @param itemId
+ * the ID of the Item to be removed.
+ * @return true
if the operation succeeded,
+ * false
if not
+ * @throws UnsupportedOperationException
+ * if the removeItem is not supported.
+ */
+ public boolean removeItem(Object itemId)
+ throws UnsupportedOperationException {
+
+ boolean success = container.removeItem(itemId);
+ if (success) {
+ removeFromOrderWrapper(itemId);
+ }
+ return success;
+ }
+
+ /**
+ * Removes the specified Property from the underlying container and from the
+ * ordering.
+ * true
if the operation succeeded,
+ * false
if not
+ * @throws UnsupportedOperationException
+ * if the removeContainerProperty is not supported.
+ */
+ public boolean removeContainerProperty(Object propertyId)
+ throws UnsupportedOperationException {
+ return container.removeContainerProperty(propertyId);
+ }
+
+ /*
+ * Does the container contain the specified Item? Don't add a JavaDoc
+ * comment here, we use the default documentation from implemented
+ * interface.
+ */
+ public boolean containsId(Object itemId) {
+ return container.containsId(itemId);
+ }
+
+ /*
+ * Gets the specified Item from the container. Don't add a JavaDoc comment
+ * here, we use the default documentation from implemented interface.
+ */
+ public Item getItem(Object itemId) {
+ return container.getItem(itemId);
+ }
+
+ /*
+ * Gets the ID's of all Items stored in the Container Don't add a JavaDoc
+ * comment here, we use the default documentation from implemented
+ * interface.
+ */
+ public Collection getItemIds() {
+ return container.getItemIds();
+ }
+
+ /*
+ * Gets the Property identified by the given itemId and propertyId from the
+ * Container Don't add a JavaDoc comment here, we use the default
+ * documentation from implemented interface.
+ */
+ public Property getContainerProperty(Object itemId, Object propertyId) {
+ return container.getContainerProperty(itemId, propertyId);
+ }
+
+ /*
+ * Gets the ID's of all Properties stored in the Container Don't add a
+ * JavaDoc comment here, we use the default documentation from implemented
+ * interface.
+ */
+ public Collection getContainerPropertyIds() {
+ return container.getContainerPropertyIds();
+ }
+
+ /*
+ * Gets the data type of all Properties identified by the given Property ID.
+ * Don't add a JavaDoc comment here, we use the default documentation from
+ * implemented interface.
+ */
+ public Class getType(Object propertyId) {
+ return container.getType(propertyId);
+ }
+
+ /*
+ * Gets the number of Items in the Container. Don't add a JavaDoc comment
+ * here, we use the default documentation from implemented interface.
+ */
+ public int size() {
+ return container.size();
+ }
+
+ /*
+ * Registers a new Item set change listener for this Container. Don't add a
+ * JavaDoc comment here, we use the default documentation from implemented
+ * interface.
+ */
+ public void addListener(Container.ItemSetChangeListener listener) {
+ if (container instanceof Container.ItemSetChangeNotifier) {
+ ((Container.ItemSetChangeNotifier) container).addListener(listener);
+ }
+ }
+
+ /*
+ * Removes a Item set change listener from the object. Don't add a JavaDoc
+ * comment here, we use the default documentation from implemented
+ * interface.
+ */
+ public void removeListener(Container.ItemSetChangeListener listener) {
+ if (container instanceof Container.ItemSetChangeNotifier) {
+ ((Container.ItemSetChangeNotifier) container)
+ .removeListener(listener);
+ }
+ }
+
+ /*
+ * Registers a new Property set change listener for this Container. Don't
+ * add a JavaDoc comment here, we use the default documentation from
+ * implemented interface.
+ */
+ public void addListener(Container.PropertySetChangeListener listener) {
+ if (container instanceof Container.PropertySetChangeNotifier) {
+ ((Container.PropertySetChangeNotifier) container)
+ .addListener(listener);
+ }
+ }
+
+ /*
+ * Removes a Property set change listener from the object. Don't add a
+ * JavaDoc comment here, we use the default documentation from implemented
+ * interface.
+ */
+ public void removeListener(Container.PropertySetChangeListener listener) {
+ if (container instanceof Container.PropertySetChangeNotifier) {
+ ((Container.PropertySetChangeNotifier) container)
+ .removeListener(listener);
+ }
+ }
+
+ /**
+ * @see com.itmill.toolkit.data.Container.Ordered#addItemAfter(Object,
+ * Object)
+ */
+ public Item addItemAfter(Object previousItemId, Object newItemId)
+ throws UnsupportedOperationException {
+
+ // If the previous item is not in the container, fail
+ if (previousItemId != null && !containsId(previousItemId)) {
+ return null;
+ }
+
+ // Adds the item to container
+ Item item = container.addItem(newItemId);
+
+ // Puts the new item to its correct place
+ if (item != null) {
+ addToOrderWrapper(newItemId, previousItemId);
+ }
+
+ return item;
+ }
+
+ /**
+ * @see com.itmill.toolkit.data.Container.Ordered#addItemAfter(Object)
+ */
+ public Object addItemAfter(Object previousItemId)
+ throws UnsupportedOperationException {
+
+ // If the previous item is not in the container, fail
+ if (previousItemId != null && !containsId(previousItemId)) {
+ return null;
+ }
+
+ // Adds the item to container
+ Object id = container.addItem();
+
+ // Puts the new item to its correct place
+ if (id != null) {
+ addToOrderWrapper(id, previousItemId);
+ }
+
+ return id;
+ }
}
diff --git a/src/com/itmill/toolkit/data/util/FilesystemContainer.java b/src/com/itmill/toolkit/data/util/FilesystemContainer.java
index f502b0fee8..789dd110aa 100644
--- a/src/com/itmill/toolkit/data/util/FilesystemContainer.java
+++ b/src/com/itmill/toolkit/data/util/FilesystemContainer.java
@@ -28,6 +28,10 @@
package com.itmill.toolkit.data.util;
+import java.io.File;
+import java.io.FilenameFilter;
+import java.io.IOException;
+import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
@@ -36,10 +40,6 @@ import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
-import java.io.File;
-import java.io.FilenameFilter;
-import java.io.IOException;
-import java.lang.reflect.Method;
import com.itmill.toolkit.data.Container;
import com.itmill.toolkit.data.Item;
@@ -57,802 +57,837 @@ import com.itmill.toolkit.terminal.Resource;
*/
public class FilesystemContainer implements Container.Hierarchical {
- /**
- * String identifier of a file's "name" property.
- */
- public static String PROPERTY_NAME = "Name";
-
- /**
- * String identifier of a file's "size" property.
- */
- public static String PROPERTY_SIZE = "Size";
-
- /**
- * String identifier of a file's "icon" property.
- */
- public static String PROPERTY_ICON = "Icon";
-
- /**
- * String identifier of a file's "last modified" property.
- */
- public static String PROPERTY_LASTMODIFIED = "Last Modified";
-
- /**
- * List of the string identifiers for the available properties.
- */
- public static Collection FILE_PROPERTIES;
-
- private static Method FILEITEM_LASTMODIFIED;
-
- private static Method FILEITEM_NAME;
-
- private static Method FILEITEM_ICON;
-
- private static Method FILEITEM_SIZE;
-
- static {
-
- FILE_PROPERTIES = new ArrayList();
- FILE_PROPERTIES.add(PROPERTY_NAME);
- FILE_PROPERTIES.add(PROPERTY_ICON);
- FILE_PROPERTIES.add(PROPERTY_SIZE);
- FILE_PROPERTIES.add(PROPERTY_LASTMODIFIED);
- FILE_PROPERTIES = Collections.unmodifiableCollection(FILE_PROPERTIES);
- try {
- FILEITEM_LASTMODIFIED = FileItem.class.getMethod("lastModified",
- new Class[] {});
- FILEITEM_NAME = FileItem.class.getMethod("getName", new Class[] {});
- FILEITEM_ICON = FileItem.class.getMethod("getIcon", new Class[] {});
- FILEITEM_SIZE = FileItem.class.getMethod("getSize", new Class[] {});
- } catch (NoSuchMethodException e) {
-
- }
- }
-
- private File[] roots = new File[] {};
-
- private FilenameFilter filter = null;
-
- private boolean recursive = true;
-
- /**
- * Constructs a new FileSystemContainer
with the specified
- * file as the root of the filesystem. The files are included recursively.
- *
- * @param root
- * the root file for the new file-system container. Null values
- * are ignored.
- */
- public FilesystemContainer(File root) {
- if (root != null) {
- this.roots = new File[] { root };
- }
- }
-
- /**
- * Constructs a new FileSystemContainer
with the specified
- * file as the root of the filesystem. The files are included recursively.
- *
- * @param root
- * the root file for the new file-system container.
- * @param recursive
- * should the container recursively contain subdirectories.
- */
- public FilesystemContainer(File root, boolean recursive) {
- this(root);
- this.setRecursive(recursive);
- }
-
- /**
- * Constructs a new FileSystemContainer
with the specified
- * file as the root of the filesystem.
- *
- * @param root
- * the root file for the new file-system container.
- * @param extension
- * the Filename extension (w/o separator) to limit the files in
- * container.
- * @param recursive
- * should the container recursively contain subdirectories.
- */
- public FilesystemContainer(File root, String extension, boolean recursive) {
- this(root);
- this.setFilter(extension);
- this.setRecursive(recursive);
- }
-
- /**
- * Constructs a new FileSystemContainer
with the specified
- * root and recursivity status.
- *
- * @param root
- * the root file for the new file-system container.
- * @param filter
- * the Filename filter to limit the files in container.
- * @param recursive
- * should the container recursively contain subdirectories.
- */
- public FilesystemContainer(File root, FilenameFilter filter,
- boolean recursive) {
- this(root);
- this.setFilter(filter);
- this.setRecursive(recursive);
- }
-
- /**
- * Adds new root file directory. Adds a file to be included as root file
- * directory in the FilesystemContainer
.
- *
- * @param root
- * the File to be added as root directory. Null values are
- * ignored.
- */
- public void addRoot(File root) {
- if (root != null) {
- File[] newRoots = new File[this.roots.length + 1];
- for (int i = 0; i < this.roots.length; i++) {
- newRoots[i] = this.roots[i];
- }
- newRoots[this.roots.length] = root;
- this.roots = newRoots;
- }
- }
-
- /**
- * Tests if the specified Item in the container may have children. Since a
- * FileSystemContainer
contains files and directories, this
- * method returns true
for directory Items only.
- *
- * @param itemId
- * the id of the item.
- * @return true
if the specified Item is a directory,
- * false
otherwise.
- */
- public boolean areChildrenAllowed(Object itemId) {
- return itemId instanceof File && ((File) itemId).canRead()
- && ((File) itemId).isDirectory();
- }
-
- /*
- * Gets the ID's of all Items who are children of the specified Item. Don't
- * add a JavaDoc comment here, we use the default documentation from
- * implemented interface.
- */
- public Collection getChildren(Object itemId) {
-
- if (!(itemId instanceof File))
- return Collections.unmodifiableCollection(new LinkedList());
- File[] f;
- if (this.filter != null)
- f = ((File) itemId).listFiles(this.filter);
- else
- f = ((File) itemId).listFiles();
-
- if (f == null)
- return Collections.unmodifiableCollection(new LinkedList());
-
- List l = Arrays.asList(f);
- Collections.sort(l);
-
- return Collections.unmodifiableCollection(l);
- }
-
- /*
- * Gets the parent item of the specified Item. Don't add a JavaDoc comment
- * here, we use the default documentation from implemented interface.
- */
- public Object getParent(Object itemId) {
-
- if (!(itemId instanceof File))
- return null;
- return ((File) itemId).getParentFile();
- }
-
- /*
- * Tests if the specified Item has any children. Don't add a JavaDoc comment
- * here, we use the default documentation from implemented interface.
- */
- public boolean hasChildren(Object itemId) {
-
- if (!(itemId instanceof File))
- return false;
- String[] l;
- if (this.filter != null)
- l = ((File) itemId).list(this.filter);
- else
- l = ((File) itemId).list();
- return (l != null) && (l.length > 0);
- }
-
- /*
- * Tests if the specified Item is the root of the filesystem. Don't add a
- * JavaDoc comment here, we use the default documentation from implemented
- * interface.
- */
- public boolean isRoot(Object itemId) {
-
- if (!(itemId instanceof File))
- return false;
- for (int i = 0; i < roots.length; i++) {
- if (roots[i].equals((File) itemId))
- return true;
- }
- return false;
- }
-
- /*
- * Gets the ID's of all root Items in the container. Don't add a JavaDoc
- * comment here, we use the default documentation from implemented
- * interface.
- */
- public Collection rootItemIds() {
-
- File[] f;
-
- // in single root case we use children
- if (roots.length == 1) {
- if (this.filter != null)
- f = roots[0].listFiles(this.filter);
- else
- f = roots[0].listFiles();
- } else {
- f = this.roots;
- }
-
- if (f == null)
- return Collections.unmodifiableCollection(new LinkedList());
-
- List l = Arrays.asList(f);
- Collections.sort(l);
-
- return Collections.unmodifiableCollection(l);
- }
-
- /**
- * Returns false
when conversion from files to directories is
- * not supported.
- *
- * @param itemId
- * the ID of the item.
- * @param areChildrenAllowed
- * the boolean value specifying if the Item can have children or
- * not.
- * @return true
if the operaton is successful otherwise
- * false
.
- * @throws UnsupportedOperationException
- * if the setChildrenAllowed is not supported.
- */
- public boolean setChildrenAllowed(Object itemId, boolean areChildrenAllowed)
- throws UnsupportedOperationException {
-
- throw new UnsupportedOperationException(
- "Conversion file to/from directory is not supported");
- }
-
- /**
- * Returns false
when moving files around in the filesystem
- * is not supported.
- *
- * @param itemId
- * the ID of the item.
- * @param newParentId
- * the ID of the Item that's to be the new parent of the Item
- * identified with itemId.
- * @return true
if the operation is successful otherwise
- * false
.
- * @throws UnsupportedOperationException
- * if the setParent is not supported.
- */
- public boolean setParent(Object itemId, Object newParentId)
- throws UnsupportedOperationException {
-
- throw new UnsupportedOperationException("File moving is not supported");
- }
-
- /*
- * Tests if the filesystem contains the specified Item. Don't add a JavaDoc
- * comment here, we use the default documentation from implemented
- * interface.
- */
- public boolean containsId(Object itemId) {
-
- if (!(itemId instanceof File))
- return false;
- boolean val = false;
-
- // Try to match all roots
- for (int i = 0; i < roots.length; i++) {
- try {
- val |= ((File) itemId).getCanonicalPath().startsWith(
- roots[i].getCanonicalPath());
- } catch (IOException e) {
- // Exception ignored
- }
-
- }
- if (val && this.filter != null)
- val &= this.filter.accept(((File) itemId).getParentFile(),
- ((File) itemId).getName());
- return val;
- }
-
- /*
- * Gets the specified Item from the filesystem. Don't add a JavaDoc comment
- * here, we use the default documentation from implemented interface.
- */
- public Item getItem(Object itemId) {
-
- if (!(itemId instanceof File))
- return null;
- return new FileItem((File) itemId);
- }
-
- /**
- * Internal recursive method to add the files under the specified directory
- * to the collection.
- *
- * @param col
- * the collection where the found items are added
- * @param f
- * the root file where to start adding files
- */
- private void addItemIds(Collection col, File f) {
- File[] l;
- if (this.filter != null)
- l = f.listFiles(this.filter);
- else
- l = f.listFiles();
- List ll = Arrays.asList(l);
- Collections.sort(ll);
-
- for (Iterator i = ll.iterator(); i.hasNext();) {
- File lf = (File) i.next();
- if (lf.isDirectory())
- addItemIds(col, lf);
- else
- col.add(lf);
- }
- }
-
- /*
- * Gets the IDs of Items in the filesystem. Don't add a JavaDoc comment
- * here, we use the default documentation from implemented interface.
- */
- public Collection getItemIds() {
-
- if (recursive) {
- Collection col = new ArrayList();
- for (int i = 0; i < roots.length; i++) {
- addItemIds(col, roots[i]);
- }
- return Collections.unmodifiableCollection(col);
- } else {
- File[] f;
- if (roots.length == 1) {
- if (this.filter != null)
- f = roots[0].listFiles(this.filter);
- else
- f = roots[0].listFiles();
- } else {
- f = roots;
- }
-
- if (f == null)
- return Collections.unmodifiableCollection(new LinkedList());
-
- List l = Arrays.asList(f);
- Collections.sort(l);
- return Collections.unmodifiableCollection(l);
- }
-
- }
-
- /**
- * Gets the specified property of the specified file Item. The available
- * file properties are "Name", "Size" and "Last Modified". If propertyId is
- * not one of those, null
is returned.
- *
- * @param itemId
- * the ID of the file whose property is requested.
- * @param propertyId
- * the property's ID.
- * @return the requested property's value, or null
- */
- public Property getContainerProperty(Object itemId, Object propertyId) {
-
- if (!(itemId instanceof File))
- return null;
-
- if (propertyId.equals(PROPERTY_NAME))
- return new MethodProperty(getType(propertyId), new FileItem(
- (File) itemId), FILEITEM_NAME, null);
-
- if (propertyId.equals(PROPERTY_ICON))
- return new MethodProperty(getType(propertyId), new FileItem(
- (File) itemId), FILEITEM_ICON, null);
-
- if (propertyId.equals(PROPERTY_SIZE))
- return new MethodProperty(getType(propertyId), new FileItem(
- (File) itemId), FILEITEM_SIZE, null);
-
- if (propertyId.equals(PROPERTY_LASTMODIFIED))
- return new MethodProperty(getType(propertyId), new FileItem(
- (File) itemId), FILEITEM_LASTMODIFIED, null);
-
- return null;
- }
-
- /**
- * Gets the collection of available file properties.
- *
- * @return Unmodifiable collection containing all available file properties.
- */
- public Collection getContainerPropertyIds() {
- return FILE_PROPERTIES;
- }
-
- /**
- * Gets the specified property's data type. "Name" is a String
,
- * "Size" is a Long
, "Last Modified" is a Date
.
- * If propertyId is not one of those, null
is returned.
- *
- * @param propertyId
- * the ID of the property whose type is requested.
- * @return data type of the requested property, or null
- */
- public Class getType(Object propertyId) {
-
- if (propertyId.equals(PROPERTY_NAME))
- return String.class;
- if (propertyId.equals(PROPERTY_ICON))
- return Resource.class;
- if (propertyId.equals(PROPERTY_SIZE))
- return Long.class;
- if (propertyId.equals(PROPERTY_LASTMODIFIED))
- return Date.class;
- return null;
- }
-
- /**
- * Internal method to recursively calculate the number of files under a root
- * directory.
- *
- * @param f
- * the root to start counting from.
- */
- private int getFileCounts(File f) {
- File[] l;
- if (this.filter != null)
- l = f.listFiles(this.filter);
- else
- l = f.listFiles();
-
- if (l == null)
- return 0;
- int ret = l.length;
- for (int i = 0; i < l.length; i++) {
- if (l[i].isDirectory())
- ret += getFileCounts(l[i]);
- }
- return ret;
- }
-
- /**
- * Gets the number of Items in the container. In effect, this is the
- * combined amount of files and directories.
- *
- * @return Number of Items in the container.
- */
- public int size() {
-
- if (recursive) {
- int counts = 0;
- for (int i = 0; i < roots.length; i++) {
- counts += getFileCounts(this.roots[i]);
- }
- return counts;
- } else {
- File[] f;
- if (roots.length == 1) {
- if (this.filter != null)
- f = roots[0].listFiles(this.filter);
- else
- f = roots[0].listFiles();
- } else {
- f = roots;
- }
-
- if (f == null)
- return 0;
- return f.length;
- }
- }
-
- /**
- * A Item wrapper for files in a filesystem.
- *
- * @author IT Mill Ltd.
- * @version
- * @VERSION@
- * @since 3.0
- */
- public class FileItem implements Item {
-
- /**
- * The wrapped file.
- */
- private File file;
-
- /**
- * Constructs a FileItem from a existing file.
- */
- private FileItem(File file) {
- this.file = file;
- }
-
- /*
- * Gets the specified property of this file. Don't add a JavaDoc comment
- * here, we use the default documentation from implemented interface.
- */
- public Property getItemProperty(Object id) {
- return FilesystemContainer.this.getContainerProperty(file, id);
- }
-
- /*
- * Gets the IDs of all properties available for this item Don't add a
- * JavaDoc comment here, we use the default documentation from
- * implemented interface.
- */
- public Collection getItemPropertyIds() {
- return FilesystemContainer.this.getContainerPropertyIds();
- }
-
- /**
- * Calculates a integer hash-code for the Property that's unique inside
- * the Item containing the Property. Two different Properties inside the
- * same Item contained in the same list always have different
- * hash-codes, though Properties in different Items may have identical
- * hash-codes.
- *
- * @return A locally unique hash-code as integer
- */
- public int hashCode() {
- return file.hashCode() ^ FilesystemContainer.this.hashCode();
- }
-
- /**
- * Tests if the given object is the same as the this object. Two
- * Properties got from an Item with the same ID are equal.
- *
- * @param obj
- * an object to compare with this object.
- * @return true
if the given object is the same as this
- * object, false
if not
- */
- public boolean equals(Object obj) {
- if (obj == null || !(obj instanceof FileItem))
- return false;
- FileItem fi = (FileItem) obj;
- return fi.getHost() == getHost() && fi.file.equals(file);
- }
-
- /**
- * Gets the host of this file.
- */
- private FilesystemContainer getHost() {
- return FilesystemContainer.this;
- }
-
- /**
- * Gets the last modified date of this file.
- *
- * @return Date
- */
- public Date lastModified() {
- return new Date(this.file.lastModified());
- }
-
- /**
- * Gets the name of this file.
- *
- * @return file name of this file.
- */
- public String getName() {
- return this.file.getName();
- }
-
- /**
- * Gets the icon of this file.
- *
- * @return the icon of this file.
- */
- public Resource getIcon() {
- return FileTypeResolver.getIcon(this.file);
- }
-
- /**
- * Gets the size of this file.
- *
- * @return size
- */
- public long getSize() {
- if (this.file.isDirectory())
- return 0;
- return this.file.length();
- }
-
- /**
- * @see java.lang.Object#toString()
- */
- public String toString() {
- if ("".equals(file.getName()))
- return file.getAbsolutePath();
- return file.getName();
- }
-
- /**
- * Filesystem container does not support adding new properties.
- *
- * @see com.itmill.toolkit.data.Item#addItemProperty(Object, Property)
- */
- public boolean addItemProperty(Object id, Property property)
- throws UnsupportedOperationException {
- throw new UnsupportedOperationException("Filesystem container "
- + "does not support adding new properties");
- }
-
- /**
- * Filesystem container does not support removing properties.
- *
- * @see com.itmill.toolkit.data.Item#removeItemProperty(Object)
- */
- public boolean removeItemProperty(Object id)
- throws UnsupportedOperationException {
- throw new UnsupportedOperationException(
- "Filesystem container does not support property removal");
- }
-
- }
-
- /**
- * Generic file extension filter for displaying only files having certain
- * extension.
- *
- * @author IT Mill Ltd.
- * @version
- * @VERSION@
- * @since 3.0
- */
- public class FileExtensionFilter implements FilenameFilter {
-
- private String filter;
-
- /**
- * Constructs a new FileExtensionFilter using given extension.
- *
- * @param fileExtension
- * the File extension without the separator (dot).
- */
- public FileExtensionFilter(String fileExtension) {
- this.filter = "." + fileExtension;
- }
-
- /**
- * Allows only files with the extension and directories.
- *
- * @see java.io.FilenameFilter#accept(File, String)
- */
- public boolean accept(File dir, String name) {
- if (name.endsWith(filter))
- return true;
- return new File(dir, name).isDirectory();
- }
-
- }
-
- /**
- * Returns the file filter used to limit the files in this container.
- *
- * @return Used filter instance or null if no filter is assigned.
- */
- public FilenameFilter getFilter() {
- return filter;
- }
-
- /**
- * Sets the file filter used to limit the files in this container.
- *
- * @param filter
- * The filter to set. null
disables filtering.
- */
- public void setFilter(FilenameFilter filter) {
- this.filter = filter;
- }
-
- /**
- * Sets the file filter used to limit the files in this container.
- *
- * @param extension
- * the Filename extension (w/o separator) to limit the files in
- * container.
- */
- public void setFilter(String extension) {
- this.filter = new FileExtensionFilter(extension);
- }
-
- /**
- * Is this container recursive filesystem.
- *
- * @return true
if container is recursive, false
- * otherwise.
- */
- public boolean isRecursive() {
- return recursive;
- }
-
- /**
- * Sets the container recursive property. Set this to false to limit the
- * files directly under the root file.
- * FileSystemContainer
with the specified
+ * file as the root of the filesystem. The files are included recursively.
+ *
+ * @param root
+ * the root file for the new file-system container. Null
+ * values are ignored.
+ */
+ public FilesystemContainer(File root) {
+ if (root != null) {
+ roots = new File[] { root };
+ }
+ }
+
+ /**
+ * Constructs a new FileSystemContainer
with the specified
+ * file as the root of the filesystem. The files are included recursively.
+ *
+ * @param root
+ * the root file for the new file-system container.
+ * @param recursive
+ * should the container recursively contain subdirectories.
+ */
+ public FilesystemContainer(File root, boolean recursive) {
+ this(root);
+ setRecursive(recursive);
+ }
+
+ /**
+ * Constructs a new FileSystemContainer
with the specified
+ * file as the root of the filesystem.
+ *
+ * @param root
+ * the root file for the new file-system container.
+ * @param extension
+ * the Filename extension (w/o separator) to limit the files
+ * in container.
+ * @param recursive
+ * should the container recursively contain subdirectories.
+ */
+ public FilesystemContainer(File root, String extension, boolean recursive) {
+ this(root);
+ this.setFilter(extension);
+ setRecursive(recursive);
+ }
+
+ /**
+ * Constructs a new FileSystemContainer
with the specified
+ * root and recursivity status.
+ *
+ * @param root
+ * the root file for the new file-system container.
+ * @param filter
+ * the Filename filter to limit the files in container.
+ * @param recursive
+ * should the container recursively contain subdirectories.
+ */
+ public FilesystemContainer(File root, FilenameFilter filter,
+ boolean recursive) {
+ this(root);
+ this.setFilter(filter);
+ setRecursive(recursive);
+ }
+
+ /**
+ * Adds new root file directory. Adds a file to be included as root file
+ * directory in the FilesystemContainer
.
+ *
+ * @param root
+ * the File to be added as root directory. Null values are
+ * ignored.
+ */
+ public void addRoot(File root) {
+ if (root != null) {
+ File[] newRoots = new File[roots.length + 1];
+ for (int i = 0; i < roots.length; i++) {
+ newRoots[i] = roots[i];
+ }
+ newRoots[roots.length] = root;
+ roots = newRoots;
+ }
+ }
+
+ /**
+ * Tests if the specified Item in the container may have children. Since a
+ * FileSystemContainer
contains files and directories, this
+ * method returns true
for directory Items only.
+ *
+ * @param itemId
+ * the id of the item.
+ * @return true
if the specified Item is a directory,
+ * false
otherwise.
+ */
+ public boolean areChildrenAllowed(Object itemId) {
+ return itemId instanceof File && ((File) itemId).canRead()
+ && ((File) itemId).isDirectory();
+ }
+
+ /*
+ * Gets the ID's of all Items who are children of the specified Item. Don't
+ * add a JavaDoc comment here, we use the default documentation from
+ * implemented interface.
+ */
+ public Collection getChildren(Object itemId) {
+
+ if (!(itemId instanceof File)) {
+ return Collections.unmodifiableCollection(new LinkedList());
+ }
+ File[] f;
+ if (filter != null) {
+ f = ((File) itemId).listFiles(filter);
+ } else {
+ f = ((File) itemId).listFiles();
+ }
+
+ if (f == null) {
+ return Collections.unmodifiableCollection(new LinkedList());
+ }
+
+ List l = Arrays.asList(f);
+ Collections.sort(l);
+
+ return Collections.unmodifiableCollection(l);
+ }
+
+ /*
+ * Gets the parent item of the specified Item. Don't add a JavaDoc comment
+ * here, we use the default documentation from implemented interface.
+ */
+ public Object getParent(Object itemId) {
+
+ if (!(itemId instanceof File)) {
+ return null;
+ }
+ return ((File) itemId).getParentFile();
+ }
+
+ /*
+ * Tests if the specified Item has any children. Don't add a JavaDoc comment
+ * here, we use the default documentation from implemented interface.
+ */
+ public boolean hasChildren(Object itemId) {
+
+ if (!(itemId instanceof File)) {
+ return false;
+ }
+ String[] l;
+ if (filter != null) {
+ l = ((File) itemId).list(filter);
+ } else {
+ l = ((File) itemId).list();
+ }
+ return (l != null) && (l.length > 0);
+ }
+
+ /*
+ * Tests if the specified Item is the root of the filesystem. Don't add a
+ * JavaDoc comment here, we use the default documentation from implemented
+ * interface.
+ */
+ public boolean isRoot(Object itemId) {
+
+ if (!(itemId instanceof File)) {
+ return false;
+ }
+ for (int i = 0; i < roots.length; i++) {
+ if (roots[i].equals(itemId)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /*
+ * Gets the ID's of all root Items in the container. Don't add a JavaDoc
+ * comment here, we use the default documentation from implemented
+ * interface.
+ */
+ public Collection rootItemIds() {
+
+ File[] f;
+
+ // in single root case we use children
+ if (roots.length == 1) {
+ if (filter != null) {
+ f = roots[0].listFiles(filter);
+ } else {
+ f = roots[0].listFiles();
+ }
+ } else {
+ f = roots;
+ }
+
+ if (f == null) {
+ return Collections.unmodifiableCollection(new LinkedList());
+ }
+
+ List l = Arrays.asList(f);
+ Collections.sort(l);
+
+ return Collections.unmodifiableCollection(l);
+ }
+
+ /**
+ * Returns false
when conversion from files to directories is
+ * not supported.
+ *
+ * @param itemId
+ * the ID of the item.
+ * @param areChildrenAllowed
+ * the boolean value specifying if the Item can have children
+ * or not.
+ * @return true
if the operaton is successful otherwise
+ * false
.
+ * @throws UnsupportedOperationException
+ * if the setChildrenAllowed is not supported.
+ */
+ public boolean setChildrenAllowed(Object itemId, boolean areChildrenAllowed)
+ throws UnsupportedOperationException {
+
+ throw new UnsupportedOperationException(
+ "Conversion file to/from directory is not supported");
+ }
+
+ /**
+ * Returns false
when moving files around in the filesystem
+ * is not supported.
+ *
+ * @param itemId
+ * the ID of the item.
+ * @param newParentId
+ * the ID of the Item that's to be the new parent of the Item
+ * identified with itemId.
+ * @return true
if the operation is successful otherwise
+ * false
.
+ * @throws UnsupportedOperationException
+ * if the setParent is not supported.
+ */
+ public boolean setParent(Object itemId, Object newParentId)
+ throws UnsupportedOperationException {
+
+ throw new UnsupportedOperationException("File moving is not supported");
+ }
+
+ /*
+ * Tests if the filesystem contains the specified Item. Don't add a JavaDoc
+ * comment here, we use the default documentation from implemented
+ * interface.
+ */
+ public boolean containsId(Object itemId) {
+
+ if (!(itemId instanceof File)) {
+ return false;
+ }
+ boolean val = false;
+
+ // Try to match all roots
+ for (int i = 0; i < roots.length; i++) {
+ try {
+ val |= ((File) itemId).getCanonicalPath().startsWith(
+ roots[i].getCanonicalPath());
+ } catch (IOException e) {
+ // Exception ignored
+ }
+
+ }
+ if (val && filter != null) {
+ val &= filter.accept(((File) itemId).getParentFile(),
+ ((File) itemId).getName());
+ }
+ return val;
+ }
+
+ /*
+ * Gets the specified Item from the filesystem. Don't add a JavaDoc comment
+ * here, we use the default documentation from implemented interface.
+ */
+ public Item getItem(Object itemId) {
+
+ if (!(itemId instanceof File)) {
+ return null;
+ }
+ return new FileItem((File) itemId);
+ }
+
+ /**
+ * Internal recursive method to add the files under the specified directory
+ * to the collection.
+ *
+ * @param col
+ * the collection where the found items are added
+ * @param f
+ * the root file where to start adding files
+ */
+ private void addItemIds(Collection col, File f) {
+ File[] l;
+ if (filter != null) {
+ l = f.listFiles(filter);
+ } else {
+ l = f.listFiles();
+ }
+ List ll = Arrays.asList(l);
+ Collections.sort(ll);
+
+ for (Iterator i = ll.iterator(); i.hasNext();) {
+ File lf = (File) i.next();
+ if (lf.isDirectory()) {
+ addItemIds(col, lf);
+ } else {
+ col.add(lf);
+ }
+ }
+ }
+
+ /*
+ * Gets the IDs of Items in the filesystem. Don't add a JavaDoc comment
+ * here, we use the default documentation from implemented interface.
+ */
+ public Collection getItemIds() {
+
+ if (recursive) {
+ Collection col = new ArrayList();
+ for (int i = 0; i < roots.length; i++) {
+ addItemIds(col, roots[i]);
+ }
+ return Collections.unmodifiableCollection(col);
+ } else {
+ File[] f;
+ if (roots.length == 1) {
+ if (filter != null) {
+ f = roots[0].listFiles(filter);
+ } else {
+ f = roots[0].listFiles();
+ }
+ } else {
+ f = roots;
+ }
+
+ if (f == null) {
+ return Collections.unmodifiableCollection(new LinkedList());
+ }
+
+ List l = Arrays.asList(f);
+ Collections.sort(l);
+ return Collections.unmodifiableCollection(l);
+ }
+
+ }
+
+ /**
+ * Gets the specified property of the specified file Item. The available
+ * file properties are "Name", "Size" and "Last Modified". If propertyId is
+ * not one of those, null
is returned.
+ *
+ * @param itemId
+ * the ID of the file whose property is requested.
+ * @param propertyId
+ * the property's ID.
+ * @return the requested property's value, or null
+ */
+ public Property getContainerProperty(Object itemId, Object propertyId) {
+
+ if (!(itemId instanceof File)) {
+ return null;
+ }
+
+ if (propertyId.equals(PROPERTY_NAME)) {
+ return new MethodProperty(getType(propertyId), new FileItem(
+ (File) itemId), FILEITEM_NAME, null);
+ }
+
+ if (propertyId.equals(PROPERTY_ICON)) {
+ return new MethodProperty(getType(propertyId), new FileItem(
+ (File) itemId), FILEITEM_ICON, null);
+ }
+
+ if (propertyId.equals(PROPERTY_SIZE)) {
+ return new MethodProperty(getType(propertyId), new FileItem(
+ (File) itemId), FILEITEM_SIZE, null);
+ }
+
+ if (propertyId.equals(PROPERTY_LASTMODIFIED)) {
+ return new MethodProperty(getType(propertyId), new FileItem(
+ (File) itemId), FILEITEM_LASTMODIFIED, null);
+ }
+
+ return null;
+ }
+
+ /**
+ * Gets the collection of available file properties.
+ *
+ * @return Unmodifiable collection containing all available file properties.
+ */
+ public Collection getContainerPropertyIds() {
+ return FILE_PROPERTIES;
+ }
+
+ /**
+ * Gets the specified property's data type. "Name" is a String
,
+ * "Size" is a Long
, "Last Modified" is a Date
.
+ * If propertyId is not one of those, null
is returned.
+ *
+ * @param propertyId
+ * the ID of the property whose type is requested.
+ * @return data type of the requested property, or null
+ */
+ public Class getType(Object propertyId) {
+
+ if (propertyId.equals(PROPERTY_NAME)) {
+ return String.class;
+ }
+ if (propertyId.equals(PROPERTY_ICON)) {
+ return Resource.class;
+ }
+ if (propertyId.equals(PROPERTY_SIZE)) {
+ return Long.class;
+ }
+ if (propertyId.equals(PROPERTY_LASTMODIFIED)) {
+ return Date.class;
+ }
+ return null;
+ }
+
+ /**
+ * Internal method to recursively calculate the number of files under a root
+ * directory.
+ *
+ * @param f
+ * the root to start counting from.
+ */
+ private int getFileCounts(File f) {
+ File[] l;
+ if (filter != null) {
+ l = f.listFiles(filter);
+ } else {
+ l = f.listFiles();
+ }
+
+ if (l == null) {
+ return 0;
+ }
+ int ret = l.length;
+ for (int i = 0; i < l.length; i++) {
+ if (l[i].isDirectory()) {
+ ret += getFileCounts(l[i]);
+ }
+ }
+ return ret;
+ }
+
+ /**
+ * Gets the number of Items in the container. In effect, this is the
+ * combined amount of files and directories.
+ *
+ * @return Number of Items in the container.
+ */
+ public int size() {
+
+ if (recursive) {
+ int counts = 0;
+ for (int i = 0; i < roots.length; i++) {
+ counts += getFileCounts(roots[i]);
+ }
+ return counts;
+ } else {
+ File[] f;
+ if (roots.length == 1) {
+ if (filter != null) {
+ f = roots[0].listFiles(filter);
+ } else {
+ f = roots[0].listFiles();
+ }
+ } else {
+ f = roots;
+ }
+
+ if (f == null) {
+ return 0;
+ }
+ return f.length;
+ }
+ }
+
+ /**
+ * A Item wrapper for files in a filesystem.
+ *
+ * @author IT Mill Ltd.
+ * @version
+ * @VERSION@
+ * @since 3.0
+ */
+ public class FileItem implements Item {
+
+ /**
+ * The wrapped file.
+ */
+ private File file;
+
+ /**
+ * Constructs a FileItem from a existing file.
+ */
+ private FileItem(File file) {
+ this.file = file;
+ }
+
+ /*
+ * Gets the specified property of this file. Don't add a JavaDoc comment
+ * here, we use the default documentation from implemented interface.
+ */
+ public Property getItemProperty(Object id) {
+ return getContainerProperty(file, id);
+ }
+
+ /*
+ * Gets the IDs of all properties available for this item Don't add a
+ * JavaDoc comment here, we use the default documentation from
+ * implemented interface.
+ */
+ public Collection getItemPropertyIds() {
+ return getContainerPropertyIds();
+ }
+
+ /**
+ * Calculates a integer hash-code for the Property that's unique inside
+ * the Item containing the Property. Two different Properties inside the
+ * same Item contained in the same list always have different
+ * hash-codes, though Properties in different Items may have identical
+ * hash-codes.
+ *
+ * @return A locally unique hash-code as integer
+ */
+ public int hashCode() {
+ return file.hashCode() ^ FilesystemContainer.this.hashCode();
+ }
+
+ /**
+ * Tests if the given object is the same as the this object. Two
+ * Properties got from an Item with the same ID are equal.
+ *
+ * @param obj
+ * an object to compare with this object.
+ * @return true
if the given object is the same as this
+ * object, false
if not
+ */
+ public boolean equals(Object obj) {
+ if (obj == null || !(obj instanceof FileItem)) {
+ return false;
+ }
+ FileItem fi = (FileItem) obj;
+ return fi.getHost() == getHost() && fi.file.equals(file);
+ }
+
+ /**
+ * Gets the host of this file.
+ */
+ private FilesystemContainer getHost() {
+ return FilesystemContainer.this;
+ }
+
+ /**
+ * Gets the last modified date of this file.
+ *
+ * @return Date
+ */
+ public Date lastModified() {
+ return new Date(file.lastModified());
+ }
+
+ /**
+ * Gets the name of this file.
+ *
+ * @return file name of this file.
+ */
+ public String getName() {
+ return file.getName();
+ }
+
+ /**
+ * Gets the icon of this file.
+ *
+ * @return the icon of this file.
+ */
+ public Resource getIcon() {
+ return FileTypeResolver.getIcon(file);
+ }
+
+ /**
+ * Gets the size of this file.
+ *
+ * @return size
+ */
+ public long getSize() {
+ if (file.isDirectory()) {
+ return 0;
+ }
+ return file.length();
+ }
+
+ /**
+ * @see java.lang.Object#toString()
+ */
+ public String toString() {
+ if ("".equals(file.getName())) {
+ return file.getAbsolutePath();
+ }
+ return file.getName();
+ }
+
+ /**
+ * Filesystem container does not support adding new properties.
+ *
+ * @see com.itmill.toolkit.data.Item#addItemProperty(Object, Property)
+ */
+ public boolean addItemProperty(Object id, Property property)
+ throws UnsupportedOperationException {
+ throw new UnsupportedOperationException("Filesystem container "
+ + "does not support adding new properties");
+ }
+
+ /**
+ * Filesystem container does not support removing properties.
+ *
+ * @see com.itmill.toolkit.data.Item#removeItemProperty(Object)
+ */
+ public boolean removeItemProperty(Object id)
+ throws UnsupportedOperationException {
+ throw new UnsupportedOperationException(
+ "Filesystem container does not support property removal");
+ }
+
+ }
+
+ /**
+ * Generic file extension filter for displaying only files having certain
+ * extension.
+ *
+ * @author IT Mill Ltd.
+ * @version
+ * @VERSION@
+ * @since 3.0
+ */
+ public class FileExtensionFilter implements FilenameFilter {
+
+ private String filter;
+
+ /**
+ * Constructs a new FileExtensionFilter using given extension.
+ *
+ * @param fileExtension
+ * the File extension without the separator (dot).
+ */
+ public FileExtensionFilter(String fileExtension) {
+ filter = "." + fileExtension;
+ }
+
+ /**
+ * Allows only files with the extension and directories.
+ *
+ * @see java.io.FilenameFilter#accept(File, String)
+ */
+ public boolean accept(File dir, String name) {
+ if (name.endsWith(filter)) {
+ return true;
+ }
+ return new File(dir, name).isDirectory();
+ }
+
+ }
+
+ /**
+ * Returns the file filter used to limit the files in this container.
+ *
+ * @return Used filter instance or null if no filter is assigned.
+ */
+ public FilenameFilter getFilter() {
+ return filter;
+ }
+
+ /**
+ * Sets the file filter used to limit the files in this container.
+ *
+ * @param filter
+ * The filter to set. null
disables filtering.
+ */
+ public void setFilter(FilenameFilter filter) {
+ this.filter = filter;
+ }
+
+ /**
+ * Sets the file filter used to limit the files in this container.
+ *
+ * @param extension
+ * the Filename extension (w/o separator) to limit the files
+ * in container.
+ */
+ public void setFilter(String extension) {
+ filter = new FileExtensionFilter(extension);
+ }
+
+ /**
+ * Is this container recursive filesystem.
+ *
+ * @return true
if container is recursive, false
+ * otherwise.
+ */
+ public boolean isRecursive() {
+ return recursive;
+ }
+
+ /**
+ * Sets the container recursive property. Set this to false to limit the
+ * files directly under the root file.
+ * false
is returned; the children must
- * be first explicitly removed with
- * {@link #setParent(Object itemId, Object newParentId)} or
- * {@link com.itmill.toolkit.data.Container#removeItem(Object itemId)}.
- * true
if the operation succeeded,
- * false
if not
- */
- public boolean setChildrenAllowed(Object itemId, boolean childrenAllowed) {
-
- // Checks that the item is in the container
- if (!containsId(itemId))
- return false;
-
- // Updates status
- if (childrenAllowed)
- noChildrenAllowed.remove(itemId);
- else
- noChildrenAllowed.add(itemId);
-
- return true;
- }
-
- /**
- * canHaveChildren(newParentId) == true
).
- * It is also possible to detach a node from the hierarchy (and thus make it
- * root) by setting the parent null
.
- * true
if the operation succeeded,
- * false
if not
- */
- public boolean setParent(Object itemId, Object newParentId) {
-
- // Checks that the item is in the container
- if (!containsId(itemId))
- return false;
-
- // Gets the old parent
- Object oldParentId = parent.get(itemId);
-
- // Checks if no change is necessary
- if ((newParentId == null && oldParentId == null)
- || newParentId.equals(oldParentId))
- return true;
-
- // Making root
- if (newParentId == null) {
-
- // Removes from old parents children list
- LinkedList l = (LinkedList) children.get(itemId);
- if (l != null) {
- l.remove(itemId);
- if (l.isEmpty())
- children.remove(itemId);
- }
-
- // Add to be a root
- roots.add(itemId);
-
- // Updates parent
- parent.remove(itemId);
-
- return true;
- }
-
- // Checks that the new parent exists in container and can have
- // children
- if (!containsId(newParentId) || noChildrenAllowed.contains(newParentId))
- return false;
-
- // Checks that setting parent doesn't result to a loop
- Object o = newParentId;
- while (o != null && !o.equals(itemId))
- o = parent.get(o);
- if (o != null)
- return false;
-
- // Updates parent
- parent.put(itemId, newParentId);
- LinkedList pcl = (LinkedList) children.get(newParentId);
- if (pcl == null) {
- pcl = new LinkedList();
- children.put(newParentId, pcl);
- }
- pcl.add(itemId);
-
- // Removes from old parent or root
- if (oldParentId == null)
- roots.remove(itemId);
- else {
- LinkedList l = (LinkedList) children.get(oldParentId);
- if (l != null) {
- l.remove(itemId);
- if (l.isEmpty())
- children.remove(oldParentId);
- }
- }
-
- return true;
- }
-
- /**
- * @see com.itmill.toolkit.data.Container#addItem()
- */
- public Object addItem() {
- Object id = super.addItem();
- if (id != null && !roots.contains(id))
- roots.add(id);
- return id;
-
- }
-
- /**
- * @see com.itmill.toolkit.data.Container#addItem(Object)
- */
- public Item addItem(Object itemId) {
- Item item = super.addItem(itemId);
- if (item != null)
- roots.add(itemId);
- return item;
- }
-
- /**
- * @see com.itmill.toolkit.data.Container#removeAllItems()
- */
- public boolean removeAllItems() {
- boolean success = super.removeAllItems();
-
- if (success) {
- roots.clear();
- parent.clear();
- children.clear();
- noChildrenAllowed.clear();
- }
- return success;
- }
-
- /**
- * @see com.itmill.toolkit.data.Container#removeItem(Object)
- */
- public boolean removeItem(Object itemId) {
- boolean success = super.removeItem(itemId);
-
- if (success) {
- if (isRoot(itemId))
- roots.remove(itemId);
- children.remove(itemId);
- Object p = parent.get(itemId);
- if (p != null) {
- LinkedList c = (LinkedList) children.get(p);
- if (c != null)
- c.remove(itemId);
- }
- parent.remove(itemId);
- noChildrenAllowed.remove(itemId);
- }
-
- return success;
- }
+ Container.Hierarchical {
+
+ /**
+ * Set of IDs of those contained Items that can't have children.
+ */
+ private HashSet noChildrenAllowed = new HashSet();
+
+ /**
+ * Mapping from Item ID to parent Item.
+ */
+ private Hashtable parent = new Hashtable();
+
+ /**
+ * Mapping from Item ID to a list of child IDs.
+ */
+ private Hashtable children = new Hashtable();
+
+ /**
+ * List that contains all root elements of the container.
+ */
+ private LinkedList roots = new LinkedList();
+
+ /*
+ * Can the specified Item have any children? Don't add a JavaDoc comment
+ * here, we use the default documentation from implemented interface.
+ */
+ public boolean areChildrenAllowed(Object itemId) {
+ return !noChildrenAllowed.contains(itemId);
+ }
+
+ /*
+ * Gets the IDs of the children of the specified Item. Don't add a JavaDoc
+ * comment here, we use the default documentation from implemented
+ * interface.
+ */
+ public Collection getChildren(Object itemId) {
+ Collection c = (Collection) children.get(itemId);
+ if (c == null) {
+ return null;
+ }
+ return Collections.unmodifiableCollection(c);
+ }
+
+ /*
+ * Gets the ID of the parent of the specified Item. Don't add a JavaDoc
+ * comment here, we use the default documentation from implemented
+ * interface.
+ */
+ public Object getParent(Object itemId) {
+ return parent.get(itemId);
+ }
+
+ /*
+ * Is the Item corresponding to the given ID a leaf node? Don't add a
+ * JavaDoc comment here, we use the default documentation from implemented
+ * interface.
+ */
+ public boolean hasChildren(Object itemId) {
+ return children.get(itemId) != null;
+ }
+
+ /*
+ * Is the Item corresponding to the given ID a root node? Don't add a
+ * JavaDoc comment here, we use the default documentation from implemented
+ * interface.
+ */
+ public boolean isRoot(Object itemId) {
+ return parent.get(itemId) == null;
+ }
+
+ /*
+ * Gets the IDs of the root elements in the container. Don't add a JavaDoc
+ * comment here, we use the default documentation from implemented
+ * interface.
+ */
+ public Collection rootItemIds() {
+ return Collections.unmodifiableCollection(roots);
+ }
+
+ /**
+ * false
is returned; the children must
+ * be first explicitly removed with
+ * {@link #setParent(Object itemId, Object newParentId)} or
+ * {@link com.itmill.toolkit.data.Container#removeItem(Object itemId)}.
+ * true
if the operation succeeded,
+ * false
if not
+ */
+ public boolean setChildrenAllowed(Object itemId, boolean childrenAllowed) {
+
+ // Checks that the item is in the container
+ if (!containsId(itemId)) {
+ return false;
+ }
+
+ // Updates status
+ if (childrenAllowed) {
+ noChildrenAllowed.remove(itemId);
+ } else {
+ noChildrenAllowed.add(itemId);
+ }
+
+ return true;
+ }
+
+ /**
+ * canHaveChildren(newParentId) == true
).
+ * It is also possible to detach a node from the hierarchy (and thus make it
+ * root) by setting the parent null
.
+ * true
if the operation succeeded,
+ * false
if not
+ */
+ public boolean setParent(Object itemId, Object newParentId) {
+
+ // Checks that the item is in the container
+ if (!containsId(itemId)) {
+ return false;
+ }
+
+ // Gets the old parent
+ Object oldParentId = parent.get(itemId);
+
+ // Checks if no change is necessary
+ if ((newParentId == null && oldParentId == null)
+ || newParentId.equals(oldParentId)) {
+ return true;
+ }
+
+ // Making root
+ if (newParentId == null) {
+
+ // Removes from old parents children list
+ LinkedList l = (LinkedList) children.get(itemId);
+ if (l != null) {
+ l.remove(itemId);
+ if (l.isEmpty()) {
+ children.remove(itemId);
+ }
+ }
+
+ // Add to be a root
+ roots.add(itemId);
+
+ // Updates parent
+ parent.remove(itemId);
+
+ return true;
+ }
+
+ // Checks that the new parent exists in container and can have
+ // children
+ if (!containsId(newParentId) || noChildrenAllowed.contains(newParentId)) {
+ return false;
+ }
+
+ // Checks that setting parent doesn't result to a loop
+ Object o = newParentId;
+ while (o != null && !o.equals(itemId)) {
+ o = parent.get(o);
+ }
+ if (o != null) {
+ return false;
+ }
+
+ // Updates parent
+ parent.put(itemId, newParentId);
+ LinkedList pcl = (LinkedList) children.get(newParentId);
+ if (pcl == null) {
+ pcl = new LinkedList();
+ children.put(newParentId, pcl);
+ }
+ pcl.add(itemId);
+
+ // Removes from old parent or root
+ if (oldParentId == null) {
+ roots.remove(itemId);
+ } else {
+ LinkedList l = (LinkedList) children.get(oldParentId);
+ if (l != null) {
+ l.remove(itemId);
+ if (l.isEmpty()) {
+ children.remove(oldParentId);
+ }
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * @see com.itmill.toolkit.data.Container#addItem()
+ */
+ public Object addItem() {
+ Object id = super.addItem();
+ if (id != null && !roots.contains(id)) {
+ roots.add(id);
+ }
+ return id;
+
+ }
+
+ /**
+ * @see com.itmill.toolkit.data.Container#addItem(Object)
+ */
+ public Item addItem(Object itemId) {
+ Item item = super.addItem(itemId);
+ if (item != null) {
+ roots.add(itemId);
+ }
+ return item;
+ }
+
+ /**
+ * @see com.itmill.toolkit.data.Container#removeAllItems()
+ */
+ public boolean removeAllItems() {
+ boolean success = super.removeAllItems();
+
+ if (success) {
+ roots.clear();
+ parent.clear();
+ children.clear();
+ noChildrenAllowed.clear();
+ }
+ return success;
+ }
+
+ /**
+ * @see com.itmill.toolkit.data.Container#removeItem(Object)
+ */
+ public boolean removeItem(Object itemId) {
+ boolean success = super.removeItem(itemId);
+
+ if (success) {
+ if (isRoot(itemId)) {
+ roots.remove(itemId);
+ }
+ children.remove(itemId);
+ Object p = parent.get(itemId);
+ if (p != null) {
+ LinkedList c = (LinkedList) children.get(p);
+ if (c != null) {
+ c.remove(itemId);
+ }
+ }
+ parent.remove(itemId);
+ noChildrenAllowed.remove(itemId);
+ }
+
+ return success;
+ }
}
diff --git a/src/com/itmill/toolkit/data/util/IndexedContainer.java b/src/com/itmill/toolkit/data/util/IndexedContainer.java
index 5271dc8015..081385fc0c 100644
--- a/src/com/itmill/toolkit/data/util/IndexedContainer.java
+++ b/src/com/itmill/toolkit/data/util/IndexedContainer.java
@@ -28,8 +28,18 @@
package com.itmill.toolkit.data.util;
-import java.util.*;
import java.lang.reflect.Constructor;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.EventObject;
+import java.util.HashSet;
+import java.util.Hashtable;
+import java.util.Iterator;
+import java.util.LinkedHashSet;
+import java.util.LinkedList;
+import java.util.NoSuchElementException;
import com.itmill.toolkit.data.Container;
import com.itmill.toolkit.data.Item;
@@ -53,1593 +63,1724 @@ import com.itmill.toolkit.data.Property;
*/
public class IndexedContainer implements Container, Container.Indexed,
- Container.ItemSetChangeNotifier, Container.PropertySetChangeNotifier,
- Property.ValueChangeNotifier, Container.Sortable, Comparator, Cloneable, Container.Filterable {
-
- /* Internal structure *************************************************** */
-
- /**
- * Linked list of ordered Item IDs.
- */
- private ArrayList itemIds = new ArrayList();
-
- /** List of item ids that passes the filtering */
- private LinkedHashSet filteredItemIds = null;
-
- /**
- * Linked list of ordered Property IDs.
- */
- private ArrayList propertyIds = new ArrayList();
-
- /**
- * Property ID to type mapping.
- */
- private Hashtable types = new Hashtable();
-
- /**
- * Hash of Items, where each Item is implemented as a mapping from Property
- * ID to Property value.
- */
- private Hashtable items = new Hashtable();
-
- /**
- * Set of properties that are read-only.
- */
- private HashSet readOnlyProperties = new HashSet();
-
- /**
- * List of all Property value change event listeners listening all the
- * properties.
- */
- private LinkedList propertyValueChangeListeners = null;
-
- /**
- * Data structure containing all listeners interested in changes to single
- * Properties. The data structure is a hashtable mapping Property IDs to a
- * hashtable that maps Item IDs to a linked list of listeners listening
- * Property identified by given Property ID and Item ID.
- */
- private Hashtable singlePropertyValueChangeListeners = null;
-
- /**
- * List of all Property set change event listeners.
- */
- private LinkedList propertySetChangeListeners = null;
-
- /**
- * List of all container Item set change event listeners.
- */
- private LinkedList itemSetChangeListeners = null;
-
- /**
- * Temporary store for sorting property ids.
- */
- private Object[] sortPropertyId;
-
- /**
- * Temporary store for sorting direction.
- */
- private boolean[] sortDirection;
-
- /** Filters that are applied to the container to limit the items visible in it */
- private HashSet filters;
-
- /* Container constructors *********************************************** */
-
- public IndexedContainer() {
- }
-
- public IndexedContainer(Collection itemIds) {
- if (items != null) {
- for (Iterator i = itemIds.iterator(); i.hasNext();) {
- this.addItem(i.next());
- }
- }
- }
-
- /* Container methods **************************************************** */
-
- /**
- * Gets the Item with the given Item ID from the list. If the list does not
- * contain the requested Item (or it is filtered to be invisible),
- * null
is returned.
- *
- * @param itemId
- * the ID of the Item to retrieve.
- * @return the Item with the given ID or null
if the Item is
- * not found in the list
- */
- public Item getItem(Object itemId) {
- if (items.containsKey(itemId) && (filteredItemIds == null || filteredItemIds.contains(itemId)))
- return new IndexedContainerItem(itemId);
- return null;
- }
-
- /**
- * Gets the ID's of all Items stored in the list. The ID's are returned as a
- * unmodifiable collection.
- *
- * @return unmodifiable collection of Item IDs
- */
- public Collection getItemIds() {
- if (filteredItemIds != null) return Collections.unmodifiableCollection(filteredItemIds);
- return Collections.unmodifiableCollection(itemIds);
- }
-
- /**
- * Gets the ID's of all Properties stored in the list. The ID's are returned
- * as a unmodifiable collection.
- *
- * @return unmodifiable collection of Property IDs
- */
- public Collection getContainerPropertyIds() {
- return Collections.unmodifiableCollection(propertyIds);
- }
-
- /**
- * Gets the type of a Property stored in the list.
- *
- * @param id
- * the ID of the Property.
- * @return Type of the requested Property
- */
- public Class getType(Object propertyId) {
- return (Class) types.get(propertyId);
- }
-
- /**
- * Gets the Property identified by the given Item ID and Property ID from
- * the lsit. If the list does not contain the Property, null
- * is returned.
- *
- * @param itemId
- * the ID of the Item which contains the requested Property.
- * @param propertyId
- * the ID of the Property to retrieve.
- * @return Property with the given ID or null
- *
- * @see com.itmill.toolkit.data.Container#getContainerProperty(Object,
- * Object)
- */
- public Property getContainerProperty(Object itemId, Object propertyId) {
- if (filteredItemIds == null) {
- if (!items.containsKey(itemId)) return null;
- } else if (!filteredItemIds.contains(itemId)) return null;
-
- return new IndexedContainerProperty(itemId, propertyId);
- }
-
- /**
- * Gets the number of Items in the list.
- *
- * @return number of Items in the list
- */
- public int size() {
- if (filteredItemIds == null) return itemIds.size();
- return filteredItemIds.size();
- }
-
- /**
- * Tests if the list contains the specified Item
- *
- * @param itemId
- * the ID the of Item to be tested for.
- * @return true
if the operation succeeded,
- * false
if not
- */
- public boolean containsId(Object itemId) {
- if (filteredItemIds != null) return filteredItemIds.contains(itemId);
- return items.containsKey(itemId);
- }
-
- /**
- * Adds a new Property to all Items in the list. The Property ID, data type
- * and default value of the new Property are given as parameters.
- *
- * @param propertyId
- * the ID of the new Property.
- * @param type
- * the Data type of the new Property.
- * @param defaultValue
- * the value all created Properties are initialized to.
- * @return true
if the operation succeeded,
- * false
if not
- */
- public boolean addContainerProperty(Object propertyId, Class type,
- Object defaultValue) {
-
- // Fails, if nulls are given
- if (propertyId == null || type == null)
- return false;
-
- // Fails if the Property is already present
- if (propertyIds.contains(propertyId))
- return false;
-
- // Adds the Property to Property list and types
- propertyIds.add(propertyId);
- types.put(propertyId, type);
-
- // If default value is given, set it
- if (defaultValue != null)
- for (Iterator i = itemIds.iterator(); i.hasNext();)
- getItem(i.next()).getItemProperty(propertyId).setValue(
- defaultValue);
-
- // Sends a change event
- fireContainerPropertySetChange();
-
- return true;
- }
-
- /**
- * Removes all Items from the list.
- * true
if the operation succeeded,
- * false
if not
- */
- public boolean removeAllItems() {
-
- // Removes all Items
- itemIds.clear();
- items.clear();
- if (filteredItemIds != null) filteredItemIds.clear();
-
- // Sends a change event
- fireContentsChange();
-
- return true;
- }
-
- /**
- * Creates a new Item into the list, and assign it an automatic ID. The new
- * ID is returned, or null
if the operation fails. After a
- * successful call you can use the
- * {@link #getItem(Object ItemId) getItem
}method to fetch the
- * Item.
- *
- * @return ID of the newly created Item, or null
in case of a
- * failure
- */
- public Object addItem() {
-
- // Creates a new id
- Object id = new Object();
-
- // Adds the Item into container
- addItem(id);
-
- return id;
- }
-
- /**
- * Creates a new Item with the given ID into the list. The new Item is
- * returned, and it is ready to have its Properties modified. Returns
- * null
if the operation fails or the Container already
- * contains a Item with the given ID.
- *
- * @param itemId
- * the ID of the Item to be created.
- * @return Created new Item, or null
in case of a failure
- */
- public Item addItem(Object itemId) {
-
- // Makes sure that the Item has not been created yet
- if (items.containsKey(itemId))
- return null;
-
- // Adds the Item to container
- itemIds.add(itemId);
- items.put(itemId, new Hashtable());
- Item item = getItem(itemId);
- if (filteredItemIds != null)
- if (passesFilters(item))
- filteredItemIds.add(itemId);
-
- // Sends the event
- fireContentsChange();
-
- return item;
- }
-
- /**
- * Removes the Item corresponding to the given Item ID from the list.
- *
- * @param itemId
- * the ID of the Item to remove.
- * @return true
if the operation succeeded,
- * false
if not
- */
- public boolean removeItem(Object itemId) {
-
- if (items.remove(itemId) == null)
- return false;
- itemIds.remove(itemId);
- if (filteredItemIds != null) filteredItemIds.remove(itemId);
-
- fireContentsChange();
-
- return true;
- }
-
- /**
- * Removes a Property specified by the given Property ID from the list. Note
- * that the Property will be removed from all Items in the list.
- *
- * @param propertyId
- * the ID of the Property to remove.
- * @return true
if the operation succeeded,
- * false
if not
- */
- public boolean removeContainerProperty(Object propertyId) {
-
- // Fails if the Property is not present
- if (!propertyIds.contains(propertyId))
- return false;
-
- // Removes the Property to Property list and types
- propertyIds.remove(propertyId);
- types.remove(propertyId);
-
- // If remove the Property from all Items
- for (Iterator i = itemIds.iterator(); i.hasNext();)
- ((Hashtable) items.get(i.next())).remove(propertyId);
-
- // Sends a change event
- fireContainerPropertySetChange();
-
- return true;
- }
-
- /* Container.Ordered methods ******************************************** */
-
- /**
- * Gets the ID of the first Item in the list.
- *
- * @return ID of the first Item in the list
- */
- public Object firstItemId() {
- try {
- if (filteredItemIds != null) return filteredItemIds.iterator().next();
- return itemIds.get(0);
- } catch (IndexOutOfBoundsException e) {
- } catch (NoSuchElementException e) {
- }
- return null;
- }
-
- /**
- * Gets the ID of the last Item in the list.
- *
- * @return ID of the last Item in the list
- */
- public Object lastItemId() {
- try {
- if (filteredItemIds != null) {
- Iterator i=filteredItemIds.iterator();
- Object last = null;
- while (i.hasNext()) last = i.next();
- return last;
- }
- return itemIds.get(itemIds.size() - 1);
- } catch (IndexOutOfBoundsException e) {
- }
- return null;
- }
-
- /**
- * Gets the ID of the Item following the Item that corresponds to the
- * itemId. If the given Item is the last or not found in the list,
- * null
is returned.
- *
- * @param itemId
- * the ID of an Item in the list.
- * @return ID of the next Item or null
- */
- public Object nextItemId(Object itemId) {
- if (filteredItemIds != null) {
- if (!filteredItemIds.contains(itemId)) return null;
- Iterator i=filteredItemIds.iterator();
- if (itemId == null) return null;
- while (i.hasNext() && !itemId.equals(i.next()));
- if (i.hasNext()) return i.next();
- return null;
- }
- try {
- return itemIds.get(itemIds.indexOf(itemId) + 1);
- } catch (IndexOutOfBoundsException e) {
- return null;
- }
- }
-
- /**
- * Gets the ID of the Item preceding the Item that corresponds to the
- * itemId. If the given Item is the first or not found in the list,
- * null
is returned.
- *
- * @param itemId
- * the ID of an Item in the list.
- * @return ID of the previous Item or null
- */
- public Object prevItemId(Object itemId) {
- if (filteredItemIds != null) {
- if (!filteredItemIds.contains(itemId)) return null;
- Iterator i=filteredItemIds.iterator();
- if (itemId == null) return null;
- Object prev = null;
- Object current;
- while (i.hasNext() && !itemId.equals(current = i.next())) prev = current;
- return prev;
- }
- try {
- return itemIds.get(itemIds.indexOf(itemId) - 1);
- } catch (IndexOutOfBoundsException e) {
- return null;
- }
- }
-
- /**
- * Tests if the Item corresponding to the given Item ID is the first Item in
- * the list.
- *
- * @param itemId
- * the ID of an Item in the list.
- * @return true
if the Item is first in the list,
- * false
if not
- */
- public boolean isFirstId(Object itemId) {
- if (filteredItemIds != null) {
- try {
- Object first = filteredItemIds.iterator().next();
- return (itemId != null && itemId.equals(first));
- } catch (NoSuchElementException e) {
- return false;
- }
- }
- return (size() >= 1 && itemIds.get(0).equals(itemId));
- }
-
- /**
- * Tests if the Item corresponding to the given Item ID is the last Item in
- * the list.
- *
- * @param itemId
- * the ID of an Item in the list.
- * @return true
if the Item is last in the list,
- * false
if not
- */
- public boolean isLastId(Object itemId) {
- if (filteredItemIds != null) {
- try {
- Object last = null;
- for (Iterator i=filteredItemIds.iterator(); i.hasNext();) last = i.next();
- return (itemId != null && itemId.equals(last));
- } catch (NoSuchElementException e) {
- return false;
- }
- }
- int s = size();
- return (s >= 1 && itemIds.get(s - 1).equals(itemId));
- }
-
- /**
- * @see com.itmill.toolkit.data.Container.Ordered#addItemAfter(Object,
- * Object)
- */
- public Item addItemAfter(Object previousItemId, Object newItemId) {
-
- // Get the index of the addition
- int index = 0;
- if (previousItemId != null) {
- index = 1 + indexOfId(previousItemId);
- if (index <= 0 || index > size())
- return null;
- }
-
- return addItemAt(index, newItemId);
- }
-
- /**
- * @see com.itmill.toolkit.data.Container.Ordered#addItemAfter(Object)
- */
- public Object addItemAfter(Object previousItemId) {
-
- // Get the index of the addition
- int index = 0;
- if (previousItemId != null) {
- index = 1 + indexOfId(previousItemId);
- if (index <= 0 || index > size())
- return null;
- }
-
- return addItemAt(index);
- }
-
- /**
- * Gets ID with the index. The following is true for the index: 0 <= index <
- * size().
- *
- * @return ID in the given index.
- * @param index
- * Index of the requested ID in the container.
- */
- public Object getIdByIndex(int index) {
-
- if (filteredItemIds != null) {
- if (index<0) throw new IndexOutOfBoundsException();
- try {
- Iterator i = filteredItemIds.iterator();
- while (index-- > 0) i.next();
- return i.next();
- } catch (NoSuchElementException e) {
- throw new IndexOutOfBoundsException();
- }
- }
-
- return itemIds.get(index);
- }
-
- /**
- * Gets the index of an id. The following is true for the index: 0 <= index <
- * size().
- *
- * @return Index of the Item or -1 if the Item is not in the container.
- * @param itemId
- * ID of an Item in the collection
- */
- public int indexOfId(Object itemId) {
- if (filteredItemIds != null) {
- int index=0;
- if (itemId == null) return -1;
- try {
- for (Iterator i=filteredItemIds.iterator(); itemId.equals(i.next());) index++;
- return index;
- } catch (NoSuchElementException e) {
- return -1;
- }
- }
- return itemIds.indexOf(itemId);
- }
-
- /**
- * @see com.itmill.toolkit.data.Container.Indexed#addItemAt(int, Object)
- */
- public Item addItemAt(int index, Object newItemId) {
-
- // Make sure that the Item has not been created yet
- if (items.containsKey(newItemId))
- return null;
-
- // Adds the Item to container
- itemIds.add(index, newItemId);
- items.put(newItemId, new Hashtable());
-
- if (filteredItemIds != null)
- updateContainerFiltering();
- else
- fireContentsChange();
-
- return getItem(newItemId);
- }
-
- /**
- * @see com.itmill.toolkit.data.Container.Indexed#addItemAt(int)
- */
- public Object addItemAt(int index) {
-
- // Creates a new id
- Object id = new Object();
-
- // Adds the Item into container
- addItemAt(index, id);
-
- return id;
- }
-
- /* Event notifiers ****************************************************** */
-
- /**
- * An event
object specifying the list whose Property set has
- * changed.
- *
- * @author IT Mill Ltd.
- * @version
- * @VERSION@
- * @since 3.0
- */
- private class PropertySetChangeEvent extends EventObject implements
- Container.PropertySetChangeEvent {
-
- /**
- * Serial generated by eclipse.
- */
- private static final long serialVersionUID = 3257002172528079926L;
-
- private PropertySetChangeEvent(IndexedContainer source) {
- super(source);
- }
-
- /**
- * Gets the list whose Property set has changed.
- *
- * @return source object of the event as a Container
- */
- public Container getContainer() {
- return (Container) getSource();
- }
- }
-
- /**
- * An event
object specifying the list whose Item set has
- * changed.
- *
- * @author IT Mill Ltd.
- * @version
- * @VERSION@
- * @since 3.0
- */
- private class ItemSetChangeEvent extends EventObject implements
- Container.ItemSetChangeEvent {
-
- /**
- * Serial generated by eclipse.
- */
- private static final long serialVersionUID = 3832616279386372147L;
-
- private ItemSetChangeEvent(IndexedContainer source) {
- super(source);
- }
-
- /**
- * Gets the list whose Item set has changed.
- *
- * @return source object of the event as a Container
- */
- public Container getContainer() {
- return (Container) getSource();
- }
-
- }
-
- /**
- * An event
object specifying the Propery in a list whose
- * value has changed.
- *
- * @author IT Mill Ltd.
- * @version
- * @VERSION@
- * @since 3.0
- */
- private class PropertyValueChangeEvent extends EventObject implements
- Property.ValueChangeEvent {
-
- /**
- * Serial generated by eclipse.
- */
- private static final long serialVersionUID = 3833749884498359857L;
-
- private PropertyValueChangeEvent(Property source) {
- super(source);
- }
-
- /**
- * Gets the Property whose value has changed.
- *
- * @return source object of the event as a Property
- */
- public Property getProperty() {
- return (Property) getSource();
- }
-
- }
-
- /**
- * Registers a new Property set change listener for this list.
- *
- * @param listener
- * the new Listener to be registered.
- */
- public void addListener(Container.PropertySetChangeListener listener) {
- if (propertySetChangeListeners == null)
- propertySetChangeListeners = new LinkedList();
- propertySetChangeListeners.add(listener);
- }
-
- /**
- * Removes a previously registered Property set change listener.
- *
- * @param listener
- * the listener to be removed.
- */
- public void removeListener(Container.PropertySetChangeListener listener) {
- if (propertySetChangeListeners != null)
- propertySetChangeListeners.remove(listener);
- }
-
- /**
- * Adds a Item set change listener for the list.
- *
- * @param listener
- * the listener to be added.
- */
- public void addListener(Container.ItemSetChangeListener listener) {
- if (itemSetChangeListeners == null)
- itemSetChangeListeners = new LinkedList();
- itemSetChangeListeners.add(listener);
- }
-
- /**
- * Removes a Item set change listener from the object.
- *
- * @param listener
- * the listener to be removed.
- */
- public void removeListener(Container.ItemSetChangeListener listener) {
- if (itemSetChangeListeners != null)
- itemSetChangeListeners.remove(listener);
- }
-
- /**
- * Registers a new value change listener for this object.
- *
- * @param listener
- * the new Listener to be registered
- */
- public void addListener(Property.ValueChangeListener listener) {
- if (propertyValueChangeListeners == null)
- propertyValueChangeListeners = new LinkedList();
- propertyValueChangeListeners.add(listener);
- }
-
- /**
- * Removes a previously registered value change listener.
- *
- * @param listener
- * the listener to be removed.
- */
- public void removeListener(Property.ValueChangeListener listener) {
- if (propertyValueChangeListeners != null)
- propertyValueChangeListeners.remove(listener);
- }
-
- /**
- * Sends a Property value change event to all interested listeners.
- *
- * @param source
- * the IndexedContainerProperty object.
- */
- private void firePropertyValueChange(IndexedContainerProperty source) {
-
- // Sends event to listeners listening all value changes
- if (propertyValueChangeListeners != null) {
- Object[] l = propertyValueChangeListeners.toArray();
- Property.ValueChangeEvent event = new IndexedContainer.PropertyValueChangeEvent(
- source);
- for (int i = 0; i < l.length; i++)
- ((Property.ValueChangeListener) l[i]).valueChange(event);
- }
-
- // Sends event to single property value change listeners
- if (singlePropertyValueChangeListeners != null) {
- Hashtable propertySetToListenerListMap = (Hashtable) singlePropertyValueChangeListeners
- .get(source.propertyId);
- if (propertySetToListenerListMap != null) {
- LinkedList listenerList = (LinkedList) propertySetToListenerListMap
- .get(source.itemId);
- if (listenerList != null) {
- Property.ValueChangeEvent event = new IndexedContainer.PropertyValueChangeEvent(
- source);
- for (Iterator i = listenerList.iterator(); i.hasNext();)
- ((Property.ValueChangeListener) i.next())
- .valueChange(event);
- }
- }
- }
-
- }
-
- /**
- * Sends a Property set change event to all interested listeners.
- */
- private void fireContainerPropertySetChange() {
- if (propertySetChangeListeners != null) {
- Object[] l = propertySetChangeListeners.toArray();
- Container.PropertySetChangeEvent event = new IndexedContainer.PropertySetChangeEvent(
- this);
- for (int i = 0; i < l.length; i++)
- ((Container.PropertySetChangeListener) l[i])
- .containerPropertySetChange(event);
- }
- }
-
- /**
- * Sends Item set change event to all registered interested listeners.
- */
- private void fireContentsChange() {
- if (itemSetChangeListeners != null) {
- Object[] l = itemSetChangeListeners.toArray();
- Container.ItemSetChangeEvent event = new IndexedContainer.ItemSetChangeEvent(
- this);
- for (int i = 0; i < l.length; i++)
- ((Container.ItemSetChangeListener) l[i])
- .containerItemSetChange(event);
- }
- }
-
- /**
- * Adds new single Property change listener.
- *
- * @param propertyId
- * the ID of the Property to add.
- * @param itemId
- * the ID of the Item .
- * @param listener
- * the listener to be added.
- */
- private void addSinglePropertyChangeListener(Object propertyId,
- Object itemId, Property.ValueChangeListener listener) {
- if (listener != null) {
- if (singlePropertyValueChangeListeners == null)
- singlePropertyValueChangeListeners = new Hashtable();
- Hashtable propertySetToListenerListMap = (Hashtable) singlePropertyValueChangeListeners
- .get(propertyId);
- if (propertySetToListenerListMap == null) {
- propertySetToListenerListMap = new Hashtable();
- singlePropertyValueChangeListeners.put(propertyId,
- propertySetToListenerListMap);
- }
- LinkedList listenerList = (LinkedList) propertySetToListenerListMap
- .get(itemId);
- if (listenerList == null) {
- listenerList = new LinkedList();
- propertySetToListenerListMap.put(itemId, listenerList);
- }
- listenerList.addLast(listener);
- }
- }
-
- /**
- * Removes a previously registered single Property change listener.
- *
- * @param propertyId
- * the ID of the Property to remove.
- * @param itemId
- * the ID of the Item.
- * @param listener
- * the listener to be removed.
- */
- private void removeSinglePropertyChangeListener(Object propertyId,
- Object itemId, Property.ValueChangeListener listener) {
- if (listener != null && singlePropertyValueChangeListeners != null) {
- Hashtable propertySetToListenerListMap = (Hashtable) singlePropertyValueChangeListeners
- .get(propertyId);
- if (propertySetToListenerListMap != null) {
- LinkedList listenerList = (LinkedList) propertySetToListenerListMap
- .get(itemId);
- if (listenerList != null) {
- listenerList.remove(listener);
- if (listenerList.isEmpty())
- propertySetToListenerListMap.remove(itemId);
- }
- if (propertySetToListenerListMap.isEmpty())
- singlePropertyValueChangeListeners.remove(propertyId);
- }
- if (singlePropertyValueChangeListeners.isEmpty())
- singlePropertyValueChangeListeners = null;
- }
- }
-
- /* Internal Item and Property implementations *************************** */
-
- /*
- * A class implementing the com.itmill.toolkit.data.Item interface to be
- * contained in the list. @author IT Mill Ltd.
- *
- * @version @VERSION@
- * @since 3.0
- */
- class IndexedContainerItem implements Item {
-
- /**
- * Item ID in the host container for this Item.
- */
- private Object itemId;
-
- /**
- * Constructs a new ListItem instance and connects it to a host
- * container.
- *
- * @param itemId
- * the Item ID of the new Item.
- */
- private IndexedContainerItem(Object itemId) {
-
- // Gets the item contents from the host
- if (itemId == null)
- throw new NullPointerException();
- this.itemId = itemId;
- }
-
- /**
- * Gets the Property corresponding to the given Property ID stored in
- * the Item. If the Item does not contain the Property,
- * null
is returned.
- *
- * @param id
- * the identifier of the Property to get.
- * @return the Property with the given ID or null
- */
- public Property getItemProperty(Object id) {
- return new IndexedContainerProperty(itemId, id);
- }
-
- /**
- * Gets the collection containing the IDs of all Properties stored in
- * the Item.
- *
- * @return unmodifiable collection contaning IDs of the Properties
- * stored the Item
- */
- public Collection getItemPropertyIds() {
- return Collections.unmodifiableCollection(propertyIds);
- }
-
- /**
- * Gets the String
representation of the contents of the
- * Item. The format of the string is a space separated catenation of the
- * String
representations of the Properties contained by
- * the Item.
- *
- * @return String
representation of the Item contents
- */
- public String toString() {
- String retValue = "";
-
- for (Iterator i = propertyIds.iterator(); i.hasNext();) {
- Object propertyId = i.next();
- retValue += getItemProperty(propertyId).toString();
- if (i.hasNext())
- retValue += " ";
- }
-
- return retValue;
- }
-
- /**
- * Calculates a integer hash-code for the Item that's unique inside the
- * list. Two Items inside the same list have always different
- * hash-codes, though Items in different lists may have identical
- * hash-codes.
- *
- * @return A locally unique hash-code as integer
- */
- public int hashCode() {
- return getHost().hashCode() ^ itemId.hashCode();
- }
-
- /**
- * Tests if the given object is the same as the this object. Two Items
- * got from a list container with the same ID are equal.
- *
- * @param obj
- * an object to compare with this object
- * @return true
if the given object is the same as this
- * object, false
if not
- */
- public boolean equals(Object obj) {
- if (obj == null
- || !obj.getClass().equals(IndexedContainerItem.class))
- return false;
- IndexedContainerItem li = (IndexedContainerItem) obj;
- return getHost() == li.getHost() && itemId.equals(li.itemId);
- }
-
- /**
- *
- * @return
- */
- private IndexedContainer getHost() {
- return IndexedContainer.this;
- }
-
- /**
- * Indexed container does not support adding new properties.
- *
- * @see com.itmill.toolkit.data.Item#addProperty(Object, Property)
- */
- public boolean addItemProperty(Object id, Property property)
- throws UnsupportedOperationException {
- throw new UnsupportedOperationException("Indexed container item "
- + "does not support adding new properties");
- }
-
- /**
- * Indexed container does not support removing properties.
- *
- * @see com.itmill.toolkit.data.Item#removeProperty(Object)
- */
- public boolean removeItemProperty(Object id)
- throws UnsupportedOperationException {
- throw new UnsupportedOperationException(
- "Indexed container item does not support property removal");
- }
-
- }
-
- /**
- * A class implementing the com.itmill.toolkit.data.Property interface to be
- * contained in the Items contained in the list.
- *
- * @author IT Mill Ltd.
- *
- * @version
- * @VERSION@
- * @since 3.0
- */
- private class IndexedContainerProperty implements Property,
- Property.ValueChangeNotifier {
-
- /**
- * ID of the Item, where the Property resides.
- */
- private Object itemId;
-
- /**
- * Id of the Property.
- */
- private Object propertyId;
-
- /**
- * Constructs a new ListProperty object and connect it to a ListItem and
- * a ListContainer.
- *
- * @param itemId
- * the ID of the Item to connect the new Property to.
- * @param propertyId
- * the Property ID of the new Property.
- * @param host
- * the list that contains the Item to contain the new
- * Property.
- */
- private IndexedContainerProperty(Object itemId, Object propertyId) {
- if (itemId == null || propertyId == null)
- throw new NullPointerException();
- this.propertyId = propertyId;
- this.itemId = itemId;
- }
-
- /**
- * Returns the type of the Property. The methods getValue
- * and setValue
must be compatible with this type: one
- * must be able to safely cast the value returned from
- * getValue
to the given type and pass any variable
- * assignable to this type as a parameter to setValue
- * Tests if the Property is in read-only mode. In read-only mode calls
- * to the method
setValue
will throw
- * ReadOnlyException
s and will not modify the value of
- * the Property.
- *
true
if the Property is in read-only mode,
- * false
if it's not.
- */
- public boolean isReadOnly() {
- return readOnlyProperties.contains(this);
- }
-
- /**
- * Sets the Property's read-only mode to the specified status.
- *
- * @param newStatus
- * the new read-only status of the Property.
- */
- public void setReadOnly(boolean newStatus) {
- if (newStatus)
- readOnlyProperties.add(this);
- else
- readOnlyProperties.remove(this);
- }
-
- /**
- * Sets the value of the Property. By default this method will try to
- * assign the value directly, but if it is unassignable, it will try to
- * use the String
constructor of the internal data type
- * to assign the value,
- *
- * @param newValue
- * the New value of the Property. This should be assignable
- * to the Property's internal type or support
- * toString
.
- *
- * @throws Property.ReadOnlyException
- * if the object is in read-only mode
- * @throws Property.ConversionException
- * if newValue
can't be converted into the
- * Property's native type directly or through
- * String
- */
- public void setValue(Object newValue)
- throws Property.ReadOnlyException, Property.ConversionException {
-
- // Gets the Property set
- Hashtable propertySet = (Hashtable) items.get(itemId);
-
- // Support null values on all types
- if (newValue == null)
- propertySet.remove(propertyId);
-
- // Try to assign the compatible value directly
- else if (getType().isAssignableFrom(newValue.getClass()))
- propertySet.put(propertyId, newValue);
-
- // Otherwise try to convert the value trough string constructor
- else
- try {
-
- // Gets the string constructor
- Constructor constr = getType().getConstructor(
- new Class[] { String.class });
-
- // Creates new object from the string
- propertySet.put(propertyId, constr
- .newInstance(new Object[] { newValue.toString() }));
-
- } catch (java.lang.Exception e) {
- throw new Property.ConversionException(
- "Conversion for value '" + newValue + "' of class "
- + newValue.getClass().getName() + " to "
- + getType().getName() + " failed");
- }
-
- firePropertyValueChange(this);
- }
-
- /**
- * Returns the value of the Property in human readable textual format.
- * The return value should be assignable to the setValue
- * method if the Property is not in read-only mode.
- *
- * @return String
representation of the value stored in
- * the Property
- */
- public String toString() {
- Object value = getValue();
- if (value == null)
- return null;
- return value.toString();
- }
-
- /**
- * Calculates a integer hash-code for the Property that's unique inside
- * the Item containing the Property. Two different Properties inside the
- * same Item contained in the same list always have different
- * hash-codes, though Properties in different Items may have identical
- * hash-codes.
- *
- * @return A locally unique hash-code as integer
- */
- public int hashCode() {
- return itemId.hashCode() ^ propertyId.hashCode()
- ^ IndexedContainer.this.hashCode();
- }
-
- /**
- * Tests if the given object is the same as the this object. Two
- * Properties got from an Item with the same ID are equal.
- *
- * @param obj
- * an object to compare with this object
- * @return true
if the given object is the same as this
- * object, false
if not
- */
- public boolean equals(Object obj) {
- if (obj == null
- || !obj.getClass().equals(IndexedContainerProperty.class))
- return false;
- IndexedContainerProperty lp = (IndexedContainerProperty) obj;
- return lp.getHost() == getHost()
- && lp.propertyId.equals(propertyId)
- && lp.itemId.equals(itemId);
- }
-
- /**
- * Registers a new value change listener for this Property.
- *
- * @param listener
- * the new Listener to be registered.
- * @see com.itmill.toolkit.data.Property.ValueChangeNotifier#addListener(ValueChangeListener)
- */
- public void addListener(Property.ValueChangeListener listener) {
- addSinglePropertyChangeListener(propertyId, itemId, listener);
- }
-
- /**
- * Removes a previously registered value change listener.
- *
- * @param listener
- * listener to be removed
- * @see com.itmill.toolkit.data.Property.ValueChangeNotifier#removeListener(ValueChangeListener)
- */
- public void removeListener(Property.ValueChangeListener listener) {
- removeSinglePropertyChangeListener(propertyId, itemId, listener);
- }
-
- private IndexedContainer getHost() {
- return IndexedContainer.this;
- }
-
- }
-
- /**
- * @see com.itmill.toolkit.data.Container.Sortable#sort(java.lang.Object[],
- * boolean[])
- */
- public synchronized void sort(Object[] propertyId, boolean[] ascending) {
-
- // Removes any non-sortable property ids
- ArrayList ids = new ArrayList();
- ArrayList orders = new ArrayList();
- Collection sortable = getSortableContainerPropertyIds();
- for (int i = 0; i < propertyId.length; i++)
- if (sortable.contains(propertyId[i])) {
- ids.add(propertyId[i]);
- orders.add(new Boolean(i < ascending.length ? ascending[i]
- : true));
- }
-
- if (ids.size() == 0)
- return;
- sortPropertyId = ids.toArray();
- sortDirection = new boolean[orders.size()];
- for (int i = 0; i < sortDirection.length; i++)
- sortDirection[i] = ((Boolean) orders.get(i)).booleanValue();
-
- // Sort
- Collections.sort(this.itemIds, this);
- if (filteredItemIds != null) updateContainerFiltering();
- else fireContentsChange();
-
- // Remove temporary references
- sortPropertyId = null;
- sortDirection = null;
-
- }
-
- /**
- * @see com.itmill.toolkit.data.Container.Sortable#getSortableContainerPropertyIds()
- */
- public Collection getSortableContainerPropertyIds() {
-
- LinkedList list = new LinkedList();
- for (Iterator i = this.propertyIds.iterator(); i.hasNext();) {
- Object id = i.next();
- Class type = this.getType(id);
- if (type != null && Comparable.class.isAssignableFrom(type)) {
- list.add(id);
- }
- }
-
- return list;
- }
-
- /**
- * Compares two items for sorting.
- *
- * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
- * @see #sort((java.lang.Object[], boolean[])
- */
- public int compare(Object o1, Object o2) {
-
- for (int i = 0; i < sortPropertyId.length; i++) {
-
- // Get the compared properties
- Property pp1 = getContainerProperty(o1, this.sortPropertyId[i]);
- Property pp2 = getContainerProperty(o2, this.sortPropertyId[i]);
-
- // Get the compared values
- Object p1 = pp1 == null ? null : pp1.getValue();
- Object p2 = pp2 == null ? null : pp2.getValue();
-
- // Result of the comparison
- int r = 0;
-
- // Normal non-null comparison
- if (p1 != null && p2 != null) {
- if ((p1 instanceof Boolean) && (p2 instanceof Boolean))
- r = p1.equals(p2) ? 0
- : ((this.sortDirection[i] ? 1 : -1) * (((Boolean) p1)
- .booleanValue() ? 1 : -1));
- else
- r = this.sortDirection[i] ? ((Comparable) p1).compareTo(p2)
- : -((Comparable) p1).compareTo(p2);
- }
-
- // If both are nulls
- else if (p1 == p2)
- r = 0;
-
- // If one of the properties are null
- else
- r = (this.sortDirection[i] ? 1 : -1) * (p1 == null ? -1 : 1);
-
- // If order can be decided
- if (r != 0)
- return r;
- }
-
- return 0;
- }
-
- /**
- * Supports cloning of the IndexedContainer cleanly.
- *
- * @throws CloneNotSupportedException
- * if an object cannot be cloned. .
- */
- public Object clone() throws CloneNotSupportedException {
-
- // Creates the clone
- IndexedContainer nc = new IndexedContainer();
-
- // Clone the shallow properties
- nc.itemIds = this.itemIds != null ? (ArrayList) this.itemIds.clone()
- : null;
- nc.itemSetChangeListeners = this.itemSetChangeListeners != null ? (LinkedList) this.itemSetChangeListeners
- .clone()
- : null;
- nc.propertyIds = this.propertyIds != null ? (ArrayList) this.propertyIds
- .clone()
- : null;
- nc.propertySetChangeListeners = this.propertySetChangeListeners != null ? (LinkedList) this.propertySetChangeListeners
- .clone()
- : null;
- nc.propertyValueChangeListeners = this.propertyValueChangeListeners != null ? (LinkedList) this.propertyValueChangeListeners
- .clone()
- : null;
- nc.readOnlyProperties = this.readOnlyProperties != null ? (HashSet) this.readOnlyProperties
- .clone()
- : null;
- nc.singlePropertyValueChangeListeners = this.singlePropertyValueChangeListeners != null ? (Hashtable) this.singlePropertyValueChangeListeners
- .clone()
- : null;
- nc.sortDirection = this.sortDirection != null ? (boolean[]) this.sortDirection
- .clone()
- : null;
- nc.sortPropertyId = this.sortPropertyId != null ? (Object[]) this.sortPropertyId
- .clone()
- : null;
- nc.types = this.types != null ? (Hashtable) this.types.clone() : null;
-
- nc.filters = this.filters == null ? null : (HashSet) this.filters.clone();
-
- nc.filteredItemIds = this.filteredItemIds == null ? null : (LinkedHashSet) this.filteredItemIds.clone();
-
- // Clone property-values
- if (this.items == null)
- nc.items = null;
- else {
- nc.items = new Hashtable();
- for (Iterator i = this.items.keySet().iterator(); i.hasNext();) {
- Object id = i.next();
- Hashtable it = (Hashtable) this.items.get(id);
- nc.items.put(id, it.clone());
- }
- }
-
- return nc;
- }
-
- /**
- * @see java.lang.Object#equals(java.lang.Object)
- */
- public boolean equals(Object obj) {
-
- // Only ones of the objects of the same class can be equal
- if (!(obj instanceof IndexedContainer))
- return false;
- IndexedContainer o = (IndexedContainer) obj;
-
- // Checks the properties one by one
- if (itemIds != o.itemIds && o.itemIds != null
- && !o.itemIds.equals(this.itemIds))
- return false;
- if (filters != o.filters && o.filters != null
- && !o.filters.equals(this.filters))
- return false;
- if (items != o.items && o.items != null && !o.items.equals(this.items))
- return false;
- if (itemSetChangeListeners != o.itemSetChangeListeners
- && o.itemSetChangeListeners != null
- && !o.itemSetChangeListeners
- .equals(this.itemSetChangeListeners))
- return false;
- if (propertyIds != o.propertyIds && o.propertyIds != null
- && !o.propertyIds.equals(this.propertyIds))
- return false;
- if (propertySetChangeListeners != o.propertySetChangeListeners
- && o.propertySetChangeListeners != null
- && !o.propertySetChangeListeners
- .equals(this.propertySetChangeListeners))
- return false;
- if (propertyValueChangeListeners != o.propertyValueChangeListeners
- && o.propertyValueChangeListeners != null
- && !o.propertyValueChangeListeners
- .equals(this.propertyValueChangeListeners))
- return false;
- if (readOnlyProperties != o.readOnlyProperties
- && o.readOnlyProperties != null
- && !o.readOnlyProperties.equals(this.readOnlyProperties))
- return false;
- if (singlePropertyValueChangeListeners != o.singlePropertyValueChangeListeners
- && o.singlePropertyValueChangeListeners != null
- && !o.singlePropertyValueChangeListeners
- .equals(this.singlePropertyValueChangeListeners))
- return false;
- if (sortDirection != o.sortDirection && o.sortDirection != null
- && !o.sortDirection.equals(this.sortDirection))
- return false;
- if (sortPropertyId != o.sortPropertyId && o.sortPropertyId != null
- && !o.sortPropertyId.equals(this.sortPropertyId))
- return false;
- if (types != o.types && o.types != null && !o.types.equals(this.types))
- return false;
-
- return true;
- }
-
- /**
- * @see java.lang.Object#hashCode()
- */
- public int hashCode() {
-
- // The hash-code is calculated as combination hash of the members
- return (this.itemIds != null ? this.itemIds.hashCode() : 0)
- ^ (this.items != null ? this.items.hashCode() : 0)
- ^ (this.filters != null ? this.filters.hashCode() : 0)
- ^ (this.itemSetChangeListeners != null ? this.itemSetChangeListeners
- .hashCode()
- : 0)
- ^ (this.propertyIds != null ? this.propertyIds.hashCode() : 0)
- ^ (this.propertySetChangeListeners != null ? this.propertySetChangeListeners
- .hashCode()
- : 0)
- ^ (this.propertyValueChangeListeners != null ? this.propertyValueChangeListeners
- .hashCode()
- : 0)
- ^ (this.readOnlyProperties != null ? this.readOnlyProperties
- .hashCode() : 0)
- ^ (this.singlePropertyValueChangeListeners != null ? this.singlePropertyValueChangeListeners
- .hashCode()
- : 0)
- ^ (this.sortPropertyId != null ? this.sortPropertyId.hashCode()
- : 0)
- ^ (this.types != null ? this.types.hashCode() : 0)
- ^ (this.sortDirection != null ? this.sortDirection.hashCode()
- : 0);
- }
-
- private class Filter {
- Object propertyId;
- String filterString;
- boolean ignoreCase;
- boolean onlyMatchPrefix;
- Filter(Object propertyId, String filterString, boolean ignoreCase, boolean onlyMatchPrefix) {
- this.propertyId = propertyId;;
- this.filterString = filterString;
- this.ignoreCase = ignoreCase;
- this.onlyMatchPrefix = onlyMatchPrefix;
- }
- public boolean equals(Object obj) {
-
- // Only ones of the objects of the same class can be equal
- if (!(obj instanceof Filter))
- return false;
- Filter o = (Filter) obj;
-
- // Checks the properties one by one
- if (propertyId != o.propertyId && o.propertyId != null
- && !o.propertyId.equals(this.propertyId))
- return false;
- if (filterString != o.filterString && o.filterString != null
- && !o.filterString.equals(this.filterString))
- return false;
- if (ignoreCase!=o.ignoreCase)
- return false;
- if (onlyMatchPrefix!=o.onlyMatchPrefix)
- return false;
-
- return true;
- }
- public int hashCode() {
- return (this.propertyId != null ? this.propertyId.hashCode() : 0)
- ^ (this.filterString != null ? this.filterString.hashCode() : 0);
- }
-
- }
-
- public void addContainerFilter(Object propertyId, String filterString, boolean ignoreCase, boolean onlyMatchPrefix) {
- if (filters == null) filters = new HashSet();
- filters.add(new Filter(propertyId, filterString, ignoreCase, onlyMatchPrefix));
- updateContainerFiltering();
- }
-
- public void removeAllContainerFilters() {
- if (filters == null) return;
- filters.clear();
- updateContainerFiltering();
- }
-
- public void removeContainerFilters(Object propertyId) {
- if (filters == null || propertyId == null) return;
- for (Iterator i=filters.iterator(); i.hasNext();) {
- Filter f = (Filter) i.next();
- if (propertyId.equals(f.propertyId)) i.remove();
- }
- updateContainerFiltering();
- }
-
- private void updateContainerFiltering() {
-
- // Clearing filters?
- if (filters == null || filters.isEmpty()) {
- filteredItemIds = null;
- if(filters != null) {
- filters = null;
- fireContentsChange();
- }
- return;
- }
-
- // Reset filteres list
- if (filteredItemIds == null) filteredItemIds = new LinkedHashSet();
- else filteredItemIds.clear();
-
- // Filter
- for (Iterator i=itemIds.iterator(); i.hasNext();) {
- Object id = i.next();
- if (passesFilters(new IndexedContainerItem(id))) filteredItemIds.add(id);
- }
-
- fireContentsChange();
- }
-
- private boolean passesFilters(Item item) {
- if (filters == null) return true;
- if (item == null) return false;
- for (Iterator i=filters.iterator(); i.hasNext();) {
- Filter f = (Filter) i.next();
- String s1 = f.ignoreCase ? f.filterString.toLowerCase() : f.filterString;
- Property p = item.getItemProperty(f.propertyId);
- if (p==null) return false;
- String s2 = f.ignoreCase ? p.toString().toLowerCase() : p.toString();
- if (f.onlyMatchPrefix) {
- if (s2.indexOf(s1) != 0) return false;
- } else {
- if (s2.indexOf(s1) < 0) return false;
- }
- }
- return true;
- }
+ Container.ItemSetChangeNotifier, Container.PropertySetChangeNotifier,
+ Property.ValueChangeNotifier, Container.Sortable, Comparator,
+ Cloneable, Container.Filterable {
+
+ /* Internal structure *************************************************** */
+
+ /**
+ * Linked list of ordered Item IDs.
+ */
+ private ArrayList itemIds = new ArrayList();
+
+ /** List of item ids that passes the filtering */
+ private LinkedHashSet filteredItemIds = null;
+
+ /**
+ * Linked list of ordered Property IDs.
+ */
+ private ArrayList propertyIds = new ArrayList();
+
+ /**
+ * Property ID to type mapping.
+ */
+ private Hashtable types = new Hashtable();
+
+ /**
+ * Hash of Items, where each Item is implemented as a mapping from Property
+ * ID to Property value.
+ */
+ private Hashtable items = new Hashtable();
+
+ /**
+ * Set of properties that are read-only.
+ */
+ private HashSet readOnlyProperties = new HashSet();
+
+ /**
+ * List of all Property value change event listeners listening all the
+ * properties.
+ */
+ private LinkedList propertyValueChangeListeners = null;
+
+ /**
+ * Data structure containing all listeners interested in changes to single
+ * Properties. The data structure is a hashtable mapping Property IDs to a
+ * hashtable that maps Item IDs to a linked list of listeners listening
+ * Property identified by given Property ID and Item ID.
+ */
+ private Hashtable singlePropertyValueChangeListeners = null;
+
+ /**
+ * List of all Property set change event listeners.
+ */
+ private LinkedList propertySetChangeListeners = null;
+
+ /**
+ * List of all container Item set change event listeners.
+ */
+ private LinkedList itemSetChangeListeners = null;
+
+ /**
+ * Temporary store for sorting property ids.
+ */
+ private Object[] sortPropertyId;
+
+ /**
+ * Temporary store for sorting direction.
+ */
+ private boolean[] sortDirection;
+
+ /**
+ * Filters that are applied to the container to limit the items visible in
+ * it
+ */
+ private HashSet filters;
+
+ /* Container constructors *********************************************** */
+
+ public IndexedContainer() {
+ }
+
+ public IndexedContainer(Collection itemIds) {
+ if (items != null) {
+ for (Iterator i = itemIds.iterator(); i.hasNext();) {
+ this.addItem(i.next());
+ }
+ }
+ }
+
+ /* Container methods **************************************************** */
+
+ /**
+ * Gets the Item with the given Item ID from the list. If the list does not
+ * contain the requested Item (or it is filtered to be invisible),
+ * null
is returned.
+ *
+ * @param itemId
+ * the ID of the Item to retrieve.
+ * @return the Item with the given ID or null
if the Item is
+ * not found in the list
+ */
+ public Item getItem(Object itemId) {
+ if (items.containsKey(itemId)
+ && (filteredItemIds == null || filteredItemIds.contains(itemId))) {
+ return new IndexedContainerItem(itemId);
+ }
+ return null;
+ }
+
+ /**
+ * Gets the ID's of all Items stored in the list. The ID's are returned as a
+ * unmodifiable collection.
+ *
+ * @return unmodifiable collection of Item IDs
+ */
+ public Collection getItemIds() {
+ if (filteredItemIds != null) {
+ return Collections.unmodifiableCollection(filteredItemIds);
+ }
+ return Collections.unmodifiableCollection(itemIds);
+ }
+
+ /**
+ * Gets the ID's of all Properties stored in the list. The ID's are returned
+ * as a unmodifiable collection.
+ *
+ * @return unmodifiable collection of Property IDs
+ */
+ public Collection getContainerPropertyIds() {
+ return Collections.unmodifiableCollection(propertyIds);
+ }
+
+ /**
+ * Gets the type of a Property stored in the list.
+ *
+ * @param id
+ * the ID of the Property.
+ * @return Type of the requested Property
+ */
+ public Class getType(Object propertyId) {
+ return (Class) types.get(propertyId);
+ }
+
+ /**
+ * Gets the Property identified by the given Item ID and Property ID from
+ * the lsit. If the list does not contain the Property, null
+ * is returned.
+ *
+ * @param itemId
+ * the ID of the Item which contains the requested Property.
+ * @param propertyId
+ * the ID of the Property to retrieve.
+ * @return Property with the given ID or null
+ *
+ * @see com.itmill.toolkit.data.Container#getContainerProperty(Object,
+ * Object)
+ */
+ public Property getContainerProperty(Object itemId, Object propertyId) {
+ if (filteredItemIds == null) {
+ if (!items.containsKey(itemId)) {
+ return null;
+ }
+ } else if (!filteredItemIds.contains(itemId)) {
+ return null;
+ }
+
+ return new IndexedContainerProperty(itemId, propertyId);
+ }
+
+ /**
+ * Gets the number of Items in the list.
+ *
+ * @return number of Items in the list
+ */
+ public int size() {
+ if (filteredItemIds == null) {
+ return itemIds.size();
+ }
+ return filteredItemIds.size();
+ }
+
+ /**
+ * Tests if the list contains the specified Item
+ *
+ * @param itemId
+ * the ID the of Item to be tested for.
+ * @return true
if the operation succeeded,
+ * false
if not
+ */
+ public boolean containsId(Object itemId) {
+ if (filteredItemIds != null) {
+ return filteredItemIds.contains(itemId);
+ }
+ return items.containsKey(itemId);
+ }
+
+ /**
+ * Adds a new Property to all Items in the list. The Property ID, data type
+ * and default value of the new Property are given as parameters.
+ *
+ * @param propertyId
+ * the ID of the new Property.
+ * @param type
+ * the Data type of the new Property.
+ * @param defaultValue
+ * the value all created Properties are initialized to.
+ * @return true
if the operation succeeded,
+ * false
if not
+ */
+ public boolean addContainerProperty(Object propertyId, Class type,
+ Object defaultValue) {
+
+ // Fails, if nulls are given
+ if (propertyId == null || type == null) {
+ return false;
+ }
+
+ // Fails if the Property is already present
+ if (propertyIds.contains(propertyId)) {
+ return false;
+ }
+
+ // Adds the Property to Property list and types
+ propertyIds.add(propertyId);
+ types.put(propertyId, type);
+
+ // If default value is given, set it
+ if (defaultValue != null) {
+ for (Iterator i = itemIds.iterator(); i.hasNext();) {
+ getItem(i.next()).getItemProperty(propertyId).setValue(
+ defaultValue);
+ }
+ }
+
+ // Sends a change event
+ fireContainerPropertySetChange();
+
+ return true;
+ }
+
+ /**
+ * Removes all Items from the list.
+ * + * Note : The Property ID and type information is preserved. + *
+ * + * @returntrue
if the operation succeeded,
+ * false
if not
+ */
+ public boolean removeAllItems() {
+
+ // Removes all Items
+ itemIds.clear();
+ items.clear();
+ if (filteredItemIds != null) {
+ filteredItemIds.clear();
+ }
+
+ // Sends a change event
+ fireContentsChange();
+
+ return true;
+ }
+
+ /**
+ * Creates a new Item into the list, and assign it an automatic ID. The new
+ * ID is returned, or null
if the operation fails. After a
+ * successful call you can use the
+ * {@link #getItem(Object ItemId) getItem
}method to fetch the
+ * Item.
+ *
+ * @return ID of the newly created Item, or null
in case of a
+ * failure
+ */
+ public Object addItem() {
+
+ // Creates a new id
+ Object id = new Object();
+
+ // Adds the Item into container
+ addItem(id);
+
+ return id;
+ }
+
+ /**
+ * Creates a new Item with the given ID into the list. The new Item is
+ * returned, and it is ready to have its Properties modified. Returns
+ * null
if the operation fails or the Container already
+ * contains a Item with the given ID.
+ *
+ * @param itemId
+ * the ID of the Item to be created.
+ * @return Created new Item, or null
in case of a failure
+ */
+ public Item addItem(Object itemId) {
+
+ // Makes sure that the Item has not been created yet
+ if (items.containsKey(itemId)) {
+ return null;
+ }
+
+ // Adds the Item to container
+ itemIds.add(itemId);
+ items.put(itemId, new Hashtable());
+ Item item = getItem(itemId);
+ if (filteredItemIds != null) {
+ if (passesFilters(item)) {
+ filteredItemIds.add(itemId);
+ }
+ }
+
+ // Sends the event
+ fireContentsChange();
+
+ return item;
+ }
+
+ /**
+ * Removes the Item corresponding to the given Item ID from the list.
+ *
+ * @param itemId
+ * the ID of the Item to remove.
+ * @return true
if the operation succeeded,
+ * false
if not
+ */
+ public boolean removeItem(Object itemId) {
+
+ if (items.remove(itemId) == null) {
+ return false;
+ }
+ itemIds.remove(itemId);
+ if (filteredItemIds != null) {
+ filteredItemIds.remove(itemId);
+ }
+
+ fireContentsChange();
+
+ return true;
+ }
+
+ /**
+ * Removes a Property specified by the given Property ID from the list. Note
+ * that the Property will be removed from all Items in the list.
+ *
+ * @param propertyId
+ * the ID of the Property to remove.
+ * @return true
if the operation succeeded,
+ * false
if not
+ */
+ public boolean removeContainerProperty(Object propertyId) {
+
+ // Fails if the Property is not present
+ if (!propertyIds.contains(propertyId)) {
+ return false;
+ }
+
+ // Removes the Property to Property list and types
+ propertyIds.remove(propertyId);
+ types.remove(propertyId);
+
+ // If remove the Property from all Items
+ for (Iterator i = itemIds.iterator(); i.hasNext();) {
+ ((Hashtable) items.get(i.next())).remove(propertyId);
+ }
+
+ // Sends a change event
+ fireContainerPropertySetChange();
+
+ return true;
+ }
+
+ /* Container.Ordered methods ******************************************** */
+
+ /**
+ * Gets the ID of the first Item in the list.
+ *
+ * @return ID of the first Item in the list
+ */
+ public Object firstItemId() {
+ try {
+ if (filteredItemIds != null) {
+ return filteredItemIds.iterator().next();
+ }
+ return itemIds.get(0);
+ } catch (IndexOutOfBoundsException e) {
+ } catch (NoSuchElementException e) {
+ }
+ return null;
+ }
+
+ /**
+ * Gets the ID of the last Item in the list.
+ *
+ * @return ID of the last Item in the list
+ */
+ public Object lastItemId() {
+ try {
+ if (filteredItemIds != null) {
+ Iterator i = filteredItemIds.iterator();
+ Object last = null;
+ while (i.hasNext()) {
+ last = i.next();
+ }
+ return last;
+ }
+ return itemIds.get(itemIds.size() - 1);
+ } catch (IndexOutOfBoundsException e) {
+ }
+ return null;
+ }
+
+ /**
+ * Gets the ID of the Item following the Item that corresponds to the
+ * itemId. If the given Item is the last or not found in the list,
+ * null
is returned.
+ *
+ * @param itemId
+ * the ID of an Item in the list.
+ * @return ID of the next Item or null
+ */
+ public Object nextItemId(Object itemId) {
+ if (filteredItemIds != null) {
+ if (!filteredItemIds.contains(itemId)) {
+ return null;
+ }
+ Iterator i = filteredItemIds.iterator();
+ if (itemId == null) {
+ return null;
+ }
+ while (i.hasNext() && !itemId.equals(i.next())) {
+ ;
+ }
+ if (i.hasNext()) {
+ return i.next();
+ }
+ return null;
+ }
+ try {
+ return itemIds.get(itemIds.indexOf(itemId) + 1);
+ } catch (IndexOutOfBoundsException e) {
+ return null;
+ }
+ }
+
+ /**
+ * Gets the ID of the Item preceding the Item that corresponds to the
+ * itemId. If the given Item is the first or not found in the list,
+ * null
is returned.
+ *
+ * @param itemId
+ * the ID of an Item in the list.
+ * @return ID of the previous Item or null
+ */
+ public Object prevItemId(Object itemId) {
+ if (filteredItemIds != null) {
+ if (!filteredItemIds.contains(itemId)) {
+ return null;
+ }
+ Iterator i = filteredItemIds.iterator();
+ if (itemId == null) {
+ return null;
+ }
+ Object prev = null;
+ Object current;
+ while (i.hasNext() && !itemId.equals(current = i.next())) {
+ prev = current;
+ }
+ return prev;
+ }
+ try {
+ return itemIds.get(itemIds.indexOf(itemId) - 1);
+ } catch (IndexOutOfBoundsException e) {
+ return null;
+ }
+ }
+
+ /**
+ * Tests if the Item corresponding to the given Item ID is the first Item in
+ * the list.
+ *
+ * @param itemId
+ * the ID of an Item in the list.
+ * @return true
if the Item is first in the list,
+ * false
if not
+ */
+ public boolean isFirstId(Object itemId) {
+ if (filteredItemIds != null) {
+ try {
+ Object first = filteredItemIds.iterator().next();
+ return (itemId != null && itemId.equals(first));
+ } catch (NoSuchElementException e) {
+ return false;
+ }
+ }
+ return (size() >= 1 && itemIds.get(0).equals(itemId));
+ }
+
+ /**
+ * Tests if the Item corresponding to the given Item ID is the last Item in
+ * the list.
+ *
+ * @param itemId
+ * the ID of an Item in the list.
+ * @return true
if the Item is last in the list,
+ * false
if not
+ */
+ public boolean isLastId(Object itemId) {
+ if (filteredItemIds != null) {
+ try {
+ Object last = null;
+ for (Iterator i = filteredItemIds.iterator(); i.hasNext();) {
+ last = i.next();
+ }
+ return (itemId != null && itemId.equals(last));
+ } catch (NoSuchElementException e) {
+ return false;
+ }
+ }
+ int s = size();
+ return (s >= 1 && itemIds.get(s - 1).equals(itemId));
+ }
+
+ /**
+ * @see com.itmill.toolkit.data.Container.Ordered#addItemAfter(Object,
+ * Object)
+ */
+ public Item addItemAfter(Object previousItemId, Object newItemId) {
+
+ // Get the index of the addition
+ int index = 0;
+ if (previousItemId != null) {
+ index = 1 + indexOfId(previousItemId);
+ if (index <= 0 || index > size()) {
+ return null;
+ }
+ }
+
+ return addItemAt(index, newItemId);
+ }
+
+ /**
+ * @see com.itmill.toolkit.data.Container.Ordered#addItemAfter(Object)
+ */
+ public Object addItemAfter(Object previousItemId) {
+
+ // Get the index of the addition
+ int index = 0;
+ if (previousItemId != null) {
+ index = 1 + indexOfId(previousItemId);
+ if (index <= 0 || index > size()) {
+ return null;
+ }
+ }
+
+ return addItemAt(index);
+ }
+
+ /**
+ * Gets ID with the index. The following is true for the index: 0 <= index <
+ * size().
+ *
+ * @return ID in the given index.
+ * @param index
+ * Index of the requested ID in the container.
+ */
+ public Object getIdByIndex(int index) {
+
+ if (filteredItemIds != null) {
+ if (index < 0) {
+ throw new IndexOutOfBoundsException();
+ }
+ try {
+ Iterator i = filteredItemIds.iterator();
+ while (index-- > 0) {
+ i.next();
+ }
+ return i.next();
+ } catch (NoSuchElementException e) {
+ throw new IndexOutOfBoundsException();
+ }
+ }
+
+ return itemIds.get(index);
+ }
+
+ /**
+ * Gets the index of an id. The following is true for the index: 0 <= index <
+ * size().
+ *
+ * @return Index of the Item or -1 if the Item is not in the container.
+ * @param itemId
+ * ID of an Item in the collection
+ */
+ public int indexOfId(Object itemId) {
+ if (filteredItemIds != null) {
+ int index = 0;
+ if (itemId == null) {
+ return -1;
+ }
+ try {
+ for (Iterator i = filteredItemIds.iterator(); itemId.equals(i
+ .next());) {
+ index++;
+ }
+ return index;
+ } catch (NoSuchElementException e) {
+ return -1;
+ }
+ }
+ return itemIds.indexOf(itemId);
+ }
+
+ /**
+ * @see com.itmill.toolkit.data.Container.Indexed#addItemAt(int, Object)
+ */
+ public Item addItemAt(int index, Object newItemId) {
+
+ // Make sure that the Item has not been created yet
+ if (items.containsKey(newItemId)) {
+ return null;
+ }
+
+ // Adds the Item to container
+ itemIds.add(index, newItemId);
+ items.put(newItemId, new Hashtable());
+
+ if (filteredItemIds != null) {
+ updateContainerFiltering();
+ } else {
+ fireContentsChange();
+ }
+
+ return getItem(newItemId);
+ }
+
+ /**
+ * @see com.itmill.toolkit.data.Container.Indexed#addItemAt(int)
+ */
+ public Object addItemAt(int index) {
+
+ // Creates a new id
+ Object id = new Object();
+
+ // Adds the Item into container
+ addItemAt(index, id);
+
+ return id;
+ }
+
+ /* Event notifiers ****************************************************** */
+
+ /**
+ * An event
object specifying the list whose Property set has
+ * changed.
+ *
+ * @author IT Mill Ltd.
+ * @version
+ * @VERSION@
+ * @since 3.0
+ */
+ private class PropertySetChangeEvent extends EventObject implements
+ Container.PropertySetChangeEvent {
+
+ /**
+ * Serial generated by eclipse.
+ */
+ private static final long serialVersionUID = 3257002172528079926L;
+
+ private PropertySetChangeEvent(IndexedContainer source) {
+ super(source);
+ }
+
+ /**
+ * Gets the list whose Property set has changed.
+ *
+ * @return source object of the event as a Container
+ */
+ public Container getContainer() {
+ return (Container) getSource();
+ }
+ }
+
+ /**
+ * An event
object specifying the list whose Item set has
+ * changed.
+ *
+ * @author IT Mill Ltd.
+ * @version
+ * @VERSION@
+ * @since 3.0
+ */
+ private class ItemSetChangeEvent extends EventObject implements
+ Container.ItemSetChangeEvent {
+
+ /**
+ * Serial generated by eclipse.
+ */
+ private static final long serialVersionUID = 3832616279386372147L;
+
+ private ItemSetChangeEvent(IndexedContainer source) {
+ super(source);
+ }
+
+ /**
+ * Gets the list whose Item set has changed.
+ *
+ * @return source object of the event as a Container
+ */
+ public Container getContainer() {
+ return (Container) getSource();
+ }
+
+ }
+
+ /**
+ * An event
object specifying the Propery in a list whose
+ * value has changed.
+ *
+ * @author IT Mill Ltd.
+ * @version
+ * @VERSION@
+ * @since 3.0
+ */
+ private class PropertyValueChangeEvent extends EventObject implements
+ Property.ValueChangeEvent {
+
+ /**
+ * Serial generated by eclipse.
+ */
+ private static final long serialVersionUID = 3833749884498359857L;
+
+ private PropertyValueChangeEvent(Property source) {
+ super(source);
+ }
+
+ /**
+ * Gets the Property whose value has changed.
+ *
+ * @return source object of the event as a Property
+ */
+ public Property getProperty() {
+ return (Property) getSource();
+ }
+
+ }
+
+ /**
+ * Registers a new Property set change listener for this list.
+ *
+ * @param listener
+ * the new Listener to be registered.
+ */
+ public void addListener(Container.PropertySetChangeListener listener) {
+ if (propertySetChangeListeners == null) {
+ propertySetChangeListeners = new LinkedList();
+ }
+ propertySetChangeListeners.add(listener);
+ }
+
+ /**
+ * Removes a previously registered Property set change listener.
+ *
+ * @param listener
+ * the listener to be removed.
+ */
+ public void removeListener(Container.PropertySetChangeListener listener) {
+ if (propertySetChangeListeners != null) {
+ propertySetChangeListeners.remove(listener);
+ }
+ }
+
+ /**
+ * Adds a Item set change listener for the list.
+ *
+ * @param listener
+ * the listener to be added.
+ */
+ public void addListener(Container.ItemSetChangeListener listener) {
+ if (itemSetChangeListeners == null) {
+ itemSetChangeListeners = new LinkedList();
+ }
+ itemSetChangeListeners.add(listener);
+ }
+
+ /**
+ * Removes a Item set change listener from the object.
+ *
+ * @param listener
+ * the listener to be removed.
+ */
+ public void removeListener(Container.ItemSetChangeListener listener) {
+ if (itemSetChangeListeners != null) {
+ itemSetChangeListeners.remove(listener);
+ }
+ }
+
+ /**
+ * Registers a new value change listener for this object.
+ *
+ * @param listener
+ * the new Listener to be registered
+ */
+ public void addListener(Property.ValueChangeListener listener) {
+ if (propertyValueChangeListeners == null) {
+ propertyValueChangeListeners = new LinkedList();
+ }
+ propertyValueChangeListeners.add(listener);
+ }
+
+ /**
+ * Removes a previously registered value change listener.
+ *
+ * @param listener
+ * the listener to be removed.
+ */
+ public void removeListener(Property.ValueChangeListener listener) {
+ if (propertyValueChangeListeners != null) {
+ propertyValueChangeListeners.remove(listener);
+ }
+ }
+
+ /**
+ * Sends a Property value change event to all interested listeners.
+ *
+ * @param source
+ * the IndexedContainerProperty object.
+ */
+ private void firePropertyValueChange(IndexedContainerProperty source) {
+
+ // Sends event to listeners listening all value changes
+ if (propertyValueChangeListeners != null) {
+ Object[] l = propertyValueChangeListeners.toArray();
+ Property.ValueChangeEvent event = new IndexedContainer.PropertyValueChangeEvent(
+ source);
+ for (int i = 0; i < l.length; i++) {
+ ((Property.ValueChangeListener) l[i]).valueChange(event);
+ }
+ }
+
+ // Sends event to single property value change listeners
+ if (singlePropertyValueChangeListeners != null) {
+ Hashtable propertySetToListenerListMap = (Hashtable) singlePropertyValueChangeListeners
+ .get(source.propertyId);
+ if (propertySetToListenerListMap != null) {
+ LinkedList listenerList = (LinkedList) propertySetToListenerListMap
+ .get(source.itemId);
+ if (listenerList != null) {
+ Property.ValueChangeEvent event = new IndexedContainer.PropertyValueChangeEvent(
+ source);
+ for (Iterator i = listenerList.iterator(); i.hasNext();) {
+ ((Property.ValueChangeListener) i.next())
+ .valueChange(event);
+ }
+ }
+ }
+ }
+
+ }
+
+ /**
+ * Sends a Property set change event to all interested listeners.
+ */
+ private void fireContainerPropertySetChange() {
+ if (propertySetChangeListeners != null) {
+ Object[] l = propertySetChangeListeners.toArray();
+ Container.PropertySetChangeEvent event = new IndexedContainer.PropertySetChangeEvent(
+ this);
+ for (int i = 0; i < l.length; i++) {
+ ((Container.PropertySetChangeListener) l[i])
+ .containerPropertySetChange(event);
+ }
+ }
+ }
+
+ /**
+ * Sends Item set change event to all registered interested listeners.
+ */
+ private void fireContentsChange() {
+ if (itemSetChangeListeners != null) {
+ Object[] l = itemSetChangeListeners.toArray();
+ Container.ItemSetChangeEvent event = new IndexedContainer.ItemSetChangeEvent(
+ this);
+ for (int i = 0; i < l.length; i++) {
+ ((Container.ItemSetChangeListener) l[i])
+ .containerItemSetChange(event);
+ }
+ }
+ }
+
+ /**
+ * Adds new single Property change listener.
+ *
+ * @param propertyId
+ * the ID of the Property to add.
+ * @param itemId
+ * the ID of the Item .
+ * @param listener
+ * the listener to be added.
+ */
+ private void addSinglePropertyChangeListener(Object propertyId,
+ Object itemId, Property.ValueChangeListener listener) {
+ if (listener != null) {
+ if (singlePropertyValueChangeListeners == null) {
+ singlePropertyValueChangeListeners = new Hashtable();
+ }
+ Hashtable propertySetToListenerListMap = (Hashtable) singlePropertyValueChangeListeners
+ .get(propertyId);
+ if (propertySetToListenerListMap == null) {
+ propertySetToListenerListMap = new Hashtable();
+ singlePropertyValueChangeListeners.put(propertyId,
+ propertySetToListenerListMap);
+ }
+ LinkedList listenerList = (LinkedList) propertySetToListenerListMap
+ .get(itemId);
+ if (listenerList == null) {
+ listenerList = new LinkedList();
+ propertySetToListenerListMap.put(itemId, listenerList);
+ }
+ listenerList.addLast(listener);
+ }
+ }
+
+ /**
+ * Removes a previously registered single Property change listener.
+ *
+ * @param propertyId
+ * the ID of the Property to remove.
+ * @param itemId
+ * the ID of the Item.
+ * @param listener
+ * the listener to be removed.
+ */
+ private void removeSinglePropertyChangeListener(Object propertyId,
+ Object itemId, Property.ValueChangeListener listener) {
+ if (listener != null && singlePropertyValueChangeListeners != null) {
+ Hashtable propertySetToListenerListMap = (Hashtable) singlePropertyValueChangeListeners
+ .get(propertyId);
+ if (propertySetToListenerListMap != null) {
+ LinkedList listenerList = (LinkedList) propertySetToListenerListMap
+ .get(itemId);
+ if (listenerList != null) {
+ listenerList.remove(listener);
+ if (listenerList.isEmpty()) {
+ propertySetToListenerListMap.remove(itemId);
+ }
+ }
+ if (propertySetToListenerListMap.isEmpty()) {
+ singlePropertyValueChangeListeners.remove(propertyId);
+ }
+ }
+ if (singlePropertyValueChangeListeners.isEmpty()) {
+ singlePropertyValueChangeListeners = null;
+ }
+ }
+ }
+
+ /* Internal Item and Property implementations *************************** */
+
+ /*
+ * A class implementing the com.itmill.toolkit.data.Item interface to be
+ * contained in the list. @author IT Mill Ltd.
+ *
+ * @version @VERSION@
+ * @since 3.0
+ */
+ class IndexedContainerItem implements Item {
+
+ /**
+ * Item ID in the host container for this Item.
+ */
+ private Object itemId;
+
+ /**
+ * Constructs a new ListItem instance and connects it to a host
+ * container.
+ *
+ * @param itemId
+ * the Item ID of the new Item.
+ */
+ private IndexedContainerItem(Object itemId) {
+
+ // Gets the item contents from the host
+ if (itemId == null) {
+ throw new NullPointerException();
+ }
+ this.itemId = itemId;
+ }
+
+ /**
+ * Gets the Property corresponding to the given Property ID stored in
+ * the Item. If the Item does not contain the Property,
+ * null
is returned.
+ *
+ * @param id
+ * the identifier of the Property to get.
+ * @return the Property with the given ID or null
+ */
+ public Property getItemProperty(Object id) {
+ return new IndexedContainerProperty(itemId, id);
+ }
+
+ /**
+ * Gets the collection containing the IDs of all Properties stored in
+ * the Item.
+ *
+ * @return unmodifiable collection contaning IDs of the Properties
+ * stored the Item
+ */
+ public Collection getItemPropertyIds() {
+ return Collections.unmodifiableCollection(propertyIds);
+ }
+
+ /**
+ * Gets the String
representation of the contents of the
+ * Item. The format of the string is a space separated catenation of the
+ * String
representations of the Properties contained by
+ * the Item.
+ *
+ * @return String
representation of the Item contents
+ */
+ public String toString() {
+ String retValue = "";
+
+ for (Iterator i = propertyIds.iterator(); i.hasNext();) {
+ Object propertyId = i.next();
+ retValue += getItemProperty(propertyId).toString();
+ if (i.hasNext()) {
+ retValue += " ";
+ }
+ }
+
+ return retValue;
+ }
+
+ /**
+ * Calculates a integer hash-code for the Item that's unique inside the
+ * list. Two Items inside the same list have always different
+ * hash-codes, though Items in different lists may have identical
+ * hash-codes.
+ *
+ * @return A locally unique hash-code as integer
+ */
+ public int hashCode() {
+ return getHost().hashCode() ^ itemId.hashCode();
+ }
+
+ /**
+ * Tests if the given object is the same as the this object. Two Items
+ * got from a list container with the same ID are equal.
+ *
+ * @param obj
+ * an object to compare with this object
+ * @return true
if the given object is the same as this
+ * object, false
if not
+ */
+ public boolean equals(Object obj) {
+ if (obj == null
+ || !obj.getClass().equals(IndexedContainerItem.class)) {
+ return false;
+ }
+ IndexedContainerItem li = (IndexedContainerItem) obj;
+ return getHost() == li.getHost() && itemId.equals(li.itemId);
+ }
+
+ /**
+ *
+ * @return
+ */
+ private IndexedContainer getHost() {
+ return IndexedContainer.this;
+ }
+
+ /**
+ * Indexed container does not support adding new properties.
+ *
+ * @see com.itmill.toolkit.data.Item#addProperty(Object, Property)
+ */
+ public boolean addItemProperty(Object id, Property property)
+ throws UnsupportedOperationException {
+ throw new UnsupportedOperationException("Indexed container item "
+ + "does not support adding new properties");
+ }
+
+ /**
+ * Indexed container does not support removing properties.
+ *
+ * @see com.itmill.toolkit.data.Item#removeProperty(Object)
+ */
+ public boolean removeItemProperty(Object id)
+ throws UnsupportedOperationException {
+ throw new UnsupportedOperationException(
+ "Indexed container item does not support property removal");
+ }
+
+ }
+
+ /**
+ * A class implementing the com.itmill.toolkit.data.Property interface to be
+ * contained in the Items contained in the list.
+ *
+ * @author IT Mill Ltd.
+ *
+ * @version
+ * @VERSION@
+ * @since 3.0
+ */
+ private class IndexedContainerProperty implements Property,
+ Property.ValueChangeNotifier {
+
+ /**
+ * ID of the Item, where the Property resides.
+ */
+ private Object itemId;
+
+ /**
+ * Id of the Property.
+ */
+ private Object propertyId;
+
+ /**
+ * Constructs a new ListProperty object and connect it to a ListItem and
+ * a ListContainer.
+ *
+ * @param itemId
+ * the ID of the Item to connect the new Property to.
+ * @param propertyId
+ * the Property ID of the new Property.
+ * @param host
+ * the list that contains the Item to contain the new
+ * Property.
+ */
+ private IndexedContainerProperty(Object itemId, Object propertyId) {
+ if (itemId == null || propertyId == null) {
+ throw new NullPointerException();
+ }
+ this.propertyId = propertyId;
+ this.itemId = itemId;
+ }
+
+ /**
+ * Returns the type of the Property. The methods getValue
+ * and setValue
must be compatible with this type: one
+ * must be able to safely cast the value returned from
+ * getValue
to the given type and pass any variable
+ * assignable to this type as a parameter to setValue
+ * Tests if the Property is in read-only mode. In read-only mode calls
+ * to the method setValue
will throw
+ * ReadOnlyException
s and will not modify the value of
+ * the Property.
+ *
+ *
+ * @return true
if the Property is in read-only mode,
+ * false
if it's not.
+ */
+ public boolean isReadOnly() {
+ return readOnlyProperties.contains(this);
+ }
+
+ /**
+ * Sets the Property's read-only mode to the specified status.
+ *
+ * @param newStatus
+ * the new read-only status of the Property.
+ */
+ public void setReadOnly(boolean newStatus) {
+ if (newStatus) {
+ readOnlyProperties.add(this);
+ } else {
+ readOnlyProperties.remove(this);
+ }
+ }
+
+ /**
+ * Sets the value of the Property. By default this method will try to
+ * assign the value directly, but if it is unassignable, it will try to
+ * use the String
constructor of the internal data type
+ * to assign the value,
+ *
+ * @param newValue
+ * the New value of the Property. This should be
+ * assignable to the Property's internal type or support
+ * toString
.
+ *
+ * @throws Property.ReadOnlyException
+ * if the object is in read-only mode
+ * @throws Property.ConversionException
+ * if newValue
can't be converted into
+ * the Property's native type directly or through
+ * String
+ */
+ public void setValue(Object newValue)
+ throws Property.ReadOnlyException, Property.ConversionException {
+
+ // Gets the Property set
+ Hashtable propertySet = (Hashtable) items.get(itemId);
+
+ // Support null values on all types
+ if (newValue == null) {
+ propertySet.remove(propertyId);
+ } else if (getType().isAssignableFrom(newValue.getClass())) {
+ propertySet.put(propertyId, newValue);
+ } else {
+ try {
+
+ // Gets the string constructor
+ Constructor constr = getType().getConstructor(
+ new Class[] { String.class });
+
+ // Creates new object from the string
+ propertySet.put(propertyId, constr
+ .newInstance(new Object[] { newValue.toString() }));
+
+ } catch (java.lang.Exception e) {
+ throw new Property.ConversionException(
+ "Conversion for value '" + newValue + "' of class "
+ + newValue.getClass().getName() + " to "
+ + getType().getName() + " failed");
+ }
+ }
+
+ firePropertyValueChange(this);
+ }
+
+ /**
+ * Returns the value of the Property in human readable textual format.
+ * The return value should be assignable to the setValue
+ * method if the Property is not in read-only mode.
+ *
+ * @return String
representation of the value stored in
+ * the Property
+ */
+ public String toString() {
+ Object value = getValue();
+ if (value == null) {
+ return null;
+ }
+ return value.toString();
+ }
+
+ /**
+ * Calculates a integer hash-code for the Property that's unique inside
+ * the Item containing the Property. Two different Properties inside the
+ * same Item contained in the same list always have different
+ * hash-codes, though Properties in different Items may have identical
+ * hash-codes.
+ *
+ * @return A locally unique hash-code as integer
+ */
+ public int hashCode() {
+ return itemId.hashCode() ^ propertyId.hashCode()
+ ^ IndexedContainer.this.hashCode();
+ }
+
+ /**
+ * Tests if the given object is the same as the this object. Two
+ * Properties got from an Item with the same ID are equal.
+ *
+ * @param obj
+ * an object to compare with this object
+ * @return true
if the given object is the same as this
+ * object, false
if not
+ */
+ public boolean equals(Object obj) {
+ if (obj == null
+ || !obj.getClass().equals(IndexedContainerProperty.class)) {
+ return false;
+ }
+ IndexedContainerProperty lp = (IndexedContainerProperty) obj;
+ return lp.getHost() == getHost()
+ && lp.propertyId.equals(propertyId)
+ && lp.itemId.equals(itemId);
+ }
+
+ /**
+ * Registers a new value change listener for this Property.
+ *
+ * @param listener
+ * the new Listener to be registered.
+ * @see com.itmill.toolkit.data.Property.ValueChangeNotifier#addListener(ValueChangeListener)
+ */
+ public void addListener(Property.ValueChangeListener listener) {
+ addSinglePropertyChangeListener(propertyId, itemId, listener);
+ }
+
+ /**
+ * Removes a previously registered value change listener.
+ *
+ * @param listener
+ * listener to be removed
+ * @see com.itmill.toolkit.data.Property.ValueChangeNotifier#removeListener(ValueChangeListener)
+ */
+ public void removeListener(Property.ValueChangeListener listener) {
+ removeSinglePropertyChangeListener(propertyId, itemId, listener);
+ }
+
+ private IndexedContainer getHost() {
+ return IndexedContainer.this;
+ }
+
+ }
+
+ /**
+ * @see com.itmill.toolkit.data.Container.Sortable#sort(java.lang.Object[],
+ * boolean[])
+ */
+ public synchronized void sort(Object[] propertyId, boolean[] ascending) {
+
+ // Removes any non-sortable property ids
+ ArrayList ids = new ArrayList();
+ ArrayList orders = new ArrayList();
+ Collection sortable = getSortableContainerPropertyIds();
+ for (int i = 0; i < propertyId.length; i++) {
+ if (sortable.contains(propertyId[i])) {
+ ids.add(propertyId[i]);
+ orders.add(new Boolean(i < ascending.length ? ascending[i]
+ : true));
+ }
+ }
+
+ if (ids.size() == 0) {
+ return;
+ }
+ sortPropertyId = ids.toArray();
+ sortDirection = new boolean[orders.size()];
+ for (int i = 0; i < sortDirection.length; i++) {
+ sortDirection[i] = ((Boolean) orders.get(i)).booleanValue();
+ }
+
+ // Sort
+ Collections.sort(itemIds, this);
+ if (filteredItemIds != null) {
+ updateContainerFiltering();
+ } else {
+ fireContentsChange();
+ }
+
+ // Remove temporary references
+ sortPropertyId = null;
+ sortDirection = null;
+
+ }
+
+ /**
+ * @see com.itmill.toolkit.data.Container.Sortable#getSortableContainerPropertyIds()
+ */
+ public Collection getSortableContainerPropertyIds() {
+
+ LinkedList list = new LinkedList();
+ for (Iterator i = propertyIds.iterator(); i.hasNext();) {
+ Object id = i.next();
+ Class type = getType(id);
+ if (type != null && Comparable.class.isAssignableFrom(type)) {
+ list.add(id);
+ }
+ }
+
+ return list;
+ }
+
+ /**
+ * Compares two items for sorting.
+ *
+ * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
+ * @see #sort((java.lang.Object[], boolean[])
+ */
+ public int compare(Object o1, Object o2) {
+
+ for (int i = 0; i < sortPropertyId.length; i++) {
+
+ // Get the compared properties
+ Property pp1 = getContainerProperty(o1, sortPropertyId[i]);
+ Property pp2 = getContainerProperty(o2, sortPropertyId[i]);
+
+ // Get the compared values
+ Object p1 = pp1 == null ? null : pp1.getValue();
+ Object p2 = pp2 == null ? null : pp2.getValue();
+
+ // Result of the comparison
+ int r = 0;
+
+ // Normal non-null comparison
+ if (p1 != null && p2 != null) {
+ if ((p1 instanceof Boolean) && (p2 instanceof Boolean)) {
+ r = p1.equals(p2) ? 0
+ : ((sortDirection[i] ? 1 : -1) * (((Boolean) p1)
+ .booleanValue() ? 1 : -1));
+ } else {
+ r = sortDirection[i] ? ((Comparable) p1).compareTo(p2)
+ : -((Comparable) p1).compareTo(p2);
+ }
+ }
+
+ // If both are nulls
+ else if (p1 == p2) {
+ r = 0;
+ } else {
+ r = (sortDirection[i] ? 1 : -1) * (p1 == null ? -1 : 1);
+ }
+
+ // If order can be decided
+ if (r != 0) {
+ return r;
+ }
+ }
+
+ return 0;
+ }
+
+ /**
+ * Supports cloning of the IndexedContainer cleanly.
+ *
+ * @throws CloneNotSupportedException
+ * if an object cannot be cloned. .
+ */
+ public Object clone() throws CloneNotSupportedException {
+
+ // Creates the clone
+ IndexedContainer nc = new IndexedContainer();
+
+ // Clone the shallow properties
+ nc.itemIds = itemIds != null ? (ArrayList) itemIds.clone() : null;
+ nc.itemSetChangeListeners = itemSetChangeListeners != null ? (LinkedList) itemSetChangeListeners
+ .clone()
+ : null;
+ nc.propertyIds = propertyIds != null ? (ArrayList) propertyIds.clone()
+ : null;
+ nc.propertySetChangeListeners = propertySetChangeListeners != null ? (LinkedList) propertySetChangeListeners
+ .clone()
+ : null;
+ nc.propertyValueChangeListeners = propertyValueChangeListeners != null ? (LinkedList) propertyValueChangeListeners
+ .clone()
+ : null;
+ nc.readOnlyProperties = readOnlyProperties != null ? (HashSet) readOnlyProperties
+ .clone()
+ : null;
+ nc.singlePropertyValueChangeListeners = singlePropertyValueChangeListeners != null ? (Hashtable) singlePropertyValueChangeListeners
+ .clone()
+ : null;
+ nc.sortDirection = sortDirection != null ? (boolean[]) sortDirection
+ .clone() : null;
+ nc.sortPropertyId = sortPropertyId != null ? (Object[]) sortPropertyId
+ .clone() : null;
+ nc.types = types != null ? (Hashtable) types.clone() : null;
+
+ nc.filters = filters == null ? null : (HashSet) filters.clone();
+
+ nc.filteredItemIds = filteredItemIds == null ? null
+ : (LinkedHashSet) filteredItemIds.clone();
+
+ // Clone property-values
+ if (items == null) {
+ nc.items = null;
+ } else {
+ nc.items = new Hashtable();
+ for (Iterator i = items.keySet().iterator(); i.hasNext();) {
+ Object id = i.next();
+ Hashtable it = (Hashtable) items.get(id);
+ nc.items.put(id, it.clone());
+ }
+ }
+
+ return nc;
+ }
+
+ /**
+ * @see java.lang.Object#equals(java.lang.Object)
+ */
+ public boolean equals(Object obj) {
+
+ // Only ones of the objects of the same class can be equal
+ if (!(obj instanceof IndexedContainer)) {
+ return false;
+ }
+ IndexedContainer o = (IndexedContainer) obj;
+
+ // Checks the properties one by one
+ if (itemIds != o.itemIds && o.itemIds != null
+ && !o.itemIds.equals(itemIds)) {
+ return false;
+ }
+ if (filters != o.filters && o.filters != null
+ && !o.filters.equals(filters)) {
+ return false;
+ }
+ if (items != o.items && o.items != null && !o.items.equals(items)) {
+ return false;
+ }
+ if (itemSetChangeListeners != o.itemSetChangeListeners
+ && o.itemSetChangeListeners != null
+ && !o.itemSetChangeListeners.equals(itemSetChangeListeners)) {
+ return false;
+ }
+ if (propertyIds != o.propertyIds && o.propertyIds != null
+ && !o.propertyIds.equals(propertyIds)) {
+ return false;
+ }
+ if (propertySetChangeListeners != o.propertySetChangeListeners
+ && o.propertySetChangeListeners != null
+ && !o.propertySetChangeListeners
+ .equals(propertySetChangeListeners)) {
+ return false;
+ }
+ if (propertyValueChangeListeners != o.propertyValueChangeListeners
+ && o.propertyValueChangeListeners != null
+ && !o.propertyValueChangeListeners
+ .equals(propertyValueChangeListeners)) {
+ return false;
+ }
+ if (readOnlyProperties != o.readOnlyProperties
+ && o.readOnlyProperties != null
+ && !o.readOnlyProperties.equals(readOnlyProperties)) {
+ return false;
+ }
+ if (singlePropertyValueChangeListeners != o.singlePropertyValueChangeListeners
+ && o.singlePropertyValueChangeListeners != null
+ && !o.singlePropertyValueChangeListeners
+ .equals(singlePropertyValueChangeListeners)) {
+ return false;
+ }
+ if (sortDirection != o.sortDirection && o.sortDirection != null
+ && !o.sortDirection.equals(sortDirection)) {
+ return false;
+ }
+ if (sortPropertyId != o.sortPropertyId && o.sortPropertyId != null
+ && !o.sortPropertyId.equals(sortPropertyId)) {
+ return false;
+ }
+ if (types != o.types && o.types != null && !o.types.equals(types)) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * @see java.lang.Object#hashCode()
+ */
+ public int hashCode() {
+
+ // The hash-code is calculated as combination hash of the members
+ return (itemIds != null ? itemIds.hashCode() : 0)
+ ^ (items != null ? items.hashCode() : 0)
+ ^ (filters != null ? filters.hashCode() : 0)
+ ^ (itemSetChangeListeners != null ? itemSetChangeListeners
+ .hashCode() : 0)
+ ^ (propertyIds != null ? propertyIds.hashCode() : 0)
+ ^ (propertySetChangeListeners != null ? propertySetChangeListeners
+ .hashCode()
+ : 0)
+ ^ (propertyValueChangeListeners != null ? propertyValueChangeListeners
+ .hashCode()
+ : 0)
+ ^ (readOnlyProperties != null ? readOnlyProperties.hashCode()
+ : 0)
+ ^ (singlePropertyValueChangeListeners != null ? singlePropertyValueChangeListeners
+ .hashCode()
+ : 0)
+ ^ (sortPropertyId != null ? sortPropertyId.hashCode() : 0)
+ ^ (types != null ? types.hashCode() : 0)
+ ^ (sortDirection != null ? sortDirection.hashCode() : 0);
+ }
+
+ private class Filter {
+ Object propertyId;
+ String filterString;
+ boolean ignoreCase;
+ boolean onlyMatchPrefix;
+
+ Filter(Object propertyId, String filterString, boolean ignoreCase,
+ boolean onlyMatchPrefix) {
+ this.propertyId = propertyId;
+ ;
+ this.filterString = filterString;
+ this.ignoreCase = ignoreCase;
+ this.onlyMatchPrefix = onlyMatchPrefix;
+ }
+
+ public boolean equals(Object obj) {
+
+ // Only ones of the objects of the same class can be equal
+ if (!(obj instanceof Filter)) {
+ return false;
+ }
+ Filter o = (Filter) obj;
+
+ // Checks the properties one by one
+ if (propertyId != o.propertyId && o.propertyId != null
+ && !o.propertyId.equals(propertyId)) {
+ return false;
+ }
+ if (filterString != o.filterString && o.filterString != null
+ && !o.filterString.equals(filterString)) {
+ return false;
+ }
+ if (ignoreCase != o.ignoreCase) {
+ return false;
+ }
+ if (onlyMatchPrefix != o.onlyMatchPrefix) {
+ return false;
+ }
+
+ return true;
+ }
+
+ public int hashCode() {
+ return (propertyId != null ? propertyId.hashCode() : 0)
+ ^ (filterString != null ? filterString.hashCode() : 0);
+ }
+
+ }
+
+ public void addContainerFilter(Object propertyId, String filterString,
+ boolean ignoreCase, boolean onlyMatchPrefix) {
+ if (filters == null) {
+ filters = new HashSet();
+ }
+ filters.add(new Filter(propertyId, filterString, ignoreCase,
+ onlyMatchPrefix));
+ updateContainerFiltering();
+ }
+
+ public void removeAllContainerFilters() {
+ if (filters == null) {
+ return;
+ }
+ filters.clear();
+ updateContainerFiltering();
+ }
+
+ public void removeContainerFilters(Object propertyId) {
+ if (filters == null || propertyId == null) {
+ return;
+ }
+ for (Iterator i = filters.iterator(); i.hasNext();) {
+ Filter f = (Filter) i.next();
+ if (propertyId.equals(f.propertyId)) {
+ i.remove();
+ }
+ }
+ updateContainerFiltering();
+ }
+
+ private void updateContainerFiltering() {
+
+ // Clearing filters?
+ if (filters == null || filters.isEmpty()) {
+ filteredItemIds = null;
+ if (filters != null) {
+ filters = null;
+ fireContentsChange();
+ }
+ return;
+ }
+
+ // Reset filteres list
+ if (filteredItemIds == null) {
+ filteredItemIds = new LinkedHashSet();
+ } else {
+ filteredItemIds.clear();
+ }
+
+ // Filter
+ for (Iterator i = itemIds.iterator(); i.hasNext();) {
+ Object id = i.next();
+ if (passesFilters(new IndexedContainerItem(id))) {
+ filteredItemIds.add(id);
+ }
+ }
+
+ fireContentsChange();
+ }
+
+ private boolean passesFilters(Item item) {
+ if (filters == null) {
+ return true;
+ }
+ if (item == null) {
+ return false;
+ }
+ for (Iterator i = filters.iterator(); i.hasNext();) {
+ Filter f = (Filter) i.next();
+ String s1 = f.ignoreCase ? f.filterString.toLowerCase()
+ : f.filterString;
+ Property p = item.getItemProperty(f.propertyId);
+ if (p == null) {
+ return false;
+ }
+ String s2 = f.ignoreCase ? p.toString().toLowerCase() : p
+ .toString();
+ if (f.onlyMatchPrefix) {
+ if (s2.indexOf(s1) != 0) {
+ return false;
+ }
+ } else {
+ if (s2.indexOf(s1) < 0) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
}
\ No newline at end of file
diff --git a/src/com/itmill/toolkit/data/util/MethodProperty.java b/src/com/itmill/toolkit/data/util/MethodProperty.java
index 7c56f7e3bb..e28ce8f385 100644
--- a/src/com/itmill/toolkit/data/util/MethodProperty.java
+++ b/src/com/itmill/toolkit/data/util/MethodProperty.java
@@ -62,761 +62,777 @@ import com.itmill.toolkit.data.Property;
*/
public class MethodProperty implements Property {
- /**
- * The object that includes the property the MethodProperty is bound to.
- */
- private Object instance;
-
- /**
- * Argument arrays for the getter and setter methods.
- */
- private Object[] setArgs, getArgs;
-
- /**
- * Is the MethodProperty read-only?
- */
- private boolean readOnly;
-
- /**
- * The getter and setter methods.
- */
- private Method setMethod, getMethod;
-
- /**
- * Index of the new value in the argument list for the setter method. If the
- * setter method requires several parameters, this index tells which one is
- * the actual value to change.
- */
- private int setArgumentIndex;
-
- /**
- * Type of the property.
- */
- private Class type;
-
- /**
- * List of listeners who are interested in the read-only status changes of
- * the MethodProperty
- */
- private LinkedList readOnlyStatusChangeListeners = null;
-
- /**
- *
- * Creates a new instance of MethodProperty
from a named bean
- * property. This constructor takes an object and the name of a bean
- * property and initializes itself with the accessor methods for the
- * property.
- *
- *
- * The getter method of a MethodProperty
instantiated with
- * this constructor will be called with no arguments, and the setter method
- * with only the new value as the sole argument.
- *
- *
- *
- * If the setter method is unavailable, the resulting
- * MethodProperty
will be read-only, otherwise it will be
- * read-write.
- *
- *
- *
- * Method names are constucted from the bean property by adding
- * get/is/are/set prefix and capitalising the first character in the name of
- * the given bean property.
- *
- *
- * @param instance
- * the object that includes the property.
- * @param beanPropertyName
- * the name of the property to bind to.
- */
- public MethodProperty(Object instance, String beanPropertyName) {
-
- Class beanClass = instance.getClass();
-
- // Assure that the first letter is upper cased (it is a common
- // mistake to write firstName, not FirstName).
- if (Character.isLowerCase(beanPropertyName.charAt(0))) {
- char[] buf = beanPropertyName.toCharArray();
- buf[0] = Character.toUpperCase(buf[0]);
- beanPropertyName = new String(buf);
- }
-
- // Find the get method
- getMethod = null;
- try {
- getMethod = beanClass.getMethod("get" + beanPropertyName,
- new Class[] {});
- } catch (java.lang.NoSuchMethodException ignored) {
- try {
- getMethod = beanClass.getMethod("is" + beanPropertyName,
- new Class[] {});
- } catch (java.lang.NoSuchMethodException ignoredAsWell) {
- try {
- getMethod = beanClass.getMethod("are" + beanPropertyName,
- new Class[] {});
- } catch (java.lang.NoSuchMethodException e) {
- throw new MethodProperty.MethodException("Bean property "
- + beanPropertyName + " can not be found");
- }
- }
- }
-
- // In case the get method is found, resolve the type
- type = getMethod.getReturnType();
-
- // Finds the set method
- setMethod = null;
- try {
- setMethod = beanClass.getMethod("set" + beanPropertyName,
- new Class[] { type });
- } catch (java.lang.NoSuchMethodException skipped) {
- }
-
- // Gets the return type from get method
- if (type.isPrimitive()) {
- if (type.equals(Boolean.TYPE))
- type = Boolean.class;
- else if (type.equals(Integer.TYPE))
- type = Integer.class;
- else if (type.equals(Float.TYPE))
- type = Float.class;
- else if (type.equals(Double.TYPE))
- type = Double.class;
- else if (type.equals(Byte.TYPE))
- type = Byte.class;
- else if (type.equals(Character.TYPE))
- type = Character.class;
- else if (type.equals(Short.TYPE))
- type = Short.class;
- else if (type.equals(Long.TYPE))
- type = Long.class;
- }
-
- setArguments(new Object[] {}, new Object[] { null }, 0);
- this.readOnly = (setMethod == null);
- this.instance = instance;
- }
-
- /**
- *
- * Creates a new instance of MethodProperty
from named getter
- * and setter methods. The getter method of a MethodProperty
- * instantiated with this constructor will be called with no arguments, and
- * the setter method with only the new value as the sole argument.
- *
- *
- *
- * If the setter method is null
, the resulting
- * MethodProperty
will be read-only, otherwise it will be
- * read-write.
- *
- *
- * @param type
- * the type of the property.
- * @param instance
- * the object that includes the property.
- * @param getMethodName
- * the name of the getter method.
- * @param setMethodName
- * the name of the setter method.
- *
- */
- public MethodProperty(Class type, Object instance, String getMethodName,
- String setMethodName) {
- this(type, instance, getMethodName, setMethodName, new Object[] {},
- new Object[] { null }, 0);
- }
-
- /**
- *
- * Creates a new instance of MethodProperty
with the getter
- * and setter methods. The getter method of a MethodProperty
- * instantiated with this constructor will be called with no arguments, and
- * the setter method with only the new value as the sole argument.
- *
- *
- *
- * If the setter method is null
, the resulting
- * MethodProperty
will be read-only, otherwise it will be
- * read-write.
- *
- *
- * @param type
- * the type of the property.
- * @param instance
- * the object that includes the property.
- * @param getMethod
- * the getter method.
- * @param setMethod
- * the setter method.
- */
- public MethodProperty(Class type, Object instance, Method getMethod,
- Method setMethod) {
- this(type, instance, getMethod, setMethod, new Object[] {},
- new Object[] { null }, 0);
- }
-
- /**
- *
- * Creates a new instance of MethodProperty
from named getter
- * and setter methods and argument lists. The getter method of a
- * MethodProperty
instantiated with this constructor will be
- * called with the getArgs as arguments. The setArgs will be used as the
- * arguments for the setter method, though the argument indexed by the
- * setArgumentIndex will be replaced with the argument passed to the
- * {@link #setValue(Object newValue)} method.
- *
- *
- *
- * For example, if the setArgs
contains A
,
- * B
and C
, and setArgumentIndex =
- * 1
,
- * the call methodProperty.setValue(X)
would result in the
- * setter method to be called with the parameter set of
- * {A, X, C}
- *
- *
- * @param type
- * the type of the property.
- * @param instance
- * the object that includes the property.
- * @param getMethodName
- * the name of the getter method.
- * @param setMethodName
- * the name of the setter method.
- * @param getArgs
- * the fixed argument list to be passed to the getter method.
- * @param setArgs
- * the fixed argument list to be passed to the setter method.
- * @param setArgumentIndex
- * the index of the argument in setArgs
to be
- * replaced with newValue
when
- * {@link #setValue(Object newValue)} is called.
- */
- public MethodProperty(Class type, Object instance, String getMethodName,
- String setMethodName, Object[] getArgs, Object[] setArgs,
- int setArgumentIndex) {
-
- // Check the setargs and setargs index
- if (setMethodName != null && setArgs == null)
- throw new IndexOutOfBoundsException("The setArgs can not be null");
- if (setMethodName != null
- && (setArgumentIndex < 0 || setArgumentIndex >= setArgs.length))
- throw new IndexOutOfBoundsException(
- "The setArgumentIndex must be >= 0 and < setArgs.length");
-
- // Set type
- this.type = type;
-
- // Find set and get -methods
- Method[] m = instance.getClass().getMethods();
-
- // Finds get method
- boolean found = false;
- for (int i = 0; i < m.length; i++) {
-
- // Tests the name of the get Method
- if (!m[i].getName().equals(getMethodName)) {
-
- // name does not match, try next method
- continue;
- }
-
- // Tests return type
- if (!type.equals(m[i].getReturnType()))
- continue;
-
- // Tests the parameter types
- Class[] c = m[i].getParameterTypes();
- if (c.length != getArgs.length) {
-
- // not the right amount of parameters, try next method
- continue;
- }
- int j = 0;
- while (j < c.length) {
- if (getArgs[j] != null
- && !c[j].isAssignableFrom(getArgs[j].getClass())) {
-
- // parameter type does not match, try next method
- break;
- }
- j++;
- }
- if (j == c.length) {
-
- // all paramteters matched
- if (found == true) {
- throw new MethodProperty.MethodException(
- "Could not uniquely identify " + getMethodName
- + "-method");
- } else {
- found = true;
- getMethod = m[i];
- }
- }
- }
- if (found != true) {
- throw new MethodProperty.MethodException("Could not find "
- + getMethodName + "-method");
- }
-
- // Finds set method
- if (setMethodName != null) {
-
- // Finds setMethod
- found = false;
- for (int i = 0; i < m.length; i++) {
-
- // Checks name
- if (!m[i].getName().equals(setMethodName)) {
-
- // name does not match, try next method
- continue;
- }
-
- // Checks parameter compatibility
- Class[] c = m[i].getParameterTypes();
- if (c.length != setArgs.length) {
-
- // not the right amount of parameters, try next method
- continue;
- }
- int j = 0;
- while (j < c.length) {
- if (setArgs[j] != null
- && !c[j].isAssignableFrom(setArgs[j].getClass())) {
-
- // parameter type does not match, try next method
- break;
- } else if (j == setArgumentIndex && !c[j].equals(type)) {
-
- // Property type is not the same as setArg type
- break;
- }
- j++;
- }
- if (j == c.length) {
-
- // all parameters match
- if (found == true) {
- throw new MethodProperty.MethodException(
- "Could not identify unique " + setMethodName
- + "-method");
- } else {
- found = true;
- setMethod = m[i];
- }
- }
- }
- if (found != true) {
- throw new MethodProperty.MethodException("Could not identify "
- + setMethodName + "-method");
- }
- }
-
- // Gets the return type from get method
- if (type.isPrimitive()) {
- if (type.equals(Boolean.TYPE))
- type = Boolean.class;
- else if (type.equals(Integer.TYPE))
- type = Integer.class;
- else if (type.equals(Float.TYPE))
- type = Float.class;
- else if (type.equals(Double.TYPE))
- type = Double.class;
- else if (type.equals(Byte.TYPE))
- type = Byte.class;
- else if (type.equals(Character.TYPE))
- type = Character.class;
- else if (type.equals(Short.TYPE))
- type = Short.class;
- else if (type.equals(Long.TYPE))
- type = Long.class;
- }
-
- setArguments(getArgs, setArgs, setArgumentIndex);
- this.readOnly = (setMethod == null);
- this.instance = instance;
- }
-
- /**
- *
- * Creates a new instance of MethodProperty
from the getter
- * and setter methods, and argument lists.
- *
- *
- * This constructor behaves exactly like
- * {@link #MethodProperty(Class type, Object instance, String getMethodName,
- * String setMethodName, Object [] getArgs, Object [] setArgs, int
- * setArgumentIndex)} except that instead of names of the getter and setter
- * methods this constructor is given the actual methods themselves.
- *
- *
- * @param type
- * the type of the property.
- * @param instance
- * the object that includes the property.
- * @param getMethod
- * the getter method.
- * @param setMethod
- * the setter method.
- * @param getArgs
- * the fixed argument list to be passed to the getter method.
- * @param setArgs
- * the fixed argument list to be passed to the setter method.
- * @param setArgumentIndex
- * the index of the argument in setArgs
to be
- * replaced with newValue
when
- * {@link #setValue(Object newValue)} is called.
- */
- public MethodProperty(Class type, Object instance, Method getMethod,
- Method setMethod, Object[] getArgs, Object[] setArgs,
- int setArgumentIndex) {
-
- if (getMethod == null) {
- throw new MethodProperty.MethodException(
- "Property GET-method cannot not be null: " + type);
- }
-
- if (setMethod != null
- && (setArgumentIndex < 0 || setArgumentIndex >= setArgs.length))
- throw new IndexOutOfBoundsException(
- "The setArgumentIndex must be >= 0 and < setArgs.length");
-
- // Gets the return type from get method
- if (type.isPrimitive()) {
- if (type.equals(Boolean.TYPE))
- type = Boolean.class;
- else if (type.equals(Integer.TYPE))
- type = Integer.class;
- else if (type.equals(Float.TYPE))
- type = Float.class;
- else if (type.equals(Double.TYPE))
- type = Double.class;
- else if (type.equals(Byte.TYPE))
- type = Byte.class;
- else if (type.equals(Character.TYPE))
- type = Character.class;
- else if (type.equals(Short.TYPE))
- type = Short.class;
- else if (type.equals(Long.TYPE))
- type = Long.class;
- }
-
- this.getMethod = getMethod;
- this.setMethod = setMethod;
- setArguments(getArgs, setArgs, setArgumentIndex);
- this.readOnly = (setMethod == null);
- this.instance = instance;
- this.type = type;
- }
-
- /**
- * Returns the type of the Property. The methods getValue
and
- * setValue
must be compatible with this type: one must be
- * able to safely cast the value returned from getValue
to
- * the given type and pass any variable assignable to this type as an
- * argument to setValue
.
- *
- * @return type of the Property
- */
- public final Class getType() {
- return type;
- }
-
- /**
- * Tests if the object is in read-only mode. In read-only mode calls to
- * setValue
will throw ReadOnlyException
and
- * will not modify the value of the Property.
- *
- * @return true
if the object is in read-only mode,
- * false
if it's not
- */
- public boolean isReadOnly() {
- return readOnly;
- }
-
- /**
- * Gets the value stored in the Property. The value is resolved by calling
- * the specified getter method with the argument specified at instantiation.
- *
- * @return the value of the Property
- */
- public Object getValue() {
- try {
- return getMethod.invoke(instance, getArgs);
- } catch (Throwable e) {
- throw new MethodProperty.MethodException(e);
- }
- }
-
- /**
- * Returns the value of the MethodProperty
in human readable
- * textual format. The return value should be assignable to the
- * setValue
method if the Property is not in read-only mode.
- *
- * @return String representation of the value stored in the Property
- */
- public String toString() {
- Object value = getValue();
- if (value == null)
- return null;
- return value.toString();
- }
-
- /**
- *
- * Sets the setter method and getter method argument lists.
- *
- *
- * @param getArgs
- * the fixed argument list to be passed to the getter method.
- * @param setArgs
- * the fixed argument list to be passed to the setter method.
- * @param setArgumentIndex
- * the index of the argument in setArgs
to be
- * replaced with newValue
when
- * {@link #setValue(Object newValue)} is called.
- */
- public void setArguments(Object[] getArgs, Object[] setArgs,
- int setArgumentIndex) {
- this.getArgs = new Object[getArgs.length];
- for (int i = 0; i < getArgs.length; i++)
- this.getArgs[i] = getArgs[i];
- this.setArgs = new Object[setArgs.length];
- for (int i = 0; i < setArgs.length; i++)
- this.setArgs[i] = setArgs[i];
- this.setArgumentIndex = setArgumentIndex;
- }
-
- /**
- * Sets the value of the property. This method supports setting from
- * String
s if either String
is directly
- * assignable to property type, or the type class contains a string
- * constructor.
- *
- * @param newValue
- * the New value of the property.
- * @throws Property.ReadOnlyException
if the object is in
- * read-only mode.
- * @throws Property.ConversionException
if newValue
- * can't be converted into the Property's native type directly
- * or through String
.
- * @see #invokeSetMethod(Object)
- */
- public void setValue(Object newValue) throws Property.ReadOnlyException,
- Property.ConversionException {
-
- // Checks the mode
- if (isReadOnly())
- throw new Property.ReadOnlyException();
-
- // Try to assign the compatible value directly
- if (newValue == null || type.isAssignableFrom(newValue.getClass()))
- invokeSetMethod(newValue);
-
- // Otherwise try to convert the value trough string constructor
- else {
-
- Object value;
- try {
-
- // Gets the string constructor
- Constructor constr = getType().getConstructor(
- new Class[] { String.class });
-
- value = constr
- .newInstance(new Object[] { newValue.toString() });
-
- } catch (java.lang.Exception e) {
- throw new Property.ConversionException(e);
- }
-
- // Creates new object from the string
- invokeSetMethod(value);
- }
- }
-
- /**
- * Internal method to actually call the setter method of the wrapped
- * property.
- *
- * @param value
- */
- private void invokeSetMethod(Object value) {
-
- try {
- // Construct a temporary argument array only if needed
- if (setArgs.length == 1)
- setMethod.invoke(instance, new Object[] { value });
- else {
-
- // Sets the value to argument array
- Object[] args = new Object[setArgs.length];
- for (int i = 0; i < setArgs.length; i++)
- args[i] = (i == setArgumentIndex) ? value : setArgs[i];
- setMethod.invoke(instance, args);
- }
- } catch (InvocationTargetException e) {
- Throwable targetException = e.getTargetException();
- throw new MethodProperty.MethodException(targetException);
- } catch (Exception e) {
- throw new MethodProperty.MethodException(e);
- }
- }
-
- /**
- * Sets the Property's read-only mode to the specified status.
- *
- * @param newStatus
- * the new read-only status of the Property.
- */
- public void setReadOnly(boolean newStatus) {
- boolean prevStatus = readOnly;
- if (newStatus)
- readOnly = true;
- else
- readOnly = (setMethod == null);
- if (prevStatus != readOnly)
- fireReadOnlyStatusChange();
- }
-
- /**
- * Exception
object that signals that there were problems
- * calling or finding the specified getter or setter methods of the
- * property.
- *
- * @author IT Mill Ltd.
- * @version
- * @VERSION@
- * @since 3.0
- */
- public class MethodException extends RuntimeException {
-
- /**
- * Serial generated by eclipse.
- */
- private static final long serialVersionUID = 3690473623827855153L;
-
- /**
- * Cause of the method exception
- */
- private Throwable cause;
-
- /**
- * Constructs a new MethodException
with the specified
- * detail message.
- *
- * @param msg
- * the detail message.
- */
- public MethodException(String msg) {
- super(msg);
- }
-
- /**
- * Constructs a new MethodException
from another
- * exception.
- *
- * @param cause
- * the cause of the exception.
- */
- public MethodException(Throwable cause) {
- this.cause = cause;
- }
-
- /**
- * @see java.lang.Throwable#getCause()
- */
- public Throwable getCause() {
- return cause;
- }
-
- /**
- * Gets the method property this exception originates from.
- */
- public MethodProperty getMethodProperty() {
- return MethodProperty.this;
- }
- }
-
- /* Events *************************************************************** */
-
- /**
- * An Event
object specifying the Property whose read-only
- * status has been changed.
- *
- * @author IT Mill Ltd.
- * @version
- * @VERSION@
- * @since 3.0
- */
- private class ReadOnlyStatusChangeEvent extends java.util.EventObject
- implements Property.ReadOnlyStatusChangeEvent {
-
- /**
- * Serial generated by eclipse.
- */
- private static final long serialVersionUID = 3258129163305955896L;
-
- /**
- * Constructs a new read-only status change event for this object.
- *
- * @param source
- * source object of the event.
- */
- protected ReadOnlyStatusChangeEvent(MethodProperty source) {
- super(source);
- }
-
- /**
- * Gets the Property whose read-only state has changed.
- *
- * @return source Property of the event.
- */
- public Property getProperty() {
- return (Property) getSource();
- }
-
- }
-
- /**
- * Registers a new read-only status change listener for this Property.
- *
- * @param listener
- * the new Listener to be registered.
- */
- public void addListener(Property.ReadOnlyStatusChangeListener listener) {
- if (readOnlyStatusChangeListeners == null)
- readOnlyStatusChangeListeners = new LinkedList();
- readOnlyStatusChangeListeners.add(listener);
- }
-
- /**
- * Removes a previously registered read-only status change listener.
- *
- * @param listener
- * the listener to be removed.
- */
- public void removeListener(Property.ReadOnlyStatusChangeListener listener) {
- if (readOnlyStatusChangeListeners != null)
- readOnlyStatusChangeListeners.remove(listener);
- }
-
- /**
- * Sends a read only status change event to all registered listeners.
- */
- private void fireReadOnlyStatusChange() {
- if (readOnlyStatusChangeListeners != null) {
- Object[] l = readOnlyStatusChangeListeners.toArray();
- Property.ReadOnlyStatusChangeEvent event = new MethodProperty.ReadOnlyStatusChangeEvent(
- this);
- for (int i = 0; i < l.length; i++)
- ((Property.ReadOnlyStatusChangeListener) l[i])
- .readOnlyStatusChange(event);
- }
- }
+ /**
+ * The object that includes the property the MethodProperty is bound to.
+ */
+ private Object instance;
+
+ /**
+ * Argument arrays for the getter and setter methods.
+ */
+ private Object[] setArgs, getArgs;
+
+ /**
+ * Is the MethodProperty read-only?
+ */
+ private boolean readOnly;
+
+ /**
+ * The getter and setter methods.
+ */
+ private Method setMethod, getMethod;
+
+ /**
+ * Index of the new value in the argument list for the setter method. If the
+ * setter method requires several parameters, this index tells which one is
+ * the actual value to change.
+ */
+ private int setArgumentIndex;
+
+ /**
+ * Type of the property.
+ */
+ private Class type;
+
+ /**
+ * List of listeners who are interested in the read-only status changes of
+ * the MethodProperty
+ */
+ private LinkedList readOnlyStatusChangeListeners = null;
+
+ /**
+ *
+ * Creates a new instance of MethodProperty
from a named bean
+ * property. This constructor takes an object and the name of a bean
+ * property and initializes itself with the accessor methods for the
+ * property.
+ *
+ *
+ * The getter method of a MethodProperty
instantiated with
+ * this constructor will be called with no arguments, and the setter method
+ * with only the new value as the sole argument.
+ *
+ *
+ *
+ * If the setter method is unavailable, the resulting
+ * MethodProperty
will be read-only, otherwise it will be
+ * read-write.
+ *
+ *
+ *
+ * Method names are constucted from the bean property by adding
+ * get/is/are/set prefix and capitalising the first character in the name of
+ * the given bean property.
+ *
+ *
+ * @param instance
+ * the object that includes the property.
+ * @param beanPropertyName
+ * the name of the property to bind to.
+ */
+ public MethodProperty(Object instance, String beanPropertyName) {
+
+ Class beanClass = instance.getClass();
+
+ // Assure that the first letter is upper cased (it is a common
+ // mistake to write firstName, not FirstName).
+ if (Character.isLowerCase(beanPropertyName.charAt(0))) {
+ char[] buf = beanPropertyName.toCharArray();
+ buf[0] = Character.toUpperCase(buf[0]);
+ beanPropertyName = new String(buf);
+ }
+
+ // Find the get method
+ getMethod = null;
+ try {
+ getMethod = beanClass.getMethod("get" + beanPropertyName,
+ new Class[] {});
+ } catch (java.lang.NoSuchMethodException ignored) {
+ try {
+ getMethod = beanClass.getMethod("is" + beanPropertyName,
+ new Class[] {});
+ } catch (java.lang.NoSuchMethodException ignoredAsWell) {
+ try {
+ getMethod = beanClass.getMethod("are" + beanPropertyName,
+ new Class[] {});
+ } catch (java.lang.NoSuchMethodException e) {
+ throw new MethodProperty.MethodException("Bean property "
+ + beanPropertyName + " can not be found");
+ }
+ }
+ }
+
+ // In case the get method is found, resolve the type
+ type = getMethod.getReturnType();
+
+ // Finds the set method
+ setMethod = null;
+ try {
+ setMethod = beanClass.getMethod("set" + beanPropertyName,
+ new Class[] { type });
+ } catch (java.lang.NoSuchMethodException skipped) {
+ }
+
+ // Gets the return type from get method
+ if (type.isPrimitive()) {
+ if (type.equals(Boolean.TYPE)) {
+ type = Boolean.class;
+ } else if (type.equals(Integer.TYPE)) {
+ type = Integer.class;
+ } else if (type.equals(Float.TYPE)) {
+ type = Float.class;
+ } else if (type.equals(Double.TYPE)) {
+ type = Double.class;
+ } else if (type.equals(Byte.TYPE)) {
+ type = Byte.class;
+ } else if (type.equals(Character.TYPE)) {
+ type = Character.class;
+ } else if (type.equals(Short.TYPE)) {
+ type = Short.class;
+ } else if (type.equals(Long.TYPE)) {
+ type = Long.class;
+ }
+ }
+
+ setArguments(new Object[] {}, new Object[] { null }, 0);
+ readOnly = (setMethod == null);
+ this.instance = instance;
+ }
+
+ /**
+ *
+ * Creates a new instance of MethodProperty
from named getter
+ * and setter methods. The getter method of a MethodProperty
+ * instantiated with this constructor will be called with no arguments, and
+ * the setter method with only the new value as the sole argument.
+ *
+ *
+ *
+ * If the setter method is null
, the resulting
+ * MethodProperty
will be read-only, otherwise it will be
+ * read-write.
+ *
+ *
+ * @param type
+ * the type of the property.
+ * @param instance
+ * the object that includes the property.
+ * @param getMethodName
+ * the name of the getter method.
+ * @param setMethodName
+ * the name of the setter method.
+ *
+ */
+ public MethodProperty(Class type, Object instance, String getMethodName,
+ String setMethodName) {
+ this(type, instance, getMethodName, setMethodName, new Object[] {},
+ new Object[] { null }, 0);
+ }
+
+ /**
+ *
+ * Creates a new instance of MethodProperty
with the getter
+ * and setter methods. The getter method of a MethodProperty
+ * instantiated with this constructor will be called with no arguments, and
+ * the setter method with only the new value as the sole argument.
+ *
+ *
+ *
+ * If the setter method is null
, the resulting
+ * MethodProperty
will be read-only, otherwise it will be
+ * read-write.
+ *
+ *
+ * @param type
+ * the type of the property.
+ * @param instance
+ * the object that includes the property.
+ * @param getMethod
+ * the getter method.
+ * @param setMethod
+ * the setter method.
+ */
+ public MethodProperty(Class type, Object instance, Method getMethod,
+ Method setMethod) {
+ this(type, instance, getMethod, setMethod, new Object[] {},
+ new Object[] { null }, 0);
+ }
+
+ /**
+ *
+ * Creates a new instance of MethodProperty
from named getter
+ * and setter methods and argument lists. The getter method of a
+ * MethodProperty
instantiated with this constructor will be
+ * called with the getArgs as arguments. The setArgs will be used as the
+ * arguments for the setter method, though the argument indexed by the
+ * setArgumentIndex will be replaced with the argument passed to the
+ * {@link #setValue(Object newValue)} method.
+ *
+ *
+ *
+ * For example, if the setArgs
contains A
,
+ * B
and C
, and setArgumentIndex =
+ * 1
,
+ * the call methodProperty.setValue(X)
would result in the
+ * setter method to be called with the parameter set of
+ * {A, X, C}
+ *
+ *
+ * @param type
+ * the type of the property.
+ * @param instance
+ * the object that includes the property.
+ * @param getMethodName
+ * the name of the getter method.
+ * @param setMethodName
+ * the name of the setter method.
+ * @param getArgs
+ * the fixed argument list to be passed to the getter method.
+ * @param setArgs
+ * the fixed argument list to be passed to the setter method.
+ * @param setArgumentIndex
+ * the index of the argument in setArgs
to be
+ * replaced with newValue
when
+ * {@link #setValue(Object newValue)} is called.
+ */
+ public MethodProperty(Class type, Object instance, String getMethodName,
+ String setMethodName, Object[] getArgs, Object[] setArgs,
+ int setArgumentIndex) {
+
+ // Check the setargs and setargs index
+ if (setMethodName != null && setArgs == null) {
+ throw new IndexOutOfBoundsException("The setArgs can not be null");
+ }
+ if (setMethodName != null
+ && (setArgumentIndex < 0 || setArgumentIndex >= setArgs.length)) {
+ throw new IndexOutOfBoundsException(
+ "The setArgumentIndex must be >= 0 and < setArgs.length");
+ }
+
+ // Set type
+ this.type = type;
+
+ // Find set and get -methods
+ Method[] m = instance.getClass().getMethods();
+
+ // Finds get method
+ boolean found = false;
+ for (int i = 0; i < m.length; i++) {
+
+ // Tests the name of the get Method
+ if (!m[i].getName().equals(getMethodName)) {
+
+ // name does not match, try next method
+ continue;
+ }
+
+ // Tests return type
+ if (!type.equals(m[i].getReturnType())) {
+ continue;
+ }
+
+ // Tests the parameter types
+ Class[] c = m[i].getParameterTypes();
+ if (c.length != getArgs.length) {
+
+ // not the right amount of parameters, try next method
+ continue;
+ }
+ int j = 0;
+ while (j < c.length) {
+ if (getArgs[j] != null
+ && !c[j].isAssignableFrom(getArgs[j].getClass())) {
+
+ // parameter type does not match, try next method
+ break;
+ }
+ j++;
+ }
+ if (j == c.length) {
+
+ // all paramteters matched
+ if (found == true) {
+ throw new MethodProperty.MethodException(
+ "Could not uniquely identify " + getMethodName
+ + "-method");
+ } else {
+ found = true;
+ getMethod = m[i];
+ }
+ }
+ }
+ if (found != true) {
+ throw new MethodProperty.MethodException("Could not find "
+ + getMethodName + "-method");
+ }
+
+ // Finds set method
+ if (setMethodName != null) {
+
+ // Finds setMethod
+ found = false;
+ for (int i = 0; i < m.length; i++) {
+
+ // Checks name
+ if (!m[i].getName().equals(setMethodName)) {
+
+ // name does not match, try next method
+ continue;
+ }
+
+ // Checks parameter compatibility
+ Class[] c = m[i].getParameterTypes();
+ if (c.length != setArgs.length) {
+
+ // not the right amount of parameters, try next method
+ continue;
+ }
+ int j = 0;
+ while (j < c.length) {
+ if (setArgs[j] != null
+ && !c[j].isAssignableFrom(setArgs[j].getClass())) {
+
+ // parameter type does not match, try next method
+ break;
+ } else if (j == setArgumentIndex && !c[j].equals(type)) {
+
+ // Property type is not the same as setArg type
+ break;
+ }
+ j++;
+ }
+ if (j == c.length) {
+
+ // all parameters match
+ if (found == true) {
+ throw new MethodProperty.MethodException(
+ "Could not identify unique " + setMethodName
+ + "-method");
+ } else {
+ found = true;
+ setMethod = m[i];
+ }
+ }
+ }
+ if (found != true) {
+ throw new MethodProperty.MethodException("Could not identify "
+ + setMethodName + "-method");
+ }
+ }
+
+ // Gets the return type from get method
+ if (type.isPrimitive()) {
+ if (type.equals(Boolean.TYPE)) {
+ type = Boolean.class;
+ } else if (type.equals(Integer.TYPE)) {
+ type = Integer.class;
+ } else if (type.equals(Float.TYPE)) {
+ type = Float.class;
+ } else if (type.equals(Double.TYPE)) {
+ type = Double.class;
+ } else if (type.equals(Byte.TYPE)) {
+ type = Byte.class;
+ } else if (type.equals(Character.TYPE)) {
+ type = Character.class;
+ } else if (type.equals(Short.TYPE)) {
+ type = Short.class;
+ } else if (type.equals(Long.TYPE)) {
+ type = Long.class;
+ }
+ }
+
+ setArguments(getArgs, setArgs, setArgumentIndex);
+ readOnly = (setMethod == null);
+ this.instance = instance;
+ }
+
+ /**
+ *
+ * Creates a new instance of MethodProperty
from the getter
+ * and setter methods, and argument lists.
+ *
+ *
+ * This constructor behaves exactly like
+ * {@link #MethodProperty(Class type, Object instance, String getMethodName,
+ * String setMethodName, Object [] getArgs, Object [] setArgs, int
+ * setArgumentIndex)} except that instead of names of the getter and setter
+ * methods this constructor is given the actual methods themselves.
+ *
+ *
+ * @param type
+ * the type of the property.
+ * @param instance
+ * the object that includes the property.
+ * @param getMethod
+ * the getter method.
+ * @param setMethod
+ * the setter method.
+ * @param getArgs
+ * the fixed argument list to be passed to the getter method.
+ * @param setArgs
+ * the fixed argument list to be passed to the setter method.
+ * @param setArgumentIndex
+ * the index of the argument in setArgs
to be
+ * replaced with newValue
when
+ * {@link #setValue(Object newValue)} is called.
+ */
+ public MethodProperty(Class type, Object instance, Method getMethod,
+ Method setMethod, Object[] getArgs, Object[] setArgs,
+ int setArgumentIndex) {
+
+ if (getMethod == null) {
+ throw new MethodProperty.MethodException(
+ "Property GET-method cannot not be null: " + type);
+ }
+
+ if (setMethod != null
+ && (setArgumentIndex < 0 || setArgumentIndex >= setArgs.length)) {
+ throw new IndexOutOfBoundsException(
+ "The setArgumentIndex must be >= 0 and < setArgs.length");
+ }
+
+ // Gets the return type from get method
+ if (type.isPrimitive()) {
+ if (type.equals(Boolean.TYPE)) {
+ type = Boolean.class;
+ } else if (type.equals(Integer.TYPE)) {
+ type = Integer.class;
+ } else if (type.equals(Float.TYPE)) {
+ type = Float.class;
+ } else if (type.equals(Double.TYPE)) {
+ type = Double.class;
+ } else if (type.equals(Byte.TYPE)) {
+ type = Byte.class;
+ } else if (type.equals(Character.TYPE)) {
+ type = Character.class;
+ } else if (type.equals(Short.TYPE)) {
+ type = Short.class;
+ } else if (type.equals(Long.TYPE)) {
+ type = Long.class;
+ }
+ }
+
+ this.getMethod = getMethod;
+ this.setMethod = setMethod;
+ setArguments(getArgs, setArgs, setArgumentIndex);
+ readOnly = (setMethod == null);
+ this.instance = instance;
+ this.type = type;
+ }
+
+ /**
+ * Returns the type of the Property. The methods getValue
and
+ * setValue
must be compatible with this type: one must be
+ * able to safely cast the value returned from getValue
to
+ * the given type and pass any variable assignable to this type as an
+ * argument to setValue
.
+ *
+ * @return type of the Property
+ */
+ public final Class getType() {
+ return type;
+ }
+
+ /**
+ * Tests if the object is in read-only mode. In read-only mode calls to
+ * setValue
will throw ReadOnlyException
and
+ * will not modify the value of the Property.
+ *
+ * @return true
if the object is in read-only mode,
+ * false
if it's not
+ */
+ public boolean isReadOnly() {
+ return readOnly;
+ }
+
+ /**
+ * Gets the value stored in the Property. The value is resolved by calling
+ * the specified getter method with the argument specified at instantiation.
+ *
+ * @return the value of the Property
+ */
+ public Object getValue() {
+ try {
+ return getMethod.invoke(instance, getArgs);
+ } catch (Throwable e) {
+ throw new MethodProperty.MethodException(e);
+ }
+ }
+
+ /**
+ * Returns the value of the MethodProperty
in human readable
+ * textual format. The return value should be assignable to the
+ * setValue
method if the Property is not in read-only mode.
+ *
+ * @return String representation of the value stored in the Property
+ */
+ public String toString() {
+ Object value = getValue();
+ if (value == null) {
+ return null;
+ }
+ return value.toString();
+ }
+
+ /**
+ *
+ * Sets the setter method and getter method argument lists.
+ *
+ *
+ * @param getArgs
+ * the fixed argument list to be passed to the getter method.
+ * @param setArgs
+ * the fixed argument list to be passed to the setter method.
+ * @param setArgumentIndex
+ * the index of the argument in setArgs
to be
+ * replaced with newValue
when
+ * {@link #setValue(Object newValue)} is called.
+ */
+ public void setArguments(Object[] getArgs, Object[] setArgs,
+ int setArgumentIndex) {
+ this.getArgs = new Object[getArgs.length];
+ for (int i = 0; i < getArgs.length; i++) {
+ this.getArgs[i] = getArgs[i];
+ }
+ this.setArgs = new Object[setArgs.length];
+ for (int i = 0; i < setArgs.length; i++) {
+ this.setArgs[i] = setArgs[i];
+ }
+ this.setArgumentIndex = setArgumentIndex;
+ }
+
+ /**
+ * Sets the value of the property. This method supports setting from
+ * String
s if either String
is directly
+ * assignable to property type, or the type class contains a string
+ * constructor.
+ *
+ * @param newValue
+ * the New value of the property.
+ * @throws Property.ReadOnlyException
if the object is in
+ * read-only mode.
+ * @throws Property.ConversionException
if
+ * newValue
can't be converted into the
+ * Property's native type directly or through
+ * String
.
+ * @see #invokeSetMethod(Object)
+ */
+ public void setValue(Object newValue) throws Property.ReadOnlyException,
+ Property.ConversionException {
+
+ // Checks the mode
+ if (isReadOnly()) {
+ throw new Property.ReadOnlyException();
+ }
+
+ // Try to assign the compatible value directly
+ if (newValue == null || type.isAssignableFrom(newValue.getClass())) {
+ invokeSetMethod(newValue);
+ } else {
+
+ Object value;
+ try {
+
+ // Gets the string constructor
+ Constructor constr = getType().getConstructor(
+ new Class[] { String.class });
+
+ value = constr
+ .newInstance(new Object[] { newValue.toString() });
+
+ } catch (java.lang.Exception e) {
+ throw new Property.ConversionException(e);
+ }
+
+ // Creates new object from the string
+ invokeSetMethod(value);
+ }
+ }
+
+ /**
+ * Internal method to actually call the setter method of the wrapped
+ * property.
+ *
+ * @param value
+ */
+ private void invokeSetMethod(Object value) {
+
+ try {
+ // Construct a temporary argument array only if needed
+ if (setArgs.length == 1) {
+ setMethod.invoke(instance, new Object[] { value });
+ } else {
+
+ // Sets the value to argument array
+ Object[] args = new Object[setArgs.length];
+ for (int i = 0; i < setArgs.length; i++) {
+ args[i] = (i == setArgumentIndex) ? value : setArgs[i];
+ }
+ setMethod.invoke(instance, args);
+ }
+ } catch (InvocationTargetException e) {
+ Throwable targetException = e.getTargetException();
+ throw new MethodProperty.MethodException(targetException);
+ } catch (Exception e) {
+ throw new MethodProperty.MethodException(e);
+ }
+ }
+
+ /**
+ * Sets the Property's read-only mode to the specified status.
+ *
+ * @param newStatus
+ * the new read-only status of the Property.
+ */
+ public void setReadOnly(boolean newStatus) {
+ boolean prevStatus = readOnly;
+ if (newStatus) {
+ readOnly = true;
+ } else {
+ readOnly = (setMethod == null);
+ }
+ if (prevStatus != readOnly) {
+ fireReadOnlyStatusChange();
+ }
+ }
+
+ /**
+ * Exception
object that signals that there were problems
+ * calling or finding the specified getter or setter methods of the
+ * property.
+ *
+ * @author IT Mill Ltd.
+ * @version
+ * @VERSION@
+ * @since 3.0
+ */
+ public class MethodException extends RuntimeException {
+
+ /**
+ * Serial generated by eclipse.
+ */
+ private static final long serialVersionUID = 3690473623827855153L;
+
+ /**
+ * Cause of the method exception
+ */
+ private Throwable cause;
+
+ /**
+ * Constructs a new MethodException
with the specified
+ * detail message.
+ *
+ * @param msg
+ * the detail message.
+ */
+ public MethodException(String msg) {
+ super(msg);
+ }
+
+ /**
+ * Constructs a new MethodException
from another
+ * exception.
+ *
+ * @param cause
+ * the cause of the exception.
+ */
+ public MethodException(Throwable cause) {
+ this.cause = cause;
+ }
+
+ /**
+ * @see java.lang.Throwable#getCause()
+ */
+ public Throwable getCause() {
+ return cause;
+ }
+
+ /**
+ * Gets the method property this exception originates from.
+ */
+ public MethodProperty getMethodProperty() {
+ return MethodProperty.this;
+ }
+ }
+
+ /* Events *************************************************************** */
+
+ /**
+ * An Event
object specifying the Property whose read-only
+ * status has been changed.
+ *
+ * @author IT Mill Ltd.
+ * @version
+ * @VERSION@
+ * @since 3.0
+ */
+ private class ReadOnlyStatusChangeEvent extends java.util.EventObject
+ implements Property.ReadOnlyStatusChangeEvent {
+
+ /**
+ * Serial generated by eclipse.
+ */
+ private static final long serialVersionUID = 3258129163305955896L;
+
+ /**
+ * Constructs a new read-only status change event for this object.
+ *
+ * @param source
+ * source object of the event.
+ */
+ protected ReadOnlyStatusChangeEvent(MethodProperty source) {
+ super(source);
+ }
+
+ /**
+ * Gets the Property whose read-only state has changed.
+ *
+ * @return source Property of the event.
+ */
+ public Property getProperty() {
+ return (Property) getSource();
+ }
+
+ }
+
+ /**
+ * Registers a new read-only status change listener for this Property.
+ *
+ * @param listener
+ * the new Listener to be registered.
+ */
+ public void addListener(Property.ReadOnlyStatusChangeListener listener) {
+ if (readOnlyStatusChangeListeners == null) {
+ readOnlyStatusChangeListeners = new LinkedList();
+ }
+ readOnlyStatusChangeListeners.add(listener);
+ }
+
+ /**
+ * Removes a previously registered read-only status change listener.
+ *
+ * @param listener
+ * the listener to be removed.
+ */
+ public void removeListener(Property.ReadOnlyStatusChangeListener listener) {
+ if (readOnlyStatusChangeListeners != null) {
+ readOnlyStatusChangeListeners.remove(listener);
+ }
+ }
+
+ /**
+ * Sends a read only status change event to all registered listeners.
+ */
+ private void fireReadOnlyStatusChange() {
+ if (readOnlyStatusChangeListeners != null) {
+ Object[] l = readOnlyStatusChangeListeners.toArray();
+ Property.ReadOnlyStatusChangeEvent event = new MethodProperty.ReadOnlyStatusChangeEvent(
+ this);
+ for (int i = 0; i < l.length; i++) {
+ ((Property.ReadOnlyStatusChangeListener) l[i])
+ .readOnlyStatusChange(event);
+ }
+ }
+ }
}
diff --git a/src/com/itmill/toolkit/data/util/ObjectProperty.java b/src/com/itmill/toolkit/data/util/ObjectProperty.java
index 4f20dc230f..eddb870973 100644
--- a/src/com/itmill/toolkit/data/util/ObjectProperty.java
+++ b/src/com/itmill/toolkit/data/util/ObjectProperty.java
@@ -28,11 +28,11 @@
package com.itmill.toolkit.data.util;
-import com.itmill.toolkit.data.Property;
-
import java.lang.reflect.Constructor;
import java.util.LinkedList;
+import com.itmill.toolkit.data.Property;
+
/**
* A simple data object containing one typed value. This class is a
* straightforward implementation of the the
@@ -44,332 +44,339 @@ import java.util.LinkedList;
* @since 3.0
*/
public class ObjectProperty implements Property, Property.ValueChangeNotifier,
- Property.ReadOnlyStatusChangeNotifier {
-
- /**
- * A boolean value storing the Property's read-only status information.
- */
- private boolean readOnly = false;
-
- /**
- * The value contained by the Property.
- */
- private Object value;
-
- /**
- * Data type of the Property's value.
- */
- private Class type;
-
- /**
- * Internal list of registered value change listeners.
- */
- private LinkedList valueChangeListeners = null;
-
- /**
- * Internal list of registered read-only status change listeners.
- */
- private LinkedList readOnlyStatusChangeListeners = null;
-
- /**
- * Creates a new instance of ObjectProperty with the given value. The type
- * of the property is automatically initialized to be the type of the given
- * value.
- *
- * @param value
- * the Initial value of the Property.
- */
- public ObjectProperty(Object value) {
- this(value, value.getClass());
- }
-
- /**
- * Creates a new instance of ObjectProperty with the given value and type.
- *
- * @param value
- * the Initial value of the Property.
- * @param type
- * the type of the value. The value must be assignable to given
- * type.
- */
- public ObjectProperty(Object value, Class type) {
-
- // Set the values
- this.type = type;
- setValue(value);
- }
-
- /**
- * Creates a new instance of ObjectProperty with the given value, type and
- * read-only mode status.
- *
- * @param value
- * the Initial value of the property.
- * @param type
- * the type of the value. value
must be assignable
- * to this type.
- * @param readOnly
- * Sets the read-only mode.
- */
- public ObjectProperty(Object value, Class type, boolean readOnly) {
- this(value, type);
- setReadOnly(readOnly);
- }
-
- /**
- * Returns the type of the ObjectProperty. The methods getValue
- * and setValue
must be compatible with this type: one must
- * be able to safely cast the value returned from getValue
to
- * the given type and pass any variable assignable to this type as an
- * argument to setValue
.
- *
- * @return type of the Property
- */
- public final Class getType() {
- return type;
- }
-
- /**
- * Gets the value stored in the Property.
- *
- * @return the value stored in the Property
- */
- public Object getValue() {
- return value;
- }
-
- /**
- * Returns the value of the ObjectProperty in human readable textual format.
- * The return value should be assignable to the setValue
- * method if the Property is not in read-only mode.
- *
- * @return String
representation of the value stored in the
- * ObjectProperty
- */
- public String toString() {
- Object value = getValue();
- if (value != null)
- return value.toString();
- else
- return null;
- }
-
- /**
- * Tests if the Property is in read-only mode. In read-only mode calls to
- * the method setValue
will throw
- * ReadOnlyException
s and will not modify the value of the
- * Property.
- *
- * @return true
if the Property is in read-only mode,
- * false
if it's not
- */
- public boolean isReadOnly() {
- return readOnly;
- }
-
- /**
- * Sets the Property's read-only mode to the specified status.
- *
- * @param newStatus
- * the new read-only status of the Property.
- */
- public void setReadOnly(boolean newStatus) {
- if (newStatus != readOnly) {
- readOnly = newStatus;
- fireReadOnlyStatusChange();
- }
- }
-
- /**
- * Sets the value of the property. This method supports setting from
- * String
if either String
is directly
- * assignable to property type, or the type class contains a string
- * constructor.
- *
- * @param newValue
- * the New value of the property.
- * @throws Property.ReadOnlyException
if the object is in
- * read-only mode
- * @throws Property.ConversionException
if the newValue can't be
- * converted into the Property's native type directly or through
- * String
- */
- public void setValue(Object newValue) throws Property.ReadOnlyException,
- Property.ConversionException {
-
- // Checks the mode
- if (isReadOnly())
- throw new Property.ReadOnlyException();
-
- // Tries to assign the compatible value directly
- if (newValue == null || type.isAssignableFrom(newValue.getClass()))
- value = newValue;
-
- // Otherwise try to convert the value trough string constructor
- else
- try {
-
- // Gets the string constructor
- Constructor constr = getType().getConstructor(
- new Class[] { String.class });
-
- // Creates new object from the string
- value = constr
- .newInstance(new Object[] { newValue.toString() });
-
- } catch (java.lang.Exception e) {
- throw new Property.ConversionException(e);
- }
-
- fireValueChange();
- }
-
- /* Events *************************************************************** */
-
- /**
- * An Event
object specifying the ObjectProperty whose value
- * has changed.
- *
- * @author IT Mill Ltd.
- * @version
- * @VERSION@
- * @since 3.0
- */
- private class ValueChangeEvent extends java.util.EventObject implements
- Property.ValueChangeEvent {
-
- /**
- * Serial generated by eclipse.
- */
- private static final long serialVersionUID = 3256718468479725873L;
-
- /**
- * Constructs a new value change event for this object.
- *
- * @param source
- * the source object of the event.
- */
- protected ValueChangeEvent(ObjectProperty source) {
- super(source);
- }
-
- /**
- * Gets the Property whose read-only state has changed.
- *
- * @return source the Property of the event.
- */
- public Property getProperty() {
- return (Property) getSource();
- }
- }
-
- /**
- * An Event
object specifying the Property whose read-only
- * status has been changed.
- *
- * @author IT Mill Ltd.
- * @version
- * @VERSION@
- * @since 3.0
- */
- private class ReadOnlyStatusChangeEvent extends java.util.EventObject
- implements Property.ReadOnlyStatusChangeEvent {
-
- /**
- * Serial generated by eclipse.
- */
- private static final long serialVersionUID = 3907208273529616696L;
-
- /**
- * Constructs a new read-only status change event for this object.
- *
- * @param source
- * source object of the event
- */
- protected ReadOnlyStatusChangeEvent(ObjectProperty source) {
- super(source);
- }
-
- /**
- * Gets the Property whose read-only state has changed.
- *
- * @return source Property of the event.
- */
- public Property getProperty() {
- return (Property) getSource();
- }
- }
-
- /**
- * Removes a previously registered value change listener.
- *
- * @param listener
- * the listener to be removed.
- */
- public void removeListener(Property.ValueChangeListener listener) {
- if (valueChangeListeners != null)
- valueChangeListeners.remove(listener);
- }
-
- /**
- * Registers a new value change listener for this ObjectProperty.
- *
- * @param listener
- * the new Listener to be registered
- */
- public void addListener(Property.ValueChangeListener listener) {
- if (valueChangeListeners == null)
- valueChangeListeners = new LinkedList();
- valueChangeListeners.add(listener);
- }
-
- /**
- * Registers a new read-only status change listener for this Property.
- *
- * @param listener
- * the new Listener to be registered
- */
- public void addListener(Property.ReadOnlyStatusChangeListener listener) {
- if (readOnlyStatusChangeListeners == null)
- readOnlyStatusChangeListeners = new LinkedList();
- readOnlyStatusChangeListeners.add(listener);
- }
-
- /**
- * Removes a previously registered read-only status change listener.
- *
- * @param listener
- * the listener to be removed.
- */
- public void removeListener(Property.ReadOnlyStatusChangeListener listener) {
- if (readOnlyStatusChangeListeners != null)
- readOnlyStatusChangeListeners.remove(listener);
- }
-
- /**
- * Sends a value change event to all registered listeners.
- */
- private void fireValueChange() {
- if (valueChangeListeners != null) {
- Object[] l = valueChangeListeners.toArray();
- Property.ValueChangeEvent event = new ObjectProperty.ValueChangeEvent(
- this);
- for (int i = 0; i < l.length; i++)
- ((Property.ValueChangeListener) l[i]).valueChange(event);
- }
- }
-
- /**
- * Sends a read only status change event to all registered listeners.
- */
- private void fireReadOnlyStatusChange() {
- if (readOnlyStatusChangeListeners != null) {
- Object[] l = readOnlyStatusChangeListeners.toArray();
- Property.ReadOnlyStatusChangeEvent event = new ObjectProperty.ReadOnlyStatusChangeEvent(
- this);
- for (int i = 0; i < l.length; i++)
- ((Property.ReadOnlyStatusChangeListener) l[i])
- .readOnlyStatusChange(event);
- }
- }
+ Property.ReadOnlyStatusChangeNotifier {
+
+ /**
+ * A boolean value storing the Property's read-only status information.
+ */
+ private boolean readOnly = false;
+
+ /**
+ * The value contained by the Property.
+ */
+ private Object value;
+
+ /**
+ * Data type of the Property's value.
+ */
+ private Class type;
+
+ /**
+ * Internal list of registered value change listeners.
+ */
+ private LinkedList valueChangeListeners = null;
+
+ /**
+ * Internal list of registered read-only status change listeners.
+ */
+ private LinkedList readOnlyStatusChangeListeners = null;
+
+ /**
+ * Creates a new instance of ObjectProperty with the given value. The type
+ * of the property is automatically initialized to be the type of the given
+ * value.
+ *
+ * @param value
+ * the Initial value of the Property.
+ */
+ public ObjectProperty(Object value) {
+ this(value, value.getClass());
+ }
+
+ /**
+ * Creates a new instance of ObjectProperty with the given value and type.
+ *
+ * @param value
+ * the Initial value of the Property.
+ * @param type
+ * the type of the value. The value must be assignable to
+ * given type.
+ */
+ public ObjectProperty(Object value, Class type) {
+
+ // Set the values
+ this.type = type;
+ setValue(value);
+ }
+
+ /**
+ * Creates a new instance of ObjectProperty with the given value, type and
+ * read-only mode status.
+ *
+ * @param value
+ * the Initial value of the property.
+ * @param type
+ * the type of the value. value
must be
+ * assignable to this type.
+ * @param readOnly
+ * Sets the read-only mode.
+ */
+ public ObjectProperty(Object value, Class type, boolean readOnly) {
+ this(value, type);
+ setReadOnly(readOnly);
+ }
+
+ /**
+ * Returns the type of the ObjectProperty. The methods getValue
+ * and setValue
must be compatible with this type: one must
+ * be able to safely cast the value returned from getValue
to
+ * the given type and pass any variable assignable to this type as an
+ * argument to setValue
.
+ *
+ * @return type of the Property
+ */
+ public final Class getType() {
+ return type;
+ }
+
+ /**
+ * Gets the value stored in the Property.
+ *
+ * @return the value stored in the Property
+ */
+ public Object getValue() {
+ return value;
+ }
+
+ /**
+ * Returns the value of the ObjectProperty in human readable textual format.
+ * The return value should be assignable to the setValue
+ * method if the Property is not in read-only mode.
+ *
+ * @return String
representation of the value stored in the
+ * ObjectProperty
+ */
+ public String toString() {
+ Object value = getValue();
+ if (value != null) {
+ return value.toString();
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * Tests if the Property is in read-only mode. In read-only mode calls to
+ * the method setValue
will throw
+ * ReadOnlyException
s and will not modify the value of the
+ * Property.
+ *
+ * @return true
if the Property is in read-only mode,
+ * false
if it's not
+ */
+ public boolean isReadOnly() {
+ return readOnly;
+ }
+
+ /**
+ * Sets the Property's read-only mode to the specified status.
+ *
+ * @param newStatus
+ * the new read-only status of the Property.
+ */
+ public void setReadOnly(boolean newStatus) {
+ if (newStatus != readOnly) {
+ readOnly = newStatus;
+ fireReadOnlyStatusChange();
+ }
+ }
+
+ /**
+ * Sets the value of the property. This method supports setting from
+ * String
if either String
is directly
+ * assignable to property type, or the type class contains a string
+ * constructor.
+ *
+ * @param newValue
+ * the New value of the property.
+ * @throws Property.ReadOnlyException
if the object is in
+ * read-only mode
+ * @throws Property.ConversionException
if the newValue
+ * can't be converted into the Property's native type
+ * directly or through String
+ */
+ public void setValue(Object newValue) throws Property.ReadOnlyException,
+ Property.ConversionException {
+
+ // Checks the mode
+ if (isReadOnly()) {
+ throw new Property.ReadOnlyException();
+ }
+
+ // Tries to assign the compatible value directly
+ if (newValue == null || type.isAssignableFrom(newValue.getClass())) {
+ value = newValue;
+ } else {
+ try {
+
+ // Gets the string constructor
+ Constructor constr = getType().getConstructor(
+ new Class[] { String.class });
+
+ // Creates new object from the string
+ value = constr
+ .newInstance(new Object[] { newValue.toString() });
+
+ } catch (java.lang.Exception e) {
+ throw new Property.ConversionException(e);
+ }
+ }
+
+ fireValueChange();
+ }
+
+ /* Events *************************************************************** */
+
+ /**
+ * An Event
object specifying the ObjectProperty whose value
+ * has changed.
+ *
+ * @author IT Mill Ltd.
+ * @version
+ * @VERSION@
+ * @since 3.0
+ */
+ private class ValueChangeEvent extends java.util.EventObject implements
+ Property.ValueChangeEvent {
+
+ /**
+ * Serial generated by eclipse.
+ */
+ private static final long serialVersionUID = 3256718468479725873L;
+
+ /**
+ * Constructs a new value change event for this object.
+ *
+ * @param source
+ * the source object of the event.
+ */
+ protected ValueChangeEvent(ObjectProperty source) {
+ super(source);
+ }
+
+ /**
+ * Gets the Property whose read-only state has changed.
+ *
+ * @return source the Property of the event.
+ */
+ public Property getProperty() {
+ return (Property) getSource();
+ }
+ }
+
+ /**
+ * An Event
object specifying the Property whose read-only
+ * status has been changed.
+ *
+ * @author IT Mill Ltd.
+ * @version
+ * @VERSION@
+ * @since 3.0
+ */
+ private class ReadOnlyStatusChangeEvent extends java.util.EventObject
+ implements Property.ReadOnlyStatusChangeEvent {
+
+ /**
+ * Serial generated by eclipse.
+ */
+ private static final long serialVersionUID = 3907208273529616696L;
+
+ /**
+ * Constructs a new read-only status change event for this object.
+ *
+ * @param source
+ * source object of the event
+ */
+ protected ReadOnlyStatusChangeEvent(ObjectProperty source) {
+ super(source);
+ }
+
+ /**
+ * Gets the Property whose read-only state has changed.
+ *
+ * @return source Property of the event.
+ */
+ public Property getProperty() {
+ return (Property) getSource();
+ }
+ }
+
+ /**
+ * Removes a previously registered value change listener.
+ *
+ * @param listener
+ * the listener to be removed.
+ */
+ public void removeListener(Property.ValueChangeListener listener) {
+ if (valueChangeListeners != null) {
+ valueChangeListeners.remove(listener);
+ }
+ }
+
+ /**
+ * Registers a new value change listener for this ObjectProperty.
+ *
+ * @param listener
+ * the new Listener to be registered
+ */
+ public void addListener(Property.ValueChangeListener listener) {
+ if (valueChangeListeners == null) {
+ valueChangeListeners = new LinkedList();
+ }
+ valueChangeListeners.add(listener);
+ }
+
+ /**
+ * Registers a new read-only status change listener for this Property.
+ *
+ * @param listener
+ * the new Listener to be registered
+ */
+ public void addListener(Property.ReadOnlyStatusChangeListener listener) {
+ if (readOnlyStatusChangeListeners == null) {
+ readOnlyStatusChangeListeners = new LinkedList();
+ }
+ readOnlyStatusChangeListeners.add(listener);
+ }
+
+ /**
+ * Removes a previously registered read-only status change listener.
+ *
+ * @param listener
+ * the listener to be removed.
+ */
+ public void removeListener(Property.ReadOnlyStatusChangeListener listener) {
+ if (readOnlyStatusChangeListeners != null) {
+ readOnlyStatusChangeListeners.remove(listener);
+ }
+ }
+
+ /**
+ * Sends a value change event to all registered listeners.
+ */
+ private void fireValueChange() {
+ if (valueChangeListeners != null) {
+ Object[] l = valueChangeListeners.toArray();
+ Property.ValueChangeEvent event = new ObjectProperty.ValueChangeEvent(
+ this);
+ for (int i = 0; i < l.length; i++) {
+ ((Property.ValueChangeListener) l[i]).valueChange(event);
+ }
+ }
+ }
+
+ /**
+ * Sends a read only status change event to all registered listeners.
+ */
+ private void fireReadOnlyStatusChange() {
+ if (readOnlyStatusChangeListeners != null) {
+ Object[] l = readOnlyStatusChangeListeners.toArray();
+ Property.ReadOnlyStatusChangeEvent event = new ObjectProperty.ReadOnlyStatusChangeEvent(
+ this);
+ for (int i = 0; i < l.length; i++) {
+ ((Property.ReadOnlyStatusChangeListener) l[i])
+ .readOnlyStatusChange(event);
+ }
+ }
+ }
}
diff --git a/src/com/itmill/toolkit/data/util/PropertysetItem.java b/src/com/itmill/toolkit/data/util/PropertysetItem.java
index b8d299941e..355538326d 100644
--- a/src/com/itmill/toolkit/data/util/PropertysetItem.java
+++ b/src/com/itmill/toolkit/data/util/PropertysetItem.java
@@ -50,279 +50,291 @@ import com.itmill.toolkit.data.Property;
* @since 3.0
*/
public class PropertysetItem implements Item, Item.PropertySetChangeNotifier,
- Cloneable {
-
- /* Private representation of the item *********************************** */
-
- /**
- * Mapping from property id to property.
- */
- private HashMap map = new HashMap();
-
- /**
- * List of all property ids to maintain the order.
- */
- private LinkedList list = new LinkedList();
-
- /**
- * List of property set modification listeners.
- */
- private LinkedList propertySetChangeListeners = null;
-
- /* Item methods ******************************************************** */
-
- /**
- * Gets the Property corresponding to the given Property ID stored in the
- * Item. If the Item does not contain the Property, null
is
- * returned.
- *
- * @param id
- * the identifier of the Property to get.
- * @return the Property with the given ID or null
- */
- public Property getItemProperty(Object id) {
- return (Property) map.get(id);
- }
-
- /**
- * Gets the collection of IDs of all Properties stored in the Item.
- *
- * @return unmodifiable collection containing IDs of the Properties stored
- * the Item
- */
- public Collection getItemPropertyIds() {
- return Collections.unmodifiableCollection(list);
- }
-
- /* Item.Managed methods ************************************************* */
-
- /**
- * Removes the Property identified by ID from the Item. This functionality
- * is optional. If the method is not implemented, the method always returns
- * false
.
- *
- * @param id
- * the ID of the Property to be removed.
- * @return true
if the operation succeeded false
- * if not
- */
- public boolean removeItemProperty(Object id) {
-
- // Cant remove missing properties
- if (map.remove(id) == null) {
- return false;
- }
- list.remove(id);
-
- // Send change events
- fireItemPropertySetChange();
-
- return true;
- }
-
- /**
- * Tries to add a new Property into the Item.
- *
- * @param id
- * the ID of the new Property.
- * @param property
- * the Property to be added and associated with the id.
- * @return true
if the operation succeeded,
- * false
if not
- */
- public boolean addItemProperty(Object id, Property property) {
-
- // Cant add a property twice
- if (map.containsKey(id))
- return false;
-
- // Put the property to map
- map.put(id, property);
- list.add(id);
-
- // Send event
- fireItemPropertySetChange();
-
- return true;
- }
-
- /**
- * Gets the String
representation of the contents of the
- * Item. The format of the string is a space separated catenation of the
- * String
representations of the Properties contained by the
- * Item.
- *
- * @return String
representation of the Item contents
- */
- public String toString() {
- String retValue = "";
-
- for (Iterator i = getItemPropertyIds().iterator(); i.hasNext();) {
- Object propertyId = i.next();
- retValue += getItemProperty(propertyId).toString();
- if (i.hasNext())
- retValue += " ";
- }
-
- return retValue;
- }
-
- /* Notifiers ************************************************************ */
-
- /**
- * An event
object specifying an Item whose Property set has
- * changed.
- *
- * @author IT Mill Ltd.
- * @version
- * @VERSION@
- * @since 3.0
- */
- private class PropertySetChangeEvent extends EventObject implements
- Item.PropertySetChangeEvent {
-
- /**
- * Serial generated by eclipse.
- */
- private static final long serialVersionUID = 3257562910590055991L;
-
- private PropertySetChangeEvent(Item source) {
- super(source);
- }
-
- /**
- * Gets the Item whose Property set has changed.
- *
- * @return source object of the event as an Item
- */
- public Item getItem() {
- return (Item) getSource();
- }
- }
-
- /**
- * Registers a new property set change listener for this Item.
- *
- * @param listener
- * the new Listener to be registered.
- */
- public void addListener(Item.PropertySetChangeListener listener) {
- if (propertySetChangeListeners == null)
- propertySetChangeListeners = new LinkedList();
- propertySetChangeListeners.add(listener);
- }
-
- /**
- * Removes a previously registered property set change listener.
- *
- * @param listener
- * the Listener to be removed.
- */
- public void removeListener(Item.PropertySetChangeListener listener) {
- if (propertySetChangeListeners != null)
- propertySetChangeListeners.remove(listener);
- }
-
- /**
- * Sends a Property set change event to all interested listeners.
- */
- private void fireItemPropertySetChange() {
- if (propertySetChangeListeners != null) {
- Object[] l = propertySetChangeListeners.toArray();
- Item.PropertySetChangeEvent event = new PropertysetItem.PropertySetChangeEvent(
- this);
- for (int i = 0; i < l.length; i++)
- ((Item.PropertySetChangeListener) l[i])
- .itemPropertySetChange(event);
- }
- }
-
- /**
- * Creates and returns a copy of this object.
- *
- * The method clone
performs a shallow copy of the
- * PropertysetItem
.
- *
- *
- * Note : All arrays are considered to implement the interface Cloneable.
- * Otherwise, this method creates a new instance of the class of this object
- * and initializes all its fields with exactly the contents of the
- * corresponding fields of this object, as if by assignment, the contents of
- * the fields are not themselves cloned. Thus, this method performs a
- * "shallow copy" of this object, not a "deep copy" operation.
- *
- *
- * @throws CloneNotSupportedException
- * if the object's class does not support the Cloneable
- * interface.
- *
- * @see java.lang.Object#clone()
- */
- public Object clone() throws CloneNotSupportedException {
-
- PropertysetItem npsi = new PropertysetItem();
-
- npsi.list = this.list != null ? (LinkedList) list.clone() : null;
- npsi.propertySetChangeListeners = this.propertySetChangeListeners != null ? (LinkedList) propertySetChangeListeners
- .clone()
- : null;
- npsi.map = (HashMap) this.map.clone();
-
- return npsi;
- }
-
- /**
- * Returns true
if and only if the argument is not
- * null
and is a Boolean object that represents the same
- * boolean value as this object.
- *
- * @param obj
- * the object to compare with.
- * @return true
if the Boolean objects represent the same
- * value otherwise false
.
- * @see java.lang.Object#equals(java.lang.Object)
- */
- public boolean equals(Object obj) {
-
- if (obj == null || !(obj instanceof PropertysetItem))
- return false;
-
- PropertysetItem other = (PropertysetItem) obj;
-
- if (other.list != this.list) {
- if (other.list == null)
- return false;
- if (!other.list.equals(this.list))
- return false;
- }
- if (other.map != this.map) {
- if (other.map == null)
- return false;
- if (!other.map.equals(this.map))
- return false;
- }
- if (other.propertySetChangeListeners != this.propertySetChangeListeners) {
- if (other.propertySetChangeListeners == null)
- return false;
- if (!other.propertySetChangeListeners
- .equals(this.propertySetChangeListeners))
- return false;
- }
-
- return true;
- }
-
- /**
- * Returns the hash code value for this list.
- *
- * @return the hash code value.
- * @see java.lang.Object#hashCode()
- */
- public int hashCode() {
-
- return (list == null ? 0 : list.hashCode())
- ^ (map == null ? 0 : map.hashCode())
- ^ (propertySetChangeListeners == null ? 0
- : propertySetChangeListeners.hashCode());
- }
+ Cloneable {
+
+ /* Private representation of the item *********************************** */
+
+ /**
+ * Mapping from property id to property.
+ */
+ private HashMap map = new HashMap();
+
+ /**
+ * List of all property ids to maintain the order.
+ */
+ private LinkedList list = new LinkedList();
+
+ /**
+ * List of property set modification listeners.
+ */
+ private LinkedList propertySetChangeListeners = null;
+
+ /* Item methods ******************************************************** */
+
+ /**
+ * Gets the Property corresponding to the given Property ID stored in the
+ * Item. If the Item does not contain the Property, null
is
+ * returned.
+ *
+ * @param id
+ * the identifier of the Property to get.
+ * @return the Property with the given ID or null
+ */
+ public Property getItemProperty(Object id) {
+ return (Property) map.get(id);
+ }
+
+ /**
+ * Gets the collection of IDs of all Properties stored in the Item.
+ *
+ * @return unmodifiable collection containing IDs of the Properties stored
+ * the Item
+ */
+ public Collection getItemPropertyIds() {
+ return Collections.unmodifiableCollection(list);
+ }
+
+ /* Item.Managed methods ************************************************* */
+
+ /**
+ * Removes the Property identified by ID from the Item. This functionality
+ * is optional. If the method is not implemented, the method always returns
+ * false
.
+ *
+ * @param id
+ * the ID of the Property to be removed.
+ * @return true
if the operation succeeded false
+ * if not
+ */
+ public boolean removeItemProperty(Object id) {
+
+ // Cant remove missing properties
+ if (map.remove(id) == null) {
+ return false;
+ }
+ list.remove(id);
+
+ // Send change events
+ fireItemPropertySetChange();
+
+ return true;
+ }
+
+ /**
+ * Tries to add a new Property into the Item.
+ *
+ * @param id
+ * the ID of the new Property.
+ * @param property
+ * the Property to be added and associated with the id.
+ * @return true
if the operation succeeded,
+ * false
if not
+ */
+ public boolean addItemProperty(Object id, Property property) {
+
+ // Cant add a property twice
+ if (map.containsKey(id)) {
+ return false;
+ }
+
+ // Put the property to map
+ map.put(id, property);
+ list.add(id);
+
+ // Send event
+ fireItemPropertySetChange();
+
+ return true;
+ }
+
+ /**
+ * Gets the String
representation of the contents of the
+ * Item. The format of the string is a space separated catenation of the
+ * String
representations of the Properties contained by the
+ * Item.
+ *
+ * @return String
representation of the Item contents
+ */
+ public String toString() {
+ String retValue = "";
+
+ for (Iterator i = getItemPropertyIds().iterator(); i.hasNext();) {
+ Object propertyId = i.next();
+ retValue += getItemProperty(propertyId).toString();
+ if (i.hasNext()) {
+ retValue += " ";
+ }
+ }
+
+ return retValue;
+ }
+
+ /* Notifiers ************************************************************ */
+
+ /**
+ * An event
object specifying an Item whose Property set has
+ * changed.
+ *
+ * @author IT Mill Ltd.
+ * @version
+ * @VERSION@
+ * @since 3.0
+ */
+ private class PropertySetChangeEvent extends EventObject implements
+ Item.PropertySetChangeEvent {
+
+ /**
+ * Serial generated by eclipse.
+ */
+ private static final long serialVersionUID = 3257562910590055991L;
+
+ private PropertySetChangeEvent(Item source) {
+ super(source);
+ }
+
+ /**
+ * Gets the Item whose Property set has changed.
+ *
+ * @return source object of the event as an Item
+ */
+ public Item getItem() {
+ return (Item) getSource();
+ }
+ }
+
+ /**
+ * Registers a new property set change listener for this Item.
+ *
+ * @param listener
+ * the new Listener to be registered.
+ */
+ public void addListener(Item.PropertySetChangeListener listener) {
+ if (propertySetChangeListeners == null) {
+ propertySetChangeListeners = new LinkedList();
+ }
+ propertySetChangeListeners.add(listener);
+ }
+
+ /**
+ * Removes a previously registered property set change listener.
+ *
+ * @param listener
+ * the Listener to be removed.
+ */
+ public void removeListener(Item.PropertySetChangeListener listener) {
+ if (propertySetChangeListeners != null) {
+ propertySetChangeListeners.remove(listener);
+ }
+ }
+
+ /**
+ * Sends a Property set change event to all interested listeners.
+ */
+ private void fireItemPropertySetChange() {
+ if (propertySetChangeListeners != null) {
+ Object[] l = propertySetChangeListeners.toArray();
+ Item.PropertySetChangeEvent event = new PropertysetItem.PropertySetChangeEvent(
+ this);
+ for (int i = 0; i < l.length; i++) {
+ ((Item.PropertySetChangeListener) l[i])
+ .itemPropertySetChange(event);
+ }
+ }
+ }
+
+ /**
+ * Creates and returns a copy of this object.
+ *
+ * The method clone
performs a shallow copy of the
+ * PropertysetItem
.
+ *
+ *
+ * Note : All arrays are considered to implement the interface Cloneable.
+ * Otherwise, this method creates a new instance of the class of this object
+ * and initializes all its fields with exactly the contents of the
+ * corresponding fields of this object, as if by assignment, the contents of
+ * the fields are not themselves cloned. Thus, this method performs a
+ * "shallow copy" of this object, not a "deep copy" operation.
+ *
+ *
+ * @throws CloneNotSupportedException
+ * if the object's class does not support the Cloneable
+ * interface.
+ *
+ * @see java.lang.Object#clone()
+ */
+ public Object clone() throws CloneNotSupportedException {
+
+ PropertysetItem npsi = new PropertysetItem();
+
+ npsi.list = list != null ? (LinkedList) list.clone() : null;
+ npsi.propertySetChangeListeners = propertySetChangeListeners != null ? (LinkedList) propertySetChangeListeners
+ .clone()
+ : null;
+ npsi.map = (HashMap) map.clone();
+
+ return npsi;
+ }
+
+ /**
+ * Returns true
if and only if the argument is not
+ * null
and is a Boolean object that represents the same
+ * boolean value as this object.
+ *
+ * @param obj
+ * the object to compare with.
+ * @return true
if the Boolean objects represent the same
+ * value otherwise false
.
+ * @see java.lang.Object#equals(java.lang.Object)
+ */
+ public boolean equals(Object obj) {
+
+ if (obj == null || !(obj instanceof PropertysetItem)) {
+ return false;
+ }
+
+ PropertysetItem other = (PropertysetItem) obj;
+
+ if (other.list != list) {
+ if (other.list == null) {
+ return false;
+ }
+ if (!other.list.equals(list)) {
+ return false;
+ }
+ }
+ if (other.map != map) {
+ if (other.map == null) {
+ return false;
+ }
+ if (!other.map.equals(map)) {
+ return false;
+ }
+ }
+ if (other.propertySetChangeListeners != propertySetChangeListeners) {
+ if (other.propertySetChangeListeners == null) {
+ return false;
+ }
+ if (!other.propertySetChangeListeners
+ .equals(propertySetChangeListeners)) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * Returns the hash code value for this list.
+ *
+ * @return the hash code value.
+ * @see java.lang.Object#hashCode()
+ */
+ public int hashCode() {
+
+ return (list == null ? 0 : list.hashCode())
+ ^ (map == null ? 0 : map.hashCode())
+ ^ (propertySetChangeListeners == null ? 0
+ : propertySetChangeListeners.hashCode());
+ }
}
diff --git a/src/com/itmill/toolkit/data/util/QueryContainer.java b/src/com/itmill/toolkit/data/util/QueryContainer.java
index 2593350bd9..a3ab78e5c0 100644
--- a/src/com/itmill/toolkit/data/util/QueryContainer.java
+++ b/src/com/itmill/toolkit/data/util/QueryContainer.java
@@ -37,10 +37,10 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
+
import com.itmill.toolkit.data.Container;
import com.itmill.toolkit.data.Item;
import com.itmill.toolkit.data.Property;
-import com.itmill.toolkit.data.util.ObjectProperty;
/**
*
@@ -71,578 +71,593 @@ import com.itmill.toolkit.data.util.ObjectProperty;
*/
public class QueryContainer implements Container, Container.Ordered,
- Container.Indexed {
-
- // default ResultSet type
- public static final int DEFAULT_RESULTSET_TYPE = ResultSet.TYPE_SCROLL_INSENSITIVE;
-
- // default ResultSet concurrency
- public static final int DEFAULT_RESULTSET_CONCURRENCY = ResultSet.CONCUR_READ_ONLY;
-
- private int resultSetType = DEFAULT_RESULTSET_TYPE;
-
- private int resultSetConcurrency = DEFAULT_RESULTSET_CONCURRENCY;
-
- private String queryStatement;
-
- private Connection connection;
-
- private ResultSet result;
-
- private Collection propertyIds;
-
- private HashMap propertyTypes = new HashMap();
-
- private int size = -1;
-
- private Statement statement;
-
- /**
- * Constructs new QueryContainer
with the specified
- * queryStatement
.
- *
- * @param queryStatement
- * Database query
- * @param connection
- * Connection object
- * @param resultSetType
- * @param resultSetConcurrency
- * @throws SQLException
- * when database operation fails
- */
- public QueryContainer(String queryStatement, Connection connection,
- int resultSetType, int resultSetConcurrency) throws SQLException {
- this.queryStatement = queryStatement;
- this.connection = connection;
- this.resultSetType = resultSetType;
- this.resultSetConcurrency = resultSetConcurrency;
- init();
- }
-
- /**
- * Constructs new QueryContainer
with the specified
- * queryStatement using the default resultset type and default resultset
- * concurrency.
- *
- * @param queryStatement
- * Database query
- * @param connection
- * Connection object
- * @see QueryContainer#DEFAULT_RESULTSET_TYPE
- * @see QueryContainer#DEFAULT_RESULTSET_CONCURRENCY
- * @throws SQLException
- * when database operation fails
- */
- public QueryContainer(String queryStatement, Connection connection)
- throws SQLException {
- this(queryStatement, connection, DEFAULT_RESULTSET_TYPE,
- DEFAULT_RESULTSET_CONCURRENCY);
- }
-
- /**
- * Fills the Container with the items and properties. Invoked by the
- * constructor.
- *
- * @throws SQLException
- * when parameter initialization fails.
- * @see QueryContainer#QueryContainer(String, Connection, int, int).
- */
- private void init() throws SQLException {
- refresh();
- ResultSetMetaData metadata;
- metadata = result.getMetaData();
- int count = metadata.getColumnCount();
- ArrayList list = new ArrayList(count);
- for (int i = 1; i <= count; i++) {
- String columnName = metadata.getColumnName(i);
- list.add(columnName);
- Property p = getContainerProperty(new Integer(1), columnName);
- propertyTypes.put(columnName, p == null ? Object.class : p
- .getType());
- }
- propertyIds = Collections.unmodifiableCollection(list);
- }
-
- /**
- *
- * Restores items in the container. This method will update the latest data
- * to the container.
- *
- * Note: This method should be used to update the container with the latest
- * items.
- *
- * @throws SQLException
- * when database operation fails
- *
- */
-
- public void refresh() throws SQLException {
- close();
- statement = connection.createStatement(resultSetType,
- resultSetConcurrency);
- result = statement.executeQuery(queryStatement);
- result.last();
- size = result.getRow();
- }
-
- /**
- * Releases and nullifies the statement
.
- *
- * @throws SQLException
- * when database operation fails
- */
-
- public void close() throws SQLException {
- if (statement != null)
- statement.close();
- statement = null;
- }
-
- /**
- * Gets the Item with the given Item ID from the Container.
- *
- * @param id
- * ID of the Item to retrieve
- * @return Item Id.
- */
-
- public Item getItem(Object id) {
- return new Row(id);
- }
-
- /**
- * Gets the collection of propertyId from the Container.
- *
- * @return Collection of Property ID.
- */
-
- public Collection getContainerPropertyIds() {
- return propertyIds;
- }
-
- /**
- * Gets an collection of all the item IDs in the container.
- *
- * @return collection of Item IDs
- */
- public Collection getItemIds() {
- Collection c = new ArrayList(size);
- for (int i = 1; i <= size; i++)
- c.add(new Integer(i));
- return c;
- }
-
- /**
- * Gets the property identified by the given itemId and propertyId from the
- * container. If the container does not contain the property
- * null
is returned.
- *
- * @param itemId
- * ID of the Item which contains the Property
- * @param propertyId
- * ID of the Property to retrieve
- *
- * @return Property with the given ID if exists; null
- * otherwise.
- */
-
- public synchronized Property getContainerProperty(Object itemId,
- Object propertyId) {
- if (!(itemId instanceof Integer && propertyId instanceof String))
- return null;
- Object value;
- try {
- result.absolute(((Integer) itemId).intValue());
- value = result.getObject((String) propertyId);
- } catch (Exception e) {
- return null;
- }
-
- // Handle also null values from the database
- return new ObjectProperty(value != null ? value : new String(""));
- }
-
- /**
- * Gets the data type of all properties identified by the given type ID.
- *
- * @param id
- * ID identifying the Properties
- *
- * @return data type of the Properties
- */
-
- public Class getType(Object id) {
- return (Class) propertyTypes.get(id);
- }
-
- /**
- * Gets the number of items in the container.
- *
- * @return the number of items in the container.
- */
- public int size() {
- return size;
- }
-
- /**
- * Tests if the list contains the specified Item.
- *
- * @param id
- * ID the of Item to be tested.
- * @return true
if given id is in the container;
- * false
otherwise.
- */
- public boolean containsId(Object id) {
- if (!(id instanceof Integer))
- return false;
- int i = ((Integer) id).intValue();
- if (i < 1)
- return false;
- if (i > size)
- return false;
- return true;
- }
-
- /**
- * Creates new Item with the given ID into the Container.
- *
- * @param itemId
- * ID of the Item to be created.
- *
- * @return Created new Item, or null
if it fails.
- *
- * @throws UnsupportedOperationException
- * if the addItem method is not supported.
- */
- public Item addItem(Object itemId) throws UnsupportedOperationException {
- throw new UnsupportedOperationException();
- }
-
- /**
- * Creates a new Item into the Container, and assign it an ID.
- *
- * @return ID of the newly created Item, or null
if it fails.
- * @throws UnsupportedOperationException
- * if the addItem method is not supported.
- */
- public Object addItem() throws UnsupportedOperationException {
- throw new UnsupportedOperationException();
- }
-
- /**
- * Removes the Item identified by ItemId from the Container.
- *
- * @param itemId
- * ID of the Item to remove.
- * @return true
if the operation succeeded;
- * false
otherwise.
- * @throws UnsupportedOperationException
- * if the removeItem method is not supported.
- */
- public boolean removeItem(Object itemId)
- throws UnsupportedOperationException {
- throw new UnsupportedOperationException();
- }
-
- /**
- * Adds new Property to all Items in the Container.
- *
- * @param propertyId
- * ID of the Property
- * @param type
- * Data type of the new Property
- * @param defaultValue
- * The value all created Properties are initialized to.
- * @return true
if the operation succeeded;
- * false
otherwise.
- * @throws UnsupportedOperationException
- * if the addContainerProperty method is not supported.
- */
- public boolean addContainerProperty(Object propertyId, Class type,
- Object defaultValue) throws UnsupportedOperationException {
- throw new UnsupportedOperationException();
- }
-
- /**
- * Removes a Property specified by the given Property ID from the Container.
- *
- * @param propertyId
- * ID of the Property to remove
- * @return true
if the operation succeeded;
- * false
otherwise.
- * @throws UnsupportedOperationException
- * if the removeContainerProperty method is not supported.
- */
- public boolean removeContainerProperty(Object propertyId)
- throws UnsupportedOperationException {
- throw new UnsupportedOperationException();
- }
-
- /**
- * Removes all Items from the Container.
- *
- * @return true
if the operation succeeded;
- * false
otherwise.
- * @throws UnsupportedOperationException
- * if the removeAllItems method is not supported.
- */
- public boolean removeAllItems() throws UnsupportedOperationException {
- throw new UnsupportedOperationException();
- }
-
- /**
- * Adds new item after the given item.
- *
- * @param previousItemId
- * Id of the previous item in ordered container.
- * @param newItemId
- * Id of the new item to be added.
- * @return Returns new item or null
if the operation fails.
- * @throws UnsupportedOperationException
- * if the addItemAfter method is not supported.
- */
- public Item addItemAfter(Object previousItemId, Object newItemId)
- throws UnsupportedOperationException {
- throw new UnsupportedOperationException();
- }
-
- /**
- * Adds new item after the given item.
- *
- * @param previousItemId
- * Id of the previous item in ordered container.
- * @return Returns item id created new item or null
if the
- * operation fails.
- * @throws UnsupportedOperationException
- * if the addItemAfter method is not supported.
- */
- public Object addItemAfter(Object previousItemId)
- throws UnsupportedOperationException {
- throw new UnsupportedOperationException();
- }
-
- /**
- * Returns id of first item in the Container.
- *
- * @return ID of the first Item in the list.
- */
- public Object firstItemId() {
- if (size < 1)
- return null;
- return new Integer(1);
- }
-
- /**
- * Returns true
if given id is first id at first index.
- *
- * @param id
- * ID of an Item in the Container.
- */
- public boolean isFirstId(Object id) {
- return size > 0 && (id instanceof Integer)
- && ((Integer) id).intValue() == 1;
- }
-
- /**
- * Returns true
if given id is last id at last index.
- *
- * @param id
- * ID of an Item in the Container
- *
- */
- public boolean isLastId(Object id) {
- return size > 0 && (id instanceof Integer)
- && ((Integer) id).intValue() == size;
- }
-
- /**
- * Returns id of last item in the Container.
- *
- * @return ID of the last Item.
- */
- public Object lastItemId() {
- if (size < 1)
- return null;
- return new Integer(size);
- }
-
- /**
- * Returns id of next item in container at next index.
- *
- * @param id
- * ID of an Item in the Container.
- * @return ID of the next Item or null.
- */
- public Object nextItemId(Object id) {
- if (size < 1 || !(id instanceof Integer))
- return null;
- int i = ((Integer) id).intValue();
- if (i >= size)
- return null;
- return new Integer(i + 1);
- }
-
- /**
- * Returns id of previous item in container at previous index.
- *
- * @param id
- * ID of an Item in the Container.
- * @return ID of the previous Item or null.
- */
- public Object prevItemId(Object id) {
- if (size < 1 || !(id instanceof Integer))
- return null;
- int i = ((Integer) id).intValue();
- if (i <= 1)
- return null;
- return new Integer(i - 1);
- }
-
- /**
- * The Row
class implements methods of Item.
- *
- * @author IT Mill Ltd.
- * @version
- * @since 4.0
- */
- class Row implements Item {
-
- Object id;
-
- private Row(Object rowId) {
- id = rowId;
- }
-
- /**
- * Adds the item property.
- *
- * @param id
- * ID of the new Property.
- * @param property
- * Property to be added and associated with ID.
- * @return true
if the operation succeeded;
- * false
otherwise.
- * @throws UnsupportedOperationException
- * if the addItemProperty method is not supported.
- */
- public boolean addItemProperty(Object id, Property property)
- throws UnsupportedOperationException {
- throw new UnsupportedOperationException();
- }
-
- /**
- * Gets the property corresponding to the given property ID stored in
- * the Item.
- *
- * @param propertyId
- * identifier of the Property to get
- * @return the Property with the given ID or null
- */
- public Property getItemProperty(Object propertyId) {
- return getContainerProperty(id, propertyId);
- }
-
- /**
- * Gets the collection of property IDs stored in the Item.
- *
- * @return unmodifiable collection containing IDs of the Properties
- * stored the Item.
- */
- public Collection getItemPropertyIds() {
- return propertyIds;
- }
-
- /**
- * Removes given item property.
- *
- * @param id
- * ID of the Property to be removed.
- * @return true
if the item property is removed;
- * false
otherwise.
- * @throws UnsupportedOperationException
- * if the removeItemProperty is not supported.
- */
- public boolean removeItemProperty(Object id)
- throws UnsupportedOperationException {
- throw new UnsupportedOperationException();
- }
-
- }
-
- /**
- * Closes the statement.
- *
- * @see #close()
- */
- public void finalize() {
- try {
- close();
- } catch (SQLException ignored) {
-
- }
- }
-
- /**
- * Adds the given item at the position of given index.
- *
- * @param index
- * Index to add the new item.
- * @param newItemId
- * Id of the new item to be added.
- * @return new item or null
if the operation fails.
- * @throws UnsupportedOperationException
- * if the addItemAt is not supported.
- */
- public Item addItemAt(int index, Object newItemId)
- throws UnsupportedOperationException {
- throw new UnsupportedOperationException();
- }
-
- /**
- * Adds item at the position of provided index in the container.
- *
- * @param index
- * Index to add the new item.
- * @return item id created new item or null
if the operation
- * fails.
- *
- * @throws UnsupportedOperationException
- * if the addItemAt is not supported.
- */
-
- public Object addItemAt(int index) throws UnsupportedOperationException {
- throw new UnsupportedOperationException();
- }
-
- /**
- * Gets the Index id in the container.
- *
- * @param index
- * Index Id.
- * @return ID in the given index.
- */
- public Object getIdByIndex(int index) {
- if (size < 1 || index < 0 || index >= size)
- return null;
- return new Integer(index + 1);
- }
-
- /**
- * Gets the index of the Item corresponding to id in the container.
- *
- * @param id
- * ID of an Item in the Container
- * @return index of the Item, or -1 if the Container does not include the
- * Item
- */
-
- public int indexOfId(Object id) {
- if (size < 1 || !(id instanceof Integer))
- return -1;
- int i = ((Integer) id).intValue();
- if (i >= size || i < 1)
- return -1;
- return i - 1;
- }
+ Container.Indexed {
+
+ // default ResultSet type
+ public static final int DEFAULT_RESULTSET_TYPE = ResultSet.TYPE_SCROLL_INSENSITIVE;
+
+ // default ResultSet concurrency
+ public static final int DEFAULT_RESULTSET_CONCURRENCY = ResultSet.CONCUR_READ_ONLY;
+
+ private int resultSetType = DEFAULT_RESULTSET_TYPE;
+
+ private int resultSetConcurrency = DEFAULT_RESULTSET_CONCURRENCY;
+
+ private String queryStatement;
+
+ private Connection connection;
+
+ private ResultSet result;
+
+ private Collection propertyIds;
+
+ private HashMap propertyTypes = new HashMap();
+
+ private int size = -1;
+
+ private Statement statement;
+
+ /**
+ * Constructs new QueryContainer
with the specified
+ * queryStatement
.
+ *
+ * @param queryStatement
+ * Database query
+ * @param connection
+ * Connection object
+ * @param resultSetType
+ * @param resultSetConcurrency
+ * @throws SQLException
+ * when database operation fails
+ */
+ public QueryContainer(String queryStatement, Connection connection,
+ int resultSetType, int resultSetConcurrency) throws SQLException {
+ this.queryStatement = queryStatement;
+ this.connection = connection;
+ this.resultSetType = resultSetType;
+ this.resultSetConcurrency = resultSetConcurrency;
+ init();
+ }
+
+ /**
+ * Constructs new QueryContainer
with the specified
+ * queryStatement using the default resultset type and default resultset
+ * concurrency.
+ *
+ * @param queryStatement
+ * Database query
+ * @param connection
+ * Connection object
+ * @see QueryContainer#DEFAULT_RESULTSET_TYPE
+ * @see QueryContainer#DEFAULT_RESULTSET_CONCURRENCY
+ * @throws SQLException
+ * when database operation fails
+ */
+ public QueryContainer(String queryStatement, Connection connection)
+ throws SQLException {
+ this(queryStatement, connection, DEFAULT_RESULTSET_TYPE,
+ DEFAULT_RESULTSET_CONCURRENCY);
+ }
+
+ /**
+ * Fills the Container with the items and properties. Invoked by the
+ * constructor.
+ *
+ * @throws SQLException
+ * when parameter initialization fails.
+ * @see QueryContainer#QueryContainer(String, Connection, int, int).
+ */
+ private void init() throws SQLException {
+ refresh();
+ ResultSetMetaData metadata;
+ metadata = result.getMetaData();
+ int count = metadata.getColumnCount();
+ ArrayList list = new ArrayList(count);
+ for (int i = 1; i <= count; i++) {
+ String columnName = metadata.getColumnName(i);
+ list.add(columnName);
+ Property p = getContainerProperty(new Integer(1), columnName);
+ propertyTypes.put(columnName, p == null ? Object.class : p
+ .getType());
+ }
+ propertyIds = Collections.unmodifiableCollection(list);
+ }
+
+ /**
+ *
+ * Restores items in the container. This method will update the latest data
+ * to the container.
+ *
+ * Note: This method should be used to update the container with the latest
+ * items.
+ *
+ * @throws SQLException
+ * when database operation fails
+ *
+ */
+
+ public void refresh() throws SQLException {
+ close();
+ statement = connection.createStatement(resultSetType,
+ resultSetConcurrency);
+ result = statement.executeQuery(queryStatement);
+ result.last();
+ size = result.getRow();
+ }
+
+ /**
+ * Releases and nullifies the statement
.
+ *
+ * @throws SQLException
+ * when database operation fails
+ */
+
+ public void close() throws SQLException {
+ if (statement != null) {
+ statement.close();
+ }
+ statement = null;
+ }
+
+ /**
+ * Gets the Item with the given Item ID from the Container.
+ *
+ * @param id
+ * ID of the Item to retrieve
+ * @return Item Id.
+ */
+
+ public Item getItem(Object id) {
+ return new Row(id);
+ }
+
+ /**
+ * Gets the collection of propertyId from the Container.
+ *
+ * @return Collection of Property ID.
+ */
+
+ public Collection getContainerPropertyIds() {
+ return propertyIds;
+ }
+
+ /**
+ * Gets an collection of all the item IDs in the container.
+ *
+ * @return collection of Item IDs
+ */
+ public Collection getItemIds() {
+ Collection c = new ArrayList(size);
+ for (int i = 1; i <= size; i++) {
+ c.add(new Integer(i));
+ }
+ return c;
+ }
+
+ /**
+ * Gets the property identified by the given itemId and propertyId from the
+ * container. If the container does not contain the property
+ * null
is returned.
+ *
+ * @param itemId
+ * ID of the Item which contains the Property
+ * @param propertyId
+ * ID of the Property to retrieve
+ *
+ * @return Property with the given ID if exists; null
+ * otherwise.
+ */
+
+ public synchronized Property getContainerProperty(Object itemId,
+ Object propertyId) {
+ if (!(itemId instanceof Integer && propertyId instanceof String)) {
+ return null;
+ }
+ Object value;
+ try {
+ result.absolute(((Integer) itemId).intValue());
+ value = result.getObject((String) propertyId);
+ } catch (Exception e) {
+ return null;
+ }
+
+ // Handle also null values from the database
+ return new ObjectProperty(value != null ? value : new String(""));
+ }
+
+ /**
+ * Gets the data type of all properties identified by the given type ID.
+ *
+ * @param id
+ * ID identifying the Properties
+ *
+ * @return data type of the Properties
+ */
+
+ public Class getType(Object id) {
+ return (Class) propertyTypes.get(id);
+ }
+
+ /**
+ * Gets the number of items in the container.
+ *
+ * @return the number of items in the container.
+ */
+ public int size() {
+ return size;
+ }
+
+ /**
+ * Tests if the list contains the specified Item.
+ *
+ * @param id
+ * ID the of Item to be tested.
+ * @return true
if given id is in the container;
+ * false
otherwise.
+ */
+ public boolean containsId(Object id) {
+ if (!(id instanceof Integer)) {
+ return false;
+ }
+ int i = ((Integer) id).intValue();
+ if (i < 1) {
+ return false;
+ }
+ if (i > size) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Creates new Item with the given ID into the Container.
+ *
+ * @param itemId
+ * ID of the Item to be created.
+ *
+ * @return Created new Item, or null
if it fails.
+ *
+ * @throws UnsupportedOperationException
+ * if the addItem method is not supported.
+ */
+ public Item addItem(Object itemId) throws UnsupportedOperationException {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * Creates a new Item into the Container, and assign it an ID.
+ *
+ * @return ID of the newly created Item, or null
if it fails.
+ * @throws UnsupportedOperationException
+ * if the addItem method is not supported.
+ */
+ public Object addItem() throws UnsupportedOperationException {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * Removes the Item identified by ItemId from the Container.
+ *
+ * @param itemId
+ * ID of the Item to remove.
+ * @return true
if the operation succeeded;
+ * false
otherwise.
+ * @throws UnsupportedOperationException
+ * if the removeItem method is not supported.
+ */
+ public boolean removeItem(Object itemId)
+ throws UnsupportedOperationException {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * Adds new Property to all Items in the Container.
+ *
+ * @param propertyId
+ * ID of the Property
+ * @param type
+ * Data type of the new Property
+ * @param defaultValue
+ * The value all created Properties are initialized to.
+ * @return true
if the operation succeeded;
+ * false
otherwise.
+ * @throws UnsupportedOperationException
+ * if the addContainerProperty method is not supported.
+ */
+ public boolean addContainerProperty(Object propertyId, Class type,
+ Object defaultValue) throws UnsupportedOperationException {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * Removes a Property specified by the given Property ID from the Container.
+ *
+ * @param propertyId
+ * ID of the Property to remove
+ * @return true
if the operation succeeded;
+ * false
otherwise.
+ * @throws UnsupportedOperationException
+ * if the removeContainerProperty method is not supported.
+ */
+ public boolean removeContainerProperty(Object propertyId)
+ throws UnsupportedOperationException {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * Removes all Items from the Container.
+ *
+ * @return true
if the operation succeeded;
+ * false
otherwise.
+ * @throws UnsupportedOperationException
+ * if the removeAllItems method is not supported.
+ */
+ public boolean removeAllItems() throws UnsupportedOperationException {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * Adds new item after the given item.
+ *
+ * @param previousItemId
+ * Id of the previous item in ordered container.
+ * @param newItemId
+ * Id of the new item to be added.
+ * @return Returns new item or null
if the operation fails.
+ * @throws UnsupportedOperationException
+ * if the addItemAfter method is not supported.
+ */
+ public Item addItemAfter(Object previousItemId, Object newItemId)
+ throws UnsupportedOperationException {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * Adds new item after the given item.
+ *
+ * @param previousItemId
+ * Id of the previous item in ordered container.
+ * @return Returns item id created new item or null
if the
+ * operation fails.
+ * @throws UnsupportedOperationException
+ * if the addItemAfter method is not supported.
+ */
+ public Object addItemAfter(Object previousItemId)
+ throws UnsupportedOperationException {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * Returns id of first item in the Container.
+ *
+ * @return ID of the first Item in the list.
+ */
+ public Object firstItemId() {
+ if (size < 1) {
+ return null;
+ }
+ return new Integer(1);
+ }
+
+ /**
+ * Returns true
if given id is first id at first index.
+ *
+ * @param id
+ * ID of an Item in the Container.
+ */
+ public boolean isFirstId(Object id) {
+ return size > 0 && (id instanceof Integer)
+ && ((Integer) id).intValue() == 1;
+ }
+
+ /**
+ * Returns true
if given id is last id at last index.
+ *
+ * @param id
+ * ID of an Item in the Container
+ *
+ */
+ public boolean isLastId(Object id) {
+ return size > 0 && (id instanceof Integer)
+ && ((Integer) id).intValue() == size;
+ }
+
+ /**
+ * Returns id of last item in the Container.
+ *
+ * @return ID of the last Item.
+ */
+ public Object lastItemId() {
+ if (size < 1) {
+ return null;
+ }
+ return new Integer(size);
+ }
+
+ /**
+ * Returns id of next item in container at next index.
+ *
+ * @param id
+ * ID of an Item in the Container.
+ * @return ID of the next Item or null.
+ */
+ public Object nextItemId(Object id) {
+ if (size < 1 || !(id instanceof Integer)) {
+ return null;
+ }
+ int i = ((Integer) id).intValue();
+ if (i >= size) {
+ return null;
+ }
+ return new Integer(i + 1);
+ }
+
+ /**
+ * Returns id of previous item in container at previous index.
+ *
+ * @param id
+ * ID of an Item in the Container.
+ * @return ID of the previous Item or null.
+ */
+ public Object prevItemId(Object id) {
+ if (size < 1 || !(id instanceof Integer)) {
+ return null;
+ }
+ int i = ((Integer) id).intValue();
+ if (i <= 1) {
+ return null;
+ }
+ return new Integer(i - 1);
+ }
+
+ /**
+ * The Row
class implements methods of Item.
+ *
+ * @author IT Mill Ltd.
+ * @version
+ * @since 4.0
+ */
+ class Row implements Item {
+
+ Object id;
+
+ private Row(Object rowId) {
+ id = rowId;
+ }
+
+ /**
+ * Adds the item property.
+ *
+ * @param id
+ * ID of the new Property.
+ * @param property
+ * Property to be added and associated with ID.
+ * @return true
if the operation succeeded;
+ * false
otherwise.
+ * @throws UnsupportedOperationException
+ * if the addItemProperty method is not supported.
+ */
+ public boolean addItemProperty(Object id, Property property)
+ throws UnsupportedOperationException {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * Gets the property corresponding to the given property ID stored in
+ * the Item.
+ *
+ * @param propertyId
+ * identifier of the Property to get
+ * @return the Property with the given ID or null
+ */
+ public Property getItemProperty(Object propertyId) {
+ return getContainerProperty(id, propertyId);
+ }
+
+ /**
+ * Gets the collection of property IDs stored in the Item.
+ *
+ * @return unmodifiable collection containing IDs of the Properties
+ * stored the Item.
+ */
+ public Collection getItemPropertyIds() {
+ return propertyIds;
+ }
+
+ /**
+ * Removes given item property.
+ *
+ * @param id
+ * ID of the Property to be removed.
+ * @return true
if the item property is removed;
+ * false
otherwise.
+ * @throws UnsupportedOperationException
+ * if the removeItemProperty is not supported.
+ */
+ public boolean removeItemProperty(Object id)
+ throws UnsupportedOperationException {
+ throw new UnsupportedOperationException();
+ }
+
+ }
+
+ /**
+ * Closes the statement.
+ *
+ * @see #close()
+ */
+ public void finalize() {
+ try {
+ close();
+ } catch (SQLException ignored) {
+
+ }
+ }
+
+ /**
+ * Adds the given item at the position of given index.
+ *
+ * @param index
+ * Index to add the new item.
+ * @param newItemId
+ * Id of the new item to be added.
+ * @return new item or null
if the operation fails.
+ * @throws UnsupportedOperationException
+ * if the addItemAt is not supported.
+ */
+ public Item addItemAt(int index, Object newItemId)
+ throws UnsupportedOperationException {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * Adds item at the position of provided index in the container.
+ *
+ * @param index
+ * Index to add the new item.
+ * @return item id created new item or null
if the operation
+ * fails.
+ *
+ * @throws UnsupportedOperationException
+ * if the addItemAt is not supported.
+ */
+
+ public Object addItemAt(int index) throws UnsupportedOperationException {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * Gets the Index id in the container.
+ *
+ * @param index
+ * Index Id.
+ * @return ID in the given index.
+ */
+ public Object getIdByIndex(int index) {
+ if (size < 1 || index < 0 || index >= size) {
+ return null;
+ }
+ return new Integer(index + 1);
+ }
+
+ /**
+ * Gets the index of the Item corresponding to id in the container.
+ *
+ * @param id
+ * ID of an Item in the Container
+ * @return index of the Item, or -1 if the Container does not include the
+ * Item
+ */
+
+ public int indexOfId(Object id) {
+ if (size < 1 || !(id instanceof Integer)) {
+ return -1;
+ }
+ int i = ((Integer) id).intValue();
+ if (i >= size || i < 1) {
+ return -1;
+ }
+ return i - 1;
+ }
}
diff --git a/src/com/itmill/toolkit/data/validator/CompositeValidator.java b/src/com/itmill/toolkit/data/validator/CompositeValidator.java
index 1a5839455e..3abe1d40d9 100644
--- a/src/com/itmill/toolkit/data/validator/CompositeValidator.java
+++ b/src/com/itmill/toolkit/data/validator/CompositeValidator.java
@@ -33,7 +33,7 @@ import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
-import com.itmill.toolkit.data.*;
+import com.itmill.toolkit.data.Validator;
/**
* The CompositeValidator
allows you to chain (compose) many
@@ -49,247 +49,260 @@ import com.itmill.toolkit.data.*;
*/
public class CompositeValidator implements Validator {
- /**
- * The validators are combined with AND
clause: validity of
- * the composite implies validity of the all validators it is composed of
- * must be valid.
- */
- public static final int MODE_AND = 0;
-
- /**
- * The validators are combined with OR
clause: validity of
- * the composite implies that some of validators it is composed of must be
- * valid.
- */
- public static final int MODE_OR = 1;
-
- /**
- * The validators are combined with and clause: validity of the composite
- * implies validity of the all validators it is composed of
- */
- public static final int MODE_DEFAULT = MODE_AND;
-
- /**
- * Operation mode.
- */
- private int mode = MODE_DEFAULT;
-
- /**
- * List of contained validators.
- */
- private LinkedList validators = new LinkedList();
-
- /**
- * Error message.
- */
- private String errorMessage;
-
- /**
- * Construct a composite validator in AND
mode without error
- * message.
- */
- public CompositeValidator() {
- }
-
- /**
- * Constructs a composite validator in given mode.
- */
- public CompositeValidator(int mode, String errorMessage) {
- setMode(mode);
- setErrorMessage(errorMessage);
- }
-
- /**
- * Validates the given value.
- *
- * The value is valid, if:
- *
- * MODE_AND
: All of the sub-validators are valid
- * MODE_OR
: Any of the sub-validators are valid
- *
- *
- * If the value is invalid, validation error is thrown. If the error message
- * is set (non-null), it is used. If the error message has not been set, the
- * first error occurred is thrown.
- *
- *
- * @param value
- * the value to check.
- * @throws Validator.InvalidValueException
- * if the value is not valid.
- */
- public void validate(Object value) throws Validator.InvalidValueException {
- switch (mode) {
- case MODE_AND:
- for (Iterator i = validators.iterator(); i.hasNext();)
- ((Validator) i.next()).validate(value);
- return;
-
- case MODE_OR:
- Validator.InvalidValueException first = null;
- for (Iterator i = validators.iterator(); i.hasNext();)
- try {
- ((Validator) i.next()).validate(value);
- return;
- } catch (Validator.InvalidValueException e) {
- if (first == null)
- first = e;
- }
- if (first == null)
- return;
- String em = getErrorMessage();
- if (em != null)
- throw new Validator.InvalidValueException(em);
- else
- throw first;
- }
- throw new IllegalStateException(
- "The validator is in unsupported operation mode");
- }
-
- /**
- * Checks the validity of the the given value. The value is valid, if:
- *
- * MODE_AND
: All of the sub-validators are valid
- * MODE_OR
: Any of the sub-validators are valid
- *
- *
- * @param value
- * the value to check.
- */
- public boolean isValid(Object value) {
- switch (mode) {
- case MODE_AND:
- for (Iterator i = validators.iterator(); i.hasNext();) {
- Validator v = (Validator) i.next();
- if (!v.isValid(value))
- return false;
- }
- return true;
-
- case MODE_OR:
- for (Iterator i = validators.iterator(); i.hasNext();) {
- Validator v = (Validator) i.next();
- if (v.isValid(value))
- return true;
- }
- return false;
- }
- throw new IllegalStateException(
- "The valitor is in unsupported operation mode");
- }
-
- /**
- * Gets the mode of the validator.
- *
- * @return Operation mode of the validator: MODE_AND
or
- * MODE_OR
.
- */
- public final int getMode() {
- return mode;
- }
-
- /**
- * Sets the mode of the validator. The valid modes are:
- *
- * MODE_AND
(default)
- * MODE_OR
- *
- *
- * @param mode
- * the mode to set.
- */
- public void setMode(int mode) {
- if (mode != MODE_AND && mode != MODE_OR)
- throw new IllegalArgumentException("Mode " + mode + " unsupported");
- this.mode = mode;
- }
-
- /**
- * Gets the error message for the composite validator. If the error message
- * is null, original error messages of the sub-validators are used instead.
- */
- public String getErrorMessage() {
- if (this.errorMessage != null)
- return this.errorMessage;
-
- // TODO Return composite error message
-
- return null;
- }
-
- /**
- * Sets the error message for the composite validator. If the error message
- * is null, original error messages of the sub-validators are used instead.
- *
- * @param errorMessage
- * the Error Message to set.
- */
- public void setErrorMessage(String errorMessage) {
- this.errorMessage = errorMessage;
- }
-
- /**
- * Adds validator to the interface.
- *
- * @param validator
- * the Validator object which performs validation checks on this
- * set of data field values.
- */
- public void addValidator(Validator validator) {
- if (validator == null)
- return;
- validators.add(validator);
- }
-
- /**
- * Removes a validator from the composite.
- *
- * @param validator
- * the Validator object which performs validation checks on this
- * set of data field values.
- */
- public void removeValidator(Validator validator) {
- validators.remove(validator);
- }
-
- /**
- * Gets sub-validators by class.
- *
- *
- * If the component contains directly or recursively (it contains another
- * composite containing the validator) validators compatible with given type
- * they are returned. This only applies to AND
mode composite
- * validators.
- *
- *
- *
- * If the validator is in OR
mode or does not contain any
- * validators of given type null is returned.
- *
- *
- * @return Collection of validators compatible with given type that must
- * apply or null if none fould.
- */
- public Collection getSubValidators(Class validatorType) {
- if (mode != MODE_AND)
- return null;
-
- HashSet found = new HashSet();
- for (Iterator i = validators.iterator(); i.hasNext();) {
- Validator v = (Validator) i.next();
- if (validatorType.isAssignableFrom(v.getClass()))
- found.add(v);
- if (v instanceof CompositeValidator
- && ((CompositeValidator) v).getMode() == MODE_AND) {
- Collection c = ((CompositeValidator) v)
- .getSubValidators(validatorType);
- if (c != null)
- found.addAll(c);
- }
- }
-
- return found.isEmpty() ? null : found;
- }
+ /**
+ * The validators are combined with AND
clause: validity of
+ * the composite implies validity of the all validators it is composed of
+ * must be valid.
+ */
+ public static final int MODE_AND = 0;
+
+ /**
+ * The validators are combined with OR
clause: validity of
+ * the composite implies that some of validators it is composed of must be
+ * valid.
+ */
+ public static final int MODE_OR = 1;
+
+ /**
+ * The validators are combined with and clause: validity of the composite
+ * implies validity of the all validators it is composed of
+ */
+ public static final int MODE_DEFAULT = MODE_AND;
+
+ /**
+ * Operation mode.
+ */
+ private int mode = MODE_DEFAULT;
+
+ /**
+ * List of contained validators.
+ */
+ private LinkedList validators = new LinkedList();
+
+ /**
+ * Error message.
+ */
+ private String errorMessage;
+
+ /**
+ * Construct a composite validator in AND
mode without error
+ * message.
+ */
+ public CompositeValidator() {
+ }
+
+ /**
+ * Constructs a composite validator in given mode.
+ */
+ public CompositeValidator(int mode, String errorMessage) {
+ setMode(mode);
+ setErrorMessage(errorMessage);
+ }
+
+ /**
+ * Validates the given value.
+ *
+ * The value is valid, if:
+ *
+ * MODE_AND
: All of the sub-validators are valid
+ * MODE_OR
: Any of the sub-validators are valid
+ *
+ *
+ * If the value is invalid, validation error is thrown. If the error message
+ * is set (non-null), it is used. If the error message has not been set, the
+ * first error occurred is thrown.
+ *
+ *
+ * @param value
+ * the value to check.
+ * @throws Validator.InvalidValueException
+ * if the value is not valid.
+ */
+ public void validate(Object value) throws Validator.InvalidValueException {
+ switch (mode) {
+ case MODE_AND:
+ for (Iterator i = validators.iterator(); i.hasNext();) {
+ ((Validator) i.next()).validate(value);
+ }
+ return;
+
+ case MODE_OR:
+ Validator.InvalidValueException first = null;
+ for (Iterator i = validators.iterator(); i.hasNext();) {
+ try {
+ ((Validator) i.next()).validate(value);
+ return;
+ } catch (Validator.InvalidValueException e) {
+ if (first == null) {
+ first = e;
+ }
+ }
+ }
+ if (first == null) {
+ return;
+ }
+ String em = getErrorMessage();
+ if (em != null) {
+ throw new Validator.InvalidValueException(em);
+ } else {
+ throw first;
+ }
+ }
+ throw new IllegalStateException(
+ "The validator is in unsupported operation mode");
+ }
+
+ /**
+ * Checks the validity of the the given value. The value is valid, if:
+ *
+ * MODE_AND
: All of the sub-validators are valid
+ * MODE_OR
: Any of the sub-validators are valid
+ *
+ *
+ * @param value
+ * the value to check.
+ */
+ public boolean isValid(Object value) {
+ switch (mode) {
+ case MODE_AND:
+ for (Iterator i = validators.iterator(); i.hasNext();) {
+ Validator v = (Validator) i.next();
+ if (!v.isValid(value)) {
+ return false;
+ }
+ }
+ return true;
+
+ case MODE_OR:
+ for (Iterator i = validators.iterator(); i.hasNext();) {
+ Validator v = (Validator) i.next();
+ if (v.isValid(value)) {
+ return true;
+ }
+ }
+ return false;
+ }
+ throw new IllegalStateException(
+ "The valitor is in unsupported operation mode");
+ }
+
+ /**
+ * Gets the mode of the validator.
+ *
+ * @return Operation mode of the validator: MODE_AND
or
+ * MODE_OR
.
+ */
+ public final int getMode() {
+ return mode;
+ }
+
+ /**
+ * Sets the mode of the validator. The valid modes are:
+ *
+ * MODE_AND
(default)
+ * MODE_OR
+ *
+ *
+ * @param mode
+ * the mode to set.
+ */
+ public void setMode(int mode) {
+ if (mode != MODE_AND && mode != MODE_OR) {
+ throw new IllegalArgumentException("Mode " + mode + " unsupported");
+ }
+ this.mode = mode;
+ }
+
+ /**
+ * Gets the error message for the composite validator. If the error message
+ * is null, original error messages of the sub-validators are used instead.
+ */
+ public String getErrorMessage() {
+ if (errorMessage != null) {
+ return errorMessage;
+ }
+
+ // TODO Return composite error message
+
+ return null;
+ }
+
+ /**
+ * Sets the error message for the composite validator. If the error message
+ * is null, original error messages of the sub-validators are used instead.
+ *
+ * @param errorMessage
+ * the Error Message to set.
+ */
+ public void setErrorMessage(String errorMessage) {
+ this.errorMessage = errorMessage;
+ }
+
+ /**
+ * Adds validator to the interface.
+ *
+ * @param validator
+ * the Validator object which performs validation checks on
+ * this set of data field values.
+ */
+ public void addValidator(Validator validator) {
+ if (validator == null) {
+ return;
+ }
+ validators.add(validator);
+ }
+
+ /**
+ * Removes a validator from the composite.
+ *
+ * @param validator
+ * the Validator object which performs validation checks on
+ * this set of data field values.
+ */
+ public void removeValidator(Validator validator) {
+ validators.remove(validator);
+ }
+
+ /**
+ * Gets sub-validators by class.
+ *
+ *
+ * If the component contains directly or recursively (it contains another
+ * composite containing the validator) validators compatible with given type
+ * they are returned. This only applies to AND
mode composite
+ * validators.
+ *
+ *
+ *
+ * If the validator is in OR
mode or does not contain any
+ * validators of given type null is returned.
+ *
+ *
+ * @return Collection of validators compatible with given type that must
+ * apply or null if none fould.
+ */
+ public Collection getSubValidators(Class validatorType) {
+ if (mode != MODE_AND) {
+ return null;
+ }
+
+ HashSet found = new HashSet();
+ for (Iterator i = validators.iterator(); i.hasNext();) {
+ Validator v = (Validator) i.next();
+ if (validatorType.isAssignableFrom(v.getClass())) {
+ found.add(v);
+ }
+ if (v instanceof CompositeValidator
+ && ((CompositeValidator) v).getMode() == MODE_AND) {
+ Collection c = ((CompositeValidator) v)
+ .getSubValidators(validatorType);
+ if (c != null) {
+ found.addAll(c);
+ }
+ }
+ }
+
+ return found.isEmpty() ? null : found;
+ }
}
diff --git a/src/com/itmill/toolkit/data/validator/NullValidator.java b/src/com/itmill/toolkit/data/validator/NullValidator.java
index 7c7ae464ff..24cb25b339 100644
--- a/src/com/itmill/toolkit/data/validator/NullValidator.java
+++ b/src/com/itmill/toolkit/data/validator/NullValidator.java
@@ -28,7 +28,7 @@
package com.itmill.toolkit.data.validator;
-import com.itmill.toolkit.data.*;
+import com.itmill.toolkit.data.Validator;
/**
* This validator is used for validating properties that do or do not allow null
@@ -41,83 +41,85 @@ import com.itmill.toolkit.data.*;
*/
public class NullValidator implements Validator {
- private boolean allowNull;
-
- private String errorMessage;
-
- /**
- * Creates a new NullValidator.
- *
- * @param errorMessage
- * the error message to display on invalidation.
- * @param allowNull
- * Are nulls allowed?
- */
- public NullValidator(String errorMessage, boolean allowNull) {
- setErrorMessage(errorMessage);
- setNullAllowed(allowNull);
- }
-
- /**
- * Validates the data given in value.
- *
- * @param value
- * the value to validate.
- * @throws Validator.InvalidValueException
- * if the value was invalid.
- */
- public void validate(Object value) throws Validator.InvalidValueException {
- if ((allowNull && value != null) || (!allowNull && value == null))
- throw new Validator.InvalidValueException(errorMessage);
- }
-
- /**
- * Tests if the given value is valid.
- *
- * @param value
- * the value to validate.
- * @returns true
for valid value, otherwise
- * false
.
- */
- public boolean isValid(Object value) {
- return allowNull ? value == null : value != null;
- }
-
- /**
- * Returns true
if nulls are allowed otherwise
- * false
.
- */
- public final boolean isNullAllowed() {
- return allowNull;
- }
-
- /**
- * Sets if nulls are to be allowed.
- *
- * @param allowNull If true, only nulls are allowed. If false only non-nulls are allowed.
- * Do we allow nulls?
- */
- public void setNullAllowed(boolean allowNull) {
- this.allowNull = allowNull;
- }
-
- /**
- * Gets the error message that is displayed in case the value is invalid.
- *
- * @return the Error Message.
- */
- public String getErrorMessage() {
- return errorMessage;
- }
-
- /**
- * Sets the error message to be displayed on invalid value.
- *
- * @param errorMessage
- * the Error Message to set.
- */
- public void setErrorMessage(String errorMessage) {
- this.errorMessage = errorMessage;
- }
+ private boolean allowNull;
+
+ private String errorMessage;
+
+ /**
+ * Creates a new NullValidator.
+ *
+ * @param errorMessage
+ * the error message to display on invalidation.
+ * @param allowNull
+ * Are nulls allowed?
+ */
+ public NullValidator(String errorMessage, boolean allowNull) {
+ setErrorMessage(errorMessage);
+ setNullAllowed(allowNull);
+ }
+
+ /**
+ * Validates the data given in value.
+ *
+ * @param value
+ * the value to validate.
+ * @throws Validator.InvalidValueException
+ * if the value was invalid.
+ */
+ public void validate(Object value) throws Validator.InvalidValueException {
+ if ((allowNull && value != null) || (!allowNull && value == null)) {
+ throw new Validator.InvalidValueException(errorMessage);
+ }
+ }
+
+ /**
+ * Tests if the given value is valid.
+ *
+ * @param value
+ * the value to validate.
+ * @returns true
for valid value, otherwise
+ * false
.
+ */
+ public boolean isValid(Object value) {
+ return allowNull ? value == null : value != null;
+ }
+
+ /**
+ * Returns true
if nulls are allowed otherwise
+ * false
.
+ */
+ public final boolean isNullAllowed() {
+ return allowNull;
+ }
+
+ /**
+ * Sets if nulls are to be allowed.
+ *
+ * @param allowNull
+ * If true, only nulls are allowed. If false only non-nulls
+ * are allowed. Do we allow nulls?
+ */
+ public void setNullAllowed(boolean allowNull) {
+ this.allowNull = allowNull;
+ }
+
+ /**
+ * Gets the error message that is displayed in case the value is invalid.
+ *
+ * @return the Error Message.
+ */
+ public String getErrorMessage() {
+ return errorMessage;
+ }
+
+ /**
+ * Sets the error message to be displayed on invalid value.
+ *
+ * @param errorMessage
+ * the Error Message to set.
+ */
+ public void setErrorMessage(String errorMessage) {
+ this.errorMessage = errorMessage;
+ }
}
diff --git a/src/com/itmill/toolkit/data/validator/StringLengthValidator.java b/src/com/itmill/toolkit/data/validator/StringLengthValidator.java
index 4159041e1b..68ddfe46fb 100644
--- a/src/com/itmill/toolkit/data/validator/StringLengthValidator.java
+++ b/src/com/itmill/toolkit/data/validator/StringLengthValidator.java
@@ -28,7 +28,7 @@
package com.itmill.toolkit.data.validator;
-import com.itmill.toolkit.data.*;
+import com.itmill.toolkit.data.Validator;
/**
* This StringLengthValidator
is used to validate the length of
@@ -41,161 +41,171 @@ import com.itmill.toolkit.data.*;
*/
public class StringLengthValidator implements Validator {
- private int minLength = -1;
-
- private int maxLength = -1;
-
- private boolean allowNull = true;
-
- private String errorMessage;
-
- /**
- * Creates a new StringLengthValidator with a given error message.
- *
- * @param errorMessage
- * the message to display in case the value does not validate.
- */
- public StringLengthValidator(String errorMessage) {
- setErrorMessage(errorMessage);
- }
-
- /**
- * Creates a new StringLengthValidator with a given error message,
- * permissable lengths and null-string allowance.
- *
- * @param errorMessage
- * the message to display in case the value does not validate.
- * @param minLength
- * the minimum permissable length of the string.
- * @param maxLength
- * the maximum permissable length of the string.
- * @param allowNull
- * Are null strings permissable?
- */
- public StringLengthValidator(String errorMessage, int minLength,
- int maxLength, boolean allowNull) {
- this(errorMessage);
- setMinLength(minLength);
- setMaxLength(maxLength);
- setNullAllowed(allowNull);
- }
-
- /**
- * Validates the value.
- *
- * @param value
- * the value to validate.
- * @throws Validator.InvalidValueException
- * if the value was invalid.
- */
- public void validate(Object value) throws Validator.InvalidValueException {
- if (value == null && !allowNull)
- throw new Validator.InvalidValueException(errorMessage);
- String s = value.toString();
- if (s == null && !allowNull)
- throw new Validator.InvalidValueException(errorMessage);
- int len = s.length();
- if ((minLength >= 0 && len < minLength)
- || (maxLength >= 0 && len > maxLength))
- throw new Validator.InvalidValueException(errorMessage);
- }
-
- /**
- * Checks if the given value is valid.
- *
- * @param value
- * the value to validate.
- * @return true
for valid value, otherwise false
.
- */
- public boolean isValid(Object value) {
- if (value == null && !allowNull)
- return true;
- String s = value.toString();
- if (s == null && !allowNull)
- return true;
- int len = s.length();
- if ((minLength >= 0 && len < minLength)
- || (maxLength >= 0 && len > maxLength))
- return false;
- return true;
- }
-
- /**
- * Returns true
if null strings are allowed.
- *
- * @return true
if allows null string, otherwise
- * false
.
- */
- public final boolean isNullAllowed() {
- return allowNull;
- }
-
- /**
- * Gets the maximum permissable length of the string.
- *
- * @return the maximum length of the string.
- */
- public final int getMaxLength() {
- return maxLength;
- }
-
- /**
- * Gets the minimum permissable length of the string.
- *
- * @return the minimum length of the string.
- */
- public final int getMinLength() {
- return minLength;
- }
-
- /**
- * Sets whether null-strings are to be allowed.
- */
- public void setNullAllowed(boolean allowNull) {
- this.allowNull = allowNull;
- }
-
- /**
- * Sets the maximum permissable length of the string.
- *
- * @param maxLength
- * the length to set.
- */
- public void setMaxLength(int maxLength) {
- if (maxLength < -1)
- maxLength = -1;
- this.maxLength = maxLength;
- }
-
- /**
- * Sets the minimum permissable length.
- *
- * @param minLength
- * the length to set.
- */
- public void setMinLength(int minLength) {
- if (minLength < -1)
- minLength = -1;
- this.minLength = minLength;
- }
-
- /**
- * Gets the message to be displayed in case the value does not validate.
- *
- * @return the Error Message.
- */
- public String getErrorMessage() {
- return errorMessage;
- }
-
- /**
- * Sets the message to be displayer in case the value does not validate.
- *
- * @param errorMessage
- * the Error Message to set.
- */
- public void setErrorMessage(String errorMessage) {
- this.errorMessage = errorMessage;
- }
+ private int minLength = -1;
+
+ private int maxLength = -1;
+
+ private boolean allowNull = true;
+
+ private String errorMessage;
+
+ /**
+ * Creates a new StringLengthValidator with a given error message.
+ *
+ * @param errorMessage
+ * the message to display in case the value does not
+ * validate.
+ */
+ public StringLengthValidator(String errorMessage) {
+ setErrorMessage(errorMessage);
+ }
+
+ /**
+ * Creates a new StringLengthValidator with a given error message,
+ * permissable lengths and null-string allowance.
+ *
+ * @param errorMessage
+ * the message to display in case the value does not
+ * validate.
+ * @param minLength
+ * the minimum permissable length of the string.
+ * @param maxLength
+ * the maximum permissable length of the string.
+ * @param allowNull
+ * Are null strings permissable?
+ */
+ public StringLengthValidator(String errorMessage, int minLength,
+ int maxLength, boolean allowNull) {
+ this(errorMessage);
+ setMinLength(minLength);
+ setMaxLength(maxLength);
+ setNullAllowed(allowNull);
+ }
+
+ /**
+ * Validates the value.
+ *
+ * @param value
+ * the value to validate.
+ * @throws Validator.InvalidValueException
+ * if the value was invalid.
+ */
+ public void validate(Object value) throws Validator.InvalidValueException {
+ if (value == null && !allowNull) {
+ throw new Validator.InvalidValueException(errorMessage);
+ }
+ String s = value.toString();
+ if (s == null && !allowNull) {
+ throw new Validator.InvalidValueException(errorMessage);
+ }
+ int len = s.length();
+ if ((minLength >= 0 && len < minLength)
+ || (maxLength >= 0 && len > maxLength)) {
+ throw new Validator.InvalidValueException(errorMessage);
+ }
+ }
+
+ /**
+ * Checks if the given value is valid.
+ *
+ * @param value
+ * the value to validate.
+ * @return true
for valid value, otherwise false
.
+ */
+ public boolean isValid(Object value) {
+ if (value == null && !allowNull) {
+ return true;
+ }
+ String s = value.toString();
+ if (s == null && !allowNull) {
+ return true;
+ }
+ int len = s.length();
+ if ((minLength >= 0 && len < minLength)
+ || (maxLength >= 0 && len > maxLength)) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Returns true
if null strings are allowed.
+ *
+ * @return true
if allows null string, otherwise
+ * false
.
+ */
+ public final boolean isNullAllowed() {
+ return allowNull;
+ }
+
+ /**
+ * Gets the maximum permissable length of the string.
+ *
+ * @return the maximum length of the string.
+ */
+ public final int getMaxLength() {
+ return maxLength;
+ }
+
+ /**
+ * Gets the minimum permissable length of the string.
+ *
+ * @return the minimum length of the string.
+ */
+ public final int getMinLength() {
+ return minLength;
+ }
+
+ /**
+ * Sets whether null-strings are to be allowed.
+ */
+ public void setNullAllowed(boolean allowNull) {
+ this.allowNull = allowNull;
+ }
+
+ /**
+ * Sets the maximum permissable length of the string.
+ *
+ * @param maxLength
+ * the length to set.
+ */
+ public void setMaxLength(int maxLength) {
+ if (maxLength < -1) {
+ maxLength = -1;
+ }
+ this.maxLength = maxLength;
+ }
+
+ /**
+ * Sets the minimum permissable length.
+ *
+ * @param minLength
+ * the length to set.
+ */
+ public void setMinLength(int minLength) {
+ if (minLength < -1) {
+ minLength = -1;
+ }
+ this.minLength = minLength;
+ }
+
+ /**
+ * Gets the message to be displayed in case the value does not validate.
+ *
+ * @return the Error Message.
+ */
+ public String getErrorMessage() {
+ return errorMessage;
+ }
+
+ /**
+ * Sets the message to be displayer in case the value does not validate.
+ *
+ * @param errorMessage
+ * the Error Message to set.
+ */
+ public void setErrorMessage(String errorMessage) {
+ this.errorMessage = errorMessage;
+ }
}
diff --git a/src/com/itmill/toolkit/demo/BrowserDemo.java b/src/com/itmill/toolkit/demo/BrowserDemo.java
index 62a5a5fde5..5a03dce9d9 100644
--- a/src/com/itmill/toolkit/demo/BrowserDemo.java
+++ b/src/com/itmill/toolkit/demo/BrowserDemo.java
@@ -15,58 +15,59 @@ import com.itmill.toolkit.ui.Window;
* @see com.itmill.toolkit.ui.Window
*/
public class BrowserDemo extends com.itmill.toolkit.Application implements
- Select.ValueChangeListener {
+ Select.ValueChangeListener {
- // Default URL to open.
- private static final String DEFAULT_URL = "http://www.itmill.com";
+ // Default URL to open.
+ private static final String DEFAULT_URL = "http://www.itmill.com";
- // The embedded page
- Embedded emb = new Embedded();
+ // The embedded page
+ Embedded emb = new Embedded();
- public void init() {
- // Create and set main window
- Window browser = new Window("IT Mill Browser");
- setMainWindow(browser);
+ public void init() {
+ // Create and set main window
+ Window browser = new Window("IT Mill Browser");
+ setMainWindow(browser);
- // Use the expand layout to allow one component to use as much space as
- // possible.
- ExpandLayout exl = new ExpandLayout();
- browser.setLayout(exl);
- exl.setSizeFull();
+ // Use the expand layout to allow one component to use as much
+ // space as
+ // possible.
+ ExpandLayout exl = new ExpandLayout();
+ browser.setLayout(exl);
+ exl.setSizeFull();
- // create the address combobox
- Select select = new Select();
- // allow input
- select.setNewItemsAllowed(true);
- // no empty selection
- select.setNullSelectionAllowed(false);
- // no 'go' -button clicking necessary
- select.setImmediate(true);
- // add some pre-configured URLs
- select.addItem(DEFAULT_URL);
- select.addItem("http://www.google.com");
- select.addItem("http://toolkit.itmill.com/demo");
- // add to layout
- exl.addComponent(select);
- // add listener and select initial URL
- select.addListener(this);
- select.setValue(DEFAULT_URL);
+ // create the address combobox
+ Select select = new Select();
+ // allow input
+ select.setNewItemsAllowed(true);
+ // no empty selection
+ select.setNullSelectionAllowed(false);
+ // no 'go' -button clicking necessary
+ select.setImmediate(true);
+ // add some pre-configured URLs
+ select.addItem(DEFAULT_URL);
+ select.addItem("http://www.google.com");
+ select.addItem("http://toolkit.itmill.com/demo");
+ // add to layout
+ exl.addComponent(select);
+ // add listener and select initial URL
+ select.addListener(this);
+ select.setValue(DEFAULT_URL);
- // configure the embedded and add to layout
- emb.setType(Embedded.TYPE_BROWSER);
- exl.addComponent(emb);
- // make the embedded as large as possible
- exl.expand(emb);
+ // configure the embedded and add to layout
+ emb.setType(Embedded.TYPE_BROWSER);
+ exl.addComponent(emb);
+ // make the embedded as large as possible
+ exl.expand(emb);
- }
+ }
- public void valueChange(ValueChangeEvent event) {
- String url = (String) event.getProperty().getValue();
- if (url != null) {
- // the selected url has changed, let's go there
- emb.setSource(new ExternalResource(url));
- }
+ public void valueChange(ValueChangeEvent event) {
+ String url = (String) event.getProperty().getValue();
+ if (url != null) {
+ // the selected url has changed, let's go there
+ emb.setSource(new ExternalResource(url));
+ }
- }
+ }
}
diff --git a/src/com/itmill/toolkit/demo/BufferedComponents.java b/src/com/itmill/toolkit/demo/BufferedComponents.java
index 6a560e39c6..b2a75e1a16 100644
--- a/src/com/itmill/toolkit/demo/BufferedComponents.java
+++ b/src/com/itmill/toolkit/demo/BufferedComponents.java
@@ -11,65 +11,66 @@ import com.itmill.toolkit.ui.Button.ClickEvent;
public class BufferedComponents extends Application {
- private ObjectProperty property;
+ private ObjectProperty property;
- private TextField text;
+ private TextField text;
- public void init() {
+ public void init() {
- Window w = new Window("Buffered UI components demo");
- addWindow(w);
+ Window w = new Window("Buffered UI components demo");
+ addWindow(w);
- // Create property
- Float floatValue = new Float(1.0f);
- property = new ObjectProperty(floatValue);
+ // Create property
+ Float floatValue = new Float(1.0f);
+ property = new ObjectProperty(floatValue);
- // Textfield
- text = new TextField("TextField (Buffered, using ObjectProperty)",
- property);
- text.setImmediate(true);
- text.setWriteThrough(false);
- w.addComponent(text);
+ // Textfield
+ text = new TextField("TextField (Buffered, using ObjectProperty)",
+ property);
+ text.setImmediate(true);
+ text.setWriteThrough(false);
+ w.addComponent(text);
- // Property state
- Label propertyState = new Label(property);
- propertyState.setCaption("Property (data source) state");
- w.addComponent(propertyState);
+ // Property state
+ Label propertyState = new Label(property);
+ propertyState.setCaption("Property (data source) state");
+ w.addComponent(propertyState);
- // Button state
- Label textState = new Label(text);
- textState.setCaption("TextField state");
- w.addComponent(textState);
+ // Button state
+ Label textState = new Label(text);
+ textState.setCaption("TextField state");
+ w.addComponent(textState);
- // Button to change the property
- w.addComponent(new Button("increase property value",
- new Button.ClickListener() {
- public void buttonClick(ClickEvent event) {
- Float currentValue = (Float) property.getValue();
- property.setValue(new Float(
- currentValue.floatValue() + 1.0));
- }
- }));
+ // Button to change the property
+ w.addComponent(new Button("increase property value",
+ new Button.ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ Float currentValue = (Float) property.getValue();
+ property.setValue(new Float(
+ currentValue.floatValue() + 1.0));
+ }
+ }));
- // Buffering
- w.addComponent(new Button("Write through enabled", new MethodProperty(
- text, "writeThrough")));
- w.addComponent(new Button("discard", new Button.ClickListener() {
- public void buttonClick(ClickEvent event) {
- text.discard();
- }
- }));
- w.addComponent(new Button("commit", new Button.ClickListener() {
- public void buttonClick(ClickEvent event) {
- text.commit();
- }
- }));
+ // Buffering
+ w.addComponent(new Button("Write through enabled", new MethodProperty(
+ text, "writeThrough")));
+ w.addComponent(new Button("discard", new Button.ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ text.discard();
+ }
+ }));
+ w.addComponent(new Button("commit", new Button.ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ text.commit();
+ }
+ }));
- // Restart button for application
- // (easier debugging when you dont have to restart the server to make
- // code changes)
- Button restart = new Button("restart", this, "close");
- restart.setStyle("link");
- w.addComponent(restart);
- }
+ // Restart button for application
+ // (easier debugging when you dont have to restart the server to
+ // make
+ // code changes)
+ Button restart = new Button("restart", this, "close");
+ restart.setStyle("link");
+ w.addComponent(restart);
+ }
}
diff --git a/src/com/itmill/toolkit/demo/CachingDemo.java b/src/com/itmill/toolkit/demo/CachingDemo.java
index 6b91a76174..4cc47719f5 100644
--- a/src/com/itmill/toolkit/demo/CachingDemo.java
+++ b/src/com/itmill/toolkit/demo/CachingDemo.java
@@ -19,45 +19,45 @@ import com.itmill.toolkit.ui.Window;
*/
public class CachingDemo extends com.itmill.toolkit.Application {
- public void init() {
-
- Window main = new Window("Client-side caching example");
- setMainWindow(main);
-
- setTheme("example");
-
- TabSheet ts = new TabSheet();
- main.addComponent(ts);
-
- Layout layout = new OrderedLayout();
- layout.setMargin(true);
- Label l = new Label(
- "This is a normal label, quick to render.
The second tab will be slow to render the first time, after that it will be as quick as this one.");
- l.setCaption("A normal label");
- l.setContentMode(Label.CONTENT_XHTML);
- layout.addComponent(l);
-
- ts.addTab(layout, "Normal", null);
-
- layout = new OrderedLayout();
- layout.setMargin(true);
- l = new Label(
- "The first time you change to this tab, this label is very slow to produce (server-side).
However, it will seem fast the second time you change to this tab, because it has not changed and is cached client-side.") {
- public void paintContent(PaintTarget target) throws PaintException {
- try {
- Thread.sleep(3000);
- } catch (Exception e) {
- // IGNORED
- }
- super.paintContent(target);
- }
-
- };
- l.setCaption("A slow label");
- l.setContentMode(Label.CONTENT_XHTML);
- layout.addComponent(l);
- ts.addTab(layout, "Slow", null);
-
- }
+ public void init() {
+
+ Window main = new Window("Client-side caching example");
+ setMainWindow(main);
+
+ setTheme("example");
+
+ TabSheet ts = new TabSheet();
+ main.addComponent(ts);
+
+ Layout layout = new OrderedLayout();
+ layout.setMargin(true);
+ Label l = new Label(
+ "This is a normal label, quick to render.
The second tab will be slow to render the first time, after that it will be as quick as this one.");
+ l.setCaption("A normal label");
+ l.setContentMode(Label.CONTENT_XHTML);
+ layout.addComponent(l);
+
+ ts.addTab(layout, "Normal", null);
+
+ layout = new OrderedLayout();
+ layout.setMargin(true);
+ l = new Label(
+ "The first time you change to this tab, this label is very slow to produce (server-side).
However, it will seem fast the second time you change to this tab, because it has not changed and is cached client-side.") {
+ public void paintContent(PaintTarget target) throws PaintException {
+ try {
+ Thread.sleep(3000);
+ } catch (Exception e) {
+ // IGNORED
+ }
+ super.paintContent(target);
+ }
+
+ };
+ l.setCaption("A slow label");
+ l.setContentMode(Label.CONTENT_XHTML);
+ layout.addComponent(l);
+ ts.addTab(layout, "Slow", null);
+
+ }
}
diff --git a/src/com/itmill/toolkit/demo/Calc.java b/src/com/itmill/toolkit/demo/Calc.java
index 7d57debc99..5a3788ac52 100644
--- a/src/com/itmill/toolkit/demo/Calc.java
+++ b/src/com/itmill/toolkit/demo/Calc.java
@@ -1,6 +1,9 @@
package com.itmill.toolkit.demo;
-import com.itmill.toolkit.ui.*;
+import com.itmill.toolkit.ui.Button;
+import com.itmill.toolkit.ui.GridLayout;
+import com.itmill.toolkit.ui.Label;
+import com.itmill.toolkit.ui.Window;
/**
*
@@ -20,103 +23,109 @@ import com.itmill.toolkit.ui.*;
* @see com.itmill.toolkit.ui.Button.ClickListener
*/
public class Calc extends com.itmill.toolkit.Application implements
- Button.ClickListener {
-
- /** The label used as the display */
- private Label display = null;
-
- /** Last completed result */
- private double stored = 0.0;
-
- /** The number being currently edited. */
- private double current = 0.0;
-
- /** Last activated operation. */
- private String operation = "C";
-
- /** Button captions. */
- private static String[] captions = // Captions for the buttons
- { "7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", "=",
- "C", "+" };
-
- /**
- *
- * Initializes the application. This is the only method an application is
- * required to implement. It's called by the framework and it should perform
- * whatever initialization tasks the application needs to perform.
- *
- *
- *
- * In this case we create the main window, the display, the grid to hold the
- * buttons, and the buttons themselves.
- *
- */
- public void init() {
-
- // Create a new layout for the components used by the calculator
- GridLayout layout = new GridLayout(4, 5);
-
- // Create a new label component for displaying the result
- display = new Label(Double.toString(current));
- display.setCaption("Result");
-
- // Place the label to the top of the previously created grid.
- layout.addComponent(display, 0, 0, 3, 0);
-
- // Create the buttons and place them in the grid
- for (int i = 0; i < captions.length; i++) {
- Button button = new Button(captions[i], this);
- layout.addComponent(button);
- }
-
- // Create the main window with a caption and add it to the application.
- addWindow(new Window("Calculator", layout));
-
- }
-
- /**
- *
- * The button listener method called any time a button is pressed. This
- * method catches all button presses, figures out what the user wanted the
- * application to do, and updates the UI accordingly.
- *
- *
- *
- * The button click event passed to this method contains information about
- * which button was pressed. If it was a number, the currently edited number
- * is updated. If it was something else, the requested operation is
- * performed. In either case the display label is updated to include the
- * outcome of the button click.
- *
- *
- * @param event
- * the button click event specifying which button was pressed
- */
- public void buttonClick(Button.ClickEvent event) {
-
- try {
- // Number button pressed
- current = current * 10
- + Double.parseDouble(event.getButton().getCaption());
- display.setValue(Double.toString(current));
- } catch (java.lang.NumberFormatException e) {
-
- // Operation button pressed
- if (operation.equals("+"))
- stored += current;
- if (operation.equals("-"))
- stored -= current;
- if (operation.equals("*"))
- stored *= current;
- if (operation.equals("/"))
- stored /= current;
- if (operation.equals("C"))
- stored = current;
- if (event.getButton().getCaption().equals("C"))
- stored = 0.0;
- operation = event.getButton().getCaption();
- current = 0.0;
- display.setValue(Double.toString(stored));
- }
- }
+ Button.ClickListener {
+
+ /** The label used as the display */
+ private Label display = null;
+
+ /** Last completed result */
+ private double stored = 0.0;
+
+ /** The number being currently edited. */
+ private double current = 0.0;
+
+ /** Last activated operation. */
+ private String operation = "C";
+
+ /** Button captions. */
+ private static String[] captions = // Captions for the buttons
+ { "7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", "=",
+ "C", "+" };
+
+ /**
+ *
+ * Initializes the application. This is the only method an application is
+ * required to implement. It's called by the framework and it should perform
+ * whatever initialization tasks the application needs to perform.
+ *
+ *
+ *
+ * In this case we create the main window, the display, the grid to hold the
+ * buttons, and the buttons themselves.
+ *
+ */
+ public void init() {
+
+ // Create a new layout for the components used by the calculator
+ GridLayout layout = new GridLayout(4, 5);
+
+ // Create a new label component for displaying the result
+ display = new Label(Double.toString(current));
+ display.setCaption("Result");
+
+ // Place the label to the top of the previously created grid.
+ layout.addComponent(display, 0, 0, 3, 0);
+
+ // Create the buttons and place them in the grid
+ for (int i = 0; i < captions.length; i++) {
+ Button button = new Button(captions[i], this);
+ layout.addComponent(button);
+ }
+
+ // Create the main window with a caption and add it to the application.
+ addWindow(new Window("Calculator", layout));
+
+ }
+
+ /**
+ *
+ * The button listener method called any time a button is pressed. This
+ * method catches all button presses, figures out what the user wanted the
+ * application to do, and updates the UI accordingly.
+ *
+ *
+ *
+ * The button click event passed to this method contains information about
+ * which button was pressed. If it was a number, the currently edited number
+ * is updated. If it was something else, the requested operation is
+ * performed. In either case the display label is updated to include the
+ * outcome of the button click.
+ *
+ *
+ * @param event
+ * the button click event specifying which button was pressed
+ */
+ public void buttonClick(Button.ClickEvent event) {
+
+ try {
+ // Number button pressed
+ current = current * 10
+ + Double.parseDouble(event.getButton().getCaption());
+ display.setValue(Double.toString(current));
+ } catch (java.lang.NumberFormatException e) {
+
+ // Operation button pressed
+ if (operation.equals("+")) {
+ stored += current;
+ }
+ if (operation.equals("-")) {
+ stored -= current;
+ }
+ if (operation.equals("*")) {
+ stored *= current;
+ }
+ if (operation.equals("/")) {
+ stored /= current;
+ }
+ if (operation.equals("C")) {
+ stored = current;
+ }
+ if (event.getButton().getCaption().equals("C")) {
+ stored = 0.0;
+ }
+ operation = event.getButton().getCaption();
+ current = 0.0;
+ display.setValue(Double.toString(stored));
+ }
+ }
}
diff --git a/src/com/itmill/toolkit/demo/CustomLayoutDemo.java b/src/com/itmill/toolkit/demo/CustomLayoutDemo.java
index 6035fdc0cc..0bf256b409 100644
--- a/src/com/itmill/toolkit/demo/CustomLayoutDemo.java
+++ b/src/com/itmill/toolkit/demo/CustomLayoutDemo.java
@@ -1,6 +1,13 @@
package com.itmill.toolkit.demo;
-import com.itmill.toolkit.ui.*;
+import com.itmill.toolkit.ui.Button;
+import com.itmill.toolkit.ui.CustomLayout;
+import com.itmill.toolkit.ui.Field;
+import com.itmill.toolkit.ui.Label;
+import com.itmill.toolkit.ui.Panel;
+import com.itmill.toolkit.ui.TextField;
+import com.itmill.toolkit.ui.Tree;
+import com.itmill.toolkit.ui.Window;
import com.itmill.toolkit.ui.Component.Event;
import com.itmill.toolkit.ui.Component.Listener;
@@ -18,110 +25,111 @@ import com.itmill.toolkit.ui.Component.Listener;
*
*/
public class CustomLayoutDemo extends com.itmill.toolkit.Application implements
- Listener {
-
- private CustomLayout mainLayout = null;
-
- private Panel bodyPanel = new Panel();
-
- private TextField username = new TextField("Username");
-
- private TextField loginPwd = new TextField("Password");
-
- private Button loginButton = new Button("Login", this, "loginClicked");
-
- private Tree menu = new Tree();
-
- /**
- * Initialize Application. Demo components are added to main window.
- */
- public void init() {
- Window mainWindow = new Window("CustomLayout demo");
- setMainWindow(mainWindow);
-
- // set the application to use example -theme
- setTheme("example");
-
- // Create custom layout, themes/example/layout/mainLayout.html
- mainLayout = new CustomLayout("mainLayout");
- // wrap custom layout inside a panel
- Panel customLayoutPanel = new Panel(
- "Panel containing custom layout (mainLayout.html)");
- customLayoutPanel.addComponent(mainLayout);
-
- // Login components
- loginPwd.setSecret(true);
- mainLayout.addComponent(username, "loginUser");
- mainLayout.addComponent(loginPwd, "loginPassword");
- mainLayout.addComponent(loginButton, "loginButton");
-
- // Menu component, when clicked bodyPanel is updated
- menu.addItem("Welcome");
- menu.addItem("Products");
- menu.addItem("Support");
- menu.addItem("News");
- menu.addItem("Developers");
- menu.addItem("Contact");
- // "this" handles all menu events, e.g. node clicked event
- menu.addListener((Listener) this);
- // Value changes are immediate
- menu.setImmediate(true);
- menu.setNullSelectionAllowed(false);
- mainLayout.addComponent(menu, "menu");
-
- // Body component
- mainLayout.addComponent(bodyPanel, "body");
-
- // Initial body are comes from Welcome.html
- setBody("Welcome");
-
- // Add heading label and custom layout panel to main window
- mainWindow.addComponent(new Label("Custom layout demo
",
- Label.CONTENT_XHTML));
- mainWindow.addComponent(customLayoutPanel);
- }
-
- /**
- * Login button clicked. Hide login components and replace username
- * component with "Welcome user Username" message.
- *
- */
- public void loginClicked() {
- username.setVisible(false);
- loginPwd.setVisible(false);
- if (username.getValue().toString().length() < 1)
- username.setValue("Anonymous");
- mainLayout.replaceComponent(loginButton, new Label("Welcome user "
- + username.getValue() + "", Label.CONTENT_XHTML));
- }
-
- /**
- * Set body panel caption, remove all existing components and add given
- * custom layout in it.
- *
- */
- public void setBody(String customLayout) {
- bodyPanel.setCaption(customLayout + ".html");
- bodyPanel.removeAllComponents();
- bodyPanel.addComponent(new CustomLayout(customLayout));
- }
-
- /**
- * Handle all menu events. Updates body panel contents if menu item is
- * clicked.
- */
- public void componentEvent(Event event) {
- // Check if event occured at fsTree component
- if (event.getSource() == menu) {
- // Check if event is about changing value
- if (event.getClass() == Field.ValueChangeEvent.class) {
- // Update body area with selected item
- setBody(menu.getValue().toString());
- }
- // here we could check for other type of events for tree
- // component
- }
- // here we could check for other component's events
- }
+ Listener {
+
+ private CustomLayout mainLayout = null;
+
+ private Panel bodyPanel = new Panel();
+
+ private TextField username = new TextField("Username");
+
+ private TextField loginPwd = new TextField("Password");
+
+ private Button loginButton = new Button("Login", this, "loginClicked");
+
+ private Tree menu = new Tree();
+
+ /**
+ * Initialize Application. Demo components are added to main window.
+ */
+ public void init() {
+ Window mainWindow = new Window("CustomLayout demo");
+ setMainWindow(mainWindow);
+
+ // set the application to use example -theme
+ setTheme("example");
+
+ // Create custom layout, themes/example/layout/mainLayout.html
+ mainLayout = new CustomLayout("mainLayout");
+ // wrap custom layout inside a panel
+ Panel customLayoutPanel = new Panel(
+ "Panel containing custom layout (mainLayout.html)");
+ customLayoutPanel.addComponent(mainLayout);
+
+ // Login components
+ loginPwd.setSecret(true);
+ mainLayout.addComponent(username, "loginUser");
+ mainLayout.addComponent(loginPwd, "loginPassword");
+ mainLayout.addComponent(loginButton, "loginButton");
+
+ // Menu component, when clicked bodyPanel is updated
+ menu.addItem("Welcome");
+ menu.addItem("Products");
+ menu.addItem("Support");
+ menu.addItem("News");
+ menu.addItem("Developers");
+ menu.addItem("Contact");
+ // "this" handles all menu events, e.g. node clicked event
+ menu.addListener(this);
+ // Value changes are immediate
+ menu.setImmediate(true);
+ menu.setNullSelectionAllowed(false);
+ mainLayout.addComponent(menu, "menu");
+
+ // Body component
+ mainLayout.addComponent(bodyPanel, "body");
+
+ // Initial body are comes from Welcome.html
+ setBody("Welcome");
+
+ // Add heading label and custom layout panel to main window
+ mainWindow.addComponent(new Label("Custom layout demo
",
+ Label.CONTENT_XHTML));
+ mainWindow.addComponent(customLayoutPanel);
+ }
+
+ /**
+ * Login button clicked. Hide login components and replace username
+ * component with "Welcome user Username" message.
+ *
+ */
+ public void loginClicked() {
+ username.setVisible(false);
+ loginPwd.setVisible(false);
+ if (username.getValue().toString().length() < 1) {
+ username.setValue("Anonymous");
+ }
+ mainLayout.replaceComponent(loginButton, new Label("Welcome user "
+ + username.getValue() + "", Label.CONTENT_XHTML));
+ }
+
+ /**
+ * Set body panel caption, remove all existing components and add given
+ * custom layout in it.
+ *
+ */
+ public void setBody(String customLayout) {
+ bodyPanel.setCaption(customLayout + ".html");
+ bodyPanel.removeAllComponents();
+ bodyPanel.addComponent(new CustomLayout(customLayout));
+ }
+
+ /**
+ * Handle all menu events. Updates body panel contents if menu item is
+ * clicked.
+ */
+ public void componentEvent(Event event) {
+ // Check if event occured at fsTree component
+ if (event.getSource() == menu) {
+ // Check if event is about changing value
+ if (event.getClass() == Field.ValueChangeEvent.class) {
+ // Update body area with selected item
+ setBody(menu.getValue().toString());
+ }
+ // here we could check for other type of events for tree
+ // component
+ }
+ // here we could check for other component's events
+ }
}
diff --git a/src/com/itmill/toolkit/demo/FilterSelect.java b/src/com/itmill/toolkit/demo/FilterSelect.java
index 8abda479a2..5d0136fc40 100644
--- a/src/com/itmill/toolkit/demo/FilterSelect.java
+++ b/src/com/itmill/toolkit/demo/FilterSelect.java
@@ -4,6 +4,7 @@ import com.itmill.toolkit.ui.OrderedLayout;
import com.itmill.toolkit.ui.Panel;
import com.itmill.toolkit.ui.Select;
import com.itmill.toolkit.ui.Window;
+import com.itmill.toolkit.ui.AbstractSelect.Filtering;
/**
* The classic "hello, world!" example for IT Mill Toolkit. The class simply
@@ -17,77 +18,77 @@ import com.itmill.toolkit.ui.Window;
*/
public class FilterSelect extends com.itmill.toolkit.Application {
- private static final String[] firstnames = new String[] { "John", "Mary",
- "Joe", "Sarah", "Jeff", "Jane", "Peter", "Marc", "Robert", "Paula",
- "Lenny", "Kenny", "Nathan", "Nicole", "Laura", "Jos", "Josie",
- "Linus" };
+ private static final String[] firstnames = new String[] { "John", "Mary",
+ "Joe", "Sarah", "Jeff", "Jane", "Peter", "Marc", "Robert", "Paula",
+ "Lenny", "Kenny", "Nathan", "Nicole", "Laura", "Jos", "Josie",
+ "Linus" };
- private static final String[] lastnames = new String[] { "Torvalds",
- "Smith", "Adams", "Black", "Wilson", "Richards", "Thompson",
- "McGoff", "Halas", "Jones", "Beck", "Sheridan", "Picard", "Hill",
- "Fielding", "Einstein" };
+ private static final String[] lastnames = new String[] { "Torvalds",
+ "Smith", "Adams", "Black", "Wilson", "Richards", "Thompson",
+ "McGoff", "Halas", "Jones", "Beck", "Sheridan", "Picard", "Hill",
+ "Fielding", "Einstein" };
- /**
- * The initialization method that is the only requirement for inheriting the
- * com.itmill.toolkit.service.Application class. It will be automatically
- * called by the framework when a user accesses the application.
- */
- public void init() {
+ /**
+ * The initialization method that is the only requirement for inheriting the
+ * com.itmill.toolkit.service.Application class. It will be automatically
+ * called by the framework when a user accesses the application.
+ */
+ public void init() {
- /*
- * - Create new window for the application - Give the window a visible
- * title - Set the window to be the main window of the application
- */
- Window main = new Window("Filter select demo");
- setMainWindow(main);
+ /*
+ * - Create new window for the application - Give the window a visible
+ * title - Set the window to be the main window of the application
+ */
+ Window main = new Window("Filter select demo");
+ setMainWindow(main);
- // default filter
- Select s1 = new Select();
- for (int i = 0; i < 105; i++) {
- s1
- .addItem(firstnames[(int) (Math.random() * (firstnames.length - 1))]
- + " "
- + lastnames[(int) (Math.random() * (lastnames.length - 1))]);
- }
- s1.setImmediate(true);
+ // default filter
+ Select s1 = new Select();
+ for (int i = 0; i < 105; i++) {
+ s1
+ .addItem(firstnames[(int) (Math.random() * (firstnames.length - 1))]
+ + " "
+ + lastnames[(int) (Math.random() * (lastnames.length - 1))]);
+ }
+ s1.setImmediate(true);
- // contains filter
- Select s2 = new Select();
- for (int i = 0; i < 500; i++) {
- s2
- .addItem(firstnames[(int) (Math.random() * (firstnames.length - 1))]
- + " "
- + lastnames[(int) (Math.random() * (lastnames.length - 1))]);
- }
- s2.setFilteringMode(Select.FILTERINGMODE_CONTAINS);
+ // contains filter
+ Select s2 = new Select();
+ for (int i = 0; i < 500; i++) {
+ s2
+ .addItem(firstnames[(int) (Math.random() * (firstnames.length - 1))]
+ + " "
+ + lastnames[(int) (Math.random() * (lastnames.length - 1))]);
+ }
+ s2.setFilteringMode(Filtering.FILTERINGMODE_CONTAINS);
- // startswith filter
- Select s3 = new Select();
- for (int i = 0; i < 500; i++) {
- s3
- .addItem(firstnames[(int) (Math.random() * (firstnames.length - 1))]
- + " "
- + lastnames[(int) (Math.random() * (lastnames.length - 1))]);
- }
- s3.setFilteringMode(Select.FILTERINGMODE_STARTSWITH);
+ // startswith filter
+ Select s3 = new Select();
+ for (int i = 0; i < 500; i++) {
+ s3
+ .addItem(firstnames[(int) (Math.random() * (firstnames.length - 1))]
+ + " "
+ + lastnames[(int) (Math.random() * (lastnames.length - 1))]);
+ }
+ s3.setFilteringMode(Filtering.FILTERINGMODE_STARTSWITH);
- // Add selects to UI using ordered layout and panels
- OrderedLayout orderedLayout = new OrderedLayout(
- OrderedLayout.ORIENTATION_HORIZONTAL);
+ // Add selects to UI using ordered layout and panels
+ OrderedLayout orderedLayout = new OrderedLayout(
+ OrderedLayout.ORIENTATION_HORIZONTAL);
- Panel panel1 = new Panel("Select with default filter");
- Panel panel2 = new Panel("Select with contains filter");
- Panel panel3 = new Panel("Select with custom 'EndsWith' filter");
+ Panel panel1 = new Panel("Select with default filter");
+ Panel panel2 = new Panel("Select with contains filter");
+ Panel panel3 = new Panel("Select with custom 'EndsWith' filter");
- panel1.addComponent(s1);
- panel2.addComponent(s2);
- panel3.addComponent(s3);
+ panel1.addComponent(s1);
+ panel2.addComponent(s2);
+ panel3.addComponent(s3);
- orderedLayout.addComponent(panel1);
- orderedLayout.addComponent(panel2);
- orderedLayout.addComponent(panel3);
- main.addComponent(orderedLayout);
+ orderedLayout.addComponent(panel1);
+ orderedLayout.addComponent(panel2);
+ orderedLayout.addComponent(panel3);
+ main.addComponent(orderedLayout);
- }
+ }
}
diff --git a/src/com/itmill/toolkit/demo/HelloWorld.java b/src/com/itmill/toolkit/demo/HelloWorld.java
index d4ab04e486..ace0e95913 100644
--- a/src/com/itmill/toolkit/demo/HelloWorld.java
+++ b/src/com/itmill/toolkit/demo/HelloWorld.java
@@ -1,6 +1,7 @@
package com.itmill.toolkit.demo;
-import com.itmill.toolkit.ui.*;
+import com.itmill.toolkit.ui.Label;
+import com.itmill.toolkit.ui.Window;
/**
* The classic "hello, world!" example for IT Mill Toolkit. The class simply
@@ -14,29 +15,29 @@ import com.itmill.toolkit.ui.*;
*/
public class HelloWorld extends com.itmill.toolkit.Application {
- /**
- * The initialization method that is the only requirement for inheriting the
- * com.itmill.toolkit.service.Application class. It will be automatically
- * called by the framework when a user accesses the application.
- */
- public void init() {
+ /**
+ * The initialization method that is the only requirement for inheriting the
+ * com.itmill.toolkit.service.Application class. It will be automatically
+ * called by the framework when a user accesses the application.
+ */
+ public void init() {
- /*
- * - Create new window for the application - Give the window a visible
- * title - Set the window to be the main window of the application
- */
- Window main = new Window("Hello window");
- setMainWindow(main);
+ /*
+ * - Create new window for the application - Give the window a visible
+ * title - Set the window to be the main window of the application
+ */
+ Window main = new Window("Hello window");
+ setMainWindow(main);
- /*
- * - Create a label with the classic text - Add the label to the main
- * window
- */
- main.addComponent(new Label("Hello World!"));
+ /*
+ * - Create a label with the classic text - Add the label to the main
+ * window
+ */
+ main.addComponent(new Label("Hello World!"));
- /*
- * And that's it! The framework will display the main window and its
- * contents when the application is accessed with the terminal.
- */
- }
+ /*
+ * And that's it! The framework will display the main window and its
+ * contents when the application is accessed with the terminal.
+ */
+ }
}
diff --git a/src/com/itmill/toolkit/demo/KeyboardShortcut.java b/src/com/itmill/toolkit/demo/KeyboardShortcut.java
index e5170b7758..34aeaf779b 100644
--- a/src/com/itmill/toolkit/demo/KeyboardShortcut.java
+++ b/src/com/itmill/toolkit/demo/KeyboardShortcut.java
@@ -3,7 +3,11 @@ package com.itmill.toolkit.demo;
import com.itmill.toolkit.event.Action;
import com.itmill.toolkit.event.ShortcutAction;
import com.itmill.toolkit.event.Action.Handler;
-import com.itmill.toolkit.ui.*;
+import com.itmill.toolkit.ui.AbstractField;
+import com.itmill.toolkit.ui.Button;
+import com.itmill.toolkit.ui.Label;
+import com.itmill.toolkit.ui.TextField;
+import com.itmill.toolkit.ui.Window;
/**
* Note: This feature is under development and is considered as beta
@@ -12,98 +16,102 @@ import com.itmill.toolkit.ui.*;
*
*/
public class KeyboardShortcut extends com.itmill.toolkit.Application implements
- Handler {
- private Window main;
-
- private Button a;
-
- private Button z;
-
- private Button x;
-
- private Button close;
-
- private AbstractField f;
-
- Action[] actions = new Action[] {
- new ShortcutAction("Button a action", ShortcutAction.KeyCode.A,
- new int[] { ShortcutAction.ModifierKey.CTRL,
- ShortcutAction.ModifierKey.SHIFT }),
- new ShortcutAction("Button z action", ShortcutAction.KeyCode.Z,
- new int[] { ShortcutAction.ModifierKey.CTRL,
- ShortcutAction.ModifierKey.SHIFT }),
- new ShortcutAction("Button x action", ShortcutAction.KeyCode.X,
- new int[] { ShortcutAction.ModifierKey.CTRL,
- ShortcutAction.ModifierKey.SHIFT }),
- new ShortcutAction("Restart ", ShortcutAction.KeyCode.ESCAPE, null) };
-
- public void init() {
-
- main = new Window("Keyboard shortcuts demo");
- setMainWindow(main);
-
- main
- .addComponent(new Label(
- "Test application for shortcut actions
"
- + "Notes:
"
- + "This feature is under development and it's API may still change.
"
- + "If events do not work, set focus to Textfield first.
"
- + "Browsers may have reserved the keyboard combinations used in "
- + "this demo for other purposes.
",
- Label.CONTENT_XHTML));
- main
- .addComponent(new Label(
- "ESC restarts program, ctrl-shift-a clicks A button, "
- + "ctrl-shift-z clicks Z button, ctrl-shift-x clicks X button"));
-
- // Restart button
- close = new Button("restart", this, "close");
-
- main.addComponent(close);
-
- a = new Button("Button A", this, "buttonAHandler");
-
- z = new Button("Button Z", this, "buttonZHandler");
-
- x = new Button("Button X", this, "buttonXHandler");
-
- f = new TextField("Textfield");
-
- main.addComponent(a);
- main.addComponent(z);
- main.addComponent(x);
- main.addComponent(f);
-
- main.addActionHandler(this);
-
- f.focus();
- }
-
- public Action[] getActions(Object target, Object sender) {
- return actions;
- }
-
- public void handleAction(Action action, Object sender, Object target) {
- if (action == actions[0])
- this.buttonAHandler();
- if (action == actions[1])
- this.buttonZHandler();
- if (action == actions[2])
- this.buttonXHandler();
- if (action == actions[3])
- this.close();
- }
-
- public void buttonAHandler() {
- main.addComponent(new Label("Button A handler fired"));
- }
-
- public void buttonZHandler() {
- main.addComponent(new Label("Button Z handler fired"));
- }
-
- public void buttonXHandler() {
- main.addComponent(new Label("Button X handler fired"));
- }
+ Handler {
+ private Window main;
+
+ private Button a;
+
+ private Button z;
+
+ private Button x;
+
+ private Button close;
+
+ private AbstractField f;
+
+ Action[] actions = new Action[] {
+ new ShortcutAction("Button a action", ShortcutAction.KeyCode.A,
+ new int[] { ShortcutAction.ModifierKey.CTRL,
+ ShortcutAction.ModifierKey.SHIFT }),
+ new ShortcutAction("Button z action", ShortcutAction.KeyCode.Z,
+ new int[] { ShortcutAction.ModifierKey.CTRL,
+ ShortcutAction.ModifierKey.SHIFT }),
+ new ShortcutAction("Button x action", ShortcutAction.KeyCode.X,
+ new int[] { ShortcutAction.ModifierKey.CTRL,
+ ShortcutAction.ModifierKey.SHIFT }),
+ new ShortcutAction("Restart ", ShortcutAction.KeyCode.ESCAPE, null) };
+
+ public void init() {
+
+ main = new Window("Keyboard shortcuts demo");
+ setMainWindow(main);
+
+ main
+ .addComponent(new Label(
+ "Test application for shortcut actions
"
+ + "Notes:
"
+ + "This feature is under development and it's API may still change.
"
+ + "If events do not work, set focus to Textfield first.
"
+ + "Browsers may have reserved the keyboard combinations used in "
+ + "this demo for other purposes.
",
+ Label.CONTENT_XHTML));
+ main
+ .addComponent(new Label(
+ "ESC restarts program, ctrl-shift-a clicks A button, "
+ + "ctrl-shift-z clicks Z button, ctrl-shift-x clicks X button"));
+
+ // Restart button
+ close = new Button("restart", this, "close");
+
+ main.addComponent(close);
+
+ a = new Button("Button A", this, "buttonAHandler");
+
+ z = new Button("Button Z", this, "buttonZHandler");
+
+ x = new Button("Button X", this, "buttonXHandler");
+
+ f = new TextField("Textfield");
+
+ main.addComponent(a);
+ main.addComponent(z);
+ main.addComponent(x);
+ main.addComponent(f);
+
+ main.addActionHandler(this);
+
+ f.focus();
+ }
+
+ public Action[] getActions(Object target, Object sender) {
+ return actions;
+ }
+
+ public void handleAction(Action action, Object sender, Object target) {
+ if (action == actions[0]) {
+ buttonAHandler();
+ }
+ if (action == actions[1]) {
+ buttonZHandler();
+ }
+ if (action == actions[2]) {
+ buttonXHandler();
+ }
+ if (action == actions[3]) {
+ close();
+ }
+ }
+
+ public void buttonAHandler() {
+ main.addComponent(new Label("Button A handler fired"));
+ }
+
+ public void buttonZHandler() {
+ main.addComponent(new Label("Button Z handler fired"));
+ }
+
+ public void buttonXHandler() {
+ main.addComponent(new Label("Button X handler fired"));
+ }
}
diff --git a/src/com/itmill/toolkit/demo/LayoutDemo.java b/src/com/itmill/toolkit/demo/LayoutDemo.java
index bb73a25250..60b6c02aef 100644
--- a/src/com/itmill/toolkit/demo/LayoutDemo.java
+++ b/src/com/itmill/toolkit/demo/LayoutDemo.java
@@ -1,7 +1,15 @@
package com.itmill.toolkit.demo;
import com.itmill.toolkit.terminal.ClassResource;
-import com.itmill.toolkit.ui.*;
+import com.itmill.toolkit.ui.Component;
+import com.itmill.toolkit.ui.Embedded;
+import com.itmill.toolkit.ui.GridLayout;
+import com.itmill.toolkit.ui.Label;
+import com.itmill.toolkit.ui.Layout;
+import com.itmill.toolkit.ui.OrderedLayout;
+import com.itmill.toolkit.ui.Panel;
+import com.itmill.toolkit.ui.TabSheet;
+import com.itmill.toolkit.ui.Window;
/**
* This example demonstrates layouts. Layouts are populated with sample Toolkit
@@ -13,123 +21,123 @@ import com.itmill.toolkit.ui.*;
*/
public class LayoutDemo extends com.itmill.toolkit.Application {
- /**
- * Initialize Application. Demo components are added to main window.
- */
- public void init() {
- Window mainWindow = new Window("Layout demo");
- setMainWindow(mainWindow);
+ /**
+ * Initialize Application. Demo components are added to main window.
+ */
+ public void init() {
+ Window mainWindow = new Window("Layout demo");
+ setMainWindow(mainWindow);
- //
- // Create horizontal ordered layout
- //
- OrderedLayout layoutA = new OrderedLayout(
- OrderedLayout.ORIENTATION_HORIZONTAL);
- // Add 4 panels
- fillLayout(layoutA, 4);
+ //
+ // Create horizontal ordered layout
+ //
+ OrderedLayout layoutA = new OrderedLayout(
+ OrderedLayout.ORIENTATION_HORIZONTAL);
+ // Add 4 panels
+ fillLayout(layoutA, 4);
- //
- // Create vertical ordered layout
- //
- OrderedLayout layoutB = new OrderedLayout(
- OrderedLayout.ORIENTATION_VERTICAL);
- // Add 4 panels
- fillLayout(layoutB, 4);
+ //
+ // Create vertical ordered layout
+ //
+ OrderedLayout layoutB = new OrderedLayout(
+ OrderedLayout.ORIENTATION_VERTICAL);
+ // Add 4 panels
+ fillLayout(layoutB, 4);
- //
- // Create grid layout
- //
- GridLayout layoutG = new GridLayout(4, 4);
- // Add 16 panels components
- fillLayout(layoutG, 16);
+ //
+ // Create grid layout
+ //
+ GridLayout layoutG = new GridLayout(4, 4);
+ // Add 16 panels components
+ fillLayout(layoutG, 16);
- //
- // Create grid layout
- //
- GridLayout layoutG2 = new GridLayout(4, 4);
- // Add 4 panels with absolute coordinates (diagonally)
- layoutG2.addComponent(getExampleComponent("x=0, y=0"), 0, 0);
- layoutG2.addComponent(getExampleComponent("x=1, y=1"), 1, 1);
- layoutG2.addComponent(getExampleComponent("x=2, y=2"), 2, 2);
- layoutG2.addComponent(getExampleComponent("x=3, y=3"), 3, 3);
- // Add 4 pictures with absolute coordinates (diagonally)
- layoutG2.addComponent(getExamplePicture("x=3, y=0"), 3, 0);
- layoutG2.addComponent(getExamplePicture("x=2, y=1"), 2, 1);
- layoutG2.addComponent(getExamplePicture("x=1, y=2"), 1, 2);
- layoutG2.addComponent(getExamplePicture("x=0, y=3"), 0, 3);
+ //
+ // Create grid layout
+ //
+ GridLayout layoutG2 = new GridLayout(4, 4);
+ // Add 4 panels with absolute coordinates (diagonally)
+ layoutG2.addComponent(getExampleComponent("x=0, y=0"), 0, 0);
+ layoutG2.addComponent(getExampleComponent("x=1, y=1"), 1, 1);
+ layoutG2.addComponent(getExampleComponent("x=2, y=2"), 2, 2);
+ layoutG2.addComponent(getExampleComponent("x=3, y=3"), 3, 3);
+ // Add 4 pictures with absolute coordinates (diagonally)
+ layoutG2.addComponent(getExamplePicture("x=3, y=0"), 3, 0);
+ layoutG2.addComponent(getExamplePicture("x=2, y=1"), 2, 1);
+ layoutG2.addComponent(getExamplePicture("x=1, y=2"), 1, 2);
+ layoutG2.addComponent(getExamplePicture("x=0, y=3"), 0, 3);
- //
- // Create TabSheet
- //
- TabSheet tabsheet = new TabSheet();
- tabsheet
- .setCaption("Tabsheet, above layouts are added to this component");
- tabsheet.addTab(layoutA, "Horizontal ordered layout", null);
- tabsheet.addTab(layoutB, "Vertical ordered layout", null);
- tabsheet.addTab(layoutG, "First grid layout", null);
- tabsheet.addTab(layoutG2, "Second grid layout", null);
+ //
+ // Create TabSheet
+ //
+ TabSheet tabsheet = new TabSheet();
+ tabsheet
+ .setCaption("Tabsheet, above layouts are added to this component");
+ tabsheet.addTab(layoutA, "Horizontal ordered layout", null);
+ tabsheet.addTab(layoutB, "Vertical ordered layout", null);
+ tabsheet.addTab(layoutG, "First grid layout", null);
+ tabsheet.addTab(layoutG2, "Second grid layout", null);
- //
- // Add demo layouts to main window
- //
- mainWindow.addComponent(new Label(
- "Horizontal ordered layout
Added four components.",
- Label.CONTENT_XHTML));
- mainWindow.addComponent(layoutA);
- mainWindow.addComponent(new Label(
- "
Vertical ordered layout
Added four components.",
- Label.CONTENT_XHTML));
- mainWindow.addComponent(layoutB);
- mainWindow.addComponent(new Label(
- "
Grid Layout (4 x 4)
Added 16 components.",
- Label.CONTENT_XHTML));
- mainWindow.addComponent(layoutG);
- mainWindow
- .addComponent(new Label("
Grid Layout (4 x 4)
"
- + "Added four panels and four embedded components "
- + "diagonally with absolute coordinates.",
- Label.CONTENT_XHTML));
- mainWindow.addComponent(layoutG2);
- mainWindow.addComponent(new Label(
- "
TabSheet
Added above layouts as tabs.",
- Label.CONTENT_XHTML));
- mainWindow.addComponent(tabsheet);
+ //
+ // Add demo layouts to main window
+ //
+ mainWindow.addComponent(new Label(
+ "Horizontal ordered layout
Added four components.",
+ Label.CONTENT_XHTML));
+ mainWindow.addComponent(layoutA);
+ mainWindow.addComponent(new Label(
+ "
Vertical ordered layout
Added four components.",
+ Label.CONTENT_XHTML));
+ mainWindow.addComponent(layoutB);
+ mainWindow.addComponent(new Label(
+ "
Grid Layout (4 x 4)
Added 16 components.",
+ Label.CONTENT_XHTML));
+ mainWindow.addComponent(layoutG);
+ mainWindow
+ .addComponent(new Label("
Grid Layout (4 x 4)
"
+ + "Added four panels and four embedded components "
+ + "diagonally with absolute coordinates.",
+ Label.CONTENT_XHTML));
+ mainWindow.addComponent(layoutG2);
+ mainWindow.addComponent(new Label(
+ "
TabSheet
Added above layouts as tabs.",
+ Label.CONTENT_XHTML));
+ mainWindow.addComponent(tabsheet);
- }
+ }
- private Component getExamplePicture(String caption) {
- ClassResource cr = new ClassResource("features/m-bullet-blue.gif", this);
- Embedded em = new Embedded("Embedded " + caption, cr);
- em.setWidth(170);
- return em;
- }
+ private Component getExamplePicture(String caption) {
+ ClassResource cr = new ClassResource("features/m-bullet-blue.gif", this);
+ Embedded em = new Embedded("Embedded " + caption, cr);
+ em.setWidth(170);
+ return em;
+ }
- private Component getExampleComponent(String caption) {
- Panel panel = new Panel();
- panel.setCaption("Panel component " + caption);
- panel
- .addComponent(new Label(
- "Panel is a container for other components, by default it draws a frame around it's "
- + "extremities and may have a caption to clarify the nature of the contained components' purpose."
- + " Panel contains an layout where the actual contained components are added, "
- + "this layout may be switched on the fly.",
- Label.CONTENT_XHTML));
- panel.setWidth(222);
- return panel;
- }
+ private Component getExampleComponent(String caption) {
+ Panel panel = new Panel();
+ panel.setCaption("Panel component " + caption);
+ panel
+ .addComponent(new Label(
+ "Panel is a container for other components, by default it draws a frame around it's "
+ + "extremities and may have a caption to clarify the nature of the contained components' purpose."
+ + " Panel contains an layout where the actual contained components are added, "
+ + "this layout may be switched on the fly.",
+ Label.CONTENT_XHTML));
+ panel.setWidth(222);
+ return panel;
+ }
- /**
- * Add multiple demo component to given layout.
- *
- * @param layout
- * where components are added
- * @param numberOfComponents
- * to add
- */
- private void fillLayout(Layout layout, int numberOfComponents) {
- for (int i = 1; i <= numberOfComponents; i++) {
- layout.addComponent(getExampleComponent(Integer.toString(i)));
- }
- }
+ /**
+ * Add multiple demo component to given layout.
+ *
+ * @param layout
+ * where components are added
+ * @param numberOfComponents
+ * to add
+ */
+ private void fillLayout(Layout layout, int numberOfComponents) {
+ for (int i = 1; i <= numberOfComponents; i++) {
+ layout.addComponent(getExampleComponent(Integer.toString(i)));
+ }
+ }
}
diff --git a/src/com/itmill/toolkit/demo/ModalWindow.java b/src/com/itmill/toolkit/demo/ModalWindow.java
index 8b27faa011..6ba1cf9a1f 100644
--- a/src/com/itmill/toolkit/demo/ModalWindow.java
+++ b/src/com/itmill/toolkit/demo/ModalWindow.java
@@ -1,7 +1,10 @@
package com.itmill.toolkit.demo;
import com.itmill.toolkit.event.Action;
-import com.itmill.toolkit.ui.*;
+import com.itmill.toolkit.ui.Button;
+import com.itmill.toolkit.ui.Label;
+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;
@@ -16,64 +19,64 @@ import com.itmill.toolkit.ui.Button.ClickListener;
* @see com.itmill.toolkit.ui.Label
*/
public class ModalWindow extends com.itmill.toolkit.Application implements
- Action.Handler, ClickListener {
-
- private Window test;
-
- public void init() {
-
- // Create main window
- Window main = new Window("ModalWindow demo");
- setMainWindow(main);
- main.addComponent(new Label("ModalWindow demo"));
-
- // Main window textfield
- TextField f = new TextField();
- f.setTabIndex(1);
- main.addComponent(f);
-
- // Main window button
- Button b = new Button("Button on main window");
- b.addListener(this);
- b.setTabIndex(2);
- main.addComponent(b);
-
- // Modal window
- test = new Window("Modal window");
- test.setStyle("modal");
- this.addWindow(test);
- test.addComponent(new Label(
- "You have to close this window before accessing others."));
-
- // Textfield for modal window
- f = new TextField();
- f.setTabIndex(4);
- test.addComponent(f);
- f.focus();
-
- // Modal window button
- b = new Button("Button on modal window");
- b.setTabIndex(3);
- b.addListener(this);
- test.addComponent(b);
-
- }
-
- public Action[] getActions(Object target, Object sender) {
- Action actionA = new Action("Action A for " + target.toString());
- Action actionB = new Action("Action B for " + target.toString());
- Action[] actions = new Action[] { actionA, actionB };
- return actions;
- }
-
- public void handleAction(Action action, Object sender, Object target) {
- this.test.addComponent(new Label(action.getCaption() + " clicked on "
- + target));
-
- }
-
- public void buttonClick(ClickEvent event) {
- this.test.addComponent(new Label("Clicked " + event));
-
- }
+ Action.Handler, ClickListener {
+
+ private Window test;
+
+ public void init() {
+
+ // Create main window
+ Window main = new Window("ModalWindow demo");
+ setMainWindow(main);
+ main.addComponent(new Label("ModalWindow demo"));
+
+ // Main window textfield
+ TextField f = new TextField();
+ f.setTabIndex(1);
+ main.addComponent(f);
+
+ // Main window button
+ Button b = new Button("Button on main window");
+ b.addListener(this);
+ b.setTabIndex(2);
+ main.addComponent(b);
+
+ // Modal window
+ test = new Window("Modal window");
+ test.setStyle("modal");
+ addWindow(test);
+ test.addComponent(new Label(
+ "You have to close this window before accessing others."));
+
+ // Textfield for modal window
+ f = new TextField();
+ f.setTabIndex(4);
+ test.addComponent(f);
+ f.focus();
+
+ // Modal window button
+ b = new Button("Button on modal window");
+ b.setTabIndex(3);
+ b.addListener(this);
+ test.addComponent(b);
+
+ }
+
+ public Action[] getActions(Object target, Object sender) {
+ Action actionA = new Action("Action A for " + target.toString());
+ Action actionB = new Action("Action B for " + target.toString());
+ Action[] actions = new Action[] { actionA, actionB };
+ return actions;
+ }
+
+ public void handleAction(Action action, Object sender, Object target) {
+ test.addComponent(new Label(action.getCaption() + " clicked on "
+ + target));
+
+ }
+
+ public void buttonClick(ClickEvent event) {
+ test.addComponent(new Label("Clicked " + event));
+
+ }
}
diff --git a/src/com/itmill/toolkit/demo/NotificationDemo.java b/src/com/itmill/toolkit/demo/NotificationDemo.java
index 5820b09da0..e7a0dcb7e4 100644
--- a/src/com/itmill/toolkit/demo/NotificationDemo.java
+++ b/src/com/itmill/toolkit/demo/NotificationDemo.java
@@ -1,10 +1,10 @@
package com.itmill.toolkit.demo;
import com.itmill.toolkit.data.Item;
+import com.itmill.toolkit.ui.AbstractSelect;
import com.itmill.toolkit.ui.Button;
import com.itmill.toolkit.ui.NativeSelect;
import com.itmill.toolkit.ui.RichTextArea;
-import com.itmill.toolkit.ui.Select;
import com.itmill.toolkit.ui.TextField;
import com.itmill.toolkit.ui.Window;
import com.itmill.toolkit.ui.Button.ClickEvent;
@@ -18,70 +18,70 @@ import com.itmill.toolkit.ui.Button.ClickListener;
*/
public class NotificationDemo extends com.itmill.toolkit.Application {
- // Dropdown select for notification type, using the native dropdown
- NativeSelect type;
- // Textfield for the notification caption
- TextField caption;
- // Textfield for the notification content
- TextField message;
+ // Dropdown select for notification type, using the native dropdown
+ NativeSelect type;
+ // Textfield for the notification caption
+ TextField caption;
+ // Textfield for the notification content
+ TextField message;
- /**
- * The initialization method that is the only requirement for inheriting the
- * com.itmill.toolkit.service.Application class. It will be automatically
- * called by the framework when a user accesses the application.
- */
- public void init() {
+ /**
+ * The initialization method that is the only requirement for inheriting the
+ * com.itmill.toolkit.service.Application class. It will be automatically
+ * called by the framework when a user accesses the application.
+ */
+ public void init() {
- // Create new window for the application and give the window a visible.
- Window main = new Window("Notification demo");
- // set as main window
- setMainWindow(main);
+ // Create new window for the application and give the window a visible.
+ Window main = new Window("Notification demo");
+ // set as main window
+ setMainWindow(main);
- // Create the 'type' dropdown select.
- type = new NativeSelect("Notification type");
- // no empty selection allowed
- type.setNullSelectionAllowed(false);
- // we want a different caption than the value
- type.addContainerProperty("caption", String.class, null);
- type.setItemCaptionMode(Select.ITEM_CAPTION_MODE_PROPERTY);
- type.setItemCaptionPropertyId("caption");
- // add some content (items) using the Container API
- Item i = type.addItem(new Integer(
- Window.Notification.TYPE_HUMANIZED_MESSAGE));
- i.getItemProperty("caption").setValue("Humanized message");
- i = type.addItem(new Integer(Window.Notification.TYPE_WARNING_MESSAGE));
- i.getItemProperty("caption").setValue("Warning message");
- i = type.addItem(new Integer(Window.Notification.TYPE_ERROR_MESSAGE));
- i.getItemProperty("caption").setValue("Error message");
- i = type
- .addItem(new Integer(Window.Notification.TYPE_TRAY_NOTIFICATION));
- i.getItemProperty("caption").setValue("Tray notification");
- // set the initially selected item
- type.setValue(new Integer(Window.Notification.TYPE_HUMANIZED_MESSAGE));
- main.addComponent(type); // add to layout
+ // Create the 'type' dropdown select.
+ type = new NativeSelect("Notification type");
+ // no empty selection allowed
+ type.setNullSelectionAllowed(false);
+ // we want a different caption than the value
+ type.addContainerProperty("caption", String.class, null);
+ type.setItemCaptionMode(AbstractSelect.ITEM_CAPTION_MODE_PROPERTY);
+ type.setItemCaptionPropertyId("caption");
+ // add some content (items) using the Container API
+ Item i = type.addItem(new Integer(
+ Window.Notification.TYPE_HUMANIZED_MESSAGE));
+ i.getItemProperty("caption").setValue("Humanized message");
+ i = type.addItem(new Integer(Window.Notification.TYPE_WARNING_MESSAGE));
+ i.getItemProperty("caption").setValue("Warning message");
+ i = type.addItem(new Integer(Window.Notification.TYPE_ERROR_MESSAGE));
+ i.getItemProperty("caption").setValue("Error message");
+ i = type
+ .addItem(new Integer(Window.Notification.TYPE_TRAY_NOTIFICATION));
+ i.getItemProperty("caption").setValue("Tray notification");
+ // set the initially selected item
+ type.setValue(new Integer(Window.Notification.TYPE_HUMANIZED_MESSAGE));
+ main.addComponent(type); // add to layout
- // Notification caption
- caption = new TextField("Caption");
- caption.setColumns(20);
- caption.setValue("Brown Fox!");
- main.addComponent(caption);
+ // Notification caption
+ caption = new TextField("Caption");
+ caption.setColumns(20);
+ caption.setValue("Brown Fox!");
+ main.addComponent(caption);
- // Notification message
- message = new RichTextArea();
- message.setCaption("Message");
- message.setValue("A quick one jumped over the lazy dog.");
- main.addComponent(message); // add to layout
+ // Notification message
+ message = new RichTextArea();
+ message.setCaption("Message");
+ message.setValue("A quick one jumped over the lazy dog.");
+ main.addComponent(message); // add to layout
- // Button to show the notification
- Button b = new Button("Show notification", new ClickListener() {
- // this is an inline ClickListener
- public void buttonClick(ClickEvent event) {
- // show the notification
- getMainWindow().showNotification((String) caption.getValue(),
- (String) message.getValue(),
- ((Integer) type.getValue()).intValue());
- }
- });
- main.addComponent(b); // add button to layout
- }
+ // Button to show the notification
+ Button b = new Button("Show notification", new ClickListener() {
+ // this is an inline ClickListener
+ public void buttonClick(ClickEvent event) {
+ // show the notification
+ getMainWindow().showNotification((String) caption.getValue(),
+ (String) message.getValue(),
+ ((Integer) type.getValue()).intValue());
+ }
+ });
+ main.addComponent(b); // add button to layout
+ }
}
diff --git a/src/com/itmill/toolkit/demo/Parameters.java b/src/com/itmill/toolkit/demo/Parameters.java
index 882e92f131..353a088de9 100644
--- a/src/com/itmill/toolkit/demo/Parameters.java
+++ b/src/com/itmill/toolkit/demo/Parameters.java
@@ -8,7 +8,12 @@ import com.itmill.toolkit.terminal.DownloadStream;
import com.itmill.toolkit.terminal.ExternalResource;
import com.itmill.toolkit.terminal.ParameterHandler;
import com.itmill.toolkit.terminal.URIHandler;
-import com.itmill.toolkit.ui.*;
+import com.itmill.toolkit.ui.Label;
+import com.itmill.toolkit.ui.Link;
+import com.itmill.toolkit.ui.OrderedLayout;
+import com.itmill.toolkit.ui.Panel;
+import com.itmill.toolkit.ui.Table;
+import com.itmill.toolkit.ui.Window;
/**
* This is a demonstration of how URL parameters can be recieved and handled.
@@ -18,89 +23,90 @@ import com.itmill.toolkit.ui.*;
* @since 3.1.1
*/
public class Parameters extends com.itmill.toolkit.Application implements
- URIHandler, ParameterHandler {
+ URIHandler, ParameterHandler {
- private Label context = new Label();
+ private Label context = new Label();
- private Label relative = new Label();
+ private Label relative = new Label();
- private Table params = new Table();
+ private Table params = new Table();
- public void init() {
- Window main = new Window("Parameters demo");
- setMainWindow(main);
+ public void init() {
+ Window main = new Window("Parameters demo");
+ setMainWindow(main);
- // This class acts both as URI handler and parameter handler
- main.addURIHandler(this);
- main.addParameterHandler(this);
+ // This class acts both as URI handler and parameter handler
+ main.addURIHandler(this);
+ main.addParameterHandler(this);
- OrderedLayout layout = new OrderedLayout();
- Label info = new Label("To test URI and Parameter Handlers, "
- + "add get parameters to URL. For example try examples below: ");
- info.setCaption("Usage info");
- layout.addComponent(info);
- try {
- URL u1 = new URL(getURL(), "test/uri?test=1&test=2");
- URL u2 = new URL(getURL(), "foo/bar?mary=john&count=3");
- layout.addComponent(new Link(u1.toString(),
- new ExternalResource(u1)));
- layout.addComponent(new Label("Or this: "));
- layout.addComponent(new Link(u2.toString(),
- new ExternalResource(u2)));
- } catch (Exception e) {
- System.out.println("Couldn't get hostname for this machine: "
- + e.toString());
- e.printStackTrace();
- }
+ OrderedLayout layout = new OrderedLayout();
+ Label info = new Label("To test URI and Parameter Handlers, "
+ + "add get parameters to URL. For example try examples below: ");
+ info.setCaption("Usage info");
+ layout.addComponent(info);
+ try {
+ URL u1 = new URL(getURL(), "test/uri?test=1&test=2");
+ URL u2 = new URL(getURL(), "foo/bar?mary=john&count=3");
+ layout.addComponent(new Link(u1.toString(),
+ new ExternalResource(u1)));
+ layout.addComponent(new Label("Or this: "));
+ layout.addComponent(new Link(u2.toString(),
+ new ExternalResource(u2)));
+ } catch (Exception e) {
+ System.out.println("Couldn't get hostname for this machine: "
+ + e.toString());
+ e.printStackTrace();
+ }
- // URI
- Panel panel1 = new Panel("URI Handler");
- context.setCaption("Last URI handler context");
- panel1.addComponent(context);
- relative.setCaption("Last relative URI");
- panel1.addComponent(relative);
- layout.addComponent(panel1);
+ // URI
+ Panel panel1 = new Panel("URI Handler");
+ context.setCaption("Last URI handler context");
+ panel1.addComponent(context);
+ relative.setCaption("Last relative URI");
+ panel1.addComponent(relative);
+ layout.addComponent(panel1);
- // Parameters
- params.addContainerProperty("Values", String.class, "");
- Panel panel2 = new Panel("Parameter Handler");
- params.setCaption("Last parameters");
- params.setColumnHeaderMode(Table.COLUMN_HEADER_MODE_ID);
- params.setRowHeaderMode(Table.ROW_HEADER_MODE_ID);
- panel2.addComponent(params);
- layout.addComponent(panel2);
+ // Parameters
+ params.addContainerProperty("Values", String.class, "");
+ Panel panel2 = new Panel("Parameter Handler");
+ params.setCaption("Last parameters");
+ params.setColumnHeaderMode(Table.COLUMN_HEADER_MODE_ID);
+ params.setRowHeaderMode(Table.ROW_HEADER_MODE_ID);
+ panel2.addComponent(params);
+ layout.addComponent(panel2);
- main.addComponent(layout);
- }
+ main.addComponent(layout);
+ }
- /**
- * Update URI
- *
- * @see com.itmill.toolkit.terminal.URIHandler#handleURI(URL, String)
- */
- public DownloadStream handleURI(URL context, String relativeUri) {
- this.context.setValue(context.toString());
- this.relative.setValue(relativeUri);
- return null;
- }
+ /**
+ * Update URI
+ *
+ * @see com.itmill.toolkit.terminal.URIHandler#handleURI(URL, String)
+ */
+ public DownloadStream handleURI(URL context, String relativeUri) {
+ this.context.setValue(context.toString());
+ relative.setValue(relativeUri);
+ return null;
+ }
- /**
- * Handles GET parameters, in this demo GET parameteres are used to
- * communicate with EmbeddedToolkit.jsp
- */
- public void handleParameters(Map parameters) {
- // TODO: disabled, see bug #550
- // params.removeAllItems();
- for (Iterator i = parameters.keySet().iterator(); i.hasNext();) {
- String name = (String) i.next();
- String[] values = (String[]) parameters.get(name);
- String v = "";
- for (int j = 0; j < values.length; j++) {
- if (v.length() > 0)
- v += ", ";
- v += "'" + values[j] + "'";
- }
- params.addItem(new Object[] { v }, name);
- }
- }
+ /**
+ * Handles GET parameters, in this demo GET parameteres are used to
+ * communicate with EmbeddedToolkit.jsp
+ */
+ public void handleParameters(Map parameters) {
+ // TODO: disabled, see bug #550
+ // params.removeAllItems();
+ for (Iterator i = parameters.keySet().iterator(); i.hasNext();) {
+ String name = (String) i.next();
+ String[] values = (String[]) parameters.get(name);
+ String v = "";
+ for (int j = 0; j < values.length; j++) {
+ if (v.length() > 0) {
+ v += ", ";
+ }
+ v += "'" + values[j] + "'";
+ }
+ params.addItem(new Object[] { v }, name);
+ }
+ }
}
diff --git a/src/com/itmill/toolkit/demo/QueryContainerDemo.java b/src/com/itmill/toolkit/demo/QueryContainerDemo.java
index 66ef37c699..a7889a8be2 100644
--- a/src/com/itmill/toolkit/demo/QueryContainerDemo.java
+++ b/src/com/itmill/toolkit/demo/QueryContainerDemo.java
@@ -1,9 +1,10 @@
package com.itmill.toolkit.demo;
import java.sql.SQLException;
+
import com.itmill.toolkit.data.util.QueryContainer;
-import com.itmill.toolkit.event.Action;
import com.itmill.toolkit.demo.util.SampleDatabase;
+import com.itmill.toolkit.event.Action;
import com.itmill.toolkit.ui.Label;
import com.itmill.toolkit.ui.Select;
import com.itmill.toolkit.ui.Table;
@@ -26,162 +27,162 @@ import com.itmill.toolkit.ui.Window;
*
*/
public class QueryContainerDemo extends com.itmill.toolkit.Application
- implements Action.Handler {
-
- private static final String ACTION_DESCRIPTION = "Try right mouse button to initiate "
- + "actions menu.
Note: on Opera you use meta key "
- + "and left mouse button.";
-
- private static final String TABLE_CAPTION = SampleDatabase.ROWCOUNT
- + " dynamically loaded rows from example SQL table";
-
- // Table component where SQL rows are attached (using QueryContainer)
- private Table table = new Table();
-
- private Label tableLastAction = new Label("No action selected for table.");
-
- // Select component where SQL rows are attached (using QueryContainer)
- private Select select = new Select();
-
- // Tree component that uses select as datasource
- private Tree tree = new Tree();
-
- private Label treeLastAction = new Label("No action selected for tree.");
-
- // Database provided with sample data
- private SampleDatabase sampleDatabase;
-
- // Example Actions for table
- private Action ACTION1 = new Action("Upload");
-
- private Action ACTION2 = new Action("Download");
-
- private Action ACTION3 = new Action("Show history");
-
- private Action[] actions = new Action[] { ACTION1, ACTION2, ACTION3 };
-
- /**
- * Initialize Application. Demo components are added to main window.
- */
- public void init() {
- Window main = new Window("QueryContainer demo");
- setMainWindow(main);
-
- // Main window contains heading, table, select and tree
- main
- .addComponent(new Label(
- "QueryContainer demo
"
- + "Rows are loaded from the server as they are needed.
"
- + "Try scrolling the table to see it in action.
"
- + ACTION_DESCRIPTION, Label.CONTENT_XHTML));
- main.addComponent(table);
- main.addComponent(tableLastAction);
- main.addComponent(new Label("
", Label.CONTENT_XHTML));
- main.addComponent(select);
- main.addComponent(new Label("
", Label.CONTENT_XHTML));
- main.addComponent(tree);
- main.addComponent(treeLastAction);
-
- // create demo database
- sampleDatabase = new SampleDatabase();
-
- // initialize demo components
- initTable();
- initSelect();
- initTree();
- }
-
- /**
- * Populates table component with all rows from employee table.
- *
- */
- private void initTable() {
- // init table
- table.setCaption(TABLE_CAPTION);
- table.setPageLength(10);
- table.setSelectable(true);
- table.setRowHeaderMode(Table.ROW_HEADER_MODE_INDEX);
- table.setColumnCollapsingAllowed(true);
- table.setColumnReorderingAllowed(true);
- table.setSelectable(true);
- // this class handles table actions (see handleActions method below)
- table.addActionHandler(this);
- table.setDescription(ACTION_DESCRIPTION);
-
- // populate Toolkit table component with test SQL table rows
- try {
- QueryContainer qc = new QueryContainer("SELECT * FROM employee",
- sampleDatabase.getConnection());
- table.setContainerDataSource(qc);
- } catch (SQLException e) {
- e.printStackTrace();
- }
- // define which columns should be visible on Table component
- table.setVisibleColumns(new Object[] { "FIRSTNAME", "LASTNAME",
- "TITLE", "UNIT" });
- table.setItemCaptionPropertyId("ID");
- }
-
- /**
- * Populates select component with distinct unit values from employee table.
- *
- */
- private void initSelect() {
- // init select
- select.setCaption("All distinct units from employee table.");
- select.setItemCaptionPropertyId("UNIT");
-
- // populate Toolkit select component with test SQL table rows
- try {
- QueryContainer qc = new QueryContainer(
- "SELECT DISTINCT UNIT FROM employee", sampleDatabase
- .getConnection());
- select.setContainerDataSource(qc);
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
-
- /**
- * Populates tree component using select component as data source for root
- * nodes, child nodes are queried from database. Implementation is done for
- * example purposes only.
- *
- */
- private void initTree() {
- // init tree
- tree.setCaption("All distinct units from employee table.");
- tree.setItemCaptionPropertyId("UNIT");
- tree.setSelectable(true);
- // this class handles tree actions (see handleActions method below)
- tree.addActionHandler(this);
- tree.setDescription("Try right mouse button to initiate "
- + "actions menu. Note: on Opera you use meta key "
- + "and left mouse button.");
- tree.setStyle("menu");
-
- // Populate Toolkit Tree using select component as data source
- tree.setContainerDataSource(select.getContainerDataSource());
- }
-
- /**
- * Return example actions
- */
- public Action[] getActions(Object target, Object sender) {
- return actions;
- }
-
- /**
- * Executed by right mouse button on table or tree component.
- */
- public void handleAction(Action action, Object sender, Object target) {
- if (sender == table) {
- tableLastAction.setValue("Last action clicked was '"
- + action.getCaption() + "' on item " + target);
- } else if (sender == tree) {
- treeLastAction.setValue("Last action clicked was '"
- + action.getCaption() + "' on item " + target);
- }
- }
+ implements Action.Handler {
+
+ private static final String ACTION_DESCRIPTION = "Try right mouse button to initiate "
+ + "actions menu.
Note: on Opera you use meta key "
+ + "and left mouse button.";
+
+ private static final String TABLE_CAPTION = SampleDatabase.ROWCOUNT
+ + " dynamically loaded rows from example SQL table";
+
+ // Table component where SQL rows are attached (using QueryContainer)
+ private Table table = new Table();
+
+ private Label tableLastAction = new Label("No action selected for table.");
+
+ // Select component where SQL rows are attached (using QueryContainer)
+ private Select select = new Select();
+
+ // Tree component that uses select as datasource
+ private Tree tree = new Tree();
+
+ private Label treeLastAction = new Label("No action selected for tree.");
+
+ // Database provided with sample data
+ private SampleDatabase sampleDatabase;
+
+ // Example Actions for table
+ private Action ACTION1 = new Action("Upload");
+
+ private Action ACTION2 = new Action("Download");
+
+ private Action ACTION3 = new Action("Show history");
+
+ private Action[] actions = new Action[] { ACTION1, ACTION2, ACTION3 };
+
+ /**
+ * Initialize Application. Demo components are added to main window.
+ */
+ public void init() {
+ Window main = new Window("QueryContainer demo");
+ setMainWindow(main);
+
+ // Main window contains heading, table, select and tree
+ main
+ .addComponent(new Label(
+ "QueryContainer demo
"
+ + "Rows are loaded from the server as they are needed.
"
+ + "Try scrolling the table to see it in action.
"
+ + ACTION_DESCRIPTION, Label.CONTENT_XHTML));
+ main.addComponent(table);
+ main.addComponent(tableLastAction);
+ main.addComponent(new Label("
", Label.CONTENT_XHTML));
+ main.addComponent(select);
+ main.addComponent(new Label("
", Label.CONTENT_XHTML));
+ main.addComponent(tree);
+ main.addComponent(treeLastAction);
+
+ // create demo database
+ sampleDatabase = new SampleDatabase();
+
+ // initialize demo components
+ initTable();
+ initSelect();
+ initTree();
+ }
+
+ /**
+ * Populates table component with all rows from employee table.
+ *
+ */
+ private void initTable() {
+ // init table
+ table.setCaption(TABLE_CAPTION);
+ table.setPageLength(10);
+ table.setSelectable(true);
+ table.setRowHeaderMode(Table.ROW_HEADER_MODE_INDEX);
+ table.setColumnCollapsingAllowed(true);
+ table.setColumnReorderingAllowed(true);
+ table.setSelectable(true);
+ // this class handles table actions (see handleActions method below)
+ table.addActionHandler(this);
+ table.setDescription(ACTION_DESCRIPTION);
+
+ // populate Toolkit table component with test SQL table rows
+ try {
+ QueryContainer qc = new QueryContainer("SELECT * FROM employee",
+ sampleDatabase.getConnection());
+ table.setContainerDataSource(qc);
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ // define which columns should be visible on Table component
+ table.setVisibleColumns(new Object[] { "FIRSTNAME", "LASTNAME",
+ "TITLE", "UNIT" });
+ table.setItemCaptionPropertyId("ID");
+ }
+
+ /**
+ * Populates select component with distinct unit values from employee table.
+ *
+ */
+ private void initSelect() {
+ // init select
+ select.setCaption("All distinct units from employee table.");
+ select.setItemCaptionPropertyId("UNIT");
+
+ // populate Toolkit select component with test SQL table rows
+ try {
+ QueryContainer qc = new QueryContainer(
+ "SELECT DISTINCT UNIT FROM employee", sampleDatabase
+ .getConnection());
+ select.setContainerDataSource(qc);
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * Populates tree component using select component as data source for root
+ * nodes, child nodes are queried from database. Implementation is done for
+ * example purposes only.
+ *
+ */
+ private void initTree() {
+ // init tree
+ tree.setCaption("All distinct units from employee table.");
+ tree.setItemCaptionPropertyId("UNIT");
+ tree.setSelectable(true);
+ // this class handles tree actions (see handleActions method below)
+ tree.addActionHandler(this);
+ tree.setDescription("Try right mouse button to initiate "
+ + "actions menu. Note: on Opera you use meta key "
+ + "and left mouse button.");
+ tree.setStyle("menu");
+
+ // Populate Toolkit Tree using select component as data source
+ tree.setContainerDataSource(select.getContainerDataSource());
+ }
+
+ /**
+ * Return example actions
+ */
+ public Action[] getActions(Object target, Object sender) {
+ return actions;
+ }
+
+ /**
+ * Executed by right mouse button on table or tree component.
+ */
+ public void handleAction(Action action, Object sender, Object target) {
+ if (sender == table) {
+ tableLastAction.setValue("Last action clicked was '"
+ + action.getCaption() + "' on item " + target);
+ } else if (sender == tree) {
+ treeLastAction.setValue("Last action clicked was '"
+ + action.getCaption() + "' on item " + target);
+ }
+ }
}
diff --git a/src/com/itmill/toolkit/demo/SelectDemo.java b/src/com/itmill/toolkit/demo/SelectDemo.java
index 20128ea9da..cc6816206d 100644
--- a/src/com/itmill/toolkit/demo/SelectDemo.java
+++ b/src/com/itmill/toolkit/demo/SelectDemo.java
@@ -8,6 +8,7 @@ import com.itmill.toolkit.ui.Label;
import com.itmill.toolkit.ui.Panel;
import com.itmill.toolkit.ui.Select;
import com.itmill.toolkit.ui.Window;
+import com.itmill.toolkit.ui.AbstractSelect.Filtering;
/**
* This example demonstrates what is lazy loading feature on Select component.
@@ -19,58 +20,57 @@ import com.itmill.toolkit.ui.Window;
*/
public class SelectDemo extends com.itmill.toolkit.Application {
- // Select component where SQL rows are attached (using QueryContainer)
- private final Select select = new Select();
+ // Select component where SQL rows are attached (using QueryContainer)
+ private final Select select = new Select();
- private final Select lazySelect = new Select();
+ private final Select lazySelect = new Select();
- // Database provided with sample data
- private SampleDatabase sampleDatabase;
+ // Database provided with sample data
+ private SampleDatabase sampleDatabase;
- /**
- * Initialize Application. Demo components are added to main window.
- */
- public void init() {
- Window main = new Window("Select demo");
- setMainWindow(main);
+ /**
+ * Initialize Application. Demo components are added to main window.
+ */
+ public void init() {
+ Window main = new Window("Select demo");
+ setMainWindow(main);
- // Main window contains heading, table, select and tree
- Panel panel = new Panel("Select demo (a.k.a Google Suggests)");
- panel.addComponent(this.lazySelect);
- panel.addComponent(new Label("
", Label.CONTENT_XHTML));
- panel.addComponent(this.select);
- main.addComponent(panel);
+ // Main window contains heading, table, select and tree
+ Panel panel = new Panel("Select demo (a.k.a Google Suggests)");
+ panel.addComponent(lazySelect);
+ panel.addComponent(new Label("
", Label.CONTENT_XHTML));
+ panel.addComponent(select);
+ main.addComponent(panel);
- // create demo database
- this.sampleDatabase = new SampleDatabase();
+ // create demo database
+ sampleDatabase = new SampleDatabase();
- initSelects();
- }
+ initSelects();
+ }
- private void initSelects() {
- // init select
- this.select.setCaption("All employees default functionality.");
- this.select.setItemCaptionPropertyId("WORKER");
- // populate Toolkit select component with test SQL table rows
- try {
- QueryContainer qc = new QueryContainer(
- "SELECT ID, UNIT||', '||LASTNAME||' '||FIRSTNAME"
- + " AS WORKER FROM employee ORDER BY WORKER",
- this.sampleDatabase.getConnection());
- this.select.setContainerDataSource(qc);
- } catch (SQLException e) {
- e.printStackTrace();
- }
+ private void initSelects() {
+ // init select
+ select.setCaption("All employees default functionality.");
+ select.setItemCaptionPropertyId("WORKER");
+ // populate Toolkit select component with test SQL table rows
+ try {
+ QueryContainer qc = new QueryContainer(
+ "SELECT ID, UNIT||', '||LASTNAME||' '||FIRSTNAME"
+ + " AS WORKER FROM employee ORDER BY WORKER",
+ sampleDatabase.getConnection());
+ select.setContainerDataSource(qc);
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
- // init lazySelect
- this.lazySelect.setCaption("All employees with lazy loading "
- + "(a.k.a Google Suggests) activated.");
- this.lazySelect.setItemCaptionPropertyId("WORKER");
- this.lazySelect.setFilteringMode(Select.FILTERINGMODE_CONTAINS);
+ // init lazySelect
+ lazySelect.setCaption("All employees with lazy loading "
+ + "(a.k.a Google Suggests) activated.");
+ lazySelect.setItemCaptionPropertyId("WORKER");
+ lazySelect.setFilteringMode(Filtering.FILTERINGMODE_CONTAINS);
- // use same datasource as select object uses
- this.lazySelect.setContainerDataSource(this.select
- .getContainerDataSource());
- }
+ // use same datasource as select object uses
+ lazySelect.setContainerDataSource(select.getContainerDataSource());
+ }
}
diff --git a/src/com/itmill/toolkit/demo/TableDemo.java b/src/com/itmill/toolkit/demo/TableDemo.java
index 1b7e935cd8..9010ec5a55 100644
--- a/src/com/itmill/toolkit/demo/TableDemo.java
+++ b/src/com/itmill/toolkit/demo/TableDemo.java
@@ -3,8 +3,8 @@ package com.itmill.toolkit.demo;
import java.sql.SQLException;
import com.itmill.toolkit.data.util.QueryContainer;
-import com.itmill.toolkit.event.Action;
import com.itmill.toolkit.demo.util.SampleDatabase;
+import com.itmill.toolkit.event.Action;
import com.itmill.toolkit.terminal.ExternalResource;
import com.itmill.toolkit.ui.Button;
import com.itmill.toolkit.ui.Label;
@@ -21,165 +21,165 @@ import com.itmill.toolkit.ui.Window;
*
*/
public class TableDemo extends com.itmill.toolkit.Application implements
- Action.Handler {
-
- private static final String ACTION_DESCRIPTION = "Use right mouse button to initiate "
- + "actions menu.
Note: on Opera use meta key "
- + "and left mouse button.";
-
- private static final String TABLE_CAPTION = SampleDatabase.ROWCOUNT
- + " dynamically loaded rows from example SQL table";
-
- private Link menuLink = new Link("Go back to menu", new ExternalResource(
- "index.html"));
-
- // Table component where SQL rows are attached (using QueryContainer)
- private Table table = new Table();
-
- // Label which displays last performed action against table row
- private Label tableLastAction = new Label("No action selected for table.");
-
- // Database provided with sample data
- private SampleDatabase sampleDatabase;
-
- // Example Actions for table
- private Action ACTION1 = new Action("Upload");
-
- private Action ACTION2 = new Action("Download");
-
- private Action ACTION3 = new Action("Show history");
-
- private Action[] actions = new Action[] { ACTION1, ACTION2, ACTION3 };
-
- // Button which is used to disable or enable table
- // note: when button click event occurs, tableEnabler() method is called
- private Button tableEnabler = new Button("Disable table", this,
- "tableEnabler");
-
- // Button which is used to hide or show table
- // note: when button click event occurs, tableVisibility() method is called
- private Button tableVisibility = new Button("Hide table", this,
- "tableVisibility");
-
- // Button which is used to hide or show table
- // note: when button click event occurs, tableVisibility() method is called
- private Button tableCaption = new Button("Hide caption", this,
- "tableCaption");
-
- /**
- * Initialize Application. Demo components are added to main window.
- */
- public void init() {
- Window main = new Window("Table demo");
- setMainWindow(main);
-
- // Add link back to index.html
- main.addComponent(menuLink);
-
- // create demo database
- sampleDatabase = new SampleDatabase();
-
- // Main window contains heading, two buttons, table and label
- main
- .addComponent(new Label(
- "Table demo
"
- + "Rows are loaded from the server as they are needed.
"
- + "Try scrolling the table to see it in action.
"
- + ACTION_DESCRIPTION, Label.CONTENT_XHTML));
- OrderedLayout layout = new OrderedLayout(
- OrderedLayout.ORIENTATION_HORIZONTAL);
- // TODO: disabled until #655 fixed
- // layout.addComponent(tableVisibility);
- layout.addComponent(tableEnabler);
- layout.addComponent(tableCaption);
- main.addComponent(layout);
- main.addComponent(table);
- main.addComponent(tableLastAction);
-
- // initialize demo components
- initTable();
- }
-
- /**
- * Populates table component with all rows from employee table.
- *
- */
- private void initTable() {
- // init table
- table.setCaption(TABLE_CAPTION);
- table.setPageLength(10);
- table.setSelectable(true);
- table.setRowHeaderMode(Table.ROW_HEADER_MODE_INDEX);
- table.setColumnCollapsingAllowed(true);
- table.setColumnReorderingAllowed(true);
- table.setSelectable(true);
- // this class handles table actions (see handleActions method below)
- table.addActionHandler(this);
- table.setDescription(ACTION_DESCRIPTION);
-
- // populate Toolkit table component with test SQL table rows
- try {
- QueryContainer qc = new QueryContainer("SELECT * FROM employee",
- sampleDatabase.getConnection());
- table.setContainerDataSource(qc);
- } catch (SQLException e) {
- e.printStackTrace();
- }
- // define which columns should be visible on Table component
- table.setVisibleColumns(new Object[] { "FIRSTNAME", "LASTNAME",
- "TITLE", "UNIT" });
- table.setItemCaptionPropertyId("ID");
- }
-
- public void tableVisibility() {
- if (table.isVisible()) {
- tableVisibility.setCaption("Show table");
- table.setVisible(false);
- tableEnabler.setEnabled(false);
- tableCaption.setEnabled(false);
- } else {
- tableVisibility.setCaption("Hide table");
- table.setVisible(true);
- tableEnabler.setEnabled(true);
- tableCaption.setEnabled(true);
- }
- }
-
- public void tableEnabler() {
- if (table.isEnabled()) {
- tableEnabler.setCaption("Enable table");
- table.setEnabled(false);
- } else {
- tableEnabler.setCaption("Disable table");
- table.setEnabled(true);
- }
- }
-
- public void tableCaption() {
- if (table.getCaption().equals("")) {
- table.setCaption(TABLE_CAPTION);
- tableCaption.setCaption("Hide caption");
- } else {
- table.setCaption("");
- tableCaption.setCaption("Show caption");
- }
- }
-
- /**
- * URIHandler Return example actions
- */
- public Action[] getActions(Object target, Object sender) {
- return actions;
- }
-
- /**
- * Executed by right mouse button on table or tree component.
- */
- public void handleAction(Action action, Object sender, Object target) {
- if (sender == table) {
- tableLastAction.setValue("Last action clicked was '"
- + action.getCaption() + "' on item " + target);
- }
- }
+ Action.Handler {
+
+ private static final String ACTION_DESCRIPTION = "Use right mouse button to initiate "
+ + "actions menu.
Note: on Opera use meta key "
+ + "and left mouse button.";
+
+ private static final String TABLE_CAPTION = SampleDatabase.ROWCOUNT
+ + " dynamically loaded rows from example SQL table";
+
+ private Link menuLink = new Link("Go back to menu", new ExternalResource(
+ "index.html"));
+
+ // Table component where SQL rows are attached (using QueryContainer)
+ private Table table = new Table();
+
+ // Label which displays last performed action against table row
+ private Label tableLastAction = new Label("No action selected for table.");
+
+ // Database provided with sample data
+ private SampleDatabase sampleDatabase;
+
+ // Example Actions for table
+ private Action ACTION1 = new Action("Upload");
+
+ private Action ACTION2 = new Action("Download");
+
+ private Action ACTION3 = new Action("Show history");
+
+ private Action[] actions = new Action[] { ACTION1, ACTION2, ACTION3 };
+
+ // Button which is used to disable or enable table
+ // note: when button click event occurs, tableEnabler() method is called
+ private Button tableEnabler = new Button("Disable table", this,
+ "tableEnabler");
+
+ // Button which is used to hide or show table
+ // note: when button click event occurs, tableVisibility() method is called
+ private Button tableVisibility = new Button("Hide table", this,
+ "tableVisibility");
+
+ // Button which is used to hide or show table
+ // note: when button click event occurs, tableVisibility() method is called
+ private Button tableCaption = new Button("Hide caption", this,
+ "tableCaption");
+
+ /**
+ * Initialize Application. Demo components are added to main window.
+ */
+ public void init() {
+ Window main = new Window("Table demo");
+ setMainWindow(main);
+
+ // Add link back to index.html
+ main.addComponent(menuLink);
+
+ // create demo database
+ sampleDatabase = new SampleDatabase();
+
+ // Main window contains heading, two buttons, table and label
+ main
+ .addComponent(new Label(
+ "Table demo
"
+ + "Rows are loaded from the server as they are needed.
"
+ + "Try scrolling the table to see it in action.
"
+ + ACTION_DESCRIPTION, Label.CONTENT_XHTML));
+ OrderedLayout layout = new OrderedLayout(
+ OrderedLayout.ORIENTATION_HORIZONTAL);
+ // TODO: disabled until #655 fixed
+ // layout.addComponent(tableVisibility);
+ layout.addComponent(tableEnabler);
+ layout.addComponent(tableCaption);
+ main.addComponent(layout);
+ main.addComponent(table);
+ main.addComponent(tableLastAction);
+
+ // initialize demo components
+ initTable();
+ }
+
+ /**
+ * Populates table component with all rows from employee table.
+ *
+ */
+ private void initTable() {
+ // init table
+ table.setCaption(TABLE_CAPTION);
+ table.setPageLength(10);
+ table.setSelectable(true);
+ table.setRowHeaderMode(Table.ROW_HEADER_MODE_INDEX);
+ table.setColumnCollapsingAllowed(true);
+ table.setColumnReorderingAllowed(true);
+ table.setSelectable(true);
+ // this class handles table actions (see handleActions method below)
+ table.addActionHandler(this);
+ table.setDescription(ACTION_DESCRIPTION);
+
+ // populate Toolkit table component with test SQL table rows
+ try {
+ QueryContainer qc = new QueryContainer("SELECT * FROM employee",
+ sampleDatabase.getConnection());
+ table.setContainerDataSource(qc);
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ // define which columns should be visible on Table component
+ table.setVisibleColumns(new Object[] { "FIRSTNAME", "LASTNAME",
+ "TITLE", "UNIT" });
+ table.setItemCaptionPropertyId("ID");
+ }
+
+ public void tableVisibility() {
+ if (table.isVisible()) {
+ tableVisibility.setCaption("Show table");
+ table.setVisible(false);
+ tableEnabler.setEnabled(false);
+ tableCaption.setEnabled(false);
+ } else {
+ tableVisibility.setCaption("Hide table");
+ table.setVisible(true);
+ tableEnabler.setEnabled(true);
+ tableCaption.setEnabled(true);
+ }
+ }
+
+ public void tableEnabler() {
+ if (table.isEnabled()) {
+ tableEnabler.setCaption("Enable table");
+ table.setEnabled(false);
+ } else {
+ tableEnabler.setCaption("Disable table");
+ table.setEnabled(true);
+ }
+ }
+
+ public void tableCaption() {
+ if (table.getCaption().equals("")) {
+ table.setCaption(TABLE_CAPTION);
+ tableCaption.setCaption("Hide caption");
+ } else {
+ table.setCaption("");
+ tableCaption.setCaption("Show caption");
+ }
+ }
+
+ /**
+ * URIHandler Return example actions
+ */
+ public Action[] getActions(Object target, Object sender) {
+ return actions;
+ }
+
+ /**
+ * Executed by right mouse button on table or tree component.
+ */
+ public void handleAction(Action action, Object sender, Object target) {
+ if (sender == table) {
+ tableLastAction.setValue("Last action clicked was '"
+ + action.getCaption() + "' on item " + target);
+ }
+ }
}
diff --git a/src/com/itmill/toolkit/demo/TreeFilesystem.java b/src/com/itmill/toolkit/demo/TreeFilesystem.java
index b0c4d7dca9..fc729f970a 100644
--- a/src/com/itmill/toolkit/demo/TreeFilesystem.java
+++ b/src/com/itmill/toolkit/demo/TreeFilesystem.java
@@ -1,9 +1,13 @@
package com.itmill.toolkit.demo;
import java.io.File;
+
import com.itmill.toolkit.data.Item;
import com.itmill.toolkit.demo.util.SampleDirectory;
-import com.itmill.toolkit.ui.*;
+import com.itmill.toolkit.ui.Label;
+import com.itmill.toolkit.ui.Panel;
+import com.itmill.toolkit.ui.Tree;
+import com.itmill.toolkit.ui.Window;
import com.itmill.toolkit.ui.Tree.ExpandEvent;
/**
@@ -17,79 +21,83 @@ import com.itmill.toolkit.ui.Tree.ExpandEvent;
*
*/
public class TreeFilesystem extends com.itmill.toolkit.Application implements
- Tree.ExpandListener {
+ Tree.ExpandListener {
- // Filesystem explorer panel and it's components
- private Panel explorerPanel = new Panel("Filesystem explorer");
+ // Filesystem explorer panel and it's components
+ private Panel explorerPanel = new Panel("Filesystem explorer");
- private Tree tree = new Tree();
+ private Tree tree = new Tree();
- public void init() {
- Window main = new Window("Tree filesystem demo");
- setMainWindow(main);
+ public void init() {
+ Window main = new Window("Tree filesystem demo");
+ setMainWindow(main);
- // Main window contains heading and panel
- main.addComponent(new Label("Tree demo
", Label.CONTENT_XHTML));
+ // Main window contains heading and panel
+ main.addComponent(new Label("Tree demo
", Label.CONTENT_XHTML));
- // configure file structure panel
- main.addComponent(explorerPanel);
- explorerPanel.addComponent(tree);
- explorerPanel.setHeight(400);
+ // configure file structure panel
+ main.addComponent(explorerPanel);
+ explorerPanel.addComponent(tree);
+ explorerPanel.setHeight(400);
- // "this" handles tree's expand event
- tree.addListener((Tree.ExpandListener) this);
+ // "this" handles tree's expand event
+ tree.addListener(this);
- // Get sample directory
- File sampleDir = SampleDirectory.getDirectory(this);
- // populate tree's root node with example directory
- if (sampleDir != null)
- populateNode(sampleDir.getAbsolutePath(), null);
- }
+ // Get sample directory
+ File sampleDir = SampleDirectory.getDirectory(this);
+ // populate tree's root node with example directory
+ if (sampleDir != null) {
+ populateNode(sampleDir.getAbsolutePath(), null);
+ }
+ }
- /**
- * Handle tree expand event, populate expanded node's childs with new files
- * and directories.
- */
- public void nodeExpand(ExpandEvent event) {
- Item i = tree.getItem(event.getItemId());
- if (!tree.hasChildren(i)) {
- // populate tree's node which was expanded
- populateNode(event.getItemId().toString(), event.getItemId());
- }
- }
+ /**
+ * Handle tree expand event, populate expanded node's childs with new files
+ * and directories.
+ */
+ public void nodeExpand(ExpandEvent event) {
+ Item i = tree.getItem(event.getItemId());
+ if (!tree.hasChildren(i)) {
+ // populate tree's node which was expanded
+ populateNode(event.getItemId().toString(), event.getItemId());
+ }
+ }
- /**
- * Populates files to tree as items. In this example items are of String
- * type that consist of file path. New items are added to tree and item's
- * parent and children properties are updated.
- *
- * @param file
- * path which contents are added to tree
- * @param parent
- * for added nodes, if null then new nodes are added to root node
- */
- private void populateNode(String file, Object parent) {
- File subdir = new File(file);
- File[] files = subdir.listFiles();
- for (int x = 0; x < files.length; x++) {
- try {
- // add new item (String) to tree
- String path = files[x].getCanonicalPath().toString();
- tree.addItem(path);
- // set parent if this item has one
- if (parent != null)
- tree.setParent(path, parent);
- // check if item is a directory and read access exists
- if (files[x].isDirectory() && files[x].canRead())
- // yes, childrens therefore exists
- tree.setChildrenAllowed(path, true);
- else
- // no, childrens therefore do not exists
- tree.setChildrenAllowed(path, false);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- }
+ /**
+ * Populates files to tree as items. In this example items are of String
+ * type that consist of file path. New items are added to tree and item's
+ * parent and children properties are updated.
+ *
+ * @param file
+ * path which contents are added to tree
+ * @param parent
+ * for added nodes, if null then new nodes are added to root
+ * node
+ */
+ private void populateNode(String file, Object parent) {
+ File subdir = new File(file);
+ File[] files = subdir.listFiles();
+ for (int x = 0; x < files.length; x++) {
+ try {
+ // add new item (String) to tree
+ String path = files[x].getCanonicalPath().toString();
+ tree.addItem(path);
+ // set parent if this item has one
+ if (parent != null) {
+ tree.setParent(path, parent);
+ }
+ // check if item is a directory and read access exists
+ if (files[x].isDirectory() && files[x].canRead()) {
+ // yes, childrens therefore exists
+ tree.setChildrenAllowed(path, true);
+ } else {
+ // no, childrens therefore do not exists
+ tree.setChildrenAllowed(path, false);
+ }
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+ }
}
diff --git a/src/com/itmill/toolkit/demo/TreeFilesystemContainer.java b/src/com/itmill/toolkit/demo/TreeFilesystemContainer.java
index 6311766829..33ca45e728 100644
--- a/src/com/itmill/toolkit/demo/TreeFilesystemContainer.java
+++ b/src/com/itmill/toolkit/demo/TreeFilesystemContainer.java
@@ -5,7 +5,11 @@ import java.io.File;
import com.itmill.toolkit.data.util.FilesystemContainer;
import com.itmill.toolkit.data.util.FilesystemContainer.FileItem;
import com.itmill.toolkit.demo.util.SampleDirectory;
-import com.itmill.toolkit.ui.*;
+import com.itmill.toolkit.ui.Field;
+import com.itmill.toolkit.ui.Label;
+import com.itmill.toolkit.ui.Panel;
+import com.itmill.toolkit.ui.Tree;
+import com.itmill.toolkit.ui.Window;
import com.itmill.toolkit.ui.Component.Event;
import com.itmill.toolkit.ui.Component.Listener;
@@ -21,68 +25,68 @@ import com.itmill.toolkit.ui.Component.Listener;
*
*/
public class TreeFilesystemContainer extends com.itmill.toolkit.Application
- implements Listener {
+ implements Listener {
- // Filesystem explorer panel and it's components
- private Panel explorerPanel = new Panel("Filesystem explorer");
+ // Filesystem explorer panel and it's components
+ private Panel explorerPanel = new Panel("Filesystem explorer");
- private Tree filesystem = new Tree();
+ private Tree filesystem = new Tree();
- // File properties panel and it's components
- private Panel propertyPanel = new Panel("File properties");
+ // File properties panel and it's components
+ private Panel propertyPanel = new Panel("File properties");
- private Label fileProperties = new Label();
+ private Label fileProperties = new Label();
- public void init() {
- Window main = new Window("Tree FilesystemContainer demo");
- setMainWindow(main);
+ public void init() {
+ Window main = new Window("Tree FilesystemContainer demo");
+ setMainWindow(main);
- // Main window contains heading and two panels
- main.addComponent(new Label("TreeFilesystemContainer demo
",
- Label.CONTENT_XHTML));
- main.addComponent(propertyPanel);
- main.addComponent(explorerPanel);
+ // Main window contains heading and two panels
+ main.addComponent(new Label("TreeFilesystemContainer demo
",
+ Label.CONTENT_XHTML));
+ main.addComponent(propertyPanel);
+ main.addComponent(explorerPanel);
- // Explorer panel contains tree
- explorerPanel.addComponent(filesystem);
+ // Explorer panel contains tree
+ explorerPanel.addComponent(filesystem);
- // Property panel contains label
- propertyPanel.addComponent(fileProperties);
- fileProperties.setCaption("No file selected.");
- propertyPanel.setEnabled(false);
+ // Property panel contains label
+ propertyPanel.addComponent(fileProperties);
+ fileProperties.setCaption("No file selected.");
+ propertyPanel.setEnabled(false);
- // Get sample directory
- File sampleDir = SampleDirectory.getDirectory(this);
- // Populate tree with FilesystemContainer
- FilesystemContainer fsc = new FilesystemContainer(sampleDir, true);
- filesystem.setContainerDataSource(fsc);
- // "this" handles all filesystem events
- // e.g. node clicked, expanded etc.
- filesystem.addListener((Listener) this);
- // Value changes are immediate
- filesystem.setImmediate(true);
- }
+ // Get sample directory
+ File sampleDir = SampleDirectory.getDirectory(this);
+ // Populate tree with FilesystemContainer
+ FilesystemContainer fsc = new FilesystemContainer(sampleDir, true);
+ filesystem.setContainerDataSource(fsc);
+ // "this" handles all filesystem events
+ // e.g. node clicked, expanded etc.
+ filesystem.addListener(this);
+ // Value changes are immediate
+ filesystem.setImmediate(true);
+ }
- /**
- * Listener for any component events. This class has been registered as an
- * listener for component fsTree.
- */
- public void componentEvent(Event event) {
- // Check if event occured at fsTree component
- if (event.getSource() == filesystem) {
- // Check if event is about changing value
- if (event.getClass() == Field.ValueChangeEvent.class) {
- // Update property panel contents
- FileItem fileItem = (FileItem) filesystem.getItem(filesystem
- .getValue());
- fileProperties.setIcon(fileItem.getIcon());
- fileProperties.setCaption(fileItem.getName() + ", size "
- + fileItem.getSize() + " bytes.");
- }
- // here we could check for other type of events for filesystem
- // component
- }
- // here we could check for other component's events
- }
+ /**
+ * Listener for any component events. This class has been registered as an
+ * listener for component fsTree.
+ */
+ public void componentEvent(Event event) {
+ // Check if event occured at fsTree component
+ if (event.getSource() == filesystem) {
+ // Check if event is about changing value
+ if (event.getClass() == Field.ValueChangeEvent.class) {
+ // Update property panel contents
+ FileItem fileItem = (FileItem) filesystem.getItem(filesystem
+ .getValue());
+ fileProperties.setIcon(fileItem.getIcon());
+ fileProperties.setCaption(fileItem.getName() + ", size "
+ + fileItem.getSize() + " bytes.");
+ }
+ // here we could check for other type of events for filesystem
+ // component
+ }
+ // here we could check for other component's events
+ }
}
diff --git a/src/com/itmill/toolkit/demo/UpgradingSample.java b/src/com/itmill/toolkit/demo/UpgradingSample.java
index bfbbaf2a96..922c129932 100644
--- a/src/com/itmill/toolkit/demo/UpgradingSample.java
+++ b/src/com/itmill/toolkit/demo/UpgradingSample.java
@@ -9,7 +9,15 @@ package com.itmill.toolkit.demo;
//
import com.itmill.toolkit.Application;
import com.itmill.toolkit.data.Property;
-import com.itmill.toolkit.ui.*;
+import com.itmill.toolkit.ui.Button;
+import com.itmill.toolkit.ui.CustomComponent;
+import com.itmill.toolkit.ui.GridLayout;
+import com.itmill.toolkit.ui.Label;
+import com.itmill.toolkit.ui.OrderedLayout;
+import com.itmill.toolkit.ui.Panel;
+import com.itmill.toolkit.ui.TextField;
+import com.itmill.toolkit.ui.Tree;
+import com.itmill.toolkit.ui.Window;
/**
*
@@ -23,127 +31,134 @@ import com.itmill.toolkit.ui.*;
* @author IT Mill Ltd.
*/
public class UpgradingSample extends Application implements
- Property.ValueChangeListener {
-
- /* Menu for navigating inside the application. */
- private Tree menu = new Tree();
-
- /* Contents of the website */
- private String[][] pages = { { "Welcome", "Welcome to our website..." },
- { "Products", "Public product information." },
- { "Contact", "Public contact information." },
- { "CRM", "CRM Database requiring login." },
- { "Intranet", "Internal information database." } };
-
- /* Application layout */
- private GridLayout layout = new GridLayout(2, 1);
-
- /* Initialize the application */
- public void init() {
-
- // Create the main window of the application
- Window main = new Window("Login example", layout);
- setMainWindow(main);
-
- // Add menu and loginbox to the application
- OrderedLayout l = new OrderedLayout();
- layout.addComponent(l, 0, 0);
- l.addComponent(menu);
- l.addComponent(new LoginBox());
-
- // Setup menu
- menu.setStyle("menu");
- menu.addListener(this);
- menu.setImmediate(true);
- addToMenu(new String[] { "Welcome", "Products", "Contact" });
- }
-
- // Overriding usetUser method is a simple way of updating application
- // privileges when the user is changed
- public void setUser(Object user) {
- super.setUser(user);
- if (user != null)
- addToMenu(new String[] { "CRM", "Intranet" });
- }
-
- public void addToMenu(String[] items) {
- for (int i = 0; i < items.length; i++) {
- menu.addItem(items[i]);
- menu.setChildrenAllowed(items[i], false);
- }
- if (menu.getValue() == null)
- menu.setValue(items[0]);
- }
-
- // Handle menu selection and update visible page
- public void valueChange(Property.ValueChangeEvent event) {
- layout.removeComponent(1, 0);
- String title = (String) menu.getValue();
- for (int i = 0; i < pages.length; i++)
- if (pages[i][0].equals(title)) {
- Panel p = new Panel(pages[i][0]);
- p.addComponent(new Label(pages[i][1]));
- p.setStyle("strong");
- layout.addComponent(p, 1, 0);
- }
- }
-
- // Simple loginbox component for the application
- public class LoginBox extends CustomComponent implements
- Application.UserChangeListener {
-
- // The components this loginbox is composed of
- private TextField loginName = new TextField("Name");
-
- private Button loginButton = new Button("Enter", this, "login");
-
- private Panel loginPanel = new Panel("Login");
-
- private Panel statusPanel = new Panel();
-
- private Button logoutButton = new Button("Logout",
- UpgradingSample.this, "close");
-
- private Label statusLabel = new Label();
-
- // Initialize login component
- public LoginBox() {
-
- // Initialize the component
- loginPanel.addComponent(loginName);
- loginPanel.addComponent(loginButton);
- loginPanel.setStyle("strong");
- loginName.setColumns(8);
- statusPanel.addComponent(statusLabel);
- statusPanel.addComponent(logoutButton);
-
- // Set the status of the loginbox and show correct components
- updateStatus();
-
- // Listen application user change events
- UpgradingSample.this.addListener(this);
- }
-
- // Login into application
- public void login() {
- String name = (String) loginName.getValue();
- if (name != null && name.length() > 0)
- setUser(name);
- loginName.setValue("");
- }
-
- // Update login status on application user change events
- public void applicationUserChanged(Application.UserChangeEvent event) {
- updateStatus();
- }
-
- // Update login status of the component by exposing correct components
- private void updateStatus() {
- statusLabel.setValue("User: " + getUser());
- if (getUser() != null)
- setCompositionRoot(statusPanel);
- else
- setCompositionRoot(loginPanel);
- }
- }
+ Property.ValueChangeListener {
+
+ /* Menu for navigating inside the application. */
+ private Tree menu = new Tree();
+
+ /* Contents of the website */
+ private String[][] pages = { { "Welcome", "Welcome to our website..." },
+ { "Products", "Public product information." },
+ { "Contact", "Public contact information." },
+ { "CRM", "CRM Database requiring login." },
+ { "Intranet", "Internal information database." } };
+
+ /* Application layout */
+ private GridLayout layout = new GridLayout(2, 1);
+
+ /* Initialize the application */
+ public void init() {
+
+ // Create the main window of the application
+ Window main = new Window("Login example", layout);
+ setMainWindow(main);
+
+ // Add menu and loginbox to the application
+ OrderedLayout l = new OrderedLayout();
+ layout.addComponent(l, 0, 0);
+ l.addComponent(menu);
+ l.addComponent(new LoginBox());
+
+ // Setup menu
+ menu.setStyle("menu");
+ menu.addListener(this);
+ menu.setImmediate(true);
+ addToMenu(new String[] { "Welcome", "Products", "Contact" });
+ }
+
+ // Overriding usetUser method is a simple way of updating application
+ // privileges when the user is changed
+ public void setUser(Object user) {
+ super.setUser(user);
+ if (user != null) {
+ addToMenu(new String[] { "CRM", "Intranet" });
+ }
+ }
+
+ public void addToMenu(String[] items) {
+ for (int i = 0; i < items.length; i++) {
+ menu.addItem(items[i]);
+ menu.setChildrenAllowed(items[i], false);
+ }
+ if (menu.getValue() == null) {
+ menu.setValue(items[0]);
+ }
+ }
+
+ // Handle menu selection and update visible page
+ public void valueChange(Property.ValueChangeEvent event) {
+ layout.removeComponent(1, 0);
+ String title = (String) menu.getValue();
+ for (int i = 0; i < pages.length; i++) {
+ if (pages[i][0].equals(title)) {
+ Panel p = new Panel(pages[i][0]);
+ p.addComponent(new Label(pages[i][1]));
+ p.setStyle("strong");
+ layout.addComponent(p, 1, 0);
+ }
+ }
+ }
+
+ // Simple loginbox component for the application
+ public class LoginBox extends CustomComponent implements
+ Application.UserChangeListener {
+
+ // The components this loginbox is composed of
+ private TextField loginName = new TextField("Name");
+
+ private Button loginButton = new Button("Enter", this, "login");
+
+ private Panel loginPanel = new Panel("Login");
+
+ private Panel statusPanel = new Panel();
+
+ private Button logoutButton = new Button("Logout",
+ UpgradingSample.this, "close");
+
+ private Label statusLabel = new Label();
+
+ // Initialize login component
+ public LoginBox() {
+
+ // Initialize the component
+ loginPanel.addComponent(loginName);
+ loginPanel.addComponent(loginButton);
+ loginPanel.setStyle("strong");
+ loginName.setColumns(8);
+ statusPanel.addComponent(statusLabel);
+ statusPanel.addComponent(logoutButton);
+
+ // Set the status of the loginbox and show correct
+ // components
+ updateStatus();
+
+ // Listen application user change events
+ UpgradingSample.this.addListener(this);
+ }
+
+ // Login into application
+ public void login() {
+ String name = (String) loginName.getValue();
+ if (name != null && name.length() > 0) {
+ setUser(name);
+ }
+ loginName.setValue("");
+ }
+
+ // Update login status on application user change events
+ public void applicationUserChanged(Application.UserChangeEvent event) {
+ updateStatus();
+ }
+
+ // Update login status of the component by exposing correct
+ // components
+ private void updateStatus() {
+ statusLabel.setValue("User: " + getUser());
+ if (getUser() != null) {
+ setCompositionRoot(statusPanel);
+ } else {
+ setCompositionRoot(loginPanel);
+ }
+ }
+ }
}
diff --git a/src/com/itmill/toolkit/demo/WindowedDemos.java b/src/com/itmill/toolkit/demo/WindowedDemos.java
index 04e67bbf3b..840f153ed2 100644
--- a/src/com/itmill/toolkit/demo/WindowedDemos.java
+++ b/src/com/itmill/toolkit/demo/WindowedDemos.java
@@ -17,70 +17,70 @@ import com.itmill.toolkit.ui.Button.ClickEvent;
*/
public class WindowedDemos extends com.itmill.toolkit.Application {
- // keeps track of created windows
- private final HashMap windows = new HashMap();
+ // keeps track of created windows
+ private final HashMap windows = new HashMap();
- // mapping demo name to URL
- private static final HashMap servlets = new HashMap();
- static {
- servlets.put("Caching demo", "CachingDemo/");
- servlets.put("Calculator", "Calc/");
- servlets.put("Calendar demo", "CalendarDemo/");
- servlets.put("Select demo", "SelectDemo/");
- servlets.put("Table demo", "TableDemo/");
- servlets.put("Browser demo", "BrowserDemo/");
- servlets.put("Notification demo", "NotificationDemo/");
- }
+ // mapping demo name to URL
+ private static final HashMap servlets = new HashMap();
+ static {
+ servlets.put("Caching demo", "CachingDemo/");
+ servlets.put("Calculator", "Calc/");
+ servlets.put("Calendar demo", "CalendarDemo/");
+ servlets.put("Select demo", "SelectDemo/");
+ servlets.put("Table demo", "TableDemo/");
+ servlets.put("Browser demo", "BrowserDemo/");
+ servlets.put("Notification demo", "NotificationDemo/");
+ }
- public void init() {
+ public void init() {
- // Create new window for the application and give the window a visible.
- Window main = new Window("IT Mill Toolkit 5 Windowed Demos");
- // set as main window
- setMainWindow(main);
+ // Create new window for the application and give the window a visible.
+ Window main = new Window("IT Mill Toolkit 5 Windowed Demos");
+ // set as main window
+ setMainWindow(main);
- // Create menu window.
- Window menu = new Window("Select demo");
- menu.setWidth(200);
- menu.setHeight(400);
- main.addWindow(menu); // add to layout
+ // Create menu window.
+ Window menu = new Window("Select demo");
+ menu.setWidth(200);
+ menu.setHeight(400);
+ main.addWindow(menu); // add to layout
- // Create a menu button for each demo
- for (Iterator it = servlets.keySet().iterator(); it.hasNext();) {
- String name = (String) it.next();
- Button b = new Button(name, new Button.ClickListener() {
- public void buttonClick(ClickEvent event) {
- show(event.getButton().getCaption());
- }
+ // Create a menu button for each demo
+ for (Iterator it = servlets.keySet().iterator(); it.hasNext();) {
+ String name = (String) it.next();
+ Button b = new Button(name, new Button.ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ show(event.getButton().getCaption());
+ }
- });
- b.setStyleName("link");
- menu.addComponent(b);
- }
+ });
+ b.setStyleName("link");
+ menu.addComponent(b);
+ }
- }
+ }
- /**
- * Shows the specified demo in a separate window. Creates a new window if
- * the demo has not been shown already, re-uses old window otherwise.
- *
- * @param demoName
- * the name of the demo to be shown
- */
- private void show(String demoName) {
- Window w = (Window) windows.get(demoName);
- if (w == null) {
- w = new Window(demoName);
- w.setWidth(520);
- w.setHeight(500);
- w.setPositionX(202);
- windows.put(demoName, w);
- getMainWindow().addWindow(w);
- } else {
- w.setVisible(true);
- }
- w.open(new ExternalResource((String) servlets.get(demoName)));
+ /**
+ * Shows the specified demo in a separate window. Creates a new window if
+ * the demo has not been shown already, re-uses old window otherwise.
+ *
+ * @param demoName
+ * the name of the demo to be shown
+ */
+ private void show(String demoName) {
+ Window w = (Window) windows.get(demoName);
+ if (w == null) {
+ w = new Window(demoName);
+ w.setWidth(520);
+ w.setHeight(500);
+ w.setPositionX(202);
+ windows.put(demoName, w);
+ getMainWindow().addWindow(w);
+ } else {
+ w.setVisible(true);
+ }
+ w.open(new ExternalResource((String) servlets.get(demoName)));
- }
+ }
}
diff --git a/src/com/itmill/toolkit/demo/colorpicker/ColorPicker.java b/src/com/itmill/toolkit/demo/colorpicker/ColorPicker.java
index c2a09d48b2..12ecb24dbf 100644
--- a/src/com/itmill/toolkit/demo/colorpicker/ColorPicker.java
+++ b/src/com/itmill/toolkit/demo/colorpicker/ColorPicker.java
@@ -1,57 +1,59 @@
package com.itmill.toolkit.demo.colorpicker;
import java.util.Map;
+
import com.itmill.toolkit.terminal.PaintException;
import com.itmill.toolkit.terminal.PaintTarget;
-import com.itmill.toolkit.ui.*;
+import com.itmill.toolkit.ui.AbstractField;
public class ColorPicker extends AbstractField {
- public ColorPicker() {
- super();
- setValue(new String("white"));
- }
-
- /** The property value of the field is an Integer. */
- public Class getType() {
- return String.class;
- }
-
- /** Tag is the UIDL element name for client-server communications. */
- public String getTag() {
- return "colorpicker";
- }
-
- /** Set the currently selected color. */
- public void setColor(String newcolor) {
- // Sets the color name as the property of the component.
- // Setting the property will automatically cause repainting of
- // the component with paintContent().
- setValue(newcolor);
- }
-
- /** Retrieve the currently selected color. */
- public String getColor() {
- return (String) getValue();
- }
-
- /** Paint (serialize) the component for the client. */
- public void paintContent(PaintTarget target) throws PaintException {
- // Superclass writes any common attributes in the paint target.
- super.paintContent(target);
-
- // Add the currently selected color as a variable in the paint target.
- target.addVariable(this, "colorname", getColor());
- }
-
- /** Deserialize changes received from client. */
- public void changeVariables(Object source, Map variables) {
- // Sets the currently selected color
- if (variables.containsKey("colorname") && !isReadOnly()) {
- String newValue = (String) variables.get("colorname");
- // Changing the property of the component will
- // trigger a ValueChangeEvent
- setValue(newValue, true);
- }
- }
+ public ColorPicker() {
+ super();
+ setValue(new String("white"));
+ }
+
+ /** The property value of the field is an Integer. */
+ public Class getType() {
+ return String.class;
+ }
+
+ /** Tag is the UIDL element name for client-server communications. */
+ public String getTag() {
+ return "colorpicker";
+ }
+
+ /** Set the currently selected color. */
+ public void setColor(String newcolor) {
+ // Sets the color name as the property of the component.
+ // Setting the property will automatically cause repainting of
+ // the component with paintContent().
+ setValue(newcolor);
+ }
+
+ /** Retrieve the currently selected color. */
+ public String getColor() {
+ return (String) getValue();
+ }
+
+ /** Paint (serialize) the component for the client. */
+ public void paintContent(PaintTarget target) throws PaintException {
+ // Superclass writes any common attributes in the paint target.
+ super.paintContent(target);
+
+ // Add the currently selected color as a variable in the paint
+ // target.
+ target.addVariable(this, "colorname", getColor());
+ }
+
+ /** Deserialize changes received from client. */
+ public void changeVariables(Object source, Map variables) {
+ // Sets the currently selected color
+ if (variables.containsKey("colorname") && !isReadOnly()) {
+ String newValue = (String) variables.get("colorname");
+ // Changing the property of the component will
+ // trigger a ValueChangeEvent
+ setValue(newValue, true);
+ }
+ }
}
diff --git a/src/com/itmill/toolkit/demo/colorpicker/ColorPickerApplication.java b/src/com/itmill/toolkit/demo/colorpicker/ColorPickerApplication.java
index f2e58ff9c0..248b4a5af2 100644
--- a/src/com/itmill/toolkit/demo/colorpicker/ColorPickerApplication.java
+++ b/src/com/itmill/toolkit/demo/colorpicker/ColorPickerApplication.java
@@ -2,7 +2,9 @@ package com.itmill.toolkit.demo.colorpicker;
import com.itmill.toolkit.data.Property.ValueChangeEvent;
import com.itmill.toolkit.data.Property.ValueChangeListener;
-import com.itmill.toolkit.ui.*;
+import com.itmill.toolkit.ui.Button;
+import com.itmill.toolkit.ui.Label;
+import com.itmill.toolkit.ui.Window;
import com.itmill.toolkit.ui.Button.ClickEvent;
/**
@@ -10,39 +12,39 @@ import com.itmill.toolkit.ui.Button.ClickEvent;
* GWT component, the ColorPicker.
*/
public class ColorPickerApplication extends com.itmill.toolkit.Application {
- Window main = new Window("Color Picker Demo");
-
- /* The custom component. */
- ColorPicker colorselector = new ColorPicker();
-
- /* Another component. */
- Label colorname;
-
- public void init() {
- setMainWindow(main);
-
- // Listen for value change events in the custom component,
- // triggered when user clicks a button to select another color.
- colorselector.addListener(new ValueChangeListener() {
- public void valueChange(ValueChangeEvent event) {
- // Provide some server-side feedback
- colorname.setValue("Selected color: "
- + colorselector.getColor());
- }
- });
- main.addComponent(colorselector);
-
- // Add another component to give feedback from server-side code
- colorname = new Label("Selected color: " + colorselector.getColor());
- main.addComponent(colorname);
-
- // Server-side manipulation of the component state
- Button button = new Button("Set to white");
- button.addListener(new Button.ClickListener() {
- public void buttonClick(ClickEvent event) {
- colorselector.setColor("white");
- }
- });
- main.addComponent(button);
- }
+ Window main = new Window("Color Picker Demo");
+
+ /* The custom component. */
+ ColorPicker colorselector = new ColorPicker();
+
+ /* Another component. */
+ Label colorname;
+
+ public void init() {
+ setMainWindow(main);
+
+ // Listen for value change events in the custom component,
+ // triggered when user clicks a button to select another color.
+ colorselector.addListener(new ValueChangeListener() {
+ public void valueChange(ValueChangeEvent event) {
+ // Provide some server-side feedback
+ colorname.setValue("Selected color: "
+ + colorselector.getColor());
+ }
+ });
+ main.addComponent(colorselector);
+
+ // Add another component to give feedback from server-side code
+ colorname = new Label("Selected color: " + colorselector.getColor());
+ main.addComponent(colorname);
+
+ // Server-side manipulation of the component state
+ Button button = new Button("Set to white");
+ button.addListener(new Button.ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ colorselector.setColor("white");
+ }
+ });
+ main.addComponent(button);
+ }
}
diff --git a/src/com/itmill/toolkit/demo/colorpicker/gwt/client/ColorPickerWidgetSet.java b/src/com/itmill/toolkit/demo/colorpicker/gwt/client/ColorPickerWidgetSet.java
index e54c23d686..f6d43e5f0b 100644
--- a/src/com/itmill/toolkit/demo/colorpicker/gwt/client/ColorPickerWidgetSet.java
+++ b/src/com/itmill/toolkit/demo/colorpicker/gwt/client/ColorPickerWidgetSet.java
@@ -6,24 +6,26 @@ import com.itmill.toolkit.terminal.gwt.client.DefaultWidgetSet;
import com.itmill.toolkit.terminal.gwt.client.UIDL;
public class ColorPickerWidgetSet extends DefaultWidgetSet {
- /** Creates a widget according to its class name. */
+ /** Creates a widget according to its class name. */
public Widget createWidget(UIDL uidl) {
- String className = resolveWidgetTypeName(uidl);
- if ("com.itmill.toolkit.demo.colorpicker.gwt.client.ui.IColorPicker"
- .equals(className))
- return new IColorPicker();
+ String className = resolveWidgetTypeName(uidl);
+ if ("com.itmill.toolkit.demo.colorpicker.gwt.client.ui.IColorPicker"
+ .equals(className)) {
+ return new IColorPicker();
+ }
- // Let the DefaultWidgetSet handle creation of default widgets
- return super.createWidget(uidl);
+ // Let the DefaultWidgetSet handle creation of default widgets
+ return super.createWidget(uidl);
}
/** Resolves UIDL tag name to class name. */
protected String resolveWidgetTypeName(UIDL uidl) {
- String tag = uidl.getTag();
- if ("colorpicker".equals(tag))
- return "com.itmill.toolkit.demo.colorpicker.gwt.client.ui.IColorPicker";
+ String tag = uidl.getTag();
+ if ("colorpicker".equals(tag)) {
+ return "com.itmill.toolkit.demo.colorpicker.gwt.client.ui.IColorPicker";
+ }
- // Let the DefaultWidgetSet handle resolution of default widgets
- return super.resolveWidgetTypeName(uidl);
+ // Let the DefaultWidgetSet handle resolution of default widgets
+ return super.resolveWidgetTypeName(uidl);
}
}
diff --git a/src/com/itmill/toolkit/demo/colorpicker/gwt/client/ui/GwtColorPicker.java b/src/com/itmill/toolkit/demo/colorpicker/gwt/client/ui/GwtColorPicker.java
index ca36176993..38b83f1961 100644
--- a/src/com/itmill/toolkit/demo/colorpicker/gwt/client/ui/GwtColorPicker.java
+++ b/src/com/itmill/toolkit/demo/colorpicker/gwt/client/ui/GwtColorPicker.java
@@ -2,90 +2,99 @@ package com.itmill.toolkit.demo.colorpicker.gwt.client.ui;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
-import com.google.gwt.user.client.ui.*;
+import com.google.gwt.user.client.ui.Button;
+import com.google.gwt.user.client.ui.ClickListener;
+import com.google.gwt.user.client.ui.Composite;
+import com.google.gwt.user.client.ui.Grid;
+import com.google.gwt.user.client.ui.HorizontalPanel;
+import com.google.gwt.user.client.ui.Label;
+import com.google.gwt.user.client.ui.Widget;
/**
* A regular GWT component without integration with IT Mill Toolkit.
*/
public class GwtColorPicker extends Composite implements ClickListener {
- /** Currently selected color name to give client-side feedback to the user. */
- protected Label currentcolor = new Label();
+ /** Currently selected color name to give client-side feedback to the user. */
+ protected Label currentcolor = new Label();
- public GwtColorPicker() {
- // Create a 4x4 grid of buttons with names for 16 colors
- Grid grid = new Grid(4, 4);
- String[] colors = new String[] { "aqua", "black", "blue", "fuchsia",
- "gray", "green", "lime", "maroon", "navy", "olive", "purple",
- "red", "silver", "teal", "white", "yellow" };
- int colornum = 0;
- for (int i = 0; i < 4; i++)
- for (int j = 0; j < 4; j++, colornum++) {
- // Create a button for each color
- Button button = new Button(colors[colornum]);
- button.addClickListener(this);
+ public GwtColorPicker() {
+ // Create a 4x4 grid of buttons with names for 16 colors
+ Grid grid = new Grid(4, 4);
+ String[] colors = new String[] { "aqua", "black", "blue", "fuchsia",
+ "gray", "green", "lime", "maroon", "navy", "olive", "purple",
+ "red", "silver", "teal", "white", "yellow" };
+ int colornum = 0;
+ for (int i = 0; i < 4; i++) {
+ for (int j = 0; j < 4; j++, colornum++) {
+ // Create a button for each color
+ Button button = new Button(colors[colornum]);
+ button.addClickListener(this);
- // Put the button in the Grid layout
- grid.setWidget(i, j, button);
+ // Put the button in the Grid layout
+ grid.setWidget(i, j, button);
- // Set the button background colors.
- DOM.setStyleAttribute(button.getElement(), "background",
- colors[colornum]);
+ // Set the button background colors.
+ DOM.setStyleAttribute(button.getElement(), "background",
+ colors[colornum]);
- // For dark colors, the button label must be in white.
- if ("black navy maroon blue purple".indexOf(colors[colornum]) != -1)
- DOM
- .setStyleAttribute(button.getElement(), "color",
- "white");
- }
+ // For dark colors, the button label must be in white.
+ if ("black navy maroon blue purple".indexOf(colors[colornum]) != -1) {
+ DOM
+ .setStyleAttribute(button.getElement(), "color",
+ "white");
+ }
+ }
+ }
- // Create a panel with the color grid and currently selected color
- // indicator
- HorizontalPanel panel = new HorizontalPanel();
- panel.add(grid);
- panel.add(currentcolor);
+ // Create a panel with the color grid and currently selected color
+ // indicator
+ HorizontalPanel panel = new HorizontalPanel();
+ panel.add(grid);
+ panel.add(currentcolor);
- // Set the class of the color selection feedback box to allow CSS
- // styling.
- // We need to obtain the DOM element for the current color label.
- // This assumes that the
element of the HorizontalPanel is
- // the parent of the label element. Notice that the element has no
- // parent
- // before the widget has been added to the horizontal panel.
- Element panelcell = DOM.getParent(currentcolor.getElement());
- DOM.setElementProperty(panelcell, "className",
- "colorpicker-currentcolorbox");
+ // Set the class of the color selection feedback box to allow CSS
+ // styling.
+ // We need to obtain the DOM element for the current color label.
+ // This assumes that the element of the HorizontalPanel is
+ // the parent of the label element. Notice that the element has no
+ // parent
+ // before the widget has been added to the horizontal panel.
+ Element panelcell = DOM.getParent(currentcolor.getElement());
+ DOM.setElementProperty(panelcell, "className",
+ "colorpicker-currentcolorbox");
- // Set initial color. This will be overridden with the value read from
- // server.
- setColor("white");
+ // Set initial color. This will be overridden with the value read from
+ // server.
+ setColor("white");
- // Composite GWT widgets must call initWidget().
- initWidget(panel);
- }
+ // Composite GWT widgets must call initWidget().
+ initWidget(panel);
+ }
- /** Handles click on a color button. */
- public void onClick(Widget sender) {
- // Use the button label as the color name to set
- setColor(((Button) sender).getText());
- }
+ /** Handles click on a color button. */
+ public void onClick(Widget sender) {
+ // Use the button label as the color name to set
+ setColor(((Button) sender).getText());
+ }
- /** Sets the currently selected color. */
- public void setColor(String newcolor) {
- // Give client-side feedback by changing the color name in the label
- currentcolor.setText(newcolor);
+ /** Sets the currently selected color. */
+ public void setColor(String newcolor) {
+ // Give client-side feedback by changing the color name in the label
+ currentcolor.setText(newcolor);
- // Obtain the DOM elements. This assumes that the element
- // of the HorizontalPanel is the parent of the label element.
- Element nameelement = currentcolor.getElement();
- Element cell = DOM.getParent(nameelement);
+ // Obtain the DOM elements. This assumes that the element
+ // of the HorizontalPanel is the parent of the label element.
+ Element nameelement = currentcolor.getElement();
+ Element cell = DOM.getParent(nameelement);
- // Give feedback by changing the background color
- DOM.setStyleAttribute(cell, "background", newcolor);
- DOM.setStyleAttribute(nameelement, "background", newcolor);
- if ("black navy maroon blue purple".indexOf(newcolor) != -1)
- DOM.setStyleAttribute(nameelement, "color", "white");
- else
- DOM.setStyleAttribute(nameelement, "color", "black");
- }
+ // Give feedback by changing the background color
+ DOM.setStyleAttribute(cell, "background", newcolor);
+ DOM.setStyleAttribute(nameelement, "background", newcolor);
+ if ("black navy maroon blue purple".indexOf(newcolor) != -1) {
+ DOM.setStyleAttribute(nameelement, "color", "white");
+ } else {
+ DOM.setStyleAttribute(nameelement, "color", "black");
+ }
+ }
}
diff --git a/src/com/itmill/toolkit/demo/colorpicker/gwt/client/ui/IColorPicker.java b/src/com/itmill/toolkit/demo/colorpicker/gwt/client/ui/IColorPicker.java
index e7738caead..434c4f0530 100644
--- a/src/com/itmill/toolkit/demo/colorpicker/gwt/client/ui/IColorPicker.java
+++ b/src/com/itmill/toolkit/demo/colorpicker/gwt/client/ui/IColorPicker.java
@@ -6,69 +6,72 @@ import com.itmill.toolkit.terminal.gwt.client.UIDL;
public class IColorPicker extends GwtColorPicker implements Paintable {
- /** Set the CSS class name to allow styling. */
- public static final String CLASSNAME = "example-colorpicker";
+ /** Set the CSS class name to allow styling. */
+ public static final String CLASSNAME = "example-colorpicker";
- /** Component identifier in UIDL communications. */
- String uidlId;
+ /** Component identifier in UIDL communications. */
+ String uidlId;
- /** Reference to the server connection object. */
- ApplicationConnection client;
+ /** Reference to the server connection object. */
+ ApplicationConnection client;
- /**
- * The constructor should first call super() to initialize the component and
- * then handle any initialization relevant to IT Mill Toolkit.
- */
- public IColorPicker() {
- // The superclass has a lot of relevant initialization
- super();
+ /**
+ * The constructor should first call super() to initialize the component and
+ * then handle any initialization relevant to IT Mill Toolkit.
+ */
+ public IColorPicker() {
+ // The superclass has a lot of relevant initialization
+ super();
- // This method call of the Paintable interface sets the component
- // style name in DOM tree
- setStyleName(CLASSNAME);
- }
+ // This method call of the Paintable interface sets the component
+ // style name in DOM tree
+ setStyleName(CLASSNAME);
+ }
- /**
- * This method must be implemented to update the client-side component from
- * UIDL data received from server.
- *
- * This method is called when the page is loaded for the first time, and
- * every time UI changes in the component are received from the server.
- */
- public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
- // This call should be made first. Ensure correct implementation,
- // and let the containing layout manage caption, etc.
- if (client.updateComponent(this, uidl, true))
- return;
+ /**
+ * This method must be implemented to update the client-side component from
+ * UIDL data received from server.
+ *
+ * This method is called when the page is loaded for the first time, and
+ * every time UI changes in the component are received from the server.
+ */
+ public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
+ // This call should be made first. Ensure correct implementation,
+ // and let the containing layout manage caption, etc.
+ if (client.updateComponent(this, uidl, true)) {
+ return;
+ }
- // Save reference to server connection object to be able to send
- // user interaction later
- this.client = client;
+ // Save reference to server connection object to be able to send
+ // user interaction later
+ this.client = client;
- // Save the UIDL identifier for the component
- uidlId = uidl.getId();
+ // Save the UIDL identifier for the component
+ uidlId = uidl.getId();
- // Get value received from server and actualize it in the GWT component
- setColor(uidl.getStringVariable("colorname"));
- }
+ // Get value received from server and actualize it in the GWT component
+ setColor(uidl.getStringVariable("colorname"));
+ }
- /** Override the method to communicate the new value to server. */
- public void setColor(String newcolor) {
- // Ignore if no change
- if (newcolor.equals(currentcolor.getText()))
- return;
+ /** Override the method to communicate the new value to server. */
+ public void setColor(String newcolor) {
+ // Ignore if no change
+ if (newcolor.equals(currentcolor.getText())) {
+ return;
+ }
- // Let the original implementation to do whatever it needs to do
- super.setColor(newcolor);
+ // Let the original implementation to do whatever it needs to do
+ super.setColor(newcolor);
- // Updating the state to the server can not be done before
- // the server connection is known, i.e., before updateFromUIDL()
- // has been called.
- if (uidlId == null || client == null)
- return;
+ // Updating the state to the server can not be done before
+ // the server connection is known, i.e., before updateFromUIDL()
+ // has been called.
+ if (uidlId == null || client == null) {
+ return;
+ }
- // Communicate the user interaction parameters to server. This call will
- // initiate an AJAX request to the server.
- client.updateVariable(uidlId, "colorname", newcolor, true);
- }
+ // Communicate the user interaction parameters to server. This call will
+ // initiate an AJAX request to the server.
+ client.updateVariable(uidlId, "colorname", newcolor, true);
+ }
}
diff --git a/src/com/itmill/toolkit/demo/reservation/CalendarDemo.java b/src/com/itmill/toolkit/demo/reservation/CalendarDemo.java
index 413e5a36dd..bbe5ef8778 100644
--- a/src/com/itmill/toolkit/demo/reservation/CalendarDemo.java
+++ b/src/com/itmill/toolkit/demo/reservation/CalendarDemo.java
@@ -8,6 +8,7 @@ import com.itmill.toolkit.data.Property.ValueChangeEvent;
import com.itmill.toolkit.data.Property.ValueChangeListener;
import com.itmill.toolkit.data.util.QueryContainer;
import com.itmill.toolkit.demo.util.SampleCalendarDatabase;
+import com.itmill.toolkit.ui.DateField;
import com.itmill.toolkit.ui.OrderedLayout;
import com.itmill.toolkit.ui.Window;
@@ -23,90 +24,89 @@ import com.itmill.toolkit.ui.Window;
*/
public class CalendarDemo extends com.itmill.toolkit.Application {
- // Database provided with sample data
- private SampleCalendarDatabase sampleDatabase;
-
- // The calendar UI component
- private CalendarField from;
- private CalendarField to;
-
- /**
- * Initialize Application. Demo components are added to main window.
- */
- public void init() {
- Window main = new Window("Calendar demo");
- setMainWindow(main);
-
- main.setLayout(new OrderedLayout(OrderedLayout.ORIENTATION_HORIZONTAL));
-
- // create the calendar component and add to layout
- from = new CalendarField();
- main.addComponent(from);
- from.setResolution(CalendarField.RESOLUTION_HOUR);
- from.setImmediate(true);
-
-
- to = new CalendarField();
- main.addComponent(to);
- to.setResolution(CalendarField.RESOLUTION_HOUR);
- to.setEnabled(false);
- to.setImmediate(true);
-
- from.addListener(new ValueChangeListener() {
- public void valueChange(ValueChangeEvent event) {
- Date fd = (Date) from.getValue();
- Date td = (Date) to.getValue();
- if (fd == null) {
- to.setValue(null);
- to.setEnabled(false);
- return;
- } else {
- to.setEnabled(true);
- }
- to.setMinimumDate(fd);
- if (td == null || td.before(fd)) {
- to.setValue(fd);
- }
- }
- });
-
- // initialize the sample database and set as calendar datasource
- sampleDatabase = new SampleCalendarDatabase();
-
- initCalendars();
-
- // Don't allow dates before today
- from.setMinimumDate(Calendar.getInstance().getTime());
-
- }
-
- /**
- * Populates table component with all rows from calendar table.
- */
- private void initCalendars() {
- try {
- QueryContainer qc = new QueryContainer("SELECT * FROM "
- + SampleCalendarDatabase.DB_TABLE_NAME, sampleDatabase
- .getConnection());
- from.setContainerDataSource(qc);
- to.setContainerDataSource(qc);
- } catch (SQLException e) {
- e.printStackTrace();
- }
-/*
- // Calendar will use the first date property as start if you do not
- // explicitly specify the property id. Our start -property will be the
- // first one, so it's intentionally left out.
- // Start is the only mandatory property, but you'll probably want to
- // specify title as well.
- from.setItemEndPropertyId(SampleCalendarDatabase.PROPERTY_ID_END);
- from.setItemTitlePropertyId(SampleCalendarDatabase.PROPERTY_ID_TITLE);
- from.setItemNotimePropertyId(SampleCalendarDatabase.PROPERTY_ID_NOTIME);
-
- to.setItemEndPropertyId(SampleCalendarDatabase.PROPERTY_ID_END);
- to.setItemTitlePropertyId(SampleCalendarDatabase.PROPERTY_ID_TITLE);
- to.setItemNotimePropertyId(SampleCalendarDatabase.PROPERTY_ID_NOTIME);
-*/
- }
+ // Database provided with sample data
+ private SampleCalendarDatabase sampleDatabase;
+
+ // The calendar UI component
+ private CalendarField from;
+ private CalendarField to;
+
+ /**
+ * Initialize Application. Demo components are added to main window.
+ */
+ public void init() {
+ Window main = new Window("Calendar demo");
+ setMainWindow(main);
+
+ main.setLayout(new OrderedLayout(OrderedLayout.ORIENTATION_HORIZONTAL));
+
+ // create the calendar component and add to layout
+ from = new CalendarField();
+ main.addComponent(from);
+ from.setResolution(DateField.RESOLUTION_HOUR);
+ from.setImmediate(true);
+
+ to = new CalendarField();
+ main.addComponent(to);
+ to.setResolution(DateField.RESOLUTION_HOUR);
+ to.setEnabled(false);
+ to.setImmediate(true);
+
+ from.addListener(new ValueChangeListener() {
+ public void valueChange(ValueChangeEvent event) {
+ Date fd = (Date) from.getValue();
+ Date td = (Date) to.getValue();
+ if (fd == null) {
+ to.setValue(null);
+ to.setEnabled(false);
+ return;
+ } else {
+ to.setEnabled(true);
+ }
+ to.setMinimumDate(fd);
+ if (td == null || td.before(fd)) {
+ to.setValue(fd);
+ }
+ }
+ });
+
+ // initialize the sample database and set as calendar datasource
+ sampleDatabase = new SampleCalendarDatabase();
+
+ initCalendars();
+
+ // Don't allow dates before today
+ from.setMinimumDate(Calendar.getInstance().getTime());
+
+ }
+
+ /**
+ * Populates table component with all rows from calendar table.
+ */
+ private void initCalendars() {
+ try {
+ QueryContainer qc = new QueryContainer("SELECT * FROM "
+ + SampleCalendarDatabase.DB_TABLE_NAME, sampleDatabase
+ .getConnection());
+ from.setContainerDataSource(qc);
+ to.setContainerDataSource(qc);
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ /*
+ * // Calendar will use the first date property as start if you do not //
+ * explicitly specify the property id. Our start -property will be the //
+ * first one, so it's intentionally left out. // Start is the only
+ * mandatory property, but you'll probably want to // specify title as
+ * well.
+ * from.setItemEndPropertyId(SampleCalendarDatabase.PROPERTY_ID_END);
+ * from.setItemTitlePropertyId(SampleCalendarDatabase.PROPERTY_ID_TITLE);
+ * from.setItemNotimePropertyId(SampleCalendarDatabase.PROPERTY_ID_NOTIME);
+ *
+ * to.setItemEndPropertyId(SampleCalendarDatabase.PROPERTY_ID_END);
+ * to.setItemTitlePropertyId(SampleCalendarDatabase.PROPERTY_ID_TITLE);
+ * to.setItemNotimePropertyId(SampleCalendarDatabase.PROPERTY_ID_NOTIME);
+ */
+ }
}
diff --git a/src/com/itmill/toolkit/demo/reservation/CalendarField.java b/src/com/itmill/toolkit/demo/reservation/CalendarField.java
index 8cd67500a2..a746685c4f 100644
--- a/src/com/itmill/toolkit/demo/reservation/CalendarField.java
+++ b/src/com/itmill/toolkit/demo/reservation/CalendarField.java
@@ -16,304 +16,301 @@ import com.itmill.toolkit.ui.DateField;
// TODO Allow item selection
public class CalendarField extends DateField implements Container.Viewer {
- private static final String TAGNAME = "calendarfield";
-
- private Date minDate;
- private Date maxDate;
-
- private Container dataSource;
- private Object itemStyleNamePropertyId;
- private Object itemStartPropertyId;
- private Object itemEndPropertyId;
- private Object itemTitlePropertyId;
- private Object itemDescriptionPropertyId;
- private Object itemNotimePropertyId;
-
- public CalendarField() {
- super();
- init();
- }
-
- public CalendarField(Property dataSource) throws IllegalArgumentException {
- super(dataSource);
- init();
- }
-
- public CalendarField(String caption, Date value) {
- super(caption, value);
- init();
- }
-
- public CalendarField(String caption, Property dataSource) {
- super(caption, dataSource);
- init();
- }
-
- public CalendarField(String caption) {
- super(caption);
- init();
- }
-
- /*
- * Gets the components UIDL tag string. Don't add a JavaDoc comment here, we
- * use the default documentation from implemented interface.
- */
- public String getTag() {
- return TAGNAME;
- }
-
- public void init() {
- super.setResolution(RESOLUTION_HOUR);
-
- }
-
- /**
- * Sets the resolution of the CalendarField. Only RESOLUTION_DAY and
- * RESOLUTION_HOUR are supported.
- *
- * @param resolution
- * the resolution to set.
- * @see com.itmill.toolkit.ui.DateField#setResolution(int)
- */
- public void setResolution(int resolution) {
- if (resolution != RESOLUTION_DAY && resolution != RESOLUTION_HOUR) {
- throw new IllegalArgumentException();
- }
- super.setResolution(resolution);
- }
-
- public void setMinimumDate(Date date) {
- this.minDate = date;
- requestRepaint();
- }
-
- public Date getMinimumDate() {
- return minDate;
- }
-
- public void setMaximumDate(Date date) {
- this.maxDate = date;
- requestRepaint();
- }
-
- public Date getMaximumDate() {
- return maxDate;
- }
-
- public Container getContainerDataSource() {
- return this.dataSource;
- }
-
- public void setContainerDataSource(Container newDataSource) {
- if (newDataSource == null || checkDataSource(newDataSource)) {
- this.dataSource = newDataSource;
- } else {
- // TODO error message
- throw new IllegalArgumentException();
- }
- requestRepaint();
- }
-
- private boolean checkDataSource(Container dataSource) {
-
- // Check old propertyIds
- if (this.itemEndPropertyId != null) {
- Class c = dataSource.getType(this.itemEndPropertyId);
- if (!Date.class.isAssignableFrom(c)) {
- this.itemEndPropertyId = null;
- }
- }
- if (this.itemNotimePropertyId != null) {
- Class c = dataSource.getType(this.itemNotimePropertyId);
- if (!Boolean.class.isAssignableFrom(c)) {
- this.itemNotimePropertyId = null;
- }
- }
- if (this.itemStartPropertyId != null) {
- Class c = dataSource.getType(this.itemStartPropertyId);
- if (Date.class.isAssignableFrom(c)) {
- // All we _really_ need is one date
- return true;
- } else {
- this.itemStartPropertyId = null;
- }
- }
- // We need at least one Date
- Collection ids = dataSource.getContainerPropertyIds();
- for (Iterator it = ids.iterator(); it.hasNext();) {
- Object id = it.next();
- Class c = dataSource.getType(id);
- if (Date.class.isAssignableFrom(c)) {
- this.itemStartPropertyId = id;
- return true;
- }
- }
-
- return false;
- }
-
- public Object getItemStyleNamePropertyId() {
- return itemStyleNamePropertyId;
- }
-
- public void setItemStyleNamePropertyId(Object propertyId) {
- this.itemStyleNamePropertyId = propertyId;
- }
-
- public Object getItemStartPropertyId() {
- return itemStartPropertyId;
- }
-
- public void setItemStartPropertyId(Object propertyId) {
- // TODO nullcheck for property id
- if (this.dataSource != null
- && !Date.class.isAssignableFrom(dataSource.getType(propertyId))) {
- // TODO error message
- throw new IllegalArgumentException();
- }
- this.itemStartPropertyId = propertyId;
- }
-
- public Object getItemEndPropertyId() {
- return itemEndPropertyId;
- }
-
- public void setItemEndPropertyId(Object propertyId) {
- // TODO nullcheck for property id
- if (this.dataSource != null
- && !Date.class.isAssignableFrom(dataSource.getType(propertyId))) {
- // TODO error message
- throw new IllegalArgumentException();
- }
- this.itemEndPropertyId = propertyId;
- }
-
- public Object getItemTitlePropertyId() {
- return itemTitlePropertyId;
- }
-
- public void setItemTitlePropertyId(Object propertyId) {
- this.itemTitlePropertyId = propertyId;
- }
-
- public Object getItemDescriptionPropertyId() {
- return itemDescriptionPropertyId;
- }
-
- public void setItemDescriptionPropertyId(Object propertyId) {
- this.itemDescriptionPropertyId = propertyId;
- }
-
- public Object getitemNotimePropertyId() {
- return itemNotimePropertyId;
- }
-
- public void setItemNotimePropertyId(Object propertyId) {
- // TODO nullcheck for property id
- if (this.dataSource != null
- && !Boolean.class.isAssignableFrom(dataSource
- .getType(propertyId))) {
- // TODO error message
- throw new IllegalArgumentException();
- }
- this.itemNotimePropertyId = propertyId;
- }
-
- /**
- * Paints the content of this component.
- *
- * @param target
- * the Paint Event.
- * @throws PaintException
- * if the paint operation failed.
- */
- public void paintContent(PaintTarget target) throws PaintException {
- super.paintContent(target);
-
- if (this.minDate != null) {
- target.addAttribute("min", String.valueOf(this.minDate.getTime()));
- }
- if (this.maxDate != null) {
- target.addAttribute("max", String.valueOf(this.maxDate.getTime()));
- }
-
- if (this.dataSource != null) {
- target.startTag("items");
-
- // TODO send one month now, the rest via lazyloading
- int month = new Date().getMonth();
- Object value = getValue();
- if (value != null && value instanceof Date) {
- month = ((Date) value).getMonth();
- }
-
- for (Iterator it = this.dataSource.getItemIds().iterator(); it
- .hasNext();) {
- Object itemId = it.next();
- Item item = (Item) this.dataSource.getItem(itemId);
- Property p = item.getItemProperty(this.itemStartPropertyId);
- Date start = (Date) p.getValue();
- Date end = start; // assume same day
- if (this.itemEndPropertyId != null) {
- p = item.getItemProperty(this.itemEndPropertyId);
- end = (Date) p.getValue();
- if (end == null) {
- end = start;
- } else if (end.before(start)) {
- Date tmp = start;
- start = end;
- end = tmp;
- }
- }
-
- // TODO half-done lazyloading logic (hence broken)
-
- if (start != null) {
- if ((start.getMonth() <= month || end.getMonth() >= month)) {
- target.startTag("item");
- // TODO different id?
- target.addAttribute("id", itemId.hashCode());
- if (this.itemStyleNamePropertyId != null) {
- p = item
- .getItemProperty(this.itemStyleNamePropertyId);
- String styleName = (String) p.getValue();
- target.addAttribute("styleName", styleName);
- }
- target.addAttribute("start", "" + start.getTime());
- if (end != start) {
- target.addAttribute("end", "" + end.getTime());
- }
- if (this.itemTitlePropertyId != null) {
- p = item.getItemProperty(this.itemTitlePropertyId);
- Object val = p.getValue();
- if (val != null) {
- target.addAttribute("title", val.toString());
- }
- }
- if (this.itemDescriptionPropertyId != null) {
- p = item
- .getItemProperty(this.itemDescriptionPropertyId);
- Object val = p.getValue();
- if (val != null) {
- target.addAttribute("description", val
- .toString());
- }
- }
- if (this.itemNotimePropertyId != null) {
- p = item.getItemProperty(this.itemNotimePropertyId);
- Object val = p.getValue();
- if (val != null) {
- target.addAttribute("notime", ((Boolean) val)
- .booleanValue());
- }
- }
-
- target.endTag("item");
- }
- }
- }
-
- target.endTag("items");
- }
- }
+ private static final String TAGNAME = "calendarfield";
+
+ private Date minDate;
+ private Date maxDate;
+
+ private Container dataSource;
+ private Object itemStyleNamePropertyId;
+ private Object itemStartPropertyId;
+ private Object itemEndPropertyId;
+ private Object itemTitlePropertyId;
+ private Object itemDescriptionPropertyId;
+ private Object itemNotimePropertyId;
+
+ public CalendarField() {
+ super();
+ init();
+ }
+
+ public CalendarField(Property dataSource) throws IllegalArgumentException {
+ super(dataSource);
+ init();
+ }
+
+ public CalendarField(String caption, Date value) {
+ super(caption, value);
+ init();
+ }
+
+ public CalendarField(String caption, Property dataSource) {
+ super(caption, dataSource);
+ init();
+ }
+
+ public CalendarField(String caption) {
+ super(caption);
+ init();
+ }
+
+ /*
+ * Gets the components UIDL tag string. Don't add a JavaDoc comment here, we
+ * use the default documentation from implemented interface.
+ */
+ public String getTag() {
+ return TAGNAME;
+ }
+
+ public void init() {
+ super.setResolution(RESOLUTION_HOUR);
+
+ }
+
+ /**
+ * Sets the resolution of the CalendarField. Only RESOLUTION_DAY and
+ * RESOLUTION_HOUR are supported.
+ *
+ * @param resolution
+ * the resolution to set.
+ * @see com.itmill.toolkit.ui.DateField#setResolution(int)
+ */
+ public void setResolution(int resolution) {
+ if (resolution != RESOLUTION_DAY && resolution != RESOLUTION_HOUR) {
+ throw new IllegalArgumentException();
+ }
+ super.setResolution(resolution);
+ }
+
+ public void setMinimumDate(Date date) {
+ minDate = date;
+ requestRepaint();
+ }
+
+ public Date getMinimumDate() {
+ return minDate;
+ }
+
+ public void setMaximumDate(Date date) {
+ maxDate = date;
+ requestRepaint();
+ }
+
+ public Date getMaximumDate() {
+ return maxDate;
+ }
+
+ public Container getContainerDataSource() {
+ return dataSource;
+ }
+
+ public void setContainerDataSource(Container newDataSource) {
+ if (newDataSource == null || checkDataSource(newDataSource)) {
+ dataSource = newDataSource;
+ } else {
+ // TODO error message
+ throw new IllegalArgumentException();
+ }
+ requestRepaint();
+ }
+
+ private boolean checkDataSource(Container dataSource) {
+
+ // Check old propertyIds
+ if (itemEndPropertyId != null) {
+ Class c = dataSource.getType(itemEndPropertyId);
+ if (!Date.class.isAssignableFrom(c)) {
+ itemEndPropertyId = null;
+ }
+ }
+ if (itemNotimePropertyId != null) {
+ Class c = dataSource.getType(itemNotimePropertyId);
+ if (!Boolean.class.isAssignableFrom(c)) {
+ itemNotimePropertyId = null;
+ }
+ }
+ if (itemStartPropertyId != null) {
+ Class c = dataSource.getType(itemStartPropertyId);
+ if (Date.class.isAssignableFrom(c)) {
+ // All we _really_ need is one date
+ return true;
+ } else {
+ itemStartPropertyId = null;
+ }
+ }
+ // We need at least one Date
+ Collection ids = dataSource.getContainerPropertyIds();
+ for (Iterator it = ids.iterator(); it.hasNext();) {
+ Object id = it.next();
+ Class c = dataSource.getType(id);
+ if (Date.class.isAssignableFrom(c)) {
+ itemStartPropertyId = id;
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ public Object getItemStyleNamePropertyId() {
+ return itemStyleNamePropertyId;
+ }
+
+ public void setItemStyleNamePropertyId(Object propertyId) {
+ itemStyleNamePropertyId = propertyId;
+ }
+
+ public Object getItemStartPropertyId() {
+ return itemStartPropertyId;
+ }
+
+ public void setItemStartPropertyId(Object propertyId) {
+ // TODO nullcheck for property id
+ if (dataSource != null
+ && !Date.class.isAssignableFrom(dataSource.getType(propertyId))) {
+ // TODO error message
+ throw new IllegalArgumentException();
+ }
+ itemStartPropertyId = propertyId;
+ }
+
+ public Object getItemEndPropertyId() {
+ return itemEndPropertyId;
+ }
+
+ public void setItemEndPropertyId(Object propertyId) {
+ // TODO nullcheck for property id
+ if (dataSource != null
+ && !Date.class.isAssignableFrom(dataSource.getType(propertyId))) {
+ // TODO error message
+ throw new IllegalArgumentException();
+ }
+ itemEndPropertyId = propertyId;
+ }
+
+ public Object getItemTitlePropertyId() {
+ return itemTitlePropertyId;
+ }
+
+ public void setItemTitlePropertyId(Object propertyId) {
+ itemTitlePropertyId = propertyId;
+ }
+
+ public Object getItemDescriptionPropertyId() {
+ return itemDescriptionPropertyId;
+ }
+
+ public void setItemDescriptionPropertyId(Object propertyId) {
+ itemDescriptionPropertyId = propertyId;
+ }
+
+ public Object getitemNotimePropertyId() {
+ return itemNotimePropertyId;
+ }
+
+ public void setItemNotimePropertyId(Object propertyId) {
+ // TODO nullcheck for property id
+ if (dataSource != null
+ && !Boolean.class.isAssignableFrom(dataSource
+ .getType(propertyId))) {
+ // TODO error message
+ throw new IllegalArgumentException();
+ }
+ itemNotimePropertyId = propertyId;
+ }
+
+ /**
+ * Paints the content of this component.
+ *
+ * @param target
+ * the Paint Event.
+ * @throws PaintException
+ * if the paint operation failed.
+ */
+ public void paintContent(PaintTarget target) throws PaintException {
+ super.paintContent(target);
+
+ if (minDate != null) {
+ target.addAttribute("min", String.valueOf(minDate.getTime()));
+ }
+ if (maxDate != null) {
+ target.addAttribute("max", String.valueOf(maxDate.getTime()));
+ }
+
+ if (dataSource != null) {
+ target.startTag("items");
+
+ // TODO send one month now, the rest via lazyloading
+ int month = new Date().getMonth();
+ Object value = getValue();
+ if (value != null && value instanceof Date) {
+ month = ((Date) value).getMonth();
+ }
+
+ for (Iterator it = dataSource.getItemIds().iterator(); it.hasNext();) {
+ Object itemId = it.next();
+ Item item = dataSource.getItem(itemId);
+ Property p = item.getItemProperty(itemStartPropertyId);
+ Date start = (Date) p.getValue();
+ Date end = start; // assume same day
+ if (itemEndPropertyId != null) {
+ p = item.getItemProperty(itemEndPropertyId);
+ end = (Date) p.getValue();
+ if (end == null) {
+ end = start;
+ } else if (end.before(start)) {
+ Date tmp = start;
+ start = end;
+ end = tmp;
+ }
+ }
+
+ // TODO half-done lazyloading logic (hence broken)
+
+ if (start != null) {
+ if ((start.getMonth() <= month || end.getMonth() >= month)) {
+ target.startTag("item");
+ // TODO different id?
+ target.addAttribute("id", itemId.hashCode());
+ if (itemStyleNamePropertyId != null) {
+ p = item.getItemProperty(itemStyleNamePropertyId);
+ String styleName = (String) p.getValue();
+ target.addAttribute("styleName", styleName);
+ }
+ target.addAttribute("start", "" + start.getTime());
+ if (end != start) {
+ target.addAttribute("end", "" + end.getTime());
+ }
+ if (itemTitlePropertyId != null) {
+ p = item.getItemProperty(itemTitlePropertyId);
+ Object val = p.getValue();
+ if (val != null) {
+ target.addAttribute("title", val.toString());
+ }
+ }
+ if (itemDescriptionPropertyId != null) {
+ p = item.getItemProperty(itemDescriptionPropertyId);
+ Object val = p.getValue();
+ if (val != null) {
+ target.addAttribute("description", val
+ .toString());
+ }
+ }
+ if (itemNotimePropertyId != null) {
+ p = item.getItemProperty(itemNotimePropertyId);
+ Object val = p.getValue();
+ if (val != null) {
+ target.addAttribute("notime", ((Boolean) val)
+ .booleanValue());
+ }
+ }
+
+ target.endTag("item");
+ }
+ }
+ }
+
+ target.endTag("items");
+ }
+ }
}
diff --git a/src/com/itmill/toolkit/demo/reservation/GoogleMap.java b/src/com/itmill/toolkit/demo/reservation/GoogleMap.java
index 4d421c3f66..5355b9eea3 100644
--- a/src/com/itmill/toolkit/demo/reservation/GoogleMap.java
+++ b/src/com/itmill/toolkit/demo/reservation/GoogleMap.java
@@ -14,216 +14,216 @@ import com.itmill.toolkit.terminal.Sizeable;
import com.itmill.toolkit.ui.AbstractComponent;
public class GoogleMap extends AbstractComponent implements Sizeable,
- Container.Viewer {
- private String TAG_MARKERS = "markers";
- private String TAG_MARKER = "marker";
- private int width = 400;
- private int height = 300;
- private int zoomLevel = 15;
- private Point2D.Double mapCenter;
-
- private Container dataSource;
- private Object itemMarkerHtmlPropertyId = new Object();
- private Object itemMarkerXPropertyId = new Object();
- private Object itemMarkerYPropertyId = new Object();
-
- public String getTag() {
- return "googlemap";
- }
-
- public void paintContent(PaintTarget target) throws PaintException {
- super.paintContent(target);
- if (null != mapCenter) {
- target.addAttribute("centerX", mapCenter.getX());
- target.addAttribute("centerY", mapCenter.getY());
- }
- target.addAttribute("zoom", zoomLevel);
- target.addAttribute("width", width);
- target.addAttribute("height", height);
-
- if (this.dataSource != null) {
- target.startTag(TAG_MARKERS);
- Collection itemIds = this.dataSource.getItemIds();
- for (Iterator it = itemIds.iterator(); it.hasNext();) {
- Object itemId = it.next();
- Item item = this.dataSource.getItem(itemId);
- Property p = item.getItemProperty(getItemMarkerXPropertyId());
- Double x = (Double) (p != null ? p.getValue() : null);
- p = item.getItemProperty(getItemMarkerYPropertyId());
- Double y = (Double) (p != null ? p.getValue() : null);
- if (x == null || y == null) {
- continue;
- }
- target.startTag(TAG_MARKER);
- target.addAttribute("x", x.doubleValue());
- target.addAttribute("y", y.doubleValue());
- p = item.getItemProperty(getItemMarkerHtmlPropertyId());
- String h = (String) (p != null ? p.getValue() : null);
- target.addAttribute("html", h);
- target.endTag(TAG_MARKER);
- }
- target.endTag(TAG_MARKERS);
- }
- }
-
- public void setZoomLevel(int zoomLevel) {
- this.zoomLevel = zoomLevel;
- requestRepaint();
- }
-
- public int getZoomLevel() {
- return this.zoomLevel;
- }
-
- // Sizeable methods:
-
- public int getHeight() {
- return this.height;
- }
-
- public int getHeightUnits() {
- return Sizeable.UNITS_PIXELS;
- }
-
- public int getWidth() {
- return this.width;
- }
-
- public int getWidthUnits() {
- return Sizeable.UNITS_PIXELS;
- }
-
- public void setHeight(int height) {
- this.height = height;
- requestRepaint();
- }
-
- public void setHeightUnits(int units) {
- throw new UnsupportedOperationException();
- }
-
- public void setWidth(int width) {
- this.width = width;
- requestRepaint();
- }
-
- public void setWidthUnits(int units) {
- throw new UnsupportedOperationException();
- }
-
- public void setMapCenter(Point2D.Double center) {
- this.mapCenter = center;
- }
-
- public Point2D.Double getMapCenter() {
- return this.mapCenter;
- }
-
- // Container.Viewer methods:
-
- public Container getContainerDataSource() {
- return this.dataSource;
- }
-
- public void setContainerDataSource(Container newDataSource) {
-
- this.dataSource = newDataSource;
-
- requestRepaint();
- }
-
- // Item methods
-
- public Object getItemMarkerHtmlPropertyId() {
- return itemMarkerHtmlPropertyId;
- }
-
- public void setItemMarkerHtmlPropertyId(Object itemMarkerHtmlPropertyId) {
- this.itemMarkerHtmlPropertyId = itemMarkerHtmlPropertyId;
- requestRepaint();
- }
-
- public Object getItemMarkerXPropertyId() {
- return itemMarkerXPropertyId;
- }
-
- public void setItemMarkerXPropertyId(Object itemMarkerXPropertyId) {
- this.itemMarkerXPropertyId = itemMarkerXPropertyId;
- requestRepaint();
- }
-
- public Object getItemMarkerYPropertyId() {
- return itemMarkerYPropertyId;
- }
-
- public void setItemMarkerYPropertyId(Object itemMarkerYPropertyId) {
- this.itemMarkerYPropertyId = itemMarkerYPropertyId;
- requestRepaint();
- }
-
- // Marker add
-
- public Object addMarker(String html, Point2D.Double location) {
- if (location == null) {
- throw new IllegalArgumentException("Location must be non-null");
- }
- if (this.dataSource == null) {
- initDataSource();
- }
- Object markerId = this.dataSource.addItem();
- if (markerId == null) {
- return null;
- }
- Item marker = this.dataSource.getItem(markerId);
- Property p = marker.getItemProperty(getItemMarkerXPropertyId());
- p.setValue(new Double(location.x));
- p = marker.getItemProperty(getItemMarkerYPropertyId());
- p.setValue(new Double(location.y));
- p = marker.getItemProperty(getItemMarkerHtmlPropertyId());
- p.setValue(html);
-
- requestRepaint();
-
- return markerId;
- }
-
- public void removeMarker(Object markerId) {
- if (this.dataSource != null) {
- this.dataSource.removeItem(markerId);
- requestRepaint();
- }
- }
-
- public Item getMarkerItem(Object markerId) {
- if (this.dataSource != null) {
- return this.dataSource.getItem(markerId);
- } else {
- return null;
- }
- }
-
- // dataSource init helper:
- private void initDataSource() {
- this.dataSource = new IndexedContainer();
- this.dataSource.addContainerProperty(this.itemMarkerHtmlPropertyId,
- String.class, null);
- this.dataSource.addContainerProperty(this.itemMarkerXPropertyId,
- Double.class, new Double(0));
- this.dataSource.addContainerProperty(this.itemMarkerYPropertyId,
- Double.class, new Double(0));
- }
-
- public void clear() {
- setContainerDataSource(null);
- }
-
- public void setSizeFull() {
- // TODO Auto-generated method stub
-
- }
-
- public void setSizeUndefined() {
- // TODO Auto-generated method stub
-
- }
+ Container.Viewer {
+ private String TAG_MARKERS = "markers";
+ private String TAG_MARKER = "marker";
+ private int width = 400;
+ private int height = 300;
+ private int zoomLevel = 15;
+ private Point2D.Double mapCenter;
+
+ private Container dataSource;
+ private Object itemMarkerHtmlPropertyId = new Object();
+ private Object itemMarkerXPropertyId = new Object();
+ private Object itemMarkerYPropertyId = new Object();
+
+ public String getTag() {
+ return "googlemap";
+ }
+
+ public void paintContent(PaintTarget target) throws PaintException {
+ super.paintContent(target);
+ if (null != mapCenter) {
+ target.addAttribute("centerX", mapCenter.getX());
+ target.addAttribute("centerY", mapCenter.getY());
+ }
+ target.addAttribute("zoom", zoomLevel);
+ target.addAttribute("width", width);
+ target.addAttribute("height", height);
+
+ if (dataSource != null) {
+ target.startTag(TAG_MARKERS);
+ Collection itemIds = dataSource.getItemIds();
+ for (Iterator it = itemIds.iterator(); it.hasNext();) {
+ Object itemId = it.next();
+ Item item = dataSource.getItem(itemId);
+ Property p = item.getItemProperty(getItemMarkerXPropertyId());
+ Double x = (Double) (p != null ? p.getValue() : null);
+ p = item.getItemProperty(getItemMarkerYPropertyId());
+ Double y = (Double) (p != null ? p.getValue() : null);
+ if (x == null || y == null) {
+ continue;
+ }
+ target.startTag(TAG_MARKER);
+ target.addAttribute("x", x.doubleValue());
+ target.addAttribute("y", y.doubleValue());
+ p = item.getItemProperty(getItemMarkerHtmlPropertyId());
+ String h = (String) (p != null ? p.getValue() : null);
+ target.addAttribute("html", h);
+ target.endTag(TAG_MARKER);
+ }
+ target.endTag(TAG_MARKERS);
+ }
+ }
+
+ public void setZoomLevel(int zoomLevel) {
+ this.zoomLevel = zoomLevel;
+ requestRepaint();
+ }
+
+ public int getZoomLevel() {
+ return zoomLevel;
+ }
+
+ // Sizeable methods:
+
+ public int getHeight() {
+ return height;
+ }
+
+ public int getHeightUnits() {
+ return Sizeable.UNITS_PIXELS;
+ }
+
+ public int getWidth() {
+ return width;
+ }
+
+ public int getWidthUnits() {
+ return Sizeable.UNITS_PIXELS;
+ }
+
+ public void setHeight(int height) {
+ this.height = height;
+ requestRepaint();
+ }
+
+ public void setHeightUnits(int units) {
+ throw new UnsupportedOperationException();
+ }
+
+ public void setWidth(int width) {
+ this.width = width;
+ requestRepaint();
+ }
+
+ public void setWidthUnits(int units) {
+ throw new UnsupportedOperationException();
+ }
+
+ public void setMapCenter(Point2D.Double center) {
+ mapCenter = center;
+ }
+
+ public Point2D.Double getMapCenter() {
+ return mapCenter;
+ }
+
+ // Container.Viewer methods:
+
+ public Container getContainerDataSource() {
+ return dataSource;
+ }
+
+ public void setContainerDataSource(Container newDataSource) {
+
+ dataSource = newDataSource;
+
+ requestRepaint();
+ }
+
+ // Item methods
+
+ public Object getItemMarkerHtmlPropertyId() {
+ return itemMarkerHtmlPropertyId;
+ }
+
+ public void setItemMarkerHtmlPropertyId(Object itemMarkerHtmlPropertyId) {
+ this.itemMarkerHtmlPropertyId = itemMarkerHtmlPropertyId;
+ requestRepaint();
+ }
+
+ public Object getItemMarkerXPropertyId() {
+ return itemMarkerXPropertyId;
+ }
+
+ public void setItemMarkerXPropertyId(Object itemMarkerXPropertyId) {
+ this.itemMarkerXPropertyId = itemMarkerXPropertyId;
+ requestRepaint();
+ }
+
+ public Object getItemMarkerYPropertyId() {
+ return itemMarkerYPropertyId;
+ }
+
+ public void setItemMarkerYPropertyId(Object itemMarkerYPropertyId) {
+ this.itemMarkerYPropertyId = itemMarkerYPropertyId;
+ requestRepaint();
+ }
+
+ // Marker add
+
+ public Object addMarker(String html, Point2D.Double location) {
+ if (location == null) {
+ throw new IllegalArgumentException("Location must be non-null");
+ }
+ if (dataSource == null) {
+ initDataSource();
+ }
+ Object markerId = dataSource.addItem();
+ if (markerId == null) {
+ return null;
+ }
+ Item marker = dataSource.getItem(markerId);
+ Property p = marker.getItemProperty(getItemMarkerXPropertyId());
+ p.setValue(new Double(location.x));
+ p = marker.getItemProperty(getItemMarkerYPropertyId());
+ p.setValue(new Double(location.y));
+ p = marker.getItemProperty(getItemMarkerHtmlPropertyId());
+ p.setValue(html);
+
+ requestRepaint();
+
+ return markerId;
+ }
+
+ public void removeMarker(Object markerId) {
+ if (dataSource != null) {
+ dataSource.removeItem(markerId);
+ requestRepaint();
+ }
+ }
+
+ public Item getMarkerItem(Object markerId) {
+ if (dataSource != null) {
+ return dataSource.getItem(markerId);
+ } else {
+ return null;
+ }
+ }
+
+ // dataSource init helper:
+ private void initDataSource() {
+ dataSource = new IndexedContainer();
+ dataSource.addContainerProperty(itemMarkerHtmlPropertyId, String.class,
+ null);
+ dataSource.addContainerProperty(itemMarkerXPropertyId, Double.class,
+ new Double(0));
+ dataSource.addContainerProperty(itemMarkerYPropertyId, Double.class,
+ new Double(0));
+ }
+
+ public void clear() {
+ setContainerDataSource(null);
+ }
+
+ public void setSizeFull() {
+ // TODO Auto-generated method stub
+
+ }
+
+ public void setSizeUndefined() {
+ // TODO Auto-generated method stub
+
+ }
}
\ No newline at end of file
diff --git a/src/com/itmill/toolkit/demo/reservation/ReservationApplication.java b/src/com/itmill/toolkit/demo/reservation/ReservationApplication.java
index 0f3297461c..a3830f0483 100644
--- a/src/com/itmill/toolkit/demo/reservation/ReservationApplication.java
+++ b/src/com/itmill/toolkit/demo/reservation/ReservationApplication.java
@@ -25,329 +25,332 @@ import com.itmill.toolkit.ui.TabSheet.SelectedTabChangeEvent;
public class ReservationApplication extends Application {
- private SampleDB db;
-
- ResourceSelectorPanel resourcePanel;
-
- private CalendarField reservedFrom;
-
- private static final long DEFAULT_GAP_MILLIS = 3600000; // (almost) one
-
- // hour
- private long currentGapMillis = DEFAULT_GAP_MILLIS; // current length of
-
- // reservation
- private CalendarField reservedTo;
-
- private Label resourceName;
-
- private Label statusLabel;
-
- private TextField description;
-
- private Button reservationButton;
-
- private Table allTable;
-
- private CalendarField allCalendar;
-
- private GoogleMap map;
-
- private Window popupWindow;
- private Label popupMessage;
-
- public void init() {
-
- db = new SampleDB(true);
- db.generateResources();
- db.generateDemoUser();
- db.generateReservations();
-
- Window mainWindow = new Window("Reservr");
- setMainWindow(mainWindow);
- setTheme("reservr");
-
- TabSheet mainTabs = new TabSheet();
- mainWindow.addComponent(mainTabs);
-
- OrderedLayout reservationTab = new OrderedLayout();
- mainTabs.addTab(reservationTab, "Make reservation", null);
-
- resourcePanel = new ResourceSelectorPanel("Resources");
- resourcePanel.setResourceContainer(db.getResources(null));
- resourcePanel.addListener(
- ResourceSelectorPanel.SelectedResourcesChangedEvent.class,
- this, "selectedResourcesChanged");
- reservationTab.addComponent(resourcePanel);
-
- Panel reservationPanel = new Panel("Reservation", new OrderedLayout(
- OrderedLayout.ORIENTATION_HORIZONTAL));
- reservationPanel.addStyleName(Panel.STYLE_LIGHT);
- reservationPanel.getLayout().setMargin(true);
- reservationTab.addComponent(reservationPanel);
-
- OrderedLayout infoLayout = new OrderedLayout();
- reservationPanel.addComponent(infoLayout);
- resourceName = new Label("From the list above");
- resourceName.setCaption("Choose resource");
- infoLayout.addComponent(resourceName);
- description = new TextField();
- description.setColumns(45);
- description.setRows(5);
- infoLayout.addComponent(description);
- reservationButton = new Button("Make reservation", this,
- "makeReservation");
- infoLayout.addComponent(reservationButton);
- statusLabel = new Label("");
- statusLabel.setCaption("");
- infoLayout.addComponent(statusLabel);
-
- map = new GoogleMap();
- map.setWidth(325);
- map.setHeight(210);
- map.setItemMarkerHtmlPropertyId(SampleDB.Resource.PROPERTY_ID_NAME);
- map.setItemMarkerXPropertyId(SampleDB.Resource.PROPERTY_ID_LOCATIONX);
- map.setItemMarkerYPropertyId(SampleDB.Resource.PROPERTY_ID_LOCATIONY);
- map.setContainerDataSource(db.getResources(null));
- infoLayout.addComponent(map);
-
- Calendar from = Calendar.getInstance();
- from.add(Calendar.HOUR, 1);
- from.set(Calendar.MINUTE, 0);
- from.set(Calendar.SECOND, 0);
- from.set(Calendar.MILLISECOND, 0);
- reservedFrom = new CalendarField("From");
- reservedFrom.setMinimumDate(from.getTime());
- reservedFrom.setValue(from.getTime());
- reservedFrom.setImmediate(true);
- initCalendarFieldPropertyIds(reservedFrom);
- reservationPanel.addComponent(reservedFrom);
-
- Label arrowLabel = new Label("»");
- arrowLabel.setContentMode(Label.CONTENT_XHTML);
- arrowLabel.setStyleName("arrow");
- reservationPanel.addComponent(arrowLabel);
-
- Calendar to = Calendar.getInstance();
- to.setTime(from.getTime());
- to.add(Calendar.MILLISECOND, (int) DEFAULT_GAP_MILLIS);
- reservedTo = new CalendarField("To");
- reservedTo.setMinimumDate(to.getTime());
- reservedTo.setValue(to.getTime());
- reservedTo.setImmediate(true);
- initCalendarFieldPropertyIds(reservedTo);
- reservationPanel.addComponent(reservedTo);
-
- reservedFrom.addListener(new ValueChangeListener() {
- public void valueChange(ValueChangeEvent event) {
- Date fd = (Date) reservedFrom.getValue();
- if (fd == null) {
- reservedTo.setValue(null);
- reservedTo.setEnabled(false);
- refreshSelectedResources();
- return;
- } else {
- reservedTo.setEnabled(true);
- }
- reservedTo.setMinimumDate(new Date(fd.getTime()
- + DEFAULT_GAP_MILLIS));
- Calendar to = Calendar.getInstance();
- to.setTime(fd);
- to.add(Calendar.MILLISECOND, (int) currentGapMillis);
- reservedTo.setValue(to.getTime());
- refreshSelectedResources();
- resetStatus();
- }
- });
- reservedTo.addListener(new ValueChangeListener() {
- public void valueChange(ValueChangeEvent event) {
- Date from = (Date) reservedFrom.getValue();
- Date to = (Date) reservedTo.getValue();
- currentGapMillis = to.getTime() - from.getTime();
- if (currentGapMillis <= 0) {
- Calendar t = Calendar.getInstance();
- t.setTime(from);
- t.add(Calendar.MILLISECOND, (int) DEFAULT_GAP_MILLIS);
- reservedTo.setValue(t.getTime());
- }
- refreshSelectedResources();
- resetStatus();
- }
- });
-
- Panel allLayout = new Panel(new OrderedLayout(
- OrderedLayout.ORIENTATION_HORIZONTAL));
- allLayout.addStyleName(Panel.STYLE_LIGHT);
- allLayout.getLayout().setMargin(true);
- allCalendar = new CalendarField();
- initCalendarFieldPropertyIds(allCalendar);
- allLayout.addComponent(allCalendar);
- allTable = new Table();
- allTable.setWidth(700);
- allTable.setColumnCollapsingAllowed(true);
- allTable.setColumnReorderingAllowed(true);
- allLayout.addComponent(allTable);
- mainTabs.addTab(allLayout, "All reservations", null);
- mainTabs.addListener(new TabSheet.SelectedTabChangeListener() {
- public void selectedTabChange(SelectedTabChangeEvent event) {
- refreshReservations();
- }
- });
-
- refreshReservations();
- }
-
- public void makeReservation() {
- try {
- Item resource = getActiveResource();
- if (resource != null) {
- db.addReservation(resource, 0, (Date) reservedFrom.getValue(),
- (Date) reservedTo.getValue(), (String) description
- .getValue());
- statusLabel.setCaption("Success!");
- statusLabel
- .setValue("You have reserved the resource for the selected period.");
- } else {
- showMessage("No resource selected","Please select a resource (or category) to reserve.");
- }
- } catch (ResourceNotAvailableException e) {
- showMessage("Reservation failed", "The selected resource was not available for the selected period.");
- }
- refreshReservations();
- }
-
- public void showMessage(String caption, String message) {
- if (this.popupWindow == null) {
- this.popupWindow = new Window("No resource selected");
- this.popupWindow.setHeight(50);
- this.popupWindow.setPositionX(70);
- this.popupWindow.setPositionY(400);
- this.popupMessage = new Label("Please select a resource (or category) to reserve.");
- this.popupWindow.addComponent(this.popupMessage);
- Button b = new Button("Ok", new Button.ClickListener() {
- public void buttonClick(ClickEvent event) {
- getMainWindow().removeWindow(popupWindow);
- }
- });
- this.popupWindow.addComponent(b);
- } else {
- this.popupMessage.setValue(message);
- this.popupWindow.setCaption(caption);
- }
- getMainWindow().addWindow(this.popupWindow);
- }
-
-
- private Item getActiveResource() throws ResourceNotAvailableException {
- List rids = resourcePanel.getSelectedResources();
- if (rids != null && rids.size() > 0) {
- for (Iterator it = rids.iterator(); it.hasNext();) {
- Item resource = (Item) it.next();
- int id = ((Integer) resource.getItemProperty(
- SampleDB.Resource.PROPERTY_ID_ID).getValue())
- .intValue();
- if (db.isAvailableResource(id, (Date) reservedFrom.getValue(),
- (Date) reservedTo.getValue()))
- return resource;
- }
- throw new ResourceNotAvailableException("No available resource");
- } else {
- return null;
- }
- }
-
- private void refreshReservations() {
- Container reservations = db.getReservations(resourcePanel
- .getSelectedResources());
- reservedFrom.setContainerDataSource(reservations);
- reservedTo.setContainerDataSource(reservations);
- refreshSelectedResources();
- Container allReservations = db.getReservations(null);
- allTable.setContainerDataSource(allReservations);
- if (allReservations != null && allReservations.size() > 0) {
- allTable.setVisibleColumns(new Object[] {
- SampleDB.Reservation.PROPERTY_ID_RESERVED_FROM,
- SampleDB.Reservation.PROPERTY_ID_RESERVED_TO,
- SampleDB.Resource.PROPERTY_ID_NAME,
- SampleDB.Resource.PROPERTY_ID_DESCRIPTION,
- SampleDB.Reservation.PROPERTY_ID_DESCRIPTION });
- allTable.setColumnHeaders(new String[] { "From", "To", "Resource",
- "Description", "Message" });
- }
- allCalendar.setContainerDataSource(allReservations);
- }
-
- private void refreshSelectedResources() {
- Item resource = null;
- try {
- resource = getActiveResource();
- } catch (ResourceNotAvailableException e) {
- resourceName.setCaption("Not available");
- resourceName
- .setValue("Please choose another time period or resource");
- //reservationButton.setEnabled(false);
- return;
- }
- map.clear();
- if (resource == null) {
- resourceName.setCaption("Choose resource");
- resourceName.setValue("from the list above");
- //reservationButton.setEnabled(false);
- map.setContainerDataSource(db.getResources(null));
- map.setZoomLevel(1);
-
- } else {
- // Display active resource name + desc
- String name = (String) resource.getItemProperty(
- SampleDB.Resource.PROPERTY_ID_NAME).getValue();
- String desc = (String) resource.getItemProperty(
- SampleDB.Resource.PROPERTY_ID_DESCRIPTION).getValue();
- resourceName.setCaption(name);
- resourceName.setValue(desc);
- // Put all resources on map (may be many if category was selected)
- LinkedList srs = resourcePanel.getSelectedResources();
- for (Iterator it = srs.iterator(); it.hasNext();) {
- resource = (Item) it.next();
- name = (String) resource.getItemProperty(
- SampleDB.Resource.PROPERTY_ID_NAME).getValue();
- desc = (String) resource.getItemProperty(
- SampleDB.Resource.PROPERTY_ID_DESCRIPTION).getValue();
- Double x = (Double) resource.getItemProperty(
- SampleDB.Resource.PROPERTY_ID_LOCATIONX).getValue();
- Double y = (Double) resource.getItemProperty(
- SampleDB.Resource.PROPERTY_ID_LOCATIONY).getValue();
- if (x != null && y != null) {
- map.addMarker(name + "
" + desc, new Point2D.Double(x
- .doubleValue(), y.doubleValue()));
-
- }
-
- }
- map.setZoomLevel((srs.size() == 1 ? 14 : 9));
- //reservationButton.setEnabled(true);
- }
-
- }
-
- private 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.Resource.PROPERTY_ID_NAME);
- cal
- .setItemDescriptionPropertyId(SampleDB.Reservation.PROPERTY_ID_DESCRIPTION);
- }
-
- private void resetStatus() {
- statusLabel.setCaption("");
- statusLabel.setValue("");
- }
-
- public void selectedResourcesChanged(
- ResourceSelectorPanel.SelectedResourcesChangedEvent event) {
- refreshReservations();
- resetStatus();
- }
+ private SampleDB db;
+
+ ResourceSelectorPanel resourcePanel;
+
+ private CalendarField reservedFrom;
+
+ private static final long DEFAULT_GAP_MILLIS = 3600000; // (almost) one
+
+ // hour
+ private long currentGapMillis = DEFAULT_GAP_MILLIS; // current length of
+
+ // reservation
+ private CalendarField reservedTo;
+
+ private Label resourceName;
+
+ private Label statusLabel;
+
+ private TextField description;
+
+ private Button reservationButton;
+
+ private Table allTable;
+
+ private CalendarField allCalendar;
+
+ private GoogleMap map;
+
+ private Window popupWindow;
+ private Label popupMessage;
+
+ public void init() {
+
+ db = new SampleDB(true);
+ db.generateResources();
+ db.generateDemoUser();
+ db.generateReservations();
+
+ Window mainWindow = new Window("Reservr");
+ setMainWindow(mainWindow);
+ setTheme("reservr");
+
+ TabSheet mainTabs = new TabSheet();
+ mainWindow.addComponent(mainTabs);
+
+ OrderedLayout reservationTab = new OrderedLayout();
+ mainTabs.addTab(reservationTab, "Make reservation", null);
+
+ resourcePanel = new ResourceSelectorPanel("Resources");
+ resourcePanel.setResourceContainer(db.getResources(null));
+ resourcePanel.addListener(
+ ResourceSelectorPanel.SelectedResourcesChangedEvent.class,
+ this, "selectedResourcesChanged");
+ reservationTab.addComponent(resourcePanel);
+
+ Panel reservationPanel = new Panel("Reservation", new OrderedLayout(
+ OrderedLayout.ORIENTATION_HORIZONTAL));
+ reservationPanel.addStyleName(Panel.STYLE_LIGHT);
+ reservationPanel.getLayout().setMargin(true);
+ reservationTab.addComponent(reservationPanel);
+
+ OrderedLayout infoLayout = new OrderedLayout();
+ reservationPanel.addComponent(infoLayout);
+ resourceName = new Label("From the list above");
+ resourceName.setCaption("Choose resource");
+ infoLayout.addComponent(resourceName);
+ description = new TextField();
+ description.setColumns(45);
+ description.setRows(5);
+ infoLayout.addComponent(description);
+ reservationButton = new Button("Make reservation", this,
+ "makeReservation");
+ infoLayout.addComponent(reservationButton);
+ statusLabel = new Label("");
+ statusLabel.setCaption("");
+ infoLayout.addComponent(statusLabel);
+
+ map = new GoogleMap();
+ map.setWidth(325);
+ map.setHeight(210);
+ map.setItemMarkerHtmlPropertyId(SampleDB.Resource.PROPERTY_ID_NAME);
+ map.setItemMarkerXPropertyId(SampleDB.Resource.PROPERTY_ID_LOCATIONX);
+ map.setItemMarkerYPropertyId(SampleDB.Resource.PROPERTY_ID_LOCATIONY);
+ map.setContainerDataSource(db.getResources(null));
+ infoLayout.addComponent(map);
+
+ Calendar from = Calendar.getInstance();
+ from.add(Calendar.HOUR, 1);
+ from.set(Calendar.MINUTE, 0);
+ from.set(Calendar.SECOND, 0);
+ from.set(Calendar.MILLISECOND, 0);
+ reservedFrom = new CalendarField("From");
+ reservedFrom.setMinimumDate(from.getTime());
+ reservedFrom.setValue(from.getTime());
+ reservedFrom.setImmediate(true);
+ initCalendarFieldPropertyIds(reservedFrom);
+ reservationPanel.addComponent(reservedFrom);
+
+ Label arrowLabel = new Label("»");
+ arrowLabel.setContentMode(Label.CONTENT_XHTML);
+ arrowLabel.setStyleName("arrow");
+ reservationPanel.addComponent(arrowLabel);
+
+ Calendar to = Calendar.getInstance();
+ to.setTime(from.getTime());
+ to.add(Calendar.MILLISECOND, (int) DEFAULT_GAP_MILLIS);
+ reservedTo = new CalendarField("To");
+ reservedTo.setMinimumDate(to.getTime());
+ reservedTo.setValue(to.getTime());
+ reservedTo.setImmediate(true);
+ initCalendarFieldPropertyIds(reservedTo);
+ reservationPanel.addComponent(reservedTo);
+
+ reservedFrom.addListener(new ValueChangeListener() {
+ public void valueChange(ValueChangeEvent event) {
+ Date fd = (Date) reservedFrom.getValue();
+ if (fd == null) {
+ reservedTo.setValue(null);
+ reservedTo.setEnabled(false);
+ refreshSelectedResources();
+ return;
+ } else {
+ reservedTo.setEnabled(true);
+ }
+ reservedTo.setMinimumDate(new Date(fd.getTime()
+ + DEFAULT_GAP_MILLIS));
+ Calendar to = Calendar.getInstance();
+ to.setTime(fd);
+ to.add(Calendar.MILLISECOND, (int) currentGapMillis);
+ reservedTo.setValue(to.getTime());
+ refreshSelectedResources();
+ resetStatus();
+ }
+ });
+ reservedTo.addListener(new ValueChangeListener() {
+ public void valueChange(ValueChangeEvent event) {
+ Date from = (Date) reservedFrom.getValue();
+ Date to = (Date) reservedTo.getValue();
+ currentGapMillis = to.getTime() - from.getTime();
+ if (currentGapMillis <= 0) {
+ Calendar t = Calendar.getInstance();
+ t.setTime(from);
+ t.add(Calendar.MILLISECOND, (int) DEFAULT_GAP_MILLIS);
+ reservedTo.setValue(t.getTime());
+ }
+ refreshSelectedResources();
+ resetStatus();
+ }
+ });
+
+ Panel allLayout = new Panel(new OrderedLayout(
+ OrderedLayout.ORIENTATION_HORIZONTAL));
+ allLayout.addStyleName(Panel.STYLE_LIGHT);
+ allLayout.getLayout().setMargin(true);
+ allCalendar = new CalendarField();
+ initCalendarFieldPropertyIds(allCalendar);
+ allLayout.addComponent(allCalendar);
+ allTable = new Table();
+ allTable.setWidth(700);
+ allTable.setColumnCollapsingAllowed(true);
+ allTable.setColumnReorderingAllowed(true);
+ allLayout.addComponent(allTable);
+ mainTabs.addTab(allLayout, "All reservations", null);
+ mainTabs.addListener(new TabSheet.SelectedTabChangeListener() {
+ public void selectedTabChange(SelectedTabChangeEvent event) {
+ refreshReservations();
+ }
+ });
+
+ refreshReservations();
+ }
+
+ public void makeReservation() {
+ try {
+ Item resource = getActiveResource();
+ if (resource != null) {
+ db.addReservation(resource, 0, (Date) reservedFrom.getValue(),
+ (Date) reservedTo.getValue(), (String) description
+ .getValue());
+ statusLabel.setCaption("Success!");
+ statusLabel
+ .setValue("You have reserved the resource for the selected period.");
+ } else {
+ showMessage("No resource selected",
+ "Please select a resource (or category) to reserve.");
+ }
+ } catch (ResourceNotAvailableException e) {
+ showMessage("Reservation failed",
+ "The selected resource was not available for the selected period.");
+ }
+ refreshReservations();
+ }
+
+ public void showMessage(String caption, String message) {
+ if (popupWindow == null) {
+ popupWindow = new Window("No resource selected");
+ popupWindow.setHeight(50);
+ popupWindow.setPositionX(70);
+ popupWindow.setPositionY(400);
+ popupMessage = new Label(
+ "Please select a resource (or category) to reserve.");
+ popupWindow.addComponent(popupMessage);
+ Button b = new Button("Ok", new Button.ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ getMainWindow().removeWindow(popupWindow);
+ }
+ });
+ popupWindow.addComponent(b);
+ } else {
+ popupMessage.setValue(message);
+ popupWindow.setCaption(caption);
+ }
+ getMainWindow().addWindow(popupWindow);
+ }
+
+ private Item getActiveResource() throws ResourceNotAvailableException {
+ List rids = resourcePanel.getSelectedResources();
+ if (rids != null && rids.size() > 0) {
+ for (Iterator it = rids.iterator(); it.hasNext();) {
+ Item resource = (Item) it.next();
+ int id = ((Integer) resource.getItemProperty(
+ SampleDB.Resource.PROPERTY_ID_ID).getValue())
+ .intValue();
+ if (db.isAvailableResource(id, (Date) reservedFrom.getValue(),
+ (Date) reservedTo.getValue())) {
+ return resource;
+ }
+ }
+ throw new ResourceNotAvailableException("No available resource");
+ } else {
+ return null;
+ }
+ }
+
+ private void refreshReservations() {
+ Container reservations = db.getReservations(resourcePanel
+ .getSelectedResources());
+ reservedFrom.setContainerDataSource(reservations);
+ reservedTo.setContainerDataSource(reservations);
+ refreshSelectedResources();
+ Container allReservations = db.getReservations(null);
+ allTable.setContainerDataSource(allReservations);
+ if (allReservations != null && allReservations.size() > 0) {
+ allTable.setVisibleColumns(new Object[] {
+ SampleDB.Reservation.PROPERTY_ID_RESERVED_FROM,
+ SampleDB.Reservation.PROPERTY_ID_RESERVED_TO,
+ SampleDB.Resource.PROPERTY_ID_NAME,
+ SampleDB.Resource.PROPERTY_ID_DESCRIPTION,
+ SampleDB.Reservation.PROPERTY_ID_DESCRIPTION });
+ allTable.setColumnHeaders(new String[] { "From", "To", "Resource",
+ "Description", "Message" });
+ }
+ allCalendar.setContainerDataSource(allReservations);
+ }
+
+ private void refreshSelectedResources() {
+ Item resource = null;
+ try {
+ resource = getActiveResource();
+ } catch (ResourceNotAvailableException e) {
+ resourceName.setCaption("Not available");
+ resourceName
+ .setValue("Please choose another time period or resource");
+ // reservationButton.setEnabled(false);
+ return;
+ }
+ map.clear();
+ if (resource == null) {
+ resourceName.setCaption("Choose resource");
+ resourceName.setValue("from the list above");
+ // reservationButton.setEnabled(false);
+ map.setContainerDataSource(db.getResources(null));
+ map.setZoomLevel(1);
+
+ } else {
+ // Display active resource name + desc
+ String name = (String) resource.getItemProperty(
+ SampleDB.Resource.PROPERTY_ID_NAME).getValue();
+ String desc = (String) resource.getItemProperty(
+ SampleDB.Resource.PROPERTY_ID_DESCRIPTION).getValue();
+ resourceName.setCaption(name);
+ resourceName.setValue(desc);
+ // Put all resources on map (may be many if category was selected)
+ LinkedList srs = resourcePanel.getSelectedResources();
+ for (Iterator it = srs.iterator(); it.hasNext();) {
+ resource = (Item) it.next();
+ name = (String) resource.getItemProperty(
+ SampleDB.Resource.PROPERTY_ID_NAME).getValue();
+ desc = (String) resource.getItemProperty(
+ SampleDB.Resource.PROPERTY_ID_DESCRIPTION).getValue();
+ Double x = (Double) resource.getItemProperty(
+ SampleDB.Resource.PROPERTY_ID_LOCATIONX).getValue();
+ Double y = (Double) resource.getItemProperty(
+ SampleDB.Resource.PROPERTY_ID_LOCATIONY).getValue();
+ if (x != null && y != null) {
+ map.addMarker(name + "
" + desc, new Point2D.Double(x
+ .doubleValue(), y.doubleValue()));
+
+ }
+
+ }
+ map.setZoomLevel((srs.size() == 1 ? 14 : 9));
+ // reservationButton.setEnabled(true);
+ }
+
+ }
+
+ private 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.Resource.PROPERTY_ID_NAME);
+ cal
+ .setItemDescriptionPropertyId(SampleDB.Reservation.PROPERTY_ID_DESCRIPTION);
+ }
+
+ private void resetStatus() {
+ statusLabel.setCaption("");
+ statusLabel.setValue("");
+ }
+
+ public void selectedResourcesChanged(
+ ResourceSelectorPanel.SelectedResourcesChangedEvent event) {
+ refreshReservations();
+ resetStatus();
+ }
}
diff --git a/src/com/itmill/toolkit/demo/reservation/ResourceNotAvailableException.java b/src/com/itmill/toolkit/demo/reservation/ResourceNotAvailableException.java
index 39e5a82060..673d6e9190 100644
--- a/src/com/itmill/toolkit/demo/reservation/ResourceNotAvailableException.java
+++ b/src/com/itmill/toolkit/demo/reservation/ResourceNotAvailableException.java
@@ -1,7 +1,7 @@
package com.itmill.toolkit.demo.reservation;
public class ResourceNotAvailableException extends Exception {
- public ResourceNotAvailableException(String message) {
- super(message);
- }
+ public ResourceNotAvailableException(String message) {
+ super(message);
+ }
}
diff --git a/src/com/itmill/toolkit/demo/reservation/ResourceSelectorPanel.java b/src/com/itmill/toolkit/demo/reservation/ResourceSelectorPanel.java
index d28313cc62..17bd72f9a5 100644
--- a/src/com/itmill/toolkit/demo/reservation/ResourceSelectorPanel.java
+++ b/src/com/itmill/toolkit/demo/reservation/ResourceSelectorPanel.java
@@ -13,106 +13,106 @@ import com.itmill.toolkit.ui.Panel;
import com.itmill.toolkit.ui.Button.ClickEvent;
public class ResourceSelectorPanel extends Panel implements
- Button.ClickListener {
- private HashMap categoryLayouts = new HashMap();
- private HashMap categoryResources = new HashMap();
+ Button.ClickListener {
+ private HashMap categoryLayouts = new HashMap();
+ private HashMap categoryResources = new HashMap();
- private Container allResources;
- private LinkedList selectedResources = null;
+ private Container allResources;
+ private LinkedList selectedResources = null;
- public ResourceSelectorPanel(String caption) {
- super(caption, new OrderedLayout(OrderedLayout.ORIENTATION_HORIZONTAL));
- addStyleName(Panel.STYLE_LIGHT);
- }
+ public ResourceSelectorPanel(String caption) {
+ super(caption, new OrderedLayout(OrderedLayout.ORIENTATION_HORIZONTAL));
+ addStyleName(Panel.STYLE_LIGHT);
+ }
- public void setResourceContainer(Container resources) {
- this.removeAllComponents();
- categoryLayouts.clear();
- categoryResources.clear();
- if (resources != null && resources.size() > 0) {
- for (Iterator it = resources.getItemIds().iterator(); it.hasNext();) {
- Item resource = (Item) resources.getItem(it.next());
- Integer id = (Integer) resource.getItemProperty(
- SampleDB.Resource.PROPERTY_ID_ID).getValue();
- String category = (String) resource.getItemProperty(
- SampleDB.Resource.PROPERTY_ID_CATEGORY).getValue();
- String name = (String) resource.getItemProperty(
- SampleDB.Resource.PROPERTY_ID_NAME).getValue();
- String description = (String) resource.getItemProperty(
- SampleDB.Resource.PROPERTY_ID_DESCRIPTION).getValue();
- Button rButton = new Button(name, this);
- rButton.setStyleName("link");
- rButton.setDescription(description);
- rButton.setData(resource);
- Layout resourceLayout = (Layout) categoryLayouts.get(category);
- LinkedList resourceList = (LinkedList) categoryResources
- .get(category);
- if (resourceLayout == null) {
- resourceLayout = new OrderedLayout();
- resourceLayout.setMargin(true);
- this.addComponent(resourceLayout);
- categoryLayouts.put(category, resourceLayout);
- resourceList = new LinkedList();
- categoryResources.put(category, resourceList);
- Button cButton = new Button(category + " (any)", this);
- cButton.setStyleName("important-link");
- cButton.setData(category);
- resourceLayout.addComponent(cButton);
- }
- resourceLayout.addComponent(rButton);
- resourceList.add(resource);
- }
- }
- }
+ public void setResourceContainer(Container resources) {
+ removeAllComponents();
+ categoryLayouts.clear();
+ categoryResources.clear();
+ if (resources != null && resources.size() > 0) {
+ for (Iterator it = resources.getItemIds().iterator(); it.hasNext();) {
+ Item resource = resources.getItem(it.next());
+ Integer id = (Integer) resource.getItemProperty(
+ SampleDB.Resource.PROPERTY_ID_ID).getValue();
+ String category = (String) resource.getItemProperty(
+ SampleDB.Resource.PROPERTY_ID_CATEGORY).getValue();
+ String name = (String) resource.getItemProperty(
+ SampleDB.Resource.PROPERTY_ID_NAME).getValue();
+ String description = (String) resource.getItemProperty(
+ SampleDB.Resource.PROPERTY_ID_DESCRIPTION).getValue();
+ Button rButton = new Button(name, this);
+ rButton.setStyleName("link");
+ rButton.setDescription(description);
+ rButton.setData(resource);
+ Layout resourceLayout = (Layout) categoryLayouts.get(category);
+ LinkedList resourceList = (LinkedList) categoryResources
+ .get(category);
+ if (resourceLayout == null) {
+ resourceLayout = new OrderedLayout();
+ resourceLayout.setMargin(true);
+ addComponent(resourceLayout);
+ categoryLayouts.put(category, resourceLayout);
+ resourceList = new LinkedList();
+ categoryResources.put(category, resourceList);
+ Button cButton = new Button(category + " (any)", this);
+ cButton.setStyleName("important-link");
+ cButton.setData(category);
+ resourceLayout.addComponent(cButton);
+ }
+ resourceLayout.addComponent(rButton);
+ resourceList.add(resource);
+ }
+ }
+ }
- private void setSelectedResources(LinkedList resources) {
- selectedResources = resources;
- fireEvent(new SelectedResourcesChangedEvent());
- }
+ private void setSelectedResources(LinkedList resources) {
+ selectedResources = resources;
+ fireEvent(new SelectedResourcesChangedEvent());
+ }
- public LinkedList getSelectedResources() {
- return selectedResources;
- }
+ public LinkedList getSelectedResources() {
+ return selectedResources;
+ }
- public void buttonClick(ClickEvent event) {
- Object source = event.getSource();
- if (source instanceof Button) {
- Object data = ((Button) source).getData();
- String name = ((Button) source).getCaption();
- resetStyles();
- if (data instanceof Item) {
- LinkedList rlist = new LinkedList();
- rlist.add(data);
- setSelectedResources(rlist);
- } else {
- String category = (String) data;
- LinkedList resources = (LinkedList) categoryResources
- .get(category);
- setSelectedResources(resources);
- }
- ((Button) source).setStyleName("selected-link");
- }
+ public void buttonClick(ClickEvent event) {
+ Object source = event.getSource();
+ if (source instanceof Button) {
+ Object data = ((Button) source).getData();
+ String name = ((Button) source).getCaption();
+ resetStyles();
+ if (data instanceof Item) {
+ LinkedList rlist = new LinkedList();
+ rlist.add(data);
+ setSelectedResources(rlist);
+ } else {
+ String category = (String) data;
+ LinkedList resources = (LinkedList) categoryResources
+ .get(category);
+ setSelectedResources(resources);
+ }
+ ((Button) source).setStyleName("selected-link");
+ }
- }
+ }
- private void resetStyles() {
- for (Iterator it = categoryLayouts.values().iterator(); it.hasNext();) {
- Layout lo = (Layout) it.next();
- for (Iterator bit = lo.getComponentIterator(); bit.hasNext();) {
- Button b = (Button) bit.next();
- if (b.getData() instanceof Item) {
- b.setStyleName("link");
- } else {
- b.setStyleName("important-link");
- }
- }
- }
+ private void resetStyles() {
+ for (Iterator it = categoryLayouts.values().iterator(); it.hasNext();) {
+ Layout lo = (Layout) it.next();
+ for (Iterator bit = lo.getComponentIterator(); bit.hasNext();) {
+ Button b = (Button) bit.next();
+ if (b.getData() instanceof Item) {
+ b.setStyleName("link");
+ } else {
+ b.setStyleName("important-link");
+ }
+ }
+ }
- }
+ }
- public class SelectedResourcesChangedEvent extends Event {
- public SelectedResourcesChangedEvent() {
- super(ResourceSelectorPanel.this);
- }
- }
+ public class SelectedResourcesChangedEvent extends Event {
+ public SelectedResourcesChangedEvent() {
+ super(ResourceSelectorPanel.this);
+ }
+ }
}
diff --git a/src/com/itmill/toolkit/demo/reservation/SampleDB.java b/src/com/itmill/toolkit/demo/reservation/SampleDB.java
index c8eb7c725e..4ee0e9bc33 100644
--- a/src/com/itmill/toolkit/demo/reservation/SampleDB.java
+++ b/src/com/itmill/toolkit/demo/reservation/SampleDB.java
@@ -17,529 +17,529 @@ import com.itmill.toolkit.data.Item;
import com.itmill.toolkit.data.util.QueryContainer;
public class SampleDB {
- public class User {
- public static final String TABLE = "USER";
- public static final String PROPERTY_ID_ID = TABLE + "_ID";
- public static final String PROPERTY_ID_FULLNAME = TABLE + "_FULLNAME";
- public static final String PROPERTY_ID_EMAIL = TABLE + "_EMAIL";
- public static final String PROPERTY_ID_PASSWORD = TABLE + "_PASSWORD";
- public static final String PROPERTY_ID_DELETED = TABLE + "_DELETED";
- }
-
- 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_ID = TABLE
- + "_RESERVED_BY_USER_ID";
- 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_USER = "CREATE TABLE "
- + User.TABLE + " (" + " " + User.PROPERTY_ID_ID
- + " INTEGER IDENTITY" + ", " + User.PROPERTY_ID_FULLNAME
- + " VARCHAR(100) NOT NULL" + ", " + User.PROPERTY_ID_EMAIL
- + " VARCHAR(50) NOT NULL" + ", " + User.PROPERTY_ID_PASSWORD
- + " VARCHAR(20) NOT NULL" + ", " + User.PROPERTY_ID_DELETED
- + " BOOLEAN DEFAULT false NOT NULL" + ", UNIQUE("
- + User.PROPERTY_ID_FULLNAME + "), UNIQUE(" + User.PROPERTY_ID_EMAIL
- + ") )";
- 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_BY_ID
- + " INTEGER" + ", " + Reservation.PROPERTY_ID_RESERVED_FROM
- + " TIMESTAMP NOT NULL" + ", "
- + Reservation.PROPERTY_ID_RESERVED_TO + " TIMESTAMP NOT NULL"
- + ", " + Reservation.PROPERTY_ID_DESCRIPTION + " VARCHAR(100)"
- + ", FOREIGN KEY (" + Reservation.PROPERTY_ID_RESOURCE_ID
- + ") REFERENCES " + Resource.TABLE + "(" + Resource.PROPERTY_ID_ID
- + "), FOREIGN KEY (" + Reservation.PROPERTY_ID_RESERVED_BY_ID
- + ") REFERENCES " + User.TABLE + "(" + User.PROPERTY_ID_ID + "))";
-
- private Connection connection = null;
-
- /**
- * Create database.
- */
- public SampleDB() {
- this(false);
- }
-
- public SampleDB(boolean recreate) {
- // connect to SQL database
- connect();
-
- if (recreate) {
- dropTables();
- }
-
- // initialize SQL database
- createTables();
-
- // test by executing sample JDBC query
- testDatabase();
- }
-
- private void dropTables() {
- try {
- update("DROP TABLE " + Reservation.TABLE);
- } catch (SQLException IGNORED) {
- // IGNORED, assuming it was not there
- }
- try {
- update("DROP TABLE " + Resource.TABLE);
- } catch (SQLException IGNORED) {
- // IGNORED, assuming it was not there
- }
- try {
- update("DROP TABLE " + User.TABLE);
- } catch (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 void connect() {
- try {
- Class.forName("org.hsqldb.jdbcDriver").newInstance();
- connection = DriverManager.getConnection(DB_URL);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- /**
- * use for SQL commands CREATE, DROP, INSERT and UPDATE
- *
- * @param expression
- * @throws SQLException
- */
- private void update(String expression) throws SQLException {
- Statement st = null;
- st = connection.createStatement();
- 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 void createTables() {
- try {
- String stmt = null;
- stmt = CREATE_TABLE_RESOURCE;
- update(stmt);
- } catch (SQLException e) {
- if (e.toString().indexOf("Table already exists") == -1) {
- throw new RuntimeException(e);
- }
- }
- try {
- String stmt = null;
- stmt = CREATE_TABLE_USER;
- update(stmt);
- } catch (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 (SQLException e) {
- if (e.toString().indexOf("Table already exists") == -1) {
- throw new RuntimeException(e);
- }
- }
- }
-
- /**
- * Test database connection with simple SELECT command.
- *
- */
- private String testDatabase() {
- String result = null;
- try {
- Statement stmt = connection.createStatement(
- ResultSet.TYPE_SCROLL_INSENSITIVE,
- ResultSet.CONCUR_UPDATABLE);
- ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM "
- + Resource.TABLE);
- rs.next();
- result = "rowcount for table test is " + rs.getObject(1).toString();
- stmt.close();
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }
- return result;
- }
-
- public Connection getConnection() {
- return connection;
- }
-
- public Container getCategories() {
- // TODO where deleted=?
- 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 (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 (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) {
- StringBuffer s = new StringBuffer();
- for (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 {
- QueryContainer qc = new QueryContainer(q, connection,
- ResultSet.TYPE_SCROLL_INSENSITIVE,
- ResultSet.CONCUR_READ_ONLY);
- if (qc.size() < 1) {
- return null;
- } else {
- return qc;
- }
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }
- }
-
- public void addReservation(Item resource, int reservedById,
- Date reservedFrom, Date reservedTo, String description) {
- if (reservedFrom.after(reservedTo)) {
- Date tmp = reservedTo;
- reservedTo = reservedFrom;
- reservedFrom = tmp;
- }
- int resourceId = ((Integer) resource.getItemProperty(
- Resource.PROPERTY_ID_ID).getValue()).intValue();
- String q = "INSERT INTO " + Reservation.TABLE + " ("
- + Reservation.PROPERTY_ID_RESOURCE_ID + ","
- + Reservation.PROPERTY_ID_RESERVED_BY_ID + ","
- + Reservation.PROPERTY_ID_RESERVED_FROM + ","
- + Reservation.PROPERTY_ID_RESERVED_TO + ","
- + Reservation.PROPERTY_ID_DESCRIPTION + ")"
- + "VALUES (?,?,?,?,?)";
- synchronized (DB_URL) {
- try {
- if (!isAvailableResource(resourceId, reservedFrom, reservedTo)) {
- throw new ResourceNotAvailableException(
- "The resource is not available at that time.");
- }
- PreparedStatement p = connection.prepareStatement(q);
- p.setInt(1, resourceId);
- p.setInt(2, reservedById);
- 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 (Exception e) {
- throw new RuntimeException(e);
- }
- }
- }
-
- public boolean isAvailableResource(int resourceId, Date reservedFrom,
- Date reservedTo) {
- // TODO where deleted=?
- if (reservedFrom.after(reservedTo)) {
- Date tmp = reservedTo;
- reservedTo = reservedFrom;
- reservedFrom = tmp;
- }
- String checkQ = "SELECT count(*) FROM " + Reservation.TABLE + " WHERE "
- + Reservation.PROPERTY_ID_RESOURCE_ID + "=? AND (("
- + Reservation.PROPERTY_ID_RESERVED_FROM + ">=? AND "
- + Reservation.PROPERTY_ID_RESERVED_FROM + ") OR ("
- + Reservation.PROPERTY_ID_RESERVED_TO + ">? AND "
- + Reservation.PROPERTY_ID_RESERVED_TO + "<=?) OR ("
- + Reservation.PROPERTY_ID_RESERVED_FROM + "<=? AND "
- + Reservation.PROPERTY_ID_RESERVED_TO + ">=?)" + ")";
- try {
- 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();
- ResultSet rs = p.getResultSet();
- if (rs.next() && rs.getInt(1) > 0) {
- return false;
- }
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- return true;
- }
-
- public Container getUsers() {
- // TODO where deleted=?
- String q = "SELECT * FROM " + User.TABLE + " ORDER BY "
- + User.PROPERTY_ID_FULLNAME;
- try {
- QueryContainer qc = new QueryContainer(q, connection,
- ResultSet.TYPE_SCROLL_INSENSITIVE,
- ResultSet.CONCUR_READ_ONLY);
- return qc;
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }
- }
-
- public void generateReservations() {
- int days = 30;
- 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" };
- Container cat = getCategories();
- Collection cIds = cat.getItemIds();
- for (Iterator it = cIds.iterator(); it.hasNext();) {
- Object id = it.next();
- Item ci = cat.getItem(id);
- String c = (String) ci.getItemProperty(
- Resource.PROPERTY_ID_CATEGORY).getValue();
- Container resources = getResources(c);
- Collection rIds = resources.getItemIds();
- Calendar cal = Calendar.getInstance();
- cal.set(Calendar.MINUTE, 0);
- cal.set(Calendar.SECOND, 0);
- cal.set(Calendar.MILLISECOND, 0);
- int hourNow = new Date().getHours();
- // cal.add(Calendar.DAY_OF_MONTH, -days);
- for (int i = 0; i < days; i++) {
- int r = 3;
- for (Iterator rit = rIds.iterator(); rit.hasNext() && r > 0; r--) {
- Object rid = rit.next();
- Item resource = resources.getItem(rid);
- int s = hourNow - 6 + (int) Math.round(Math.random() * 6.0);
- int e = s + 1 + (int) Math.round(Math.random() * 4.0);
- Date start = new Date(cal.getTimeInMillis());
- start.setHours(s);
- Date end = new Date(cal.getTimeInMillis());
- end.setHours(e);
- addReservation(resource, 0, start, end,
- descriptions[(int) Math.floor(Math.random()
- * descriptions.length)]);
- }
- cal.add(Calendar.DATE, 1);
- }
- }
-
- }
-
- public void generateResources() {
-
- Object[][] resources = {
- // Turku
- { "01", "01 Ford Mondeo", "w/ company logo", "Turku",
- new Double(60.510857), new Double(22.275424) },
- { "02", "02 Citroen Jumper",
- "w/ company logo. 12m3 storage space.", "Turku",
- new Double(60.452171), new Double(22.2995) },
- { "03", "03 Saab 93", "Cabriolet. Keys from the rental desk.",
- "Turku", new Double(60.4507), new Double(22.295551) },
- { "04", "04 Volvo S60", "Key from the rental desk.", "Turku",
- new Double(60.434722), new Double(22.224398) },
- { "05", "05 Smart fourtwo", "Cabrio. Keys from infodesk.",
- "Turku", new Double(60.508970), new Double(22.264790) },
- // Helsinki
- { "06", "06 Smart fourtwo", "Cabrio. Keys from infodesk.",
- "Helsinki", new Double(60.17175), new Double(24.939029) },
- { "07", "07 Smart fourtwo", "Cabrio. Keys from infodesk.",
- "Helsinki", new Double(60.17175), new Double(24.939029) },
- { "08", "08 Smart fourtwo", "Cabrio. Keys from infodesk.",
- "Helsinki", new Double(60.166579),
- new Double(24.953899) },
- { "09", "09 Volvo S60", "Keys from infodesk.", "Helsinki",
- new Double(60.317832), new Double(24.967289) },
- { "10", "10 Saab 93", "Keys from infodesk.", "Helsinki",
- new Double(60.249193), new Double(25.045921) },
- // Silicon Valley
- { "11", "11 Ford Mustang", "Keys from Acme clerk.",
- "Silicon Valley", new Double(37.615853),
- new Double(-122.386384) },
- { "12", "12 Ford Fusion", "Keys from infodesk.",
- "Silicon Valley", new Double(37.365028),
- new Double(-121.922654) },
- { "13", "13 Land Rover", "Keys from infodesk.",
- "Silicon Valley", new Double(37.365028),
- new Double(-121.922654) },
- { "14", "14 Land Rover", "Keys from infodesk.",
- "Silicon Valley", new Double(37.365028),
- new Double(-121.922654) },
- { "15", "15 Ford Mustang", "GT Cal Special. Keys from guard.",
- "Silicon Valley", new Double(37.403812),
- new Double(-121.977425) },
- { "16", "16 Ford Focus", "Keys from guard.", "Silicon Valley",
- new Double(37.403812), new Double(-121.977425) },
- // Paris
- { "17", "17 Peugeot 308", "Keys from infodesk.", "Paris",
- new Double(48.844756), new Double(2.372784) },
- { "18", "18 Citroen C6", "Keys from rental desk.", "Paris",
- new Double(49.007253), new Double(2.545025) },
- { "19", "19 Citroen C6", "Keys from infodesk.", "Paris",
- new Double(48.729061), new Double(2.368087) },
- { "20", "20 Peugeot 308", "Keys from ticket sales.", "Paris",
- new Double(48.880931), new Double(2.356988) },
- { "21", "21 Peugeot 308", "Keys from ticket sales.", "Paris",
- new Double(48.876479), new Double(2.358161) },
- // STHLM
- { "22", "22 Volvo S60", "Keys from infodesk.", "Stockholm",
- new Double(59.350414), new Double(18.106574) },
- { "23", "23 Saab 93", "Keys from infodesk.", "Stockholm",
- new Double(59.355905), new Double(17.946784) },
- { "24", "24 Smart fourtwo", "Keys from infodesk.", "Stockholm",
- new Double(59.315939), new Double(18.095904) },
- { "25", "25 Smart fourtwo", "Keys from infodesk.", "Stockholm",
- new Double(59.330716), new Double(18.058702) },
- // Boston
- { "26", "26 Ford Mustang", "Keys from infodesk.", "Boston",
- new Double(42.366588), new Double(-71.020955) },
- { "27", "27 Smart fourtwo", "Keys from infodesk.", "Boston",
- new Double(42.365419), new Double(-71.061748) },
- { "28", "28 Volvo S60", "Keys from Seaport Hotel reception.",
- "Boston", new Double(42.34811), new Double(-71.041127) },
- { "29", "29 Smart fourtwo",
- "Keys from Seaport Hotel reception.", "Boston",
- new Double(42.348072), new Double(-71.041315) },
-
- };
-
- 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 {
- 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 (SQLException e) {
- throw new RuntimeException(e);
- }
- }
-
- public void generateDemoUser() {
- String q = "INSERT INTO USER (" + User.PROPERTY_ID_FULLNAME + ","
- + User.PROPERTY_ID_EMAIL + "," + User.PROPERTY_ID_PASSWORD
- + ") VALUES (?,?,?)";
- try {
- PreparedStatement stmt = connection.prepareStatement(q);
- stmt.setString(1, "Demo User");
- stmt.setString(2, "demo.user@itmill.com");
- stmt.setString(3, "demo");
- stmt.execute();
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }
-
- }
+ public class User {
+ public static final String TABLE = "USER";
+ public static final String PROPERTY_ID_ID = TABLE + "_ID";
+ public static final String PROPERTY_ID_FULLNAME = TABLE + "_FULLNAME";
+ public static final String PROPERTY_ID_EMAIL = TABLE + "_EMAIL";
+ public static final String PROPERTY_ID_PASSWORD = TABLE + "_PASSWORD";
+ public static final String PROPERTY_ID_DELETED = TABLE + "_DELETED";
+ }
+
+ 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_ID = TABLE
+ + "_RESERVED_BY_USER_ID";
+ 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_USER = "CREATE TABLE "
+ + User.TABLE + " (" + " " + User.PROPERTY_ID_ID
+ + " INTEGER IDENTITY" + ", " + User.PROPERTY_ID_FULLNAME
+ + " VARCHAR(100) NOT NULL" + ", " + User.PROPERTY_ID_EMAIL
+ + " VARCHAR(50) NOT NULL" + ", " + User.PROPERTY_ID_PASSWORD
+ + " VARCHAR(20) NOT NULL" + ", " + User.PROPERTY_ID_DELETED
+ + " BOOLEAN DEFAULT false NOT NULL" + ", UNIQUE("
+ + User.PROPERTY_ID_FULLNAME + "), UNIQUE(" + User.PROPERTY_ID_EMAIL
+ + ") )";
+ 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_BY_ID
+ + " INTEGER" + ", " + Reservation.PROPERTY_ID_RESERVED_FROM
+ + " TIMESTAMP NOT NULL" + ", "
+ + Reservation.PROPERTY_ID_RESERVED_TO + " TIMESTAMP NOT NULL"
+ + ", " + Reservation.PROPERTY_ID_DESCRIPTION + " VARCHAR(100)"
+ + ", FOREIGN KEY (" + Reservation.PROPERTY_ID_RESOURCE_ID
+ + ") REFERENCES " + Resource.TABLE + "(" + Resource.PROPERTY_ID_ID
+ + "), FOREIGN KEY (" + Reservation.PROPERTY_ID_RESERVED_BY_ID
+ + ") REFERENCES " + User.TABLE + "(" + User.PROPERTY_ID_ID + "))";
+
+ private Connection connection = null;
+
+ /**
+ * Create database.
+ */
+ public SampleDB() {
+ this(false);
+ }
+
+ public SampleDB(boolean recreate) {
+ // connect to SQL database
+ connect();
+
+ if (recreate) {
+ dropTables();
+ }
+
+ // initialize SQL database
+ createTables();
+
+ // test by executing sample JDBC query
+ testDatabase();
+ }
+
+ private void dropTables() {
+ try {
+ update("DROP TABLE " + Reservation.TABLE);
+ } catch (SQLException IGNORED) {
+ // IGNORED, assuming it was not there
+ }
+ try {
+ update("DROP TABLE " + Resource.TABLE);
+ } catch (SQLException IGNORED) {
+ // IGNORED, assuming it was not there
+ }
+ try {
+ update("DROP TABLE " + User.TABLE);
+ } catch (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 void connect() {
+ try {
+ Class.forName("org.hsqldb.jdbcDriver").newInstance();
+ connection = DriverManager.getConnection(DB_URL);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * use for SQL commands CREATE, DROP, INSERT and UPDATE
+ *
+ * @param expression
+ * @throws SQLException
+ */
+ private void update(String expression) throws SQLException {
+ Statement st = null;
+ st = connection.createStatement();
+ 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 void createTables() {
+ try {
+ String stmt = null;
+ stmt = CREATE_TABLE_RESOURCE;
+ update(stmt);
+ } catch (SQLException e) {
+ if (e.toString().indexOf("Table already exists") == -1) {
+ throw new RuntimeException(e);
+ }
+ }
+ try {
+ String stmt = null;
+ stmt = CREATE_TABLE_USER;
+ update(stmt);
+ } catch (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 (SQLException e) {
+ if (e.toString().indexOf("Table already exists") == -1) {
+ throw new RuntimeException(e);
+ }
+ }
+ }
+
+ /**
+ * Test database connection with simple SELECT command.
+ *
+ */
+ private String testDatabase() {
+ String result = null;
+ try {
+ Statement stmt = connection.createStatement(
+ ResultSet.TYPE_SCROLL_INSENSITIVE,
+ ResultSet.CONCUR_UPDATABLE);
+ ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM "
+ + Resource.TABLE);
+ rs.next();
+ result = "rowcount for table test is " + rs.getObject(1).toString();
+ stmt.close();
+ } catch (SQLException e) {
+ throw new RuntimeException(e);
+ }
+ return result;
+ }
+
+ public Connection getConnection() {
+ return connection;
+ }
+
+ public Container getCategories() {
+ // TODO where deleted=?
+ 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 (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 (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) {
+ StringBuffer s = new StringBuffer();
+ for (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 {
+ QueryContainer qc = new QueryContainer(q, connection,
+ ResultSet.TYPE_SCROLL_INSENSITIVE,
+ ResultSet.CONCUR_READ_ONLY);
+ if (qc.size() < 1) {
+ return null;
+ } else {
+ return qc;
+ }
+ } catch (SQLException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public void addReservation(Item resource, int reservedById,
+ Date reservedFrom, Date reservedTo, String description) {
+ if (reservedFrom.after(reservedTo)) {
+ Date tmp = reservedTo;
+ reservedTo = reservedFrom;
+ reservedFrom = tmp;
+ }
+ int resourceId = ((Integer) resource.getItemProperty(
+ Resource.PROPERTY_ID_ID).getValue()).intValue();
+ String q = "INSERT INTO " + Reservation.TABLE + " ("
+ + Reservation.PROPERTY_ID_RESOURCE_ID + ","
+ + Reservation.PROPERTY_ID_RESERVED_BY_ID + ","
+ + Reservation.PROPERTY_ID_RESERVED_FROM + ","
+ + Reservation.PROPERTY_ID_RESERVED_TO + ","
+ + Reservation.PROPERTY_ID_DESCRIPTION + ")"
+ + "VALUES (?,?,?,?,?)";
+ synchronized (DB_URL) {
+ try {
+ if (!isAvailableResource(resourceId, reservedFrom, reservedTo)) {
+ throw new ResourceNotAvailableException(
+ "The resource is not available at that time.");
+ }
+ PreparedStatement p = connection.prepareStatement(q);
+ p.setInt(1, resourceId);
+ p.setInt(2, reservedById);
+ 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 (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+ }
+
+ public boolean isAvailableResource(int resourceId, Date reservedFrom,
+ Date reservedTo) {
+ // TODO where deleted=?
+ if (reservedFrom.after(reservedTo)) {
+ Date tmp = reservedTo;
+ reservedTo = reservedFrom;
+ reservedFrom = tmp;
+ }
+ String checkQ = "SELECT count(*) FROM " + Reservation.TABLE + " WHERE "
+ + Reservation.PROPERTY_ID_RESOURCE_ID + "=? AND (("
+ + Reservation.PROPERTY_ID_RESERVED_FROM + ">=? AND "
+ + Reservation.PROPERTY_ID_RESERVED_FROM + ") OR ("
+ + Reservation.PROPERTY_ID_RESERVED_TO + ">? AND "
+ + Reservation.PROPERTY_ID_RESERVED_TO + "<=?) OR ("
+ + Reservation.PROPERTY_ID_RESERVED_FROM + "<=? AND "
+ + Reservation.PROPERTY_ID_RESERVED_TO + ">=?)" + ")";
+ try {
+ 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();
+ ResultSet rs = p.getResultSet();
+ if (rs.next() && rs.getInt(1) > 0) {
+ return false;
+ }
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ return true;
+ }
+
+ public Container getUsers() {
+ // TODO where deleted=?
+ String q = "SELECT * FROM " + User.TABLE + " ORDER BY "
+ + User.PROPERTY_ID_FULLNAME;
+ try {
+ QueryContainer qc = new QueryContainer(q, connection,
+ ResultSet.TYPE_SCROLL_INSENSITIVE,
+ ResultSet.CONCUR_READ_ONLY);
+ return qc;
+ } catch (SQLException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public void generateReservations() {
+ int days = 30;
+ 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" };
+ Container cat = getCategories();
+ Collection cIds = cat.getItemIds();
+ for (Iterator it = cIds.iterator(); it.hasNext();) {
+ Object id = it.next();
+ Item ci = cat.getItem(id);
+ String c = (String) ci.getItemProperty(
+ Resource.PROPERTY_ID_CATEGORY).getValue();
+ Container resources = getResources(c);
+ Collection rIds = resources.getItemIds();
+ Calendar cal = Calendar.getInstance();
+ cal.set(Calendar.MINUTE, 0);
+ cal.set(Calendar.SECOND, 0);
+ cal.set(Calendar.MILLISECOND, 0);
+ int hourNow = new Date().getHours();
+ // cal.add(Calendar.DAY_OF_MONTH, -days);
+ for (int i = 0; i < days; i++) {
+ int r = 3;
+ for (Iterator rit = rIds.iterator(); rit.hasNext() && r > 0; r--) {
+ Object rid = rit.next();
+ Item resource = resources.getItem(rid);
+ int s = hourNow - 6 + (int) Math.round(Math.random() * 6.0);
+ int e = s + 1 + (int) Math.round(Math.random() * 4.0);
+ Date start = new Date(cal.getTimeInMillis());
+ start.setHours(s);
+ Date end = new Date(cal.getTimeInMillis());
+ end.setHours(e);
+ addReservation(resource, 0, start, end,
+ descriptions[(int) Math.floor(Math.random()
+ * descriptions.length)]);
+ }
+ cal.add(Calendar.DATE, 1);
+ }
+ }
+
+ }
+
+ public void generateResources() {
+
+ Object[][] resources = {
+ // Turku
+ { "01", "01 Ford Mondeo", "w/ company logo", "Turku",
+ new Double(60.510857), new Double(22.275424) },
+ { "02", "02 Citroen Jumper",
+ "w/ company logo. 12m3 storage space.", "Turku",
+ new Double(60.452171), new Double(22.2995) },
+ { "03", "03 Saab 93", "Cabriolet. Keys from the rental desk.",
+ "Turku", new Double(60.4507), new Double(22.295551) },
+ { "04", "04 Volvo S60", "Key from the rental desk.", "Turku",
+ new Double(60.434722), new Double(22.224398) },
+ { "05", "05 Smart fourtwo", "Cabrio. Keys from infodesk.",
+ "Turku", new Double(60.508970), new Double(22.264790) },
+ // Helsinki
+ { "06", "06 Smart fourtwo", "Cabrio. Keys from infodesk.",
+ "Helsinki", new Double(60.17175), new Double(24.939029) },
+ { "07", "07 Smart fourtwo", "Cabrio. Keys from infodesk.",
+ "Helsinki", new Double(60.17175), new Double(24.939029) },
+ { "08", "08 Smart fourtwo", "Cabrio. Keys from infodesk.",
+ "Helsinki", new Double(60.166579),
+ new Double(24.953899) },
+ { "09", "09 Volvo S60", "Keys from infodesk.", "Helsinki",
+ new Double(60.317832), new Double(24.967289) },
+ { "10", "10 Saab 93", "Keys from infodesk.", "Helsinki",
+ new Double(60.249193), new Double(25.045921) },
+ // Silicon Valley
+ { "11", "11 Ford Mustang", "Keys from Acme clerk.",
+ "Silicon Valley", new Double(37.615853),
+ new Double(-122.386384) },
+ { "12", "12 Ford Fusion", "Keys from infodesk.",
+ "Silicon Valley", new Double(37.365028),
+ new Double(-121.922654) },
+ { "13", "13 Land Rover", "Keys from infodesk.",
+ "Silicon Valley", new Double(37.365028),
+ new Double(-121.922654) },
+ { "14", "14 Land Rover", "Keys from infodesk.",
+ "Silicon Valley", new Double(37.365028),
+ new Double(-121.922654) },
+ { "15", "15 Ford Mustang", "GT Cal Special. Keys from guard.",
+ "Silicon Valley", new Double(37.403812),
+ new Double(-121.977425) },
+ { "16", "16 Ford Focus", "Keys from guard.", "Silicon Valley",
+ new Double(37.403812), new Double(-121.977425) },
+ // Paris
+ { "17", "17 Peugeot 308", "Keys from infodesk.", "Paris",
+ new Double(48.844756), new Double(2.372784) },
+ { "18", "18 Citroen C6", "Keys from rental desk.", "Paris",
+ new Double(49.007253), new Double(2.545025) },
+ { "19", "19 Citroen C6", "Keys from infodesk.", "Paris",
+ new Double(48.729061), new Double(2.368087) },
+ { "20", "20 Peugeot 308", "Keys from ticket sales.", "Paris",
+ new Double(48.880931), new Double(2.356988) },
+ { "21", "21 Peugeot 308", "Keys from ticket sales.", "Paris",
+ new Double(48.876479), new Double(2.358161) },
+ // STHLM
+ { "22", "22 Volvo S60", "Keys from infodesk.", "Stockholm",
+ new Double(59.350414), new Double(18.106574) },
+ { "23", "23 Saab 93", "Keys from infodesk.", "Stockholm",
+ new Double(59.355905), new Double(17.946784) },
+ { "24", "24 Smart fourtwo", "Keys from infodesk.", "Stockholm",
+ new Double(59.315939), new Double(18.095904) },
+ { "25", "25 Smart fourtwo", "Keys from infodesk.", "Stockholm",
+ new Double(59.330716), new Double(18.058702) },
+ // Boston
+ { "26", "26 Ford Mustang", "Keys from infodesk.", "Boston",
+ new Double(42.366588), new Double(-71.020955) },
+ { "27", "27 Smart fourtwo", "Keys from infodesk.", "Boston",
+ new Double(42.365419), new Double(-71.061748) },
+ { "28", "28 Volvo S60", "Keys from Seaport Hotel reception.",
+ "Boston", new Double(42.34811), new Double(-71.041127) },
+ { "29", "29 Smart fourtwo",
+ "Keys from Seaport Hotel reception.", "Boston",
+ new Double(42.348072), new Double(-71.041315) },
+
+ };
+
+ 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 {
+ 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 (SQLException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public void generateDemoUser() {
+ String q = "INSERT INTO USER (" + User.PROPERTY_ID_FULLNAME + ","
+ + User.PROPERTY_ID_EMAIL + "," + User.PROPERTY_ID_PASSWORD
+ + ") VALUES (?,?,?)";
+ try {
+ PreparedStatement stmt = connection.prepareStatement(q);
+ stmt.setString(1, "Demo User");
+ stmt.setString(2, "demo.user@itmill.com");
+ stmt.setString(3, "demo");
+ stmt.execute();
+ } catch (SQLException e) {
+ throw new RuntimeException(e);
+ }
+
+ }
}
diff --git a/src/com/itmill/toolkit/demo/reservation/gwt/client/ReservationWidgetSet.java b/src/com/itmill/toolkit/demo/reservation/gwt/client/ReservationWidgetSet.java
index 447b7b83c9..e8333f3ea4 100644
--- a/src/com/itmill/toolkit/demo/reservation/gwt/client/ReservationWidgetSet.java
+++ b/src/com/itmill/toolkit/demo/reservation/gwt/client/ReservationWidgetSet.java
@@ -8,33 +8,33 @@ import com.itmill.toolkit.terminal.gwt.client.DefaultWidgetSet;
import com.itmill.toolkit.terminal.gwt.client.UIDL;
public class ReservationWidgetSet extends DefaultWidgetSet {
- public Widget createWidget(UIDL uidl) {
- String className = resolveWidgetTypeName(uidl);
- if ("com.itmill.toolkit.terminal.gwt.client.ui.IGoogleMap"
- .equals(className)) {
- return new IGoogleMap();
- } else if ("com.itmill.toolkit.demo.reservation.gwt.client.ui.ICalendarField"
- .equals(className)) {
- return new ICalendarField();
- }
+ public Widget createWidget(UIDL uidl) {
+ String className = resolveWidgetTypeName(uidl);
+ if ("com.itmill.toolkit.terminal.gwt.client.ui.IGoogleMap"
+ .equals(className)) {
+ return new IGoogleMap();
+ } else if ("com.itmill.toolkit.demo.reservation.gwt.client.ui.ICalendarField"
+ .equals(className)) {
+ return new ICalendarField();
+ }
- return super.createWidget(uidl);
- }
+ return super.createWidget(uidl);
+ }
- protected String resolveWidgetTypeName(UIDL uidl) {
+ protected String resolveWidgetTypeName(UIDL uidl) {
- String tag = uidl.getTag();
- if ("googlemap".equals(tag)) {
- return "com.itmill.toolkit.terminal.gwt.client.ui.IGoogleMap";
- } else if ("calendarfield".equals(tag)) {
- return "com.itmill.toolkit.demo.reservation.gwt.client.ui.ICalendarField";
- }
+ String tag = uidl.getTag();
+ if ("googlemap".equals(tag)) {
+ return "com.itmill.toolkit.terminal.gwt.client.ui.IGoogleMap";
+ } else if ("calendarfield".equals(tag)) {
+ return "com.itmill.toolkit.demo.reservation.gwt.client.ui.ICalendarField";
+ }
- return super.resolveWidgetTypeName(uidl);
- }
+ return super.resolveWidgetTypeName(uidl);
+ }
- public boolean isCorrectImplementation(Widget currentWidget, UIDL uidl) {
- return GWT.getTypeName(currentWidget).equals(
- resolveWidgetTypeName(uidl));
- }
+ public boolean isCorrectImplementation(Widget currentWidget, UIDL uidl) {
+ return GWT.getTypeName(currentWidget).equals(
+ resolveWidgetTypeName(uidl));
+ }
}
diff --git a/src/com/itmill/toolkit/demo/reservation/gwt/client/ui/ICalendarField.java b/src/com/itmill/toolkit/demo/reservation/gwt/client/ui/ICalendarField.java
index a036488224..735b773849 100644
--- a/src/com/itmill/toolkit/demo/reservation/gwt/client/ui/ICalendarField.java
+++ b/src/com/itmill/toolkit/demo/reservation/gwt/client/ui/ICalendarField.java
@@ -18,255 +18,258 @@ import com.itmill.toolkit.terminal.gwt.client.UIDL;
import com.itmill.toolkit.terminal.gwt.client.ui.CalendarEntry;
import com.itmill.toolkit.terminal.gwt.client.ui.CalendarPanel;
import com.itmill.toolkit.terminal.gwt.client.ui.IDateField;
-import com.itmill.toolkit.terminal.gwt.client.ui.CalendarPanel.CalendarEntrySource;
public class ICalendarField extends IDateField {
- private CalendarPanel calPanel;
-
- private SimplePanel hourPanel;
-
- private FlexTable hourTable;
-
- private EntrySource entrySource;
-
- private TableListener ftListener = new HourTableListener();
-
- private int realResolution = RESOLUTION_DAY;
-
- private static final String CLASSNAME = IDateField.CLASSNAME
- + "-entrycalendar";
-
- public ICalendarField() {
- super();
- setStyleName(CLASSNAME);
- calPanel = new CalendarPanel(this);
- add(calPanel);
- this.entrySource = new EntrySource();
- calPanel.setCalendarEntrySource(this.entrySource);
- calPanel.addTableListener(new TableListener() {
- public void onCellClicked(SourcesTableEvents sender, int row,
- int cell) {
- buildDayView(date);
- }
- });
- }
-
- public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
- super.updateFromUIDL(uidl, client);
- // We want to draw our own hour list
- this.realResolution = currentResolution;
- this.currentResolution = RESOLUTION_DAY;
- if (uidl.hasAttribute("min")) {
- String mins = uidl.getStringAttribute("min");
- long min = (mins != null ? Long.parseLong(mins) : 0);
- String maxs = uidl.getStringAttribute("max");
- long max = (maxs != null ? Long.parseLong(maxs) : 0);
- Date minDate = (min > 0 ? new Date(min) : null);
- Date maxDate = (max > 0 ? new Date(max) : null);
- calPanel.setLimits(minDate, maxDate);
- }
- this.entrySource.clear();
- for (Iterator cit = uidl.getChildIterator(); cit.hasNext();) {
- UIDL child = (UIDL) cit.next();
- if (child.getTag().equals("items")) {
- for (Iterator iit = child.getChildIterator(); iit.hasNext();) {
- UIDL item = (UIDL) iit.next();
- this.entrySource.addItem(item);
- }
- break;
- }
- }
- calPanel.updateCalendar();
- buildDayView(this.date);
- }
-
- protected void buildDayView(Date date) {
- boolean firstRender = true;
- if (this.hourPanel == null) {
- this.hourPanel = new SimplePanel();
- this.hourPanel.setStyleName(CLASSNAME + "-hours");
- this.calPanel.getFlexCellFormatter().setColSpan(8, 0, 7);
- this.calPanel.setWidget(8, 0, this.hourPanel);
- } else {
- firstRender = false;
- this.hourPanel.clear();
- }
- this.hourTable = new FlexTable();
- this.hourTable.addTableListener(this.ftListener);
- this.hourPanel.add(this.hourTable);
- this.hourTable.setCellSpacing(1);
-
- for (int i = 0; i < 24; i++) {
- String style = (i % 2 == 0 ? "even" : "odd");
- if (realResolution >= RESOLUTION_HOUR) {
- if (this.date != null && this.date.getHours() == i) {
- style = "selected";
- }
- }
- hourTable.getRowFormatter().setStyleName(i,
- CLASSNAME + "-row-" + style);
- String hstr = (i < 10 ? "0" : "") + i + ":00";
- if (this.dts.isTwelveHourClock()) {
- String ampm = (i < 12 ? "am" : "pm");
- hstr = (i <= 12 ? i : i - 12) + ":00 " + ampm;
- }
- hourTable.setHTML(i, 0, "" + hstr + "");
- hourTable.getCellFormatter()
- .setStyleName(i, 0, CLASSNAME + "-time");
- }
-
- List entries = this.entrySource.getEntries(date,
- DateTimeService.RESOLUTION_DAY);
- int currentCol = 1;
- for (Iterator it = entries.iterator(); it.hasNext();) {
- CalendarEntry entry = (CalendarEntry) it.next();
- int start = 0;
- int hours = 24;
- if (!entry.isNotime()) {
- Date d = entry.getStart();
- // TODO consider month&year as well
- start = (d.getDate() < date.getDate() ? 0 : d.getHours());
- d = entry.getEnd();
- hours = (d.getDate() > date.getDate() ? 24 : d.getHours())
- - start;
- if (hours == 0) {
- // We can't draw entries smaller than one
- hours = 1;
- }
- }
- int col = currentCol;
- if (col > 1) {
- while (!this.hourTable.isCellPresent(start, col - 1))
- col--;
- }
- this.hourTable.setHTML(start, col, ""
- + (entry.getTitle() != null ? entry.getTitle() : " ")
- + "");
- this.hourTable.getFlexCellFormatter().setRowSpan(start, col, hours);
- this.hourTable.getFlexCellFormatter().setStyleName(start, col,
- CLASSNAME + "-entry");
- String sn = entry.getStyleName();
- if (sn != null && !sn.equals("")) {
- this.hourTable.getFlexCellFormatter().addStyleName(start, col,
- CLASSNAME + "-" + entry.getStyleName());
- }
- Element el = this.hourTable.getFlexCellFormatter().getElement(
- start, col);
-
- String tooltip;
- if (DateTimeService.isSameDay(entry.getStart(), entry.getEnd())) {
- tooltip = (start < 10 ? "0" : "") + start + ":00";
- if (this.dts.isTwelveHourClock()) {
- String ampm = (start < 12 ? "am" : "pm");
- tooltip = (start <= 12 ? start : start - 12) + ":00 "
- + ampm;
-
- }
- tooltip += " (" + hours + "h) ";
- if (entry.getTitle()!=null) {
- tooltip += entry.getTitle() + "\n ";
- }
- } else {
- tooltip = entry.getStringForDate(entry.getEnd()) + "\n ";
- }
- if (entry.getDescription()!=null) {
- tooltip += "\"" + entry.getDescription() + "\"";
- }
- DOM.setElementProperty(el, "title", tooltip);
-
- currentCol++;
- }
-
- // int hour = new Date().getHours()+1; // scroll to current hour
- int hour = this.date.getHours() + 1; // scroll to selected hour
- int h1 = (int) this.hourPanel.getOffsetHeight() / 2;
- int oh = this.hourTable.getOffsetHeight();
- int h2 = (int) (hour / 24.0 * oh);
- int scrollTop = (int) h2 - h1;
- Element el = this.hourPanel.getElement();
- setScrollTop(el, scrollTop);
-
- }
-
- private native void setScrollTop(Element el, int scrollTop) /*-{
- el.scrollTop = scrollTop;
- }-*/;
-
- private class HourTableListener implements TableListener {
-
- public void onCellClicked(SourcesTableEvents sender, int row, int cell) {
- if (realResolution < RESOLUTION_HOUR || date == null) {
- return;
- }
- date.setHours(row);
- client.updateVariable(id, "hour", row, immediate);
- }
-
- }
-
- private class EntrySource implements CalendarPanel.CalendarEntrySource {
-
- private HashMap dates = new HashMap();
-
- public void addItem(UIDL item) {
- String styleName = item.getStringAttribute("styleName");
- Integer id = new Integer(item.getIntAttribute("id"));
- long start = Long.parseLong(item.getStringAttribute("start"));
- Date startDate = new Date(start);
- long end = -1;
- try {
- end = Long.parseLong(item.getStringAttribute("end"));
- } catch (Exception IGNORED) {
- // IGNORED attribute not required
- }
- Date endDate = (end > 0 && end != start ? new Date(end) : new Date(
- start));
- String title = item.getStringAttribute("title");
- String desc = item.getStringAttribute("description");
- boolean notime = item.getBooleanAttribute("notime");
- CalendarEntry entry = new CalendarEntry(styleName, startDate,
- endDate, title, desc, notime);
-
- // TODO should remove+readd if the same entry (id) is added again
-
- for (Date d = entry.getStart(); d.getYear() <= entry.getEnd()
- .getYear()
- && d.getMonth() <= entry.getEnd().getYear()
- && d.getDate() <= entry.getEnd().getDate(); d.setTime(d
- .getTime() + 86400000)) {
- String key = d.getYear() + "" + d.getMonth() + "" + d.getDate();
- ArrayList l = (ArrayList) dates.get(key);
- if (l == null) {
- l = new ArrayList();
- dates.put(key, l);
- }
- l.add(entry);
- }
- }
-
- public List getEntries(Date date, int resolution) {
- List entries = (List) dates.get(date.getYear() + ""
- + date.getMonth() + "" + date.getDate());
- ArrayList res = new ArrayList();
- if (entries == null) {
- return res;
- }
- for (Iterator it = entries.iterator(); it.hasNext();) {
- CalendarEntry item = (CalendarEntry) it.next();
- if (DateTimeService.isInRange(date, item.getStart(), item
- .getEnd(), resolution)) {
- res.add(item);
- }
- }
-
- return res;
- }
-
- public void clear() {
- dates.clear();
- }
-
- }
+ private CalendarPanel calPanel;
+
+ private SimplePanel hourPanel;
+
+ private FlexTable hourTable;
+
+ private EntrySource entrySource;
+
+ private TableListener ftListener = new HourTableListener();
+
+ private int realResolution = RESOLUTION_DAY;
+
+ private static final String CLASSNAME = IDateField.CLASSNAME
+ + "-entrycalendar";
+
+ public ICalendarField() {
+ super();
+ setStyleName(CLASSNAME);
+ calPanel = new CalendarPanel(this);
+ add(calPanel);
+ entrySource = new EntrySource();
+ calPanel.setCalendarEntrySource(entrySource);
+ calPanel.addTableListener(new TableListener() {
+ public void onCellClicked(SourcesTableEvents sender, int row,
+ int cell) {
+ buildDayView(date);
+ }
+ });
+ }
+
+ public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
+ super.updateFromUIDL(uidl, client);
+ // We want to draw our own hour list
+ realResolution = currentResolution;
+ currentResolution = RESOLUTION_DAY;
+ if (uidl.hasAttribute("min")) {
+ String mins = uidl.getStringAttribute("min");
+ long min = (mins != null ? Long.parseLong(mins) : 0);
+ String maxs = uidl.getStringAttribute("max");
+ long max = (maxs != null ? Long.parseLong(maxs) : 0);
+ Date minDate = (min > 0 ? new Date(min) : null);
+ Date maxDate = (max > 0 ? new Date(max) : null);
+ calPanel.setLimits(minDate, maxDate);
+ }
+ entrySource.clear();
+ for (Iterator cit = uidl.getChildIterator(); cit.hasNext();) {
+ UIDL child = (UIDL) cit.next();
+ if (child.getTag().equals("items")) {
+ for (Iterator iit = child.getChildIterator(); iit.hasNext();) {
+ UIDL item = (UIDL) iit.next();
+ entrySource.addItem(item);
+ }
+ break;
+ }
+ }
+ calPanel.updateCalendar();
+ buildDayView(date);
+ }
+
+ protected void buildDayView(Date date) {
+ boolean firstRender = true;
+ if (hourPanel == null) {
+ hourPanel = new SimplePanel();
+ hourPanel.setStyleName(CLASSNAME + "-hours");
+ calPanel.getFlexCellFormatter().setColSpan(8, 0, 7);
+ calPanel.setWidget(8, 0, hourPanel);
+ } else {
+ firstRender = false;
+ hourPanel.clear();
+ }
+ hourTable = new FlexTable();
+ hourTable.addTableListener(ftListener);
+ hourPanel.add(hourTable);
+ hourTable.setCellSpacing(1);
+
+ for (int i = 0; i < 24; i++) {
+ String style = (i % 2 == 0 ? "even" : "odd");
+ if (realResolution >= RESOLUTION_HOUR) {
+ if (this.date != null && this.date.getHours() == i) {
+ style = "selected";
+ }
+ }
+ hourTable.getRowFormatter().setStyleName(i,
+ CLASSNAME + "-row-" + style);
+ String hstr = (i < 10 ? "0" : "") + i + ":00";
+ if (dts.isTwelveHourClock()) {
+ String ampm = (i < 12 ? "am" : "pm");
+ hstr = (i <= 12 ? i : i - 12) + ":00 " + ampm;
+ }
+ hourTable.setHTML(i, 0, "" + hstr + "");
+ hourTable.getCellFormatter()
+ .setStyleName(i, 0, CLASSNAME + "-time");
+ }
+
+ List entries = entrySource.getEntries(date,
+ DateTimeService.RESOLUTION_DAY);
+ int currentCol = 1;
+ for (Iterator it = entries.iterator(); it.hasNext();) {
+ CalendarEntry entry = (CalendarEntry) it.next();
+ int start = 0;
+ int hours = 24;
+ if (!entry.isNotime()) {
+ Date d = entry.getStart();
+ // TODO consider month&year as well
+ start = (d.getDate() < date.getDate() ? 0 : d.getHours());
+ d = entry.getEnd();
+ hours = (d.getDate() > date.getDate() ? 24 : d.getHours())
+ - start;
+ if (hours == 0) {
+ // We can't draw entries smaller than
+ // one
+ hours = 1;
+ }
+ }
+ int col = currentCol;
+ if (col > 1) {
+ while (!hourTable.isCellPresent(start, col - 1)) {
+ col--;
+ }
+ }
+ hourTable.setHTML(start, col, ""
+ + (entry.getTitle() != null ? entry.getTitle() : " ")
+ + "");
+ hourTable.getFlexCellFormatter().setRowSpan(start, col, hours);
+ hourTable.getFlexCellFormatter().setStyleName(start, col,
+ CLASSNAME + "-entry");
+ String sn = entry.getStyleName();
+ if (sn != null && !sn.equals("")) {
+ hourTable.getFlexCellFormatter().addStyleName(start, col,
+ CLASSNAME + "-" + entry.getStyleName());
+ }
+ Element el = hourTable.getFlexCellFormatter()
+ .getElement(start, col);
+
+ String tooltip;
+ if (DateTimeService.isSameDay(entry.getStart(), entry.getEnd())) {
+ tooltip = (start < 10 ? "0" : "") + start + ":00";
+ if (dts.isTwelveHourClock()) {
+ String ampm = (start < 12 ? "am" : "pm");
+ tooltip = (start <= 12 ? start : start - 12) + ":00 "
+ + ampm;
+
+ }
+ tooltip += " (" + hours + "h) ";
+ if (entry.getTitle() != null) {
+ tooltip += entry.getTitle() + "\n ";
+ }
+ } else {
+ tooltip = entry.getStringForDate(entry.getEnd()) + "\n ";
+ }
+ if (entry.getDescription() != null) {
+ tooltip += "\"" + entry.getDescription() + "\"";
+ }
+ DOM.setElementProperty(el, "title", tooltip);
+
+ currentCol++;
+ }
+
+ // int hour = new Date().getHours()+1; // scroll to current hour
+ int hour = this.date.getHours() + 1; // scroll to selected
+ // hour
+ int h1 = hourPanel.getOffsetHeight() / 2;
+ int oh = hourTable.getOffsetHeight();
+ int h2 = (int) (hour / 24.0 * oh);
+ int scrollTop = h2 - h1;
+ Element el = hourPanel.getElement();
+ setScrollTop(el, scrollTop);
+
+ }
+
+ private native void setScrollTop(Element el, int scrollTop) /*-{
+ el.scrollTop = scrollTop;
+ }-*/;
+
+ private class HourTableListener implements TableListener {
+
+ public void onCellClicked(SourcesTableEvents sender, int row, int cell) {
+ if (realResolution < RESOLUTION_HOUR || date == null) {
+ return;
+ }
+ date.setHours(row);
+ client.updateVariable(id, "hour", row, immediate);
+ }
+
+ }
+
+ private class EntrySource implements CalendarPanel.CalendarEntrySource {
+
+ private HashMap dates = new HashMap();
+
+ public void addItem(UIDL item) {
+ String styleName = item.getStringAttribute("styleName");
+ Integer id = new Integer(item.getIntAttribute("id"));
+ long start = Long.parseLong(item.getStringAttribute("start"));
+ Date startDate = new Date(start);
+ long end = -1;
+ try {
+ end = Long.parseLong(item.getStringAttribute("end"));
+ } catch (Exception IGNORED) {
+ // IGNORED attribute not required
+ }
+ Date endDate = (end > 0 && end != start ? new Date(end) : new Date(
+ start));
+ String title = item.getStringAttribute("title");
+ String desc = item.getStringAttribute("description");
+ boolean notime = item.getBooleanAttribute("notime");
+ CalendarEntry entry = new CalendarEntry(styleName, startDate,
+ endDate, title, desc, notime);
+
+ // TODO should remove+readd if the same entry (id) is
+ // added again
+
+ for (Date d = entry.getStart(); d.getYear() <= entry.getEnd()
+ .getYear()
+ && d.getMonth() <= entry.getEnd().getYear()
+ && d.getDate() <= entry.getEnd().getDate(); d.setTime(d
+ .getTime() + 86400000)) {
+ String key = d.getYear() + "" + d.getMonth() + "" + d.getDate();
+ ArrayList l = (ArrayList) dates.get(key);
+ if (l == null) {
+ l = new ArrayList();
+ dates.put(key, l);
+ }
+ l.add(entry);
+ }
+ }
+
+ public List getEntries(Date date, int resolution) {
+ List entries = (List) dates.get(date.getYear() + ""
+ + date.getMonth() + "" + date.getDate());
+ ArrayList res = new ArrayList();
+ if (entries == null) {
+ return res;
+ }
+ for (Iterator it = entries.iterator(); it.hasNext();) {
+ CalendarEntry item = (CalendarEntry) it.next();
+ if (DateTimeService.isInRange(date, item.getStart(), item
+ .getEnd(), resolution)) {
+ res.add(item);
+ }
+ }
+
+ return res;
+ }
+
+ public void clear() {
+ dates.clear();
+ }
+
+ }
}
diff --git a/src/com/itmill/toolkit/demo/reservation/gwt/client/ui/IGoogleMap.java b/src/com/itmill/toolkit/demo/reservation/gwt/client/ui/IGoogleMap.java
index 8c06561db6..1517f071a0 100644
--- a/src/com/itmill/toolkit/demo/reservation/gwt/client/ui/IGoogleMap.java
+++ b/src/com/itmill/toolkit/demo/reservation/gwt/client/ui/IGoogleMap.java
@@ -16,83 +16,83 @@ import com.mapitz.gwt.googleMaps.client.GMarkerEventManager;
public class IGoogleMap extends GMap2Widget implements Paintable {
- public static final String CLASSNAME = "i-googlemap";
-
- GMap2EventManager mapEventManager;
- GMarkerEventManager markerEventManager;
- GMap2 map;
-
- public IGoogleMap() {
- setStyleName(CLASSNAME);
- mapEventManager = GMap2EventManager.getInstance();
- map = this.getGmap();
- map.addControl(GControl.GSmallZoomControl());
- }
-
- public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
- map.clearOverlays();
- GLatLng pos = null;
- for (Iterator it = uidl.getChildIterator(); it.hasNext();) {
- UIDL u = (UIDL) it.next();
- if (u.getTag().equals("markers")) {
-
- for (Iterator m = u.getChildIterator(); m.hasNext();) {
- UIDL umarker = (UIDL) m.next();
- String html = "" + umarker.getStringAttribute("html")
- + "";
- double x = umarker.getDoubleAttribute("x");
- double y = umarker.getDoubleAttribute("y");
- pos = new GLatLng(x, y);
- GMarker marker = new GMarker(pos);
- map.addOverlay(marker);
- if (html != null) {
- addMarkerPopup(marker, html);
- }
- }
- }
- }
- if (uidl.hasAttribute("width")) {
- setWidth("" + uidl.getIntAttribute("width"));
- }
- if (uidl.hasAttribute("height")) {
- setHeight("" + uidl.getIntAttribute("height"));
- }
- if (uidl.hasAttribute("zoom")) {
- map.setZoom(uidl.getIntAttribute("zoom"));
- }
- if (uidl.hasAttribute("centerX") && uidl.hasAttribute("centerY")) {
- GLatLng center = new GLatLng(uidl.getDoubleAttribute("centerX"),
- uidl.getDoubleAttribute("centerY"));
- map.setCenter(center);
- } else if (pos != null) {
- // use last marker position
- map.setCenter(pos);
- }
-
- }
-
- private void addMarkerPopup(GMarker marker, String html) {
- if (markerEventManager == null) {
- markerEventManager = GMarkerEventManager.getInstance();
- }
-
- markerEventManager.addOnClickListener(marker, new MarkerEventListener(
- html));
-
- }
-
- private class MarkerEventListener implements GMarkerEventClickListener {
- String html;
-
- public MarkerEventListener(String html) {
- this.html = html;
- }
-
- public void onClick(GMarker marker) {
- marker.openInfoWindowHtml(html);
- }
-
- public void onDblClick(GMarker marker) {
- }
- }
+ public static final String CLASSNAME = "i-googlemap";
+
+ GMap2EventManager mapEventManager;
+ GMarkerEventManager markerEventManager;
+ GMap2 map;
+
+ public IGoogleMap() {
+ setStyleName(CLASSNAME);
+ mapEventManager = GMap2EventManager.getInstance();
+ map = getGmap();
+ map.addControl(GControl.GSmallZoomControl());
+ }
+
+ public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
+ map.clearOverlays();
+ GLatLng pos = null;
+ for (Iterator it = uidl.getChildIterator(); it.hasNext();) {
+ UIDL u = (UIDL) it.next();
+ if (u.getTag().equals("markers")) {
+
+ for (Iterator m = u.getChildIterator(); m.hasNext();) {
+ UIDL umarker = (UIDL) m.next();
+ String html = "" + umarker.getStringAttribute("html")
+ + "";
+ double x = umarker.getDoubleAttribute("x");
+ double y = umarker.getDoubleAttribute("y");
+ pos = new GLatLng(x, y);
+ GMarker marker = new GMarker(pos);
+ map.addOverlay(marker);
+ if (html != null) {
+ addMarkerPopup(marker, html);
+ }
+ }
+ }
+ }
+ if (uidl.hasAttribute("width")) {
+ setWidth("" + uidl.getIntAttribute("width"));
+ }
+ if (uidl.hasAttribute("height")) {
+ setHeight("" + uidl.getIntAttribute("height"));
+ }
+ if (uidl.hasAttribute("zoom")) {
+ map.setZoom(uidl.getIntAttribute("zoom"));
+ }
+ if (uidl.hasAttribute("centerX") && uidl.hasAttribute("centerY")) {
+ GLatLng center = new GLatLng(uidl.getDoubleAttribute("centerX"),
+ uidl.getDoubleAttribute("centerY"));
+ map.setCenter(center);
+ } else if (pos != null) {
+ // use last marker position
+ map.setCenter(pos);
+ }
+
+ }
+
+ private void addMarkerPopup(GMarker marker, String html) {
+ if (markerEventManager == null) {
+ markerEventManager = GMarkerEventManager.getInstance();
+ }
+
+ markerEventManager.addOnClickListener(marker, new MarkerEventListener(
+ html));
+
+ }
+
+ private class MarkerEventListener implements GMarkerEventClickListener {
+ String html;
+
+ public MarkerEventListener(String html) {
+ this.html = html;
+ }
+
+ public void onClick(GMarker marker) {
+ marker.openInfoWindowHtml(html);
+ }
+
+ public void onDblClick(GMarker marker) {
+ }
+ }
}
diff --git a/src/com/itmill/toolkit/demo/util/SampleCalendarDatabase.java b/src/com/itmill/toolkit/demo/util/SampleCalendarDatabase.java
index c452a44d24..3147c8bed1 100644
--- a/src/com/itmill/toolkit/demo/util/SampleCalendarDatabase.java
+++ b/src/com/itmill/toolkit/demo/util/SampleCalendarDatabase.java
@@ -1,7 +1,6 @@
package com.itmill.toolkit.demo.util;
import java.sql.Connection;
-import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
@@ -19,146 +18,146 @@ import java.sql.Timestamp;
*/
public class SampleCalendarDatabase {
- public static final int ENTRYCOUNT = 100;
-
- public static final String DB_TABLE_NAME = "calendar";
- public static final String PROPERTY_ID_START = "EVENTSTART";
- public static final String PROPERTY_ID_END = "EVENTEND";
- public static final String PROPERTY_ID_TITLE = "TITLE";
- public static final String PROPERTY_ID_NOTIME = "NOTIME";
-
- private Connection connection = null;
-
- private static final String[] titles = new String[] { "Meeting", "Dentist",
- "Haircut", "Bank", "Birthday", "Library", "Rent", "Acme test",
- "Party" };
-
- /**
- * Create temporary database.
- *
- */
- public SampleCalendarDatabase() {
- // connect to SQL database
- connect();
-
- // initialize SQL database
- createTables();
-
- // test by executing sample JDBC query
- testDatabase();
- }
-
- /**
- * Creates sample table named employee and populates it with data.Use the
- * specified database connection.
- *
- * @param connection
- */
- public SampleCalendarDatabase(Connection connection) {
- // initialize SQL database
- createTables();
-
- // test by executing sample JDBC query
- testDatabase();
- }
-
- /**
- * Connect to SQL database. In this sample we use HSQLDB and an toolkit
- * named database in implicitly created into system memory.
- *
- */
- private void connect() {
- // use memory-Only Database
- String url = "jdbc:hsqldb:mem:toolkit";
- try {
- Class.forName("org.hsqldb.jdbcDriver").newInstance();
- connection = DriverManager.getConnection(url, "sa", "");
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- /**
- * use for SQL commands CREATE, DROP, INSERT and UPDATE
- *
- * @param expression
- * @throws SQLException
- */
- public void update(String expression) throws SQLException {
- Statement st = null;
- st = connection.createStatement();
- 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 void createTables() {
- try {
- String stmt = null;
- stmt = "CREATE TABLE "
- + DB_TABLE_NAME
- + " ( ID INTEGER IDENTITY, TITLE VARCHAR(100), "
- + "EVENTSTART DATETIME, EVENTEND DATETIME, NOTIME BOOLEAN )";
- update(stmt);
- for (int j = 0; j < ENTRYCOUNT; j++) {
- Timestamp start = new Timestamp(new java.util.Date().getTime());
- start.setDate((int) ((Math.random() - 0.4) * 200));
- start.setMinutes(0);
- start.setHours(8 + (int) Math.random() * 12);
- Timestamp end = new Timestamp(start.getTime());
- if (Math.random() < 0.7) {
- long t = end.getTime();
- long hour = 60 * 60 * 1000;
- t = t + hour
- + (long) (Math.round(Math.random() * 3 * hour));
- end.setTime(t);
- }
-
- stmt = "INSERT INTO "
- + DB_TABLE_NAME
- + "(TITLE, EVENTSTART, EVENTEND, NOTIME) VALUES ("
- + "'"
- + titles[(int) (Math.round(Math.random()
- * (titles.length - 1)))] + "','" + start
- + "','" + end + "'," + (Math.random() > 0.7) + ")";
- update(stmt);
- }
- } catch (SQLException e) {
- if (e.toString().indexOf("Table already exists") == -1)
- throw new RuntimeException(e);
- }
- }
-
- /**
- * Test database connection with simple SELECT command.
- *
- */
- private String testDatabase() {
- String result = null;
- try {
- Statement stmt = connection.createStatement(
- ResultSet.TYPE_SCROLL_INSENSITIVE,
- ResultSet.CONCUR_UPDATABLE);
- ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM "
- + DB_TABLE_NAME);
- rs.next();
- result = "rowcount for table test is " + rs.getObject(1).toString();
- stmt.close();
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }
- return result;
- }
-
- public Connection getConnection() {
- return connection;
- }
+ public static final int ENTRYCOUNT = 100;
+
+ public static final String DB_TABLE_NAME = "calendar";
+ public static final String PROPERTY_ID_START = "EVENTSTART";
+ public static final String PROPERTY_ID_END = "EVENTEND";
+ public static final String PROPERTY_ID_TITLE = "TITLE";
+ public static final String PROPERTY_ID_NOTIME = "NOTIME";
+
+ private Connection connection = null;
+
+ private static final String[] titles = new String[] { "Meeting", "Dentist",
+ "Haircut", "Bank", "Birthday", "Library", "Rent", "Acme test",
+ "Party" };
+
+ /**
+ * Create temporary database.
+ *
+ */
+ public SampleCalendarDatabase() {
+ // connect to SQL database
+ connect();
+
+ // initialize SQL database
+ createTables();
+
+ // test by executing sample JDBC query
+ testDatabase();
+ }
+
+ /**
+ * Creates sample table named employee and populates it with data.Use the
+ * specified database connection.
+ *
+ * @param connection
+ */
+ public SampleCalendarDatabase(Connection connection) {
+ // initialize SQL database
+ createTables();
+
+ // test by executing sample JDBC query
+ testDatabase();
+ }
+
+ /**
+ * Connect to SQL database. In this sample we use HSQLDB and an toolkit
+ * named database in implicitly created into system memory.
+ *
+ */
+ private void connect() {
+ // use memory-Only Database
+ String url = "jdbc:hsqldb:mem:toolkit";
+ try {
+ Class.forName("org.hsqldb.jdbcDriver").newInstance();
+ connection = DriverManager.getConnection(url, "sa", "");
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * use for SQL commands CREATE, DROP, INSERT and UPDATE
+ *
+ * @param expression
+ * @throws SQLException
+ */
+ public void update(String expression) throws SQLException {
+ Statement st = null;
+ st = connection.createStatement();
+ 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 void createTables() {
+ try {
+ String stmt = null;
+ stmt = "CREATE TABLE "
+ + DB_TABLE_NAME
+ + " ( ID INTEGER IDENTITY, TITLE VARCHAR(100), "
+ + "EVENTSTART DATETIME, EVENTEND DATETIME, NOTIME BOOLEAN )";
+ update(stmt);
+ for (int j = 0; j < ENTRYCOUNT; j++) {
+ Timestamp start = new Timestamp(new java.util.Date().getTime());
+ start.setDate((int) ((Math.random() - 0.4) * 200));
+ start.setMinutes(0);
+ start.setHours(8 + (int) Math.random() * 12);
+ Timestamp end = new Timestamp(start.getTime());
+ if (Math.random() < 0.7) {
+ long t = end.getTime();
+ long hour = 60 * 60 * 1000;
+ t = t + hour + (Math.round(Math.random() * 3 * hour));
+ end.setTime(t);
+ }
+
+ stmt = "INSERT INTO "
+ + DB_TABLE_NAME
+ + "(TITLE, EVENTSTART, EVENTEND, NOTIME) VALUES ("
+ + "'"
+ + titles[(int) (Math.round(Math.random()
+ * (titles.length - 1)))] + "','" + start
+ + "','" + end + "'," + (Math.random() > 0.7) + ")";
+ update(stmt);
+ }
+ } catch (SQLException e) {
+ if (e.toString().indexOf("Table already exists") == -1) {
+ throw new RuntimeException(e);
+ }
+ }
+ }
+
+ /**
+ * Test database connection with simple SELECT command.
+ *
+ */
+ private String testDatabase() {
+ String result = null;
+ try {
+ Statement stmt = connection.createStatement(
+ ResultSet.TYPE_SCROLL_INSENSITIVE,
+ ResultSet.CONCUR_UPDATABLE);
+ ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM "
+ + DB_TABLE_NAME);
+ rs.next();
+ result = "rowcount for table test is " + rs.getObject(1).toString();
+ stmt.close();
+ } catch (SQLException e) {
+ throw new RuntimeException(e);
+ }
+ return result;
+ }
+
+ public Connection getConnection() {
+ return connection;
+ }
}
diff --git a/src/com/itmill/toolkit/demo/util/SampleDatabase.java b/src/com/itmill/toolkit/demo/util/SampleDatabase.java
index 68e3577908..8ce233b8a5 100644
--- a/src/com/itmill/toolkit/demo/util/SampleDatabase.java
+++ b/src/com/itmill/toolkit/demo/util/SampleDatabase.java
@@ -17,151 +17,152 @@ import java.sql.Statement;
*/
public class SampleDatabase {
- public static final int ROWCOUNT = 1000;
-
- private Connection connection = null;
-
- private static final String[] firstnames = new String[] { "Amanda",
- "Andrew", "Bill", "Frank", "Matt", "Xavier", "John", "Mary", "Joe",
- "Gloria", "Marcus", "Belinda", "David", "Anthony", "Julian",
- "Paul", "Carrie", "Susan", "Gregg", "Michael", "William", "Ethan",
- "Thomas", "Oscar", "Norman", "Roy", "Sarah", "Jeff", "Jane",
- "Peter", "Marc", "Josie", "Linus" };
-
- private static final String[] lastnames = new String[] { "Torvalds",
- "Smith", "Jones", "Beck", "Burton", "Bell", "Davis", "Burke",
- "Bernard", "Hood", "Scott", "Smith", "Carter", "Roller", "Conrad",
- "Martin", "Fisher", "Martell", "Freeman", "Hackman", "Jones",
- "Harper", "Russek", "Johnson", "Sheridan", "Hill", "Parker",
- "Foster", "Moss", "Fielding" };
-
- private static final String[] titles = new String[] { "Project Manager",
- "Marketing Manager", "Sales Manager", "Sales", "Trainer",
- "Technical Support", "Account Manager", "Customer Support",
- "Testing Engineer", "Software Designer", "Programmer", "Consultant" };
-
- private static final String[] units = new String[] { "Tokyo",
- "Mexico City", "Seoul", "New York", "Sao Paulo", "Bombay", "Delhi",
- "Shanghai", "Los Angeles", "London", "Shanghai", "Sydney",
- "Bangalore", "Hong Kong", "Madrid", "Milano", "Beijing", "Paris",
- "Moscow", "Berlin", "Helsinki" };
-
- /**
- * Create temporary database.
- *
- */
- public SampleDatabase() {
- // connect to SQL database
- connect();
-
- // initialize SQL database
- createTables();
-
- // test by executing sample JDBC query
- testDatabase();
- }
-
- /**
- * Creates sample table named employee and populates it with data.Use the
- * specified database connection.
- *
- * @param connection
- */
- public SampleDatabase(Connection connection) {
- // initialize SQL database
- createTables();
-
- // test by executing sample JDBC query
- testDatabase();
- }
-
- /**
- * Connect to SQL database. In this sample we use HSQLDB and an toolkit
- * named database in implicitly created into system memory.
- *
- */
- private void connect() {
- // use memory-Only Database
- String url = "jdbc:hsqldb:mem:toolkit";
- try {
- Class.forName("org.hsqldb.jdbcDriver").newInstance();
- connection = DriverManager.getConnection(url, "sa", "");
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- /**
- * use for SQL commands CREATE, DROP, INSERT and UPDATE
- *
- * @param expression
- * @throws SQLException
- */
- public void update(String expression) throws SQLException {
- Statement st = null;
- st = connection.createStatement();
- 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 void createTables() {
- try {
- String stmt = null;
- stmt = "CREATE TABLE employee ( ID INTEGER IDENTITY, FIRSTNAME VARCHAR(100), "
- + "LASTNAME VARCHAR(100), TITLE VARCHAR(100), UNIT VARCHAR(100) )";
- update(stmt);
- for (int j = 0; j < ROWCOUNT; j++) {
- stmt = "INSERT INTO employee(FIRSTNAME, LASTNAME, TITLE, UNIT) VALUES ("
- + "'"
- + firstnames[(int) (Math.random() * (firstnames.length - 1))]
- + "',"
- + "'"
- + lastnames[(int) (Math.random() * (lastnames.length - 1))]
- + "',"
- + "'"
- + titles[(int) (Math.random() * (titles.length - 1))]
- + "',"
- + "'"
- + units[(int) (Math.random() * (units.length - 1))]
- + "'" + ")";
- update(stmt);
- }
- } catch (SQLException e) {
- if (e.toString().indexOf("Table already exists") == -1)
- throw new RuntimeException(e);
- }
- }
-
- /**
- * Test database connection with simple SELECT command.
- *
- */
- private String testDatabase() {
- String result = null;
- try {
- Statement stmt = connection.createStatement(
- ResultSet.TYPE_SCROLL_INSENSITIVE,
- ResultSet.CONCUR_UPDATABLE);
- ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM employee");
- rs.next();
- result = "rowcount for table test is " + rs.getObject(1).toString();
- stmt.close();
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }
- return result;
- }
-
- public Connection getConnection() {
- return connection;
- }
+ public static final int ROWCOUNT = 1000;
+
+ private Connection connection = null;
+
+ private static final String[] firstnames = new String[] { "Amanda",
+ "Andrew", "Bill", "Frank", "Matt", "Xavier", "John", "Mary", "Joe",
+ "Gloria", "Marcus", "Belinda", "David", "Anthony", "Julian",
+ "Paul", "Carrie", "Susan", "Gregg", "Michael", "William", "Ethan",
+ "Thomas", "Oscar", "Norman", "Roy", "Sarah", "Jeff", "Jane",
+ "Peter", "Marc", "Josie", "Linus" };
+
+ private static final String[] lastnames = new String[] { "Torvalds",
+ "Smith", "Jones", "Beck", "Burton", "Bell", "Davis", "Burke",
+ "Bernard", "Hood", "Scott", "Smith", "Carter", "Roller", "Conrad",
+ "Martin", "Fisher", "Martell", "Freeman", "Hackman", "Jones",
+ "Harper", "Russek", "Johnson", "Sheridan", "Hill", "Parker",
+ "Foster", "Moss", "Fielding" };
+
+ private static final String[] titles = new String[] { "Project Manager",
+ "Marketing Manager", "Sales Manager", "Sales", "Trainer",
+ "Technical Support", "Account Manager", "Customer Support",
+ "Testing Engineer", "Software Designer", "Programmer", "Consultant" };
+
+ private static final String[] units = new String[] { "Tokyo",
+ "Mexico City", "Seoul", "New York", "Sao Paulo", "Bombay", "Delhi",
+ "Shanghai", "Los Angeles", "London", "Shanghai", "Sydney",
+ "Bangalore", "Hong Kong", "Madrid", "Milano", "Beijing", "Paris",
+ "Moscow", "Berlin", "Helsinki" };
+
+ /**
+ * Create temporary database.
+ *
+ */
+ public SampleDatabase() {
+ // connect to SQL database
+ connect();
+
+ // initialize SQL database
+ createTables();
+
+ // test by executing sample JDBC query
+ testDatabase();
+ }
+
+ /**
+ * Creates sample table named employee and populates it with data.Use the
+ * specified database connection.
+ *
+ * @param connection
+ */
+ public SampleDatabase(Connection connection) {
+ // initialize SQL database
+ createTables();
+
+ // test by executing sample JDBC query
+ testDatabase();
+ }
+
+ /**
+ * Connect to SQL database. In this sample we use HSQLDB and an toolkit
+ * named database in implicitly created into system memory.
+ *
+ */
+ private void connect() {
+ // use memory-Only Database
+ String url = "jdbc:hsqldb:mem:toolkit";
+ try {
+ Class.forName("org.hsqldb.jdbcDriver").newInstance();
+ connection = DriverManager.getConnection(url, "sa", "");
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * use for SQL commands CREATE, DROP, INSERT and UPDATE
+ *
+ * @param expression
+ * @throws SQLException
+ */
+ public void update(String expression) throws SQLException {
+ Statement st = null;
+ st = connection.createStatement();
+ 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 void createTables() {
+ try {
+ String stmt = null;
+ stmt = "CREATE TABLE employee ( ID INTEGER IDENTITY, FIRSTNAME VARCHAR(100), "
+ + "LASTNAME VARCHAR(100), TITLE VARCHAR(100), UNIT VARCHAR(100) )";
+ update(stmt);
+ for (int j = 0; j < ROWCOUNT; j++) {
+ stmt = "INSERT INTO employee(FIRSTNAME, LASTNAME, TITLE, UNIT) VALUES ("
+ + "'"
+ + firstnames[(int) (Math.random() * (firstnames.length - 1))]
+ + "',"
+ + "'"
+ + lastnames[(int) (Math.random() * (lastnames.length - 1))]
+ + "',"
+ + "'"
+ + titles[(int) (Math.random() * (titles.length - 1))]
+ + "',"
+ + "'"
+ + units[(int) (Math.random() * (units.length - 1))]
+ + "'" + ")";
+ update(stmt);
+ }
+ } catch (SQLException e) {
+ if (e.toString().indexOf("Table already exists") == -1) {
+ throw new RuntimeException(e);
+ }
+ }
+ }
+
+ /**
+ * Test database connection with simple SELECT command.
+ *
+ */
+ private String testDatabase() {
+ String result = null;
+ try {
+ Statement stmt = connection.createStatement(
+ ResultSet.TYPE_SCROLL_INSENSITIVE,
+ ResultSet.CONCUR_UPDATABLE);
+ ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM employee");
+ rs.next();
+ result = "rowcount for table test is " + rs.getObject(1).toString();
+ stmt.close();
+ } catch (SQLException e) {
+ throw new RuntimeException(e);
+ }
+ return result;
+ }
+
+ public Connection getConnection() {
+ return connection;
+ }
}
diff --git a/src/com/itmill/toolkit/demo/util/SampleDirectory.java b/src/com/itmill/toolkit/demo/util/SampleDirectory.java
index 95faf970c8..15cdf87dad 100644
--- a/src/com/itmill/toolkit/demo/util/SampleDirectory.java
+++ b/src/com/itmill/toolkit/demo/util/SampleDirectory.java
@@ -17,53 +17,53 @@ import com.itmill.toolkit.ui.Panel;
*/
public class SampleDirectory {
- /**
- * Get sample directory.
- *
- * @param application
- * @return file pointing to sample directory
- */
- public static File getDirectory(Application application) {
- String errorMessage = "Access to application "
- + "context base directory failed, "
- + "possible security constraint with Application "
- + "Server or Servlet Container.
";
- File file = application.getContext().getBaseDirectory();
- if ((file == null) || (!file.canRead())
- || (file.getAbsolutePath() == null)) {
- // cannot access example directory, possible security issue with
- // Application Server or Servlet Container
- // Try to read sample directory from web.xml parameter
- if (application.getProperty("sampleDirectory") != null) {
- file = new File(application.getProperty("sampleDirectory"));
- if ((file != null) && (file.canRead())
- && (file.getAbsolutePath() != null)) {
- // Success using property
- return file;
- }
- // Failure using property
- errorMessage += "Failed also to access sample directory ["
- + application.getProperty("sampleDirectory")
- + "] defined in sampleDirectory property.";
- } else {
- // Failure using application context base dir, no property set
- errorMessage += "Note: You can set this manually in "
- + "web.xml by defining " + "sampleDirectory property.";
- }
- } else {
- // Success using application context base dir
- return file;
- }
- // Add failure notification as an Panel to main window
- Panel errorPanel = new Panel("Demo application error");
- errorPanel.setStyle("strong");
- errorPanel.setComponentError(new SystemError(
- "Cannot provide sample directory"));
- errorPanel.addComponent(new Label(errorMessage, Label.CONTENT_XHTML));
- // Remove all components from applications main window
- application.getMainWindow().getLayout().removeAllComponents();
- // Add error panel
- application.getMainWindow().getLayout().addComponent(errorPanel);
- return null;
- }
+ /**
+ * Get sample directory.
+ *
+ * @param application
+ * @return file pointing to sample directory
+ */
+ public static File getDirectory(Application application) {
+ String errorMessage = "Access to application "
+ + "context base directory failed, "
+ + "possible security constraint with Application "
+ + "Server or Servlet Container.
";
+ File file = application.getContext().getBaseDirectory();
+ if ((file == null) || (!file.canRead())
+ || (file.getAbsolutePath() == null)) {
+ // cannot access example directory, possible security issue with
+ // Application Server or Servlet Container
+ // Try to read sample directory from web.xml parameter
+ if (application.getProperty("sampleDirectory") != null) {
+ file = new File(application.getProperty("sampleDirectory"));
+ if ((file != null) && (file.canRead())
+ && (file.getAbsolutePath() != null)) {
+ // Success using property
+ return file;
+ }
+ // Failure using property
+ errorMessage += "Failed also to access sample directory ["
+ + application.getProperty("sampleDirectory")
+ + "] defined in sampleDirectory property.";
+ } else {
+ // Failure using application context base dir, no property set
+ errorMessage += "Note: You can set this manually in "
+ + "web.xml by defining " + "sampleDirectory property.";
+ }
+ } else {
+ // Success using application context base dir
+ return file;
+ }
+ // Add failure notification as an Panel to main window
+ Panel errorPanel = new Panel("Demo application error");
+ errorPanel.setStyle("strong");
+ errorPanel.setComponentError(new SystemError(
+ "Cannot provide sample directory"));
+ errorPanel.addComponent(new Label(errorMessage, Label.CONTENT_XHTML));
+ // Remove all components from applications main window
+ application.getMainWindow().getLayout().removeAllComponents();
+ // Add error panel
+ application.getMainWindow().getLayout().addComponent(errorPanel);
+ return null;
+ }
}
diff --git a/src/com/itmill/toolkit/event/Action.java b/src/com/itmill/toolkit/event/Action.java
index cc1bbd723b..f2551f2b7b 100644
--- a/src/com/itmill/toolkit/event/Action.java
+++ b/src/com/itmill/toolkit/event/Action.java
@@ -28,7 +28,7 @@
package com.itmill.toolkit.event;
-import com.itmill.toolkit.terminal.*;
+import com.itmill.toolkit.terminal.Resource;
/**
* Implements the action framework. This class contains subinterfaces for action
@@ -42,146 +42,146 @@ import com.itmill.toolkit.terminal.*;
*/
public class Action {
- /**
- * Action title.
- */
- private String caption;
-
- /**
- * Action icon.
- */
- private Resource icon = null;
-
- /**
- * Constructs a new action with the given caption.
- *
- * @param caption
- * the caption for the new action.
- */
- public Action(String caption) {
- this.caption = caption;
- }
-
- /**
- * Constructs a new action with the given caption string and icon.
- *
- * @param caption
- * the caption for the new action.
- * @param icon
- * the icon for the new action.
- */
- public Action(String caption, Resource icon) {
- this.caption = caption;
- this.icon = icon;
- }
-
- /**
- * Returns the action's caption.
- *
- * @return the action's caption as a String
.
- */
- public String getCaption() {
- return caption;
- }
-
- /**
- * Returns the action's icon.
- *
- * @return the action's Icon.
- */
- public Resource getIcon() {
- return icon;
- }
-
- /**
- * Interface implemented by classes who wish to handle actions.
- *
- * @author IT Mill Ltd.
- * @version
- * @VERSION@
- * @since 3.0
- */
- public interface Handler {
-
- /**
- * Gets the list of actions applicable to this handler.
- *
- * @param target
- * the target handler to list actions for. For item
- * containers this is the item id.
- * @param sender
- * the party that would be sending the actions. Most of this
- * is the action container.
- * @return the list of Action
- */
- public Action[] getActions(Object target, Object sender);
-
- /**
- * Handles an action for the given target. The handler method may just
- * discard the action if it's not suitable.
- *
- * @param action
- * the action to be handled.
- * @param sender
- * the sender of the action. This is most often the action
- * container.
- * @param target
- * the target of the action. For item containers this is the
- * item id.
- */
- public void handleAction(Action action, Object sender, Object target);
- }
-
- /**
- * Interface implemented by all components where actions can be registered.
- * This means that the components lets others to register as action handlers
- * to it. When the component receives an action targeting its contents it
- * should loop all action handlers registered to it and let them handle the
- * action.
- *
- * @author IT Mill Ltd.
- * @version
- * @VERSION@
- * @since 3.0
- */
- public interface Container {
-
- /**
- * Registers a new action handler for this container
- *
- * @param actionHandler
- * the new handler to be added.
- */
- public void addActionHandler(Action.Handler actionHandler);
-
- /**
- * Removes a previously registered action handler for the contents of
- * this container.
- *
- * @param actionHandler
- * the handler to be removed.
- */
- public void removeActionHandler(Action.Handler actionHandler);
- }
-
- /**
- * Sets the caption.
- *
- * @param caption
- * the caption to set.
- */
- public void setCaption(String caption) {
- this.caption = caption;
- }
-
- /**
- * Sets the icon.
- *
- * @param icon
- * the icon to set.
- */
- public void setIcon(Resource icon) {
- this.icon = icon;
- }
+ /**
+ * Action title.
+ */
+ private String caption;
+
+ /**
+ * Action icon.
+ */
+ private Resource icon = null;
+
+ /**
+ * Constructs a new action with the given caption.
+ *
+ * @param caption
+ * the caption for the new action.
+ */
+ public Action(String caption) {
+ this.caption = caption;
+ }
+
+ /**
+ * Constructs a new action with the given caption string and icon.
+ *
+ * @param caption
+ * the caption for the new action.
+ * @param icon
+ * the icon for the new action.
+ */
+ public Action(String caption, Resource icon) {
+ this.caption = caption;
+ this.icon = icon;
+ }
+
+ /**
+ * Returns the action's caption.
+ *
+ * @return the action's caption as a String
.
+ */
+ public String getCaption() {
+ return caption;
+ }
+
+ /**
+ * Returns the action's icon.
+ *
+ * @return the action's Icon.
+ */
+ public Resource getIcon() {
+ return icon;
+ }
+
+ /**
+ * Interface implemented by classes who wish to handle actions.
+ *
+ * @author IT Mill Ltd.
+ * @version
+ * @VERSION@
+ * @since 3.0
+ */
+ public interface Handler {
+
+ /**
+ * Gets the list of actions applicable to this handler.
+ *
+ * @param target
+ * the target handler to list actions for. For item
+ * containers this is the item id.
+ * @param sender
+ * the party that would be sending the actions. Most of
+ * this is the action container.
+ * @return the list of Action
+ */
+ public Action[] getActions(Object target, Object sender);
+
+ /**
+ * Handles an action for the given target. The handler method may just
+ * discard the action if it's not suitable.
+ *
+ * @param action
+ * the action to be handled.
+ * @param sender
+ * the sender of the action. This is most often the
+ * action container.
+ * @param target
+ * the target of the action. For item containers this is
+ * the item id.
+ */
+ public void handleAction(Action action, Object sender, Object target);
+ }
+
+ /**
+ * Interface implemented by all components where actions can be registered.
+ * This means that the components lets others to register as action handlers
+ * to it. When the component receives an action targeting its contents it
+ * should loop all action handlers registered to it and let them handle the
+ * action.
+ *
+ * @author IT Mill Ltd.
+ * @version
+ * @VERSION@
+ * @since 3.0
+ */
+ public interface Container {
+
+ /**
+ * Registers a new action handler for this container
+ *
+ * @param actionHandler
+ * the new handler to be added.
+ */
+ public void addActionHandler(Action.Handler actionHandler);
+
+ /**
+ * Removes a previously registered action handler for the contents of
+ * this container.
+ *
+ * @param actionHandler
+ * the handler to be removed.
+ */
+ public void removeActionHandler(Action.Handler actionHandler);
+ }
+
+ /**
+ * Sets the caption.
+ *
+ * @param caption
+ * the caption to set.
+ */
+ public void setCaption(String caption) {
+ this.caption = caption;
+ }
+
+ /**
+ * Sets the icon.
+ *
+ * @param icon
+ * the icon to set.
+ */
+ public void setIcon(Resource icon) {
+ this.icon = icon;
+ }
}
diff --git a/src/com/itmill/toolkit/event/EventRouter.java b/src/com/itmill/toolkit/event/EventRouter.java
index 563bb7c639..a71a3e1874 100644
--- a/src/com/itmill/toolkit/event/EventRouter.java
+++ b/src/com/itmill/toolkit/event/EventRouter.java
@@ -28,10 +28,10 @@
package com.itmill.toolkit.event;
+import java.lang.reflect.Method;
import java.util.EventObject;
-import java.util.LinkedList;
import java.util.Iterator;
-import java.lang.reflect.Method;
+import java.util.LinkedList;
/**
* EventRouter
class implementing the inheritable event listening
@@ -45,134 +45,143 @@ import java.lang.reflect.Method;
*/
public class EventRouter implements MethodEventSource {
- /**
- * List of registered listeners.
- */
- private LinkedList listenerList = null;
-
- /*
- * Registers a new listener with the specified activation method to listen
- * events generated by this component. Don't add a JavaDoc comment here, we
- * use the default documentation from implemented interface.
- */
- public void addListener(Class eventType, Object object, Method method) {
-
- if (listenerList == null)
- listenerList = new LinkedList();
-
- listenerList.add(new ListenerMethod(eventType, object, method));
- }
-
- /*
- * Registers a new listener with the specified named activation method to
- * listen events generated by this component. Don't add a JavaDoc comment
- * here, we use the default documentation from implemented interface.
- */
- public void addListener(Class eventType, Object object, String methodName) {
-
- if (listenerList == null)
- listenerList = new LinkedList();
-
- listenerList.add(new ListenerMethod(eventType, object, methodName));
- }
-
- /*
- * Removes all registered listeners matching the given parameters. Don't add
- * a JavaDoc comment here, we use the default documentation from implemented
- * interface.
- */
- public void removeListener(Class eventType, Object target) {
-
- if (listenerList != null) {
- Iterator i = listenerList.iterator();
- while (i.hasNext()) {
- try {
- ListenerMethod lm = (ListenerMethod) i.next();
- if (lm.matches(eventType, target))
- i.remove();
- } catch (java.lang.ClassCastException e) {
- // Class cast exceptions are ignored
- }
- }
- }
- }
-
- /*
- * Removes the event listener methods matching the given given paramaters.
- * Don't add a JavaDoc comment here, we use the default documentation from
- * implemented interface.
- */
- public void removeListener(Class eventType, Object target, Method method) {
-
- if (listenerList != null) {
- Iterator i = listenerList.iterator();
- while (i.hasNext()) {
- try {
- ListenerMethod lm = (ListenerMethod) i.next();
- if (lm.matches(eventType, target, method))
- i.remove();
- } catch (java.lang.ClassCastException e) {
- // Class cast exceptions are ignored
- }
- }
- }
- }
-
- /*
- * Removes the event listener method matching the given given paramaters.
- * Don't add a JavaDoc comment here, we use the default documentation from
- * implemented interface.
- */
- public void removeListener(Class eventType, Object target, String methodName) {
-
- // Find the correct method
- Method[] methods = target.getClass().getMethods();
- Method method = null;
- for (int i = 0; i < methods.length; i++)
- if (methods[i].getName().equals(methodName))
- method = methods[i];
- if (method == null)
- throw new IllegalArgumentException();
-
- // Remove the listeners
- if (listenerList != null) {
- Iterator i = listenerList.iterator();
- while (i.hasNext()) {
- try {
- ListenerMethod lm = (ListenerMethod) i.next();
- if (lm.matches(eventType, target, method))
- i.remove();
- } catch (java.lang.ClassCastException e) {
- // Class cast exceptions are ignored
- }
- }
- }
- }
-
- /**
- * Removes all listeners from event router.
- */
- public void removeAllListeners() {
- listenerList = null;
- }
-
- /**
- * Sends an event to all registered listeners. The listeners will decide if
- * the activation method should be called or not.
- *
- * @param event
- * the Event to be sent to all listeners.
- */
- public void fireEvent(EventObject event) {
-
- // It is not necessary to send any events if there are no listeners
- if (listenerList != null) {
-
- // Send the event to all listeners. The listeners themselves
- // will filter out unwanted events.
- Iterator i = new LinkedList(listenerList).iterator();
- while (i.hasNext())
- ((ListenerMethod) i.next()).receiveEvent(event);
- }
- }
+ /**
+ * List of registered listeners.
+ */
+ private LinkedList listenerList = null;
+
+ /*
+ * Registers a new listener with the specified activation method to listen
+ * events generated by this component. Don't add a JavaDoc comment here, we
+ * use the default documentation from implemented interface.
+ */
+ public void addListener(Class eventType, Object object, Method method) {
+
+ if (listenerList == null) {
+ listenerList = new LinkedList();
+ }
+
+ listenerList.add(new ListenerMethod(eventType, object, method));
+ }
+
+ /*
+ * Registers a new listener with the specified named activation method to
+ * listen events generated by this component. Don't add a JavaDoc comment
+ * here, we use the default documentation from implemented interface.
+ */
+ public void addListener(Class eventType, Object object, String methodName) {
+
+ if (listenerList == null) {
+ listenerList = new LinkedList();
+ }
+
+ listenerList.add(new ListenerMethod(eventType, object, methodName));
+ }
+
+ /*
+ * Removes all registered listeners matching the given parameters. Don't add
+ * a JavaDoc comment here, we use the default documentation from implemented
+ * interface.
+ */
+ public void removeListener(Class eventType, Object target) {
+
+ if (listenerList != null) {
+ Iterator i = listenerList.iterator();
+ while (i.hasNext()) {
+ try {
+ ListenerMethod lm = (ListenerMethod) i.next();
+ if (lm.matches(eventType, target)) {
+ i.remove();
+ }
+ } catch (java.lang.ClassCastException e) {
+ // Class cast exceptions are ignored
+ }
+ }
+ }
+ }
+
+ /*
+ * Removes the event listener methods matching the given given paramaters.
+ * Don't add a JavaDoc comment here, we use the default documentation from
+ * implemented interface.
+ */
+ public void removeListener(Class eventType, Object target, Method method) {
+
+ if (listenerList != null) {
+ Iterator i = listenerList.iterator();
+ while (i.hasNext()) {
+ try {
+ ListenerMethod lm = (ListenerMethod) i.next();
+ if (lm.matches(eventType, target, method)) {
+ i.remove();
+ }
+ } catch (java.lang.ClassCastException e) {
+ // Class cast exceptions are ignored
+ }
+ }
+ }
+ }
+
+ /*
+ * Removes the event listener method matching the given given paramaters.
+ * Don't add a JavaDoc comment here, we use the default documentation from
+ * implemented interface.
+ */
+ public void removeListener(Class eventType, Object target, String methodName) {
+
+ // Find the correct method
+ Method[] methods = target.getClass().getMethods();
+ Method method = null;
+ for (int i = 0; i < methods.length; i++) {
+ if (methods[i].getName().equals(methodName)) {
+ method = methods[i];
+ }
+ }
+ if (method == null) {
+ throw new IllegalArgumentException();
+ }
+
+ // Remove the listeners
+ if (listenerList != null) {
+ Iterator i = listenerList.iterator();
+ while (i.hasNext()) {
+ try {
+ ListenerMethod lm = (ListenerMethod) i.next();
+ if (lm.matches(eventType, target, method)) {
+ i.remove();
+ }
+ } catch (java.lang.ClassCastException e) {
+ // Class cast exceptions are ignored
+ }
+ }
+ }
+ }
+
+ /**
+ * Removes all listeners from event router.
+ */
+ public void removeAllListeners() {
+ listenerList = null;
+ }
+
+ /**
+ * Sends an event to all registered listeners. The listeners will decide if
+ * the activation method should be called or not.
+ *
+ * @param event
+ * the Event to be sent to all listeners.
+ */
+ public void fireEvent(EventObject event) {
+
+ // It is not necessary to send any events if there are no listeners
+ if (listenerList != null) {
+
+ // Send the event to all listeners. The listeners themselves
+ // will filter out unwanted events.
+ Iterator i = new LinkedList(listenerList).iterator();
+ while (i.hasNext()) {
+ ((ListenerMethod) i.next()).receiveEvent(event);
+ }
+ }
+ }
}
diff --git a/src/com/itmill/toolkit/event/ListenerMethod.java b/src/com/itmill/toolkit/event/ListenerMethod.java
index f88b691987..07c9866e37 100644
--- a/src/com/itmill/toolkit/event/ListenerMethod.java
+++ b/src/com/itmill/toolkit/event/ListenerMethod.java
@@ -28,9 +28,9 @@
package com.itmill.toolkit.event;
+import java.lang.reflect.Method;
import java.util.EventListener;
import java.util.EventObject;
-import java.lang.reflect.Method;
/**
*
@@ -60,483 +60,513 @@ import java.lang.reflect.Method;
*/
public class ListenerMethod implements EventListener {
- /**
- * Type of the event that should trigger this listener. Also the subclasses
- * of this class are accepted to trigger the listener.
- */
- private Class eventType;
-
- /**
- * The object containing the trigger method.
- */
- private Object object;
-
- /**
- * The trigger method to call when an event passing the given criteria
- * fires.
- */
- private Method method;
-
- /**
- * Optional argument set to pass to the trigger method.
- */
- private Object[] arguments;
-
- /**
- * Optional index to arguments
that point out which one
- * should be replaced with the triggering event object and thus be passed to
- * the trigger method.
- */
- private int eventArgumentIndex;
-
- /**
- *
- * Constructs a new event listener from a trigger method, it's arguments and
- * the argument index specifying which one is replaced with the event object
- * when the trigger method is called.
- *
- *
- *
- * This constructor gets the trigger method as a parameter so it does not
- * need to reflect to find it out.
- *
- *
- * @param eventType
- * the event type that is listener listens to. All events of this
- * kind (or its subclasses) result in calling the trigger method.
- * @param object
- * the object instance that contains the trigger method
- * @param method
- * the trigger method
- * @param arguments
- * the arguments to be passed to the trigger method
- * @param eventArgumentIndex
- * An index to the argument list. This index points out the
- * argument that is replaced with the event object before the
- * argument set is passed to the trigger method. If the
- * eventArgumentIndex is negative, the triggering event object
- * will not be passed to the trigger method, though it is still
- * called.
- * @throws java.lang.IllegalArgumentException
- * if method
is not a member of
- * object
.
- */
- public ListenerMethod(Class eventType, Object object, Method method,
- Object[] arguments, int eventArgumentIndex)
- throws java.lang.IllegalArgumentException {
-
- // Checks that the object is of correct type
- if (!method.getDeclaringClass().isAssignableFrom(object.getClass()))
- throw new java.lang.IllegalArgumentException();
-
- // Checks that the event argument is null
- if (eventArgumentIndex >= 0 && arguments[eventArgumentIndex] != null)
- throw new java.lang.IllegalArgumentException();
-
- // Checks the event type is supported by the method
- if (eventArgumentIndex >= 0
- && !method.getParameterTypes()[eventArgumentIndex]
- .isAssignableFrom(eventType))
- throw new java.lang.IllegalArgumentException();
-
- this.eventType = eventType;
- this.object = object;
- this.method = method;
- this.arguments = arguments;
- this.eventArgumentIndex = eventArgumentIndex;
- }
-
- /**
- *
- * Constructs a new event listener from a trigger method name, it's
- * arguments and the argument index specifying which one is replaced with
- * the event object. The actual trigger method is reflected from
- * object
, and
- * java.lang.IllegalArgumentException
is thrown unless
- * exactly one match is found.
- *
- *
- * @param eventType
- * the event type that is listener listens to. All events of this
- * kind (or its subclasses) result in calling the trigger method.
- * @param object
- * the object instance that contains the trigger method.
- * @param methodName
- * the name of the trigger method. If the object does not contain
- * the method or it contains more than one matching methods
- * java.lang.IllegalArgumentException
is thrown.
- * @param arguments
- * the arguments to be passed to the trigger method.
- * @param eventArgumentIndex
- * An index to the argument list. This index points out the
- * argument that is replaced with the event object before the
- * argument set is passed to the trigger method. If the
- * eventArgumentIndex is negative, the triggering event object
- * will not be passed to the trigger method, though it is still
- * called.
- * @throws java.lang.IllegalArgumentException
- * unless exactly one match methodName
is found
- * in object
.
- */
- public ListenerMethod(Class eventType, Object object, String methodName,
- Object[] arguments, int eventArgumentIndex)
- throws java.lang.IllegalArgumentException {
-
- // Finds the correct method
- Method[] methods = object.getClass().getMethods();
- Method method = null;
- for (int i = 0; i < methods.length; i++)
- if (methods[i].getName().equals(methodName))
- method = methods[i];
- if (method == null)
- throw new IllegalArgumentException();
-
- // Checks that the event argument is null
- if (eventArgumentIndex >= 0 && arguments[eventArgumentIndex] != null)
- throw new java.lang.IllegalArgumentException();
-
- // Checks the event type is supported by the method
- if (eventArgumentIndex >= 0
- && !method.getParameterTypes()[eventArgumentIndex]
- .isAssignableFrom(eventType))
- throw new java.lang.IllegalArgumentException();
-
- this.eventType = eventType;
- this.object = object;
- this.method = method;
- this.arguments = arguments;
- this.eventArgumentIndex = eventArgumentIndex;
- }
-
- /**
- *
- * Constructs a new event listener from the trigger method and it's
- * arguments. Since the the index to the replaced parameter is not specified
- * the event triggering this listener will not be passed to the trigger
- * method.
- *
- *
- *
- * This constructor gets the trigger method as a parameter so it does not
- * need to reflect to find it out.
- *
- *
- * @param eventType
- * the event type that is listener listens to. All events of this
- * kind (or its subclasses) result in calling the trigger method.
- * @param object
- * the object instance that contains the trigger method.
- * @param method
- * the trigger method.
- * @param arguments
- * the arguments to be passed to the trigger method.
- * @throws java.lang.IllegalArgumentException
- * if method
is not a member of
- * object
.
- */
- public ListenerMethod(Class eventType, Object object, Method method,
- Object[] arguments) throws java.lang.IllegalArgumentException {
-
- // Check that the object is of correct type
- if (!method.getDeclaringClass().isAssignableFrom(object.getClass()))
- throw new java.lang.IllegalArgumentException();
-
- this.eventType = eventType;
- this.object = object;
- this.method = method;
- this.arguments = arguments;
- this.eventArgumentIndex = -1;
- }
-
- /**
- *
- * Constructs a new event listener from a trigger method name and it's
- * arguments. Since the the index to the replaced parameter is not specified
- * the event triggering this listener will not be passed to the trigger
- * method.
- *
- *
- *
- * The actual trigger method is reflected from object
, and
- * java.lang.IllegalArgumentException
is thrown unless
- * exactly one match is found.
- *
- *
- * @param eventType
- * the event type that is listener listens to. All events of this
- * kind (or its subclasses) result in calling the trigger method.
- * @param object
- * the object instance that contains the trigger method.
- * @param methodName
- * the name of the trigger method. If the object does not contain
- * the method or it contains more than one matching methods
- * java.lang.IllegalArgumentException
is thrown.
- * @param arguments
- * the arguments to be passed to the trigger method.
- * @throws java.lang.IllegalArgumentException
- * unless exactly one match methodName
is found
- * in object
.
- */
- public ListenerMethod(Class eventType, Object object, String methodName,
- Object[] arguments) throws java.lang.IllegalArgumentException {
-
- // Find the correct method
- Method[] methods = object.getClass().getMethods();
- Method method = null;
- for (int i = 0; i < methods.length; i++)
- if (methods[i].getName().equals(methodName))
- method = methods[i];
- if (method == null)
- throw new IllegalArgumentException();
-
- this.eventType = eventType;
- this.object = object;
- this.method = method;
- this.arguments = arguments;
- this.eventArgumentIndex = -1;
- }
-
- /**
- *
- * Constructs a new event listener from a trigger method. Since the argument
- * list is unspecified no parameters are passed to the trigger method when
- * the listener is triggered.
- *
- *
- *
- * This constructor gets the trigger method as a parameter so it does not
- * need to reflect to find it out.
- *
- *
- * @param eventType
- * the event type that is listener listens to. All events of this
- * kind (or its subclasses) result in calling the trigger method.
- * @param object
- * the object instance that contains the trigger method.
- * @param method
- * the trigger method.
- * @throws java.lang.IllegalArgumentException
- * if method
is not a member of
- * object
.
- */
- public ListenerMethod(Class eventType, Object object, Method method)
- throws java.lang.IllegalArgumentException {
-
- // Checks that the object is of correct type
- if (!method.getDeclaringClass().isAssignableFrom(object.getClass()))
- throw new java.lang.IllegalArgumentException();
-
- this.eventType = eventType;
- this.object = object;
- this.method = method;
- this.eventArgumentIndex = -1;
-
- Class[] params = method.getParameterTypes();
-
- if (params.length == 0)
- this.arguments = new Object[0];
- else if (params.length == 1 && params[0].isAssignableFrom(eventType)) {
- this.arguments = new Object[] { null };
- this.eventArgumentIndex = 0;
- } else
- throw new IllegalArgumentException();
- }
-
- /**
- *
- * Constructs a new event listener from a trigger method name. Since the
- * argument list is unspecified no parameters are passed to the trigger
- * method when the listener is triggered.
- *
- *
- *
- * The actual trigger method is reflected from object
, and
- * java.lang.IllegalArgumentException
is thrown unless
- * exactly one match is found.
- *
- *
- * @param eventType
- * the event type that is listener listens to. All events of this
- * kind (or its subclasses) result in calling the trigger method.
- * @param object
- * the object instance that contains the trigger method.
- * @param methodName
- * the name of the trigger method. If the object does not contain
- * the method or it contains more than one matching methods
- * java.lang.IllegalArgumentException
is thrown.
- * @throws java.lang.IllegalArgumentException
- * unless exactly one match methodName
is found
- * in object
.
- */
- public ListenerMethod(Class eventType, Object object, String methodName)
- throws java.lang.IllegalArgumentException {
-
- // Finds the correct method
- Method[] methods = object.getClass().getMethods();
- Method method = null;
- for (int i = 0; i < methods.length; i++)
- if (methods[i].getName().equals(methodName))
- method = methods[i];
- if (method == null)
- throw new IllegalArgumentException();
-
- this.eventType = eventType;
- this.object = object;
- this.method = method;
- this.eventArgumentIndex = -1;
-
- Class[] params = method.getParameterTypes();
-
- if (params.length == 0)
- this.arguments = new Object[0];
- else if (params.length == 1 && params[0].isAssignableFrom(eventType)) {
- this.arguments = new Object[] { null };
- this.eventArgumentIndex = 0;
- } else
- throw new IllegalArgumentException();
- }
-
- /**
- * Receives one event from the EventRouter
and calls the
- * trigger method if it matches with the criteria defined for the listener.
- * Only the events of the same or subclass of the specified event class
- * result in the trigger method to be called.
- *
- * @param event
- * the fired event. Unless the trigger method's argument list and
- * the index to the to be replaced argument is specified, this
- * event will not be passed to the trigger method.
- */
- public void receiveEvent(EventObject event) {
-
- // Only send events supported by the method
- if (eventType.isAssignableFrom(event.getClass())) {
- try {
- if (eventArgumentIndex >= 0) {
- if (eventArgumentIndex == 0 && arguments.length == 1)
- method.invoke(object, new Object[] { event });
- else {
- Object[] arg = new Object[arguments.length];
- for (int i = 0; i < arg.length; i++)
- arg[i] = arguments[i];
- arg[eventArgumentIndex] = event;
- method.invoke(object, arg);
- }
- } else
- method.invoke(object, arguments);
-
- } catch (java.lang.IllegalAccessException e) {
- // This should never happen
- throw new java.lang.RuntimeException(
- "Internal error - please report: " + e.toString());
- } catch (java.lang.reflect.InvocationTargetException e) {
- // This should never happen
- throw new MethodException("Invocation if method " + method
- + " failed.", e.getTargetException());
- }
- }
- }
-
- /**
- * Checks if the given object and event match with the ones stored in this
- * listener.
- *
- * @param target
- * the object to be matched against the object stored by this
- * listener.
- * @param eventType
- * the type to be tested for equality against the type stored by
- * this listener.
- * @return true
if target
is the same object
- * as the one stored in this object and eventType
- * equals the event type stored in this object.
- */
- public boolean matches(Class eventType, Object target) {
- return (target == object) && (eventType.equals(this.eventType));
- }
-
- /**
- * Checks if the given object, event and method match with the ones stored
- * in this listener.
- *
- * @param target
- * the object to be matched against the object stored by this
- * listener.
- * @param eventType
- * the type to be tested for equality against the type stored by
- * this listener.
- * @param method
- * the method to be tested for equality against the method stored
- * by this listener.
- * @return true
if target
is the same object
- * as the one stored in this object, eventType
equals
- * with the event type stored in this object and method
- * equals with the method stored in this object
- */
- public boolean matches(Class eventType, Object target, Method method) {
- return (target == object)
- && (eventType.equals(this.eventType) && method
- .equals(this.method));
- }
-
- /**
- * Exception that wraps an exception thrown by an invoked method. When
- * ListenerMethod
invokes the target method, it may throw
- * arbitrary exception. The original exception is wrapped into
- * MethodException instance and rethrown by the ListenerMethod
.
- *
- * @author IT Mill Ltd.
- * @version
- * @VERSION@
- * @since 3.0
- */
- public class MethodException extends RuntimeException {
-
- /**
- * Serial generated by eclipse.
- */
- private static final long serialVersionUID = 3257005445242894135L;
-
- private Throwable cause;
-
- private String message;
-
- private MethodException(String message, Throwable cause) {
- super(message);
- this.cause = cause;
- }
-
- /**
- * Retrieves the cause of this throwable or null
if the
- * cause does not exist or not known.
- *
- * @return the cause of this throwable or null
if the
- * cause is nonexistent or unknown.
- * @see java.lang.Throwable#getCause()
- */
- public Throwable getCause() {
- return this.cause;
- }
-
- /**
- * Returns the error message string of this throwable object.
- *
- * @return the error message.
- * @see java.lang.Throwable#getMessage()
- */
- public String getMessage() {
- return message;
- }
-
- /**
- * @see java.lang.Throwable#toString()
- */
- public String toString() {
- String msg = super.toString();
- if (cause != null)
- msg += "\nCause: " + cause.toString();
- return msg;
- }
-
- }
+ /**
+ * Type of the event that should trigger this listener. Also the subclasses
+ * of this class are accepted to trigger the listener.
+ */
+ private Class eventType;
+
+ /**
+ * The object containing the trigger method.
+ */
+ private Object object;
+
+ /**
+ * The trigger method to call when an event passing the given criteria
+ * fires.
+ */
+ private Method method;
+
+ /**
+ * Optional argument set to pass to the trigger method.
+ */
+ private Object[] arguments;
+
+ /**
+ * Optional index to arguments
that point out which one
+ * should be replaced with the triggering event object and thus be passed to
+ * the trigger method.
+ */
+ private int eventArgumentIndex;
+
+ /**
+ *
+ * Constructs a new event listener from a trigger method, it's arguments and
+ * the argument index specifying which one is replaced with the event object
+ * when the trigger method is called.
+ *
+ *
+ *
+ * This constructor gets the trigger method as a parameter so it does not
+ * need to reflect to find it out.
+ *
+ *
+ * @param eventType
+ * the event type that is listener listens to. All events of
+ * this kind (or its subclasses) result in calling the
+ * trigger method.
+ * @param object
+ * the object instance that contains the trigger method
+ * @param method
+ * the trigger method
+ * @param arguments
+ * the arguments to be passed to the trigger method
+ * @param eventArgumentIndex
+ * An index to the argument list. This index points out the
+ * argument that is replaced with the event object before the
+ * argument set is passed to the trigger method. If the
+ * eventArgumentIndex is negative, the triggering event
+ * object will not be passed to the trigger method, though it
+ * is still called.
+ * @throws java.lang.IllegalArgumentException
+ * if method
is not a member of
+ * object
.
+ */
+ public ListenerMethod(Class eventType, Object object, Method method,
+ Object[] arguments, int eventArgumentIndex)
+ throws java.lang.IllegalArgumentException {
+
+ // Checks that the object is of correct type
+ if (!method.getDeclaringClass().isAssignableFrom(object.getClass())) {
+ throw new java.lang.IllegalArgumentException();
+ }
+
+ // Checks that the event argument is null
+ if (eventArgumentIndex >= 0 && arguments[eventArgumentIndex] != null) {
+ throw new java.lang.IllegalArgumentException();
+ }
+
+ // Checks the event type is supported by the method
+ if (eventArgumentIndex >= 0
+ && !method.getParameterTypes()[eventArgumentIndex]
+ .isAssignableFrom(eventType)) {
+ throw new java.lang.IllegalArgumentException();
+ }
+
+ this.eventType = eventType;
+ this.object = object;
+ this.method = method;
+ this.arguments = arguments;
+ this.eventArgumentIndex = eventArgumentIndex;
+ }
+
+ /**
+ *
+ * Constructs a new event listener from a trigger method name, it's
+ * arguments and the argument index specifying which one is replaced with
+ * the event object. The actual trigger method is reflected from
+ * object
, and
+ * java.lang.IllegalArgumentException
is thrown unless
+ * exactly one match is found.
+ *
+ *
+ * @param eventType
+ * the event type that is listener listens to. All events of
+ * this kind (or its subclasses) result in calling the
+ * trigger method.
+ * @param object
+ * the object instance that contains the trigger method.
+ * @param methodName
+ * the name of the trigger method. If the object does not
+ * contain the method or it contains more than one matching
+ * methods java.lang.IllegalArgumentException
+ * is thrown.
+ * @param arguments
+ * the arguments to be passed to the trigger method.
+ * @param eventArgumentIndex
+ * An index to the argument list. This index points out the
+ * argument that is replaced with the event object before the
+ * argument set is passed to the trigger method. If the
+ * eventArgumentIndex is negative, the triggering event
+ * object will not be passed to the trigger method, though it
+ * is still called.
+ * @throws java.lang.IllegalArgumentException
+ * unless exactly one match methodName
is
+ * found in object
.
+ */
+ public ListenerMethod(Class eventType, Object object, String methodName,
+ Object[] arguments, int eventArgumentIndex)
+ throws java.lang.IllegalArgumentException {
+
+ // Finds the correct method
+ Method[] methods = object.getClass().getMethods();
+ Method method = null;
+ for (int i = 0; i < methods.length; i++) {
+ if (methods[i].getName().equals(methodName)) {
+ method = methods[i];
+ }
+ }
+ if (method == null) {
+ throw new IllegalArgumentException();
+ }
+
+ // Checks that the event argument is null
+ if (eventArgumentIndex >= 0 && arguments[eventArgumentIndex] != null) {
+ throw new java.lang.IllegalArgumentException();
+ }
+
+ // Checks the event type is supported by the method
+ if (eventArgumentIndex >= 0
+ && !method.getParameterTypes()[eventArgumentIndex]
+ .isAssignableFrom(eventType)) {
+ throw new java.lang.IllegalArgumentException();
+ }
+
+ this.eventType = eventType;
+ this.object = object;
+ this.method = method;
+ this.arguments = arguments;
+ this.eventArgumentIndex = eventArgumentIndex;
+ }
+
+ /**
+ *
+ * Constructs a new event listener from the trigger method and it's
+ * arguments. Since the the index to the replaced parameter is not specified
+ * the event triggering this listener will not be passed to the trigger
+ * method.
+ *
+ *
+ *
+ * This constructor gets the trigger method as a parameter so it does not
+ * need to reflect to find it out.
+ *
+ *
+ * @param eventType
+ * the event type that is listener listens to. All events of
+ * this kind (or its subclasses) result in calling the
+ * trigger method.
+ * @param object
+ * the object instance that contains the trigger method.
+ * @param method
+ * the trigger method.
+ * @param arguments
+ * the arguments to be passed to the trigger method.
+ * @throws java.lang.IllegalArgumentException
+ * if method
is not a member of
+ * object
.
+ */
+ public ListenerMethod(Class eventType, Object object, Method method,
+ Object[] arguments) throws java.lang.IllegalArgumentException {
+
+ // Check that the object is of correct type
+ if (!method.getDeclaringClass().isAssignableFrom(object.getClass())) {
+ throw new java.lang.IllegalArgumentException();
+ }
+
+ this.eventType = eventType;
+ this.object = object;
+ this.method = method;
+ this.arguments = arguments;
+ eventArgumentIndex = -1;
+ }
+
+ /**
+ *
+ * Constructs a new event listener from a trigger method name and it's
+ * arguments. Since the the index to the replaced parameter is not specified
+ * the event triggering this listener will not be passed to the trigger
+ * method.
+ *
+ *
+ *
+ * The actual trigger method is reflected from object
, and
+ * java.lang.IllegalArgumentException
is thrown unless
+ * exactly one match is found.
+ *
+ *
+ * @param eventType
+ * the event type that is listener listens to. All events of
+ * this kind (or its subclasses) result in calling the
+ * trigger method.
+ * @param object
+ * the object instance that contains the trigger method.
+ * @param methodName
+ * the name of the trigger method. If the object does not
+ * contain the method or it contains more than one matching
+ * methods java.lang.IllegalArgumentException
+ * is thrown.
+ * @param arguments
+ * the arguments to be passed to the trigger method.
+ * @throws java.lang.IllegalArgumentException
+ * unless exactly one match methodName
is
+ * found in object
.
+ */
+ public ListenerMethod(Class eventType, Object object, String methodName,
+ Object[] arguments) throws java.lang.IllegalArgumentException {
+
+ // Find the correct method
+ Method[] methods = object.getClass().getMethods();
+ Method method = null;
+ for (int i = 0; i < methods.length; i++) {
+ if (methods[i].getName().equals(methodName)) {
+ method = methods[i];
+ }
+ }
+ if (method == null) {
+ throw new IllegalArgumentException();
+ }
+
+ this.eventType = eventType;
+ this.object = object;
+ this.method = method;
+ this.arguments = arguments;
+ eventArgumentIndex = -1;
+ }
+
+ /**
+ *
+ * Constructs a new event listener from a trigger method. Since the argument
+ * list is unspecified no parameters are passed to the trigger method when
+ * the listener is triggered.
+ *
+ *
+ *
+ * This constructor gets the trigger method as a parameter so it does not
+ * need to reflect to find it out.
+ *
+ *
+ * @param eventType
+ * the event type that is listener listens to. All events of
+ * this kind (or its subclasses) result in calling the
+ * trigger method.
+ * @param object
+ * the object instance that contains the trigger method.
+ * @param method
+ * the trigger method.
+ * @throws java.lang.IllegalArgumentException
+ * if method
is not a member of
+ * object
.
+ */
+ public ListenerMethod(Class eventType, Object object, Method method)
+ throws java.lang.IllegalArgumentException {
+
+ // Checks that the object is of correct type
+ if (!method.getDeclaringClass().isAssignableFrom(object.getClass())) {
+ throw new java.lang.IllegalArgumentException();
+ }
+
+ this.eventType = eventType;
+ this.object = object;
+ this.method = method;
+ eventArgumentIndex = -1;
+
+ Class[] params = method.getParameterTypes();
+
+ if (params.length == 0) {
+ arguments = new Object[0];
+ } else if (params.length == 1 && params[0].isAssignableFrom(eventType)) {
+ arguments = new Object[] { null };
+ eventArgumentIndex = 0;
+ } else {
+ throw new IllegalArgumentException();
+ }
+ }
+
+ /**
+ *
+ * Constructs a new event listener from a trigger method name. Since the
+ * argument list is unspecified no parameters are passed to the trigger
+ * method when the listener is triggered.
+ *
+ *
+ *
+ * The actual trigger method is reflected from object
, and
+ * java.lang.IllegalArgumentException
is thrown unless
+ * exactly one match is found.
+ *
+ *
+ * @param eventType
+ * the event type that is listener listens to. All events of
+ * this kind (or its subclasses) result in calling the
+ * trigger method.
+ * @param object
+ * the object instance that contains the trigger method.
+ * @param methodName
+ * the name of the trigger method. If the object does not
+ * contain the method or it contains more than one matching
+ * methods java.lang.IllegalArgumentException
+ * is thrown.
+ * @throws java.lang.IllegalArgumentException
+ * unless exactly one match methodName
is
+ * found in object
.
+ */
+ public ListenerMethod(Class eventType, Object object, String methodName)
+ throws java.lang.IllegalArgumentException {
+
+ // Finds the correct method
+ Method[] methods = object.getClass().getMethods();
+ Method method = null;
+ for (int i = 0; i < methods.length; i++) {
+ if (methods[i].getName().equals(methodName)) {
+ method = methods[i];
+ }
+ }
+ if (method == null) {
+ throw new IllegalArgumentException();
+ }
+
+ this.eventType = eventType;
+ this.object = object;
+ this.method = method;
+ eventArgumentIndex = -1;
+
+ Class[] params = method.getParameterTypes();
+
+ if (params.length == 0) {
+ arguments = new Object[0];
+ } else if (params.length == 1 && params[0].isAssignableFrom(eventType)) {
+ arguments = new Object[] { null };
+ eventArgumentIndex = 0;
+ } else {
+ throw new IllegalArgumentException();
+ }
+ }
+
+ /**
+ * Receives one event from the EventRouter
and calls the
+ * trigger method if it matches with the criteria defined for the listener.
+ * Only the events of the same or subclass of the specified event class
+ * result in the trigger method to be called.
+ *
+ * @param event
+ * the fired event. Unless the trigger method's argument list
+ * and the index to the to be replaced argument is specified,
+ * this event will not be passed to the trigger method.
+ */
+ public void receiveEvent(EventObject event) {
+
+ // Only send events supported by the method
+ if (eventType.isAssignableFrom(event.getClass())) {
+ try {
+ if (eventArgumentIndex >= 0) {
+ if (eventArgumentIndex == 0 && arguments.length == 1) {
+ method.invoke(object, new Object[] { event });
+ } else {
+ Object[] arg = new Object[arguments.length];
+ for (int i = 0; i < arg.length; i++) {
+ arg[i] = arguments[i];
+ }
+ arg[eventArgumentIndex] = event;
+ method.invoke(object, arg);
+ }
+ } else {
+ method.invoke(object, arguments);
+ }
+
+ } catch (java.lang.IllegalAccessException e) {
+ // This should never happen
+ throw new java.lang.RuntimeException(
+ "Internal error - please report: " + e.toString());
+ } catch (java.lang.reflect.InvocationTargetException e) {
+ // This should never happen
+ throw new MethodException("Invocation if method " + method
+ + " failed.", e.getTargetException());
+ }
+ }
+ }
+
+ /**
+ * Checks if the given object and event match with the ones stored in this
+ * listener.
+ *
+ * @param target
+ * the object to be matched against the object stored by this
+ * listener.
+ * @param eventType
+ * the type to be tested for equality against the type stored
+ * by this listener.
+ * @return true
if target
is the same object
+ * as the one stored in this object and eventType
+ * equals the event type stored in this object.
+ */
+ public boolean matches(Class eventType, Object target) {
+ return (target == object) && (eventType.equals(this.eventType));
+ }
+
+ /**
+ * Checks if the given object, event and method match with the ones stored
+ * in this listener.
+ *
+ * @param target
+ * the object to be matched against the object stored by this
+ * listener.
+ * @param eventType
+ * the type to be tested for equality against the type stored
+ * by this listener.
+ * @param method
+ * the method to be tested for equality against the method
+ * stored by this listener.
+ * @return true
if target
is the same object
+ * as the one stored in this object, eventType
equals
+ * with the event type stored in this object and method
+ * equals with the method stored in this object
+ */
+ public boolean matches(Class eventType, Object target, Method method) {
+ return (target == object)
+ && (eventType.equals(this.eventType) && method
+ .equals(this.method));
+ }
+
+ /**
+ * Exception that wraps an exception thrown by an invoked method. When
+ * ListenerMethod
invokes the target method, it may throw
+ * arbitrary exception. The original exception is wrapped into
+ * MethodException instance and rethrown by the ListenerMethod
.
+ *
+ * @author IT Mill Ltd.
+ * @version
+ * @VERSION@
+ * @since 3.0
+ */
+ public class MethodException extends RuntimeException {
+
+ /**
+ * Serial generated by eclipse.
+ */
+ private static final long serialVersionUID = 3257005445242894135L;
+
+ private Throwable cause;
+
+ private String message;
+
+ private MethodException(String message, Throwable cause) {
+ super(message);
+ this.cause = cause;
+ }
+
+ /**
+ * Retrieves the cause of this throwable or null
if the
+ * cause does not exist or not known.
+ *
+ * @return the cause of this throwable or null
if the
+ * cause is nonexistent or unknown.
+ * @see java.lang.Throwable#getCause()
+ */
+ public Throwable getCause() {
+ return cause;
+ }
+
+ /**
+ * Returns the error message string of this throwable object.
+ *
+ * @return the error message.
+ * @see java.lang.Throwable#getMessage()
+ */
+ public String getMessage() {
+ return message;
+ }
+
+ /**
+ * @see java.lang.Throwable#toString()
+ */
+ public String toString() {
+ String msg = super.toString();
+ if (cause != null) {
+ msg += "\nCause: " + cause.toString();
+ }
+ return msg;
+ }
+
+ }
}
diff --git a/src/com/itmill/toolkit/event/MethodEventSource.java b/src/com/itmill/toolkit/event/MethodEventSource.java
index a11c23df92..8e80ea604e 100644
--- a/src/com/itmill/toolkit/event/MethodEventSource.java
+++ b/src/com/itmill/toolkit/event/MethodEventSource.java
@@ -47,133 +47,134 @@ import java.lang.reflect.Method;
*/
public interface MethodEventSource {
- /**
- *
- * Registers a new event listener with the specified activation method to
- * listen events generated by this component. If the activation method does
- * not have any arguments the event object will not be passed to it when
- * it's called.
- *
- *
- *
- * For more information on the inheritable event mechanism see the
- * {@link com.itmill.toolkit.event com.itmill.toolkit.event package documentation}.
- *
- *
- * @param eventType
- * the type of the listened event. Events of this type or its
- * subclasses activate the listener.
- * @param object
- * the object instance who owns the activation method.
- * @param method
- * the activation method.
- * @throws java.lang.IllegalArgumentException
- * unless method
has exactly one match in
- * object
- */
- public void addListener(Class eventType, Object object, Method method);
+ /**
+ *
+ * Registers a new event listener with the specified activation method to
+ * listen events generated by this component. If the activation method does
+ * not have any arguments the event object will not be passed to it when
+ * it's called.
+ *
+ *
+ *
+ * For more information on the inheritable event mechanism see the
+ * {@link com.itmill.toolkit.event com.itmill.toolkit.event package documentation}.
+ *
+ *
+ * @param eventType
+ * the type of the listened event. Events of this type or its
+ * subclasses activate the listener.
+ * @param object
+ * the object instance who owns the activation method.
+ * @param method
+ * the activation method.
+ * @throws java.lang.IllegalArgumentException
+ * unless method
has exactly one match in
+ * object
+ */
+ public void addListener(Class eventType, Object object, Method method);
- /**
- *
- * Registers a new listener with the specified activation method to listen
- * events generated by this component. If the activation method does not
- * have any arguments the event object will not be passed to it when it's
- * called.
- *
- *
- *
- * This version of addListener
gets the name of the
- * activation method as a parameter. The actual method is reflected from
- * object
, and unless exactly one match is found,
- * java.lang.IllegalArgumentException
is thrown.
- *
- *
- *
- * For more information on the inheritable event mechanism see the
- * {@link com.itmill.toolkit.event com.itmill.toolkit.event package documentation}.
- *
- *
- * @param eventType
- * the type of the listened event. Events of this type or its
- * subclasses activate the listener.
- * @param object
- * the object instance who owns the activation method.
- * @param methodName
- * the name of the activation method.
- * @throws java.lang.IllegalArgumentException
- * unless method
has exactly one match in
- * object
- */
- public void addListener(Class eventType, Object object, String methodName);
+ /**
+ *
+ * Registers a new listener with the specified activation method to listen
+ * events generated by this component. If the activation method does not
+ * have any arguments the event object will not be passed to it when it's
+ * called.
+ *
+ *
+ *
+ * This version of addListener
gets the name of the
+ * activation method as a parameter. The actual method is reflected from
+ * object
, and unless exactly one match is found,
+ * java.lang.IllegalArgumentException
is thrown.
+ *
+ *
+ *
+ * For more information on the inheritable event mechanism see the
+ * {@link com.itmill.toolkit.event com.itmill.toolkit.event package documentation}.
+ *
+ *
+ * @param eventType
+ * the type of the listened event. Events of this type or its
+ * subclasses activate the listener.
+ * @param object
+ * the object instance who owns the activation method.
+ * @param methodName
+ * the name of the activation method.
+ * @throws java.lang.IllegalArgumentException
+ * unless method
has exactly one match in
+ * object
+ */
+ public void addListener(Class eventType, Object object, String methodName);
- /**
- * Removes all registered listeners matching the given parameters. Since
- * this method receives the event type and the listener object as
- * parameters, it will unregister all object
's methods that
- * are registered to listen to events of type eventType
- * generated by this component.
- *
- *
- * For more information on the inheritable event mechanism see the
- * {@link com.itmill.toolkit.event com.itmill.toolkit.event package documentation}.
- *
- *
- * @param eventType
- * the exact event type the object
listens to.
- * @param target
- * the target object that has registered to listen to events of
- * type eventType
with one or more methods.
- */
- public void removeListener(Class eventType, Object target);
+ /**
+ * Removes all registered listeners matching the given parameters. Since
+ * this method receives the event type and the listener object as
+ * parameters, it will unregister all object
's methods that
+ * are registered to listen to events of type eventType
+ * generated by this component.
+ *
+ *
+ * For more information on the inheritable event mechanism see the
+ * {@link com.itmill.toolkit.event com.itmill.toolkit.event package documentation}.
+ *
+ *
+ * @param eventType
+ * the exact event type the object
listens to.
+ * @param target
+ * the target object that has registered to listen to events
+ * of type eventType
with one or more methods.
+ */
+ public void removeListener(Class eventType, Object target);
- /**
- * Removes one registered listener method. The given method owned by the
- * given object will no longer be called when the specified events are
- * generated by this component.
- *
- *
- * For more information on the inheritable event mechanism see the
- * {@link com.itmill.toolkit.event com.itmill.toolkit.event package documentation}.
- *
- *
- * @param eventType
- * the exact event type the object
listens to.
- * @param target
- * the target object that has registered to listen to events of
- * type eventType with one or more methods.
- * @param method
- * the method owned by the target that's registered to listen to
- * events of type eventType.
- */
- public void removeListener(Class eventType, Object target, Method method);
+ /**
+ * Removes one registered listener method. The given method owned by the
+ * given object will no longer be called when the specified events are
+ * generated by this component.
+ *
+ *
+ * For more information on the inheritable event mechanism see the
+ * {@link com.itmill.toolkit.event com.itmill.toolkit.event package documentation}.
+ *
+ *
+ * @param eventType
+ * the exact event type the object
listens to.
+ * @param target
+ * the target object that has registered to listen to events
+ * of type eventType with one or more methods.
+ * @param method
+ * the method owned by the target that's registered to listen
+ * to events of type eventType.
+ */
+ public void removeListener(Class eventType, Object target, Method method);
- /**
- *
- * Removes one registered listener method. The given method owned by the
- * given object will no longer be called when the specified events are
- * generated by this component.
- *
- *
- *
- * This version of removeListener
gets the name of the
- * activation method as a parameter. The actual method is reflected from the
- * target, and unless exactly one match is found,
- * java.lang.IllegalArgumentException
is thrown.
- *
- *
- *
- * For more information on the inheritable event mechanism see the
- * {@link com.itmill.toolkit.event com.itmill.toolkit.event package documentation}.
- *
- *
- * @param eventType
- * the exact event type the object
listens to.
- * @param target
- * the target object that has registered to listen to events of
- * type eventType
with one or more methods.
- * @param methodName
- * the name of the method owned by target
that's
- * registered to listen to events of type eventType
.
- */
- public void removeListener(Class eventType, Object target, String methodName);
+ /**
+ *
+ * Removes one registered listener method. The given method owned by the
+ * given object will no longer be called when the specified events are
+ * generated by this component.
+ *
+ *
+ *
+ * This version of removeListener
gets the name of the
+ * activation method as a parameter. The actual method is reflected from the
+ * target, and unless exactly one match is found,
+ * java.lang.IllegalArgumentException
is thrown.
+ *
+ *
+ *
+ * For more information on the inheritable event mechanism see the
+ * {@link com.itmill.toolkit.event com.itmill.toolkit.event package documentation}.
+ *
+ *
+ * @param eventType
+ * the exact event type the object
listens to.
+ * @param target
+ * the target object that has registered to listen to events
+ * of type eventType
with one or more methods.
+ * @param methodName
+ * the name of the method owned by target
+ * that's registered to listen to events of type
+ * eventType
.
+ */
+ public void removeListener(Class eventType, Object target, String methodName);
}
diff --git a/src/com/itmill/toolkit/event/ShortcutAction.java b/src/com/itmill/toolkit/event/ShortcutAction.java
index 8071b25097..da03d86764 100644
--- a/src/com/itmill/toolkit/event/ShortcutAction.java
+++ b/src/com/itmill/toolkit/event/ShortcutAction.java
@@ -11,169 +11,169 @@ import com.itmill.toolkit.terminal.Resource;
*/
public class ShortcutAction extends Action {
- private int keyCode;
+ private int keyCode;
- private int[] modifiers;
+ private int[] modifiers;
- public ShortcutAction(String caption, int kc, int[] m) {
- super(caption);
- keyCode = kc;
- modifiers = m;
- }
+ public ShortcutAction(String caption, int kc, int[] m) {
+ super(caption);
+ keyCode = kc;
+ modifiers = m;
+ }
- public ShortcutAction(String caption, Resource icon, int kc, int[] m) {
- super(caption, icon);
- keyCode = kc;
- modifiers = m;
- }
+ public ShortcutAction(String caption, Resource icon, int kc, int[] m) {
+ super(caption, icon);
+ keyCode = kc;
+ modifiers = m;
+ }
- public int getKeyCode() {
- return keyCode;
- }
+ public int getKeyCode() {
+ return keyCode;
+ }
- public int[] getModifiers() {
- return modifiers;
- }
+ public int[] getModifiers() {
+ return modifiers;
+ }
- /**
- * Key codes that can be used for shortcuts
- *
- */
- public interface KeyCode {
- public static final int ENTER = 13;
+ /**
+ * Key codes that can be used for shortcuts
+ *
+ */
+ public interface KeyCode {
+ public static final int ENTER = 13;
- public static final int ESCAPE = 27;
+ public static final int ESCAPE = 27;
- public static final int PAGE_UP = 33;
+ public static final int PAGE_UP = 33;
- public static final int PAGE_DOWN = 34;
+ public static final int PAGE_DOWN = 34;
- public static final int TAB = 9;
+ public static final int TAB = 9;
- public static final int ARROW_LEFT = 37;
+ public static final int ARROW_LEFT = 37;
- public static final int ARROW_UP = 38;
+ public static final int ARROW_UP = 38;
- public static final int ARROW_RIGHT = 39;
+ public static final int ARROW_RIGHT = 39;
- public static final int ARROW_DOWN = 40;
+ public static final int ARROW_DOWN = 40;
- public static final int BACKSPACE = 8;
+ public static final int BACKSPACE = 8;
- public static final int DELETE = 46;
+ public static final int DELETE = 46;
- public static final int INSERT = 45;
+ public static final int INSERT = 45;
- public static final int END = 35;
+ public static final int END = 35;
- public static final int HOME = 36;
+ public static final int HOME = 36;
- public static final int F1 = 112;
+ public static final int F1 = 112;
- public static final int F2 = 113;
+ public static final int F2 = 113;
- public static final int F3 = 114;
+ public static final int F3 = 114;
- public static final int F4 = 115;
+ public static final int F4 = 115;
- public static final int F5 = 116;
+ public static final int F5 = 116;
- public static final int F6 = 117;
+ public static final int F6 = 117;
- public static final int F7 = 118;
+ public static final int F7 = 118;
- public static final int F8 = 119;
+ public static final int F8 = 119;
- public static final int F9 = 120;
+ public static final int F9 = 120;
- public static final int F10 = 121;
+ public static final int F10 = 121;
- public static final int F11 = 122;
+ public static final int F11 = 122;
- public static final int F12 = 123;
+ public static final int F12 = 123;
- public static final int A = 65;
+ public static final int A = 65;
- public static final int B = 66;
+ public static final int B = 66;
- public static final int C = 67;
+ public static final int C = 67;
- public static final int D = 68;
+ public static final int D = 68;
- public static final int E = 69;
+ public static final int E = 69;
- public static final int F = 70;
+ public static final int F = 70;
- public static final int G = 71;
+ public static final int G = 71;
- public static final int H = 72;
+ public static final int H = 72;
- public static final int I = 73;
+ public static final int I = 73;
- public static final int J = 74;
+ public static final int J = 74;
- public static final int K = 75;
+ public static final int K = 75;
- public static final int L = 76;
+ public static final int L = 76;
- public static final int M = 77;
+ public static final int M = 77;
- public static final int N = 78;
+ public static final int N = 78;
- public static final int O = 79;
+ public static final int O = 79;
- public static final int P = 80;
+ public static final int P = 80;
- public static final int Q = 81;
+ public static final int Q = 81;
- public static final int R = 82;
+ public static final int R = 82;
- public static final int S = 83;
+ public static final int S = 83;
- public static final int T = 84;
+ public static final int T = 84;
- public static final int U = 85;
+ public static final int U = 85;
- public static final int V = 86;
+ public static final int V = 86;
- public static final int W = 87;
+ public static final int W = 87;
- public static final int X = 88;
+ public static final int X = 88;
- public static final int Y = 89;
+ public static final int Y = 89;
- public static final int Z = 90;
+ public static final int Z = 90;
- public static final int NUM0 = 48;
+ public static final int NUM0 = 48;
- public static final int NUM1 = 49;
+ public static final int NUM1 = 49;
- public static final int NUM2 = 50;
+ public static final int NUM2 = 50;
- public static final int NUM3 = 51;
+ public static final int NUM3 = 51;
- public static final int NUM4 = 52;
+ public static final int NUM4 = 52;
- public static final int NUM5 = 53;
+ public static final int NUM5 = 53;
- public static final int NUM6 = 54;
+ public static final int NUM6 = 54;
- public static final int NUM7 = 55;
+ public static final int NUM7 = 55;
- public static final int NUM8 = 56;
+ public static final int NUM8 = 56;
- public static final int NUM9 = 57;
- }
+ public static final int NUM9 = 57;
+ }
- /**
- * Modifier key constants
- *
- */
- public interface ModifierKey {
- public static final int SHIFT = 16;
+ /**
+ * Modifier key constants
+ *
+ */
+ public interface ModifierKey {
+ public static final int SHIFT = 16;
- public static final int CTRL = 17;
+ public static final int CTRL = 17;
- public static final int ALT = 18;
- }
+ public static final int ALT = 18;
+ }
}
diff --git a/src/com/itmill/toolkit/launcher/ITMillToolkitDesktopMode.java b/src/com/itmill/toolkit/launcher/ITMillToolkitDesktopMode.java
index 9636e36acc..ae14121ebe 100644
--- a/src/com/itmill/toolkit/launcher/ITMillToolkitDesktopMode.java
+++ b/src/com/itmill/toolkit/launcher/ITMillToolkitDesktopMode.java
@@ -19,6 +19,7 @@ import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
+import javax.swing.WindowConstants;
import com.itmill.toolkit.launcher.util.BrowserLauncher;
@@ -28,165 +29,165 @@ import com.itmill.toolkit.launcher.util.BrowserLauncher;
*/
public class ITMillToolkitDesktopMode {
- public static void main(String[] args) {
-
- Map serverArgs = ITMillToolkitWebMode.parseArguments(args);
- boolean deployed = false;
- try {
- // Default deployment: embedded.war
- deployed = deployEmbeddedWarfile(serverArgs);
- } catch (IOException e1) {
- e1.printStackTrace();
- deployed = false;
- }
-
- // Check if deployment was succesful
- if (!deployed && !serverArgs.containsKey("webroot")) {
- // Default deployment failed, try other means
- if (new File("WebContent").exists()) {
- // Using WebContent directory as webroot
- serverArgs.put("webroot", "WebContent");
- } else {
- System.err.print("Failed to deploy Toolkit application. "
- + "Please add --webroot parameter. Exiting.");
- return;
- }
- }
-
- // Start the Winstone servlet container
- String url = ITMillToolkitWebMode.runServer(serverArgs);
-
- // Open browser into application URL
- if (url != null) {
- BrowserLauncher.openBrowser(url);
- }
-
- // Open control dialog
- if (url != null) {
- openServerControlDialog(url);
- }
-
- }
-
- /**
- * Open a control dialog for embedded server.
- *
- * @param applicationUrl
- * Application URL
- */
- private static void openServerControlDialog(final String applicationUrl) {
-
- // Main frame
- final String title = "Desktop Server";
- final JFrame frame = new JFrame(title);
- frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
-
- // Create link label and listen mouse click
- final JLabel link = new JLabel(""
- + "Desktop Server is running at:
" + "" + applicationUrl
- + "
Close this window to shutdown the server. "
- + "");
- link.addMouseListener(new MouseAdapter() {
- public void mouseClicked(MouseEvent e) {
- BrowserLauncher.openBrowser(applicationUrl);
- }
- });
-
- // Create a panel and add components to it.
- final JPanel contentPane = new JPanel(new FlowLayout());
- frame.setContentPane(contentPane);
- contentPane.add(link);
-
- // Close confirmation
- final JLabel question = new JLabel(
- "This will stop the server. Are you sure?");
- final JButton okButton = new JButton("OK");
- final JButton cancelButton = new JButton("Cancel");
-
- // List for close verify buttons
- ActionListener buttonListener = new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- if (e.getSource() == okButton) {
- System.exit(0);
- } else {
- Rectangle bounds = frame.getBounds();
- frame.setTitle(title);
- contentPane.removeAll();
- contentPane.add(link);
- contentPane.setBounds(bounds);
- frame.setBounds(bounds);
- frame.setVisible(true);
- frame.repaint();
- }
- }
- };
- okButton.addActionListener(buttonListener);
- cancelButton.addActionListener(buttonListener);
-
- frame.addWindowListener(new WindowAdapter() {
- public void windowClosing(WindowEvent e) {
- Rectangle bounds = frame.getBounds();
- frame.setTitle("Confirm close");
- contentPane.removeAll();
- contentPane.add(question);
- contentPane.add(okButton);
- contentPane.add(cancelButton);
- frame.setBounds(bounds);
- frame.setVisible(true);
- frame.repaint();
- }
- });
-
- // Position the window nicely
- java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit()
- .getScreenSize();
- int w = 270;
- int h = 95;
- int margin = 20;
- frame.setBounds(new Rectangle(screenSize.width - w - margin,
- screenSize.height - h - margin * 2, w, h));
- frame.toFront();
- frame.setVisible(true);
- }
-
- /**
- * Deploy file named "embedded.war" from classpath (inside jar file).
- *
- * @param args
- * @return
- * @throws IOException
- */
- protected static boolean deployEmbeddedWarfile(Map args) throws IOException {
- String embeddedWarfileName = "/embedded.war";
- InputStream embeddedWarfile = ITMillToolkitDesktopMode.class
- .getResourceAsStream(embeddedWarfileName);
- if (embeddedWarfile != null) {
- File tempWarfile = File.createTempFile("embedded", ".war")
- .getAbsoluteFile();
- tempWarfile.getParentFile().mkdirs();
- tempWarfile.deleteOnExit();
-
- String embeddedWebroot = "winstoneEmbeddedWAR";
- File tempWebroot = new File(tempWarfile.getParentFile(),
- embeddedWebroot);
- tempWebroot.mkdirs();
-
- OutputStream out = new FileOutputStream(tempWarfile, true);
- int read = 0;
- byte buffer[] = new byte[2048];
- while ((read = embeddedWarfile.read(buffer)) != -1) {
- out.write(buffer, 0, read);
- }
- out.close();
- embeddedWarfile.close();
-
- args.put("warfile", tempWarfile.getAbsolutePath());
- args.put("webroot", tempWebroot.getAbsolutePath());
- args.remove("webappsDir");
- args.remove("hostsDir");
- return true;
- }
- return false;
- }
+ public static void main(String[] args) {
+
+ Map serverArgs = ITMillToolkitWebMode.parseArguments(args);
+ boolean deployed = false;
+ try {
+ // Default deployment: embedded.war
+ deployed = deployEmbeddedWarfile(serverArgs);
+ } catch (IOException e1) {
+ e1.printStackTrace();
+ deployed = false;
+ }
+
+ // Check if deployment was succesful
+ if (!deployed && !serverArgs.containsKey("webroot")) {
+ // Default deployment failed, try other means
+ if (new File("WebContent").exists()) {
+ // Using WebContent directory as webroot
+ serverArgs.put("webroot", "WebContent");
+ } else {
+ System.err.print("Failed to deploy Toolkit application. "
+ + "Please add --webroot parameter. Exiting.");
+ return;
+ }
+ }
+
+ // Start the Winstone servlet container
+ String url = ITMillToolkitWebMode.runServer(serverArgs);
+
+ // Open browser into application URL
+ if (url != null) {
+ BrowserLauncher.openBrowser(url);
+ }
+
+ // Open control dialog
+ if (url != null) {
+ openServerControlDialog(url);
+ }
+
+ }
+
+ /**
+ * Open a control dialog for embedded server.
+ *
+ * @param applicationUrl
+ * Application URL
+ */
+ private static void openServerControlDialog(final String applicationUrl) {
+
+ // Main frame
+ final String title = "Desktop Server";
+ final JFrame frame = new JFrame(title);
+ frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
+
+ // Create link label and listen mouse click
+ final JLabel link = new JLabel(""
+ + "Desktop Server is running at:
" + "" + applicationUrl
+ + "
Close this window to shutdown the server. "
+ + "");
+ link.addMouseListener(new MouseAdapter() {
+ public void mouseClicked(MouseEvent e) {
+ BrowserLauncher.openBrowser(applicationUrl);
+ }
+ });
+
+ // Create a panel and add components to it.
+ final JPanel contentPane = new JPanel(new FlowLayout());
+ frame.setContentPane(contentPane);
+ contentPane.add(link);
+
+ // Close confirmation
+ final JLabel question = new JLabel(
+ "This will stop the server. Are you sure?");
+ final JButton okButton = new JButton("OK");
+ final JButton cancelButton = new JButton("Cancel");
+
+ // List for close verify buttons
+ ActionListener buttonListener = new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ if (e.getSource() == okButton) {
+ System.exit(0);
+ } else {
+ Rectangle bounds = frame.getBounds();
+ frame.setTitle(title);
+ contentPane.removeAll();
+ contentPane.add(link);
+ contentPane.setBounds(bounds);
+ frame.setBounds(bounds);
+ frame.setVisible(true);
+ frame.repaint();
+ }
+ }
+ };
+ okButton.addActionListener(buttonListener);
+ cancelButton.addActionListener(buttonListener);
+
+ frame.addWindowListener(new WindowAdapter() {
+ public void windowClosing(WindowEvent e) {
+ Rectangle bounds = frame.getBounds();
+ frame.setTitle("Confirm close");
+ contentPane.removeAll();
+ contentPane.add(question);
+ contentPane.add(okButton);
+ contentPane.add(cancelButton);
+ frame.setBounds(bounds);
+ frame.setVisible(true);
+ frame.repaint();
+ }
+ });
+
+ // Position the window nicely
+ java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit()
+ .getScreenSize();
+ int w = 270;
+ int h = 95;
+ int margin = 20;
+ frame.setBounds(new Rectangle(screenSize.width - w - margin,
+ screenSize.height - h - margin * 2, w, h));
+ frame.toFront();
+ frame.setVisible(true);
+ }
+
+ /**
+ * Deploy file named "embedded.war" from classpath (inside jar file).
+ *
+ * @param args
+ * @return
+ * @throws IOException
+ */
+ protected static boolean deployEmbeddedWarfile(Map args) throws IOException {
+ String embeddedWarfileName = "/embedded.war";
+ InputStream embeddedWarfile = ITMillToolkitDesktopMode.class
+ .getResourceAsStream(embeddedWarfileName);
+ if (embeddedWarfile != null) {
+ File tempWarfile = File.createTempFile("embedded", ".war")
+ .getAbsoluteFile();
+ tempWarfile.getParentFile().mkdirs();
+ tempWarfile.deleteOnExit();
+
+ String embeddedWebroot = "winstoneEmbeddedWAR";
+ File tempWebroot = new File(tempWarfile.getParentFile(),
+ embeddedWebroot);
+ tempWebroot.mkdirs();
+
+ OutputStream out = new FileOutputStream(tempWarfile, true);
+ int read = 0;
+ byte buffer[] = new byte[2048];
+ while ((read = embeddedWarfile.read(buffer)) != -1) {
+ out.write(buffer, 0, read);
+ }
+ out.close();
+ embeddedWarfile.close();
+
+ args.put("warfile", tempWarfile.getAbsolutePath());
+ args.put("webroot", tempWebroot.getAbsolutePath());
+ args.remove("webappsDir");
+ args.remove("hostsDir");
+ return true;
+ }
+ return false;
+ }
}
diff --git a/src/com/itmill/toolkit/launcher/ITMillToolkitHostedMode.java b/src/com/itmill/toolkit/launcher/ITMillToolkitHostedMode.java
index fe9360d2f5..3972616afa 100644
--- a/src/com/itmill/toolkit/launcher/ITMillToolkitHostedMode.java
+++ b/src/com/itmill/toolkit/launcher/ITMillToolkitHostedMode.java
@@ -16,128 +16,128 @@ import com.google.gwt.dev.GWTShell;
*/
public class ITMillToolkitHostedMode {
- private final static String serverPort = "8888";
-
- /**
- * Main function for running Jetty.
- *
- * Command line Arguments are passed through to Jetty, see runServer method
- * for options.
- *
- * @param args
- */
- public static void main(String[] args) {
-
- // Start Jetty
- System.out.println("Starting Jetty servlet container.");
- String url = runServer(new HashMap());
-
- // Start GWT
- System.out.println("Starting GWT Hosted Mode browser.");
- GWTShell.main(args);
-
- }
-
- /**
- * Run the server with specified arguments.
- *
- * @param serverArgs
- * @return
- */
- protected static String runServer(Map serverArgs) {
-
- // Add help for System.out
- System.out
- .println("-------------------------------------------------\n"
- + "Starting IT Mill Toolkit in GWT Hosted Mode.\n"
- + "Running in http://localhost:"
- + serverPort
- + "\n-------------------------------------------------\n");
-
- // Assign default values for some arguments
- assignDefault(serverArgs, "webroot", "WebContent");
- assignDefault(serverArgs, "httpPort", serverPort);
-
- try {
- long started = System.currentTimeMillis();
-
- Server server = new Server();
-
- // String threadPoolName =
- // System.getProperty("jetty.threadpool.name",
- // "Jetty thread");
- // int maxIdleTimeMs = Integer.getInteger(
- // "jetty.threadpool.maxIdleTimeMs", 60000);
- // int maxThreads =
- // Integer.getInteger("jetty.threadpool.maxThreads",
- // 100);
- // int minThreads =
- // Integer.getInteger("jetty.threadpool.minThreads",
- // 1);
- // int lowThreads = Integer.getInteger(
- // "jetty.threadpool.maxIdleTimeMs", 25);
- // BoundedThreadPool threadPool = new BoundedThreadPool();
- // threadPool.setName(threadPoolName);
- // threadPool.setMaxIdleTimeMs(maxIdleTimeMs);
- // threadPool.setMaxThreads(maxThreads);
- // threadPool.setMinThreads(minThreads);
- // threadPool.setLowThreads(lowThreads);
- // server.setThreadPool(threadPool);
-
- Connector connector = new SelectChannelConnector();
- // FIXME httpPort hardcoded to 8888
- // connector.setPort(Integer.valueOf(serverArgs.get("httpPort")
- // .toString()));
- connector.setPort(8888);
- server.setConnectors(new Connector[] { connector });
-
- WebAppContext webappcontext = new WebAppContext();
- webappcontext.setContextPath("");
- webappcontext.setWar(serverArgs.get("webroot").toString());
-
- server.setHandler(webappcontext);
-
- server.start();
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
-
- return "http://localhost:" + serverArgs.get("httpPort");
- }
-
- /**
- * Assign default value for given key.
- *
- * @param map
- * @param key
- * @param value
- */
- private static void assignDefault(Map map, String key, String value) {
- if (!map.containsKey(key)) {
- map.put(key, value);
- }
- }
-
- /**
- * Parse all command line arguments into a map.
- *
- * Arguments format "key=value" are put into map.
- *
- * @param args
- * @return map of arguments key value pairs.
- */
- protected static Map parseArguments(String[] args) {
- Map map = new HashMap();
- for (int i = 0; i < args.length; i++) {
- int d = args[i].indexOf("=");
- if (d > 0 && d < args[i].length() && args[i].startsWith("--")) {
- String name = args[i].substring(2, d);
- String value = args[i].substring(d + 1);
- map.put(name, value);
- }
- }
- return map;
- }
+ private final static String serverPort = "8888";
+
+ /**
+ * Main function for running Jetty.
+ *
+ * Command line Arguments are passed through to Jetty, see runServer method
+ * for options.
+ *
+ * @param args
+ */
+ public static void main(String[] args) {
+
+ // Start Jetty
+ System.out.println("Starting Jetty servlet container.");
+ String url = runServer(new HashMap());
+
+ // Start GWT
+ System.out.println("Starting GWT Hosted Mode browser.");
+ GWTShell.main(args);
+
+ }
+
+ /**
+ * Run the server with specified arguments.
+ *
+ * @param serverArgs
+ * @return
+ */
+ protected static String runServer(Map serverArgs) {
+
+ // Add help for System.out
+ System.out
+ .println("-------------------------------------------------\n"
+ + "Starting IT Mill Toolkit in GWT Hosted Mode.\n"
+ + "Running in http://localhost:"
+ + serverPort
+ + "\n-------------------------------------------------\n");
+
+ // Assign default values for some arguments
+ assignDefault(serverArgs, "webroot", "WebContent");
+ assignDefault(serverArgs, "httpPort", serverPort);
+
+ try {
+ long started = System.currentTimeMillis();
+
+ Server server = new Server();
+
+ // String threadPoolName =
+ // System.getProperty("jetty.threadpool.name",
+ // "Jetty thread");
+ // int maxIdleTimeMs = Integer.getInteger(
+ // "jetty.threadpool.maxIdleTimeMs", 60000);
+ // int maxThreads =
+ // Integer.getInteger("jetty.threadpool.maxThreads",
+ // 100);
+ // int minThreads =
+ // Integer.getInteger("jetty.threadpool.minThreads",
+ // 1);
+ // int lowThreads = Integer.getInteger(
+ // "jetty.threadpool.maxIdleTimeMs", 25);
+ // BoundedThreadPool threadPool = new BoundedThreadPool();
+ // threadPool.setName(threadPoolName);
+ // threadPool.setMaxIdleTimeMs(maxIdleTimeMs);
+ // threadPool.setMaxThreads(maxThreads);
+ // threadPool.setMinThreads(minThreads);
+ // threadPool.setLowThreads(lowThreads);
+ // server.setThreadPool(threadPool);
+
+ Connector connector = new SelectChannelConnector();
+ // FIXME httpPort hardcoded to 8888
+ // connector.setPort(Integer.valueOf(serverArgs.get("httpPort")
+ // .toString()));
+ connector.setPort(8888);
+ server.setConnectors(new Connector[] { connector });
+
+ WebAppContext webappcontext = new WebAppContext();
+ webappcontext.setContextPath("");
+ webappcontext.setWar(serverArgs.get("webroot").toString());
+
+ server.setHandler(webappcontext);
+
+ server.start();
+ } catch (Exception e) {
+ e.printStackTrace();
+ return null;
+ }
+
+ return "http://localhost:" + serverArgs.get("httpPort");
+ }
+
+ /**
+ * Assign default value for given key.
+ *
+ * @param map
+ * @param key
+ * @param value
+ */
+ private static void assignDefault(Map map, String key, String value) {
+ if (!map.containsKey(key)) {
+ map.put(key, value);
+ }
+ }
+
+ /**
+ * Parse all command line arguments into a map.
+ *
+ * Arguments format "key=value" are put into map.
+ *
+ * @param args
+ * @return map of arguments key value pairs.
+ */
+ protected static Map parseArguments(String[] args) {
+ Map map = new HashMap();
+ for (int i = 0; i < args.length; i++) {
+ int d = args[i].indexOf("=");
+ if (d > 0 && d < args[i].length() && args[i].startsWith("--")) {
+ String name = args[i].substring(2, d);
+ String value = args[i].substring(d + 1);
+ map.put(name, value);
+ }
+ }
+ return map;
+ }
}
diff --git a/src/com/itmill/toolkit/launcher/ITMillToolkitWebMode.java b/src/com/itmill/toolkit/launcher/ITMillToolkitWebMode.java
index 0054de4c9e..b177a34103 100644
--- a/src/com/itmill/toolkit/launcher/ITMillToolkitWebMode.java
+++ b/src/com/itmill/toolkit/launcher/ITMillToolkitWebMode.java
@@ -16,137 +16,137 @@ import com.itmill.toolkit.launcher.util.BrowserLauncher;
*/
public class ITMillToolkitWebMode {
- private final static String serverPort = "8888";
-
- /**
- * Main function for running Jetty.
- *
- * Command line Arguments are passed through to Jetty, see runServer method
- * for options.
- *
- * @param args
- */
- public static void main(String[] args) {
-
- // Pass-through of arguments for Jetty
- Map serverArgs = parseArguments(args);
-
- // Start Jetty
- System.out.println("Starting Jetty servlet container.");
- String url = runServer(serverArgs);
-
- // Start Browser
- System.out.println("Starting Web Browser.");
- if (url != null) {
- BrowserLauncher.openBrowser(url);
- }
-
- }
-
- /**
- * Run the server with specified arguments.
- *
- * @param serverArgs
- * @return
- */
- protected static String runServer(Map serverArgs) {
-
- // Add help for System.out
- System.out
- .println("-------------------------------------------------\n"
- + "Starting IT Mill Toolkit in Web Mode.\n"
- + "Running in http://localhost:"
- + serverPort
- + "\n-------------------------------------------------\n");
-
- // Assign default values for some arguments
- assignDefault(serverArgs, "webroot", "WebContent");
- assignDefault(serverArgs, "httpPort", serverPort);
-
- try {
- long started = System.currentTimeMillis();
-
- Server server = new Server();
-
- // String threadPoolName =
- // System.getProperty("jetty.threadpool.name",
- // "Jetty thread");
- // int maxIdleTimeMs = Integer.getInteger(
- // "jetty.threadpool.maxIdleTimeMs", 60000);
- // int maxThreads =
- // Integer.getInteger("jetty.threadpool.maxThreads",
- // 100);
- // int minThreads =
- // Integer.getInteger("jetty.threadpool.minThreads",
- // 1);
- // int lowThreads = Integer.getInteger(
- // "jetty.threadpool.maxIdleTimeMs", 25);
- // BoundedThreadPool threadPool = new BoundedThreadPool();
- // threadPool.setName(threadPoolName);
- // threadPool.setMaxIdleTimeMs(maxIdleTimeMs);
- // threadPool.setMaxThreads(maxThreads);
- // threadPool.setMinThreads(minThreads);
- // threadPool.setLowThreads(lowThreads);
- // server.setThreadPool(threadPool);
-
- Connector connector = new SelectChannelConnector();
- // FIXME httpPort hardcoded to 8888
- // connector.setPort(Integer.valueOf(serverArgs.get("httpPort")
- // .toString()));
- connector.setPort(8888);
- server.setConnectors(new Connector[] { connector });
-
- WebAppContext webappcontext = new WebAppContext();
- webappcontext.setContextPath("");
- webappcontext.setWar(serverArgs.get("webroot").toString());
- // enable hot code replace
- webappcontext.setCopyWebDir(true);
-
- server.setHandler(webappcontext);
-
- server.start();
- // System.err.println("Started Jetty in "
- // + (System.currentTimeMillis() - started) + "ms.");
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
-
- return "http://localhost:" + serverArgs.get("httpPort");
- }
-
- /**
- * Assign default value for given key.
- *
- * @param map
- * @param key
- * @param value
- */
- private static void assignDefault(Map map, String key, String value) {
- if (!map.containsKey(key)) {
- map.put(key, value);
- }
- }
-
- /**
- * Parse all command line arguments into a map.
- *
- * Arguments format "key=value" are put into map.
- *
- * @param args
- * @return map of arguments key value pairs.
- */
- protected static Map parseArguments(String[] args) {
- Map map = new HashMap();
- for (int i = 0; i < args.length; i++) {
- int d = args[i].indexOf("=");
- if (d > 0 && d < args[i].length() && args[i].startsWith("--")) {
- String name = args[i].substring(2, d);
- String value = args[i].substring(d + 1);
- map.put(name, value);
- }
- }
- return map;
- }
+ private final static String serverPort = "8888";
+
+ /**
+ * Main function for running Jetty.
+ *
+ * Command line Arguments are passed through to Jetty, see runServer method
+ * for options.
+ *
+ * @param args
+ */
+ public static void main(String[] args) {
+
+ // Pass-through of arguments for Jetty
+ Map serverArgs = parseArguments(args);
+
+ // Start Jetty
+ System.out.println("Starting Jetty servlet container.");
+ String url = runServer(serverArgs);
+
+ // Start Browser
+ System.out.println("Starting Web Browser.");
+ if (url != null) {
+ BrowserLauncher.openBrowser(url);
+ }
+
+ }
+
+ /**
+ * Run the server with specified arguments.
+ *
+ * @param serverArgs
+ * @return
+ */
+ protected static String runServer(Map serverArgs) {
+
+ // Add help for System.out
+ System.out
+ .println("-------------------------------------------------\n"
+ + "Starting IT Mill Toolkit in Web Mode.\n"
+ + "Running in http://localhost:"
+ + serverPort
+ + "\n-------------------------------------------------\n");
+
+ // Assign default values for some arguments
+ assignDefault(serverArgs, "webroot", "WebContent");
+ assignDefault(serverArgs, "httpPort", serverPort);
+
+ try {
+ long started = System.currentTimeMillis();
+
+ Server server = new Server();
+
+ // String threadPoolName =
+ // System.getProperty("jetty.threadpool.name",
+ // "Jetty thread");
+ // int maxIdleTimeMs = Integer.getInteger(
+ // "jetty.threadpool.maxIdleTimeMs", 60000);
+ // int maxThreads =
+ // Integer.getInteger("jetty.threadpool.maxThreads",
+ // 100);
+ // int minThreads =
+ // Integer.getInteger("jetty.threadpool.minThreads",
+ // 1);
+ // int lowThreads = Integer.getInteger(
+ // "jetty.threadpool.maxIdleTimeMs", 25);
+ // BoundedThreadPool threadPool = new BoundedThreadPool();
+ // threadPool.setName(threadPoolName);
+ // threadPool.setMaxIdleTimeMs(maxIdleTimeMs);
+ // threadPool.setMaxThreads(maxThreads);
+ // threadPool.setMinThreads(minThreads);
+ // threadPool.setLowThreads(lowThreads);
+ // server.setThreadPool(threadPool);
+
+ Connector connector = new SelectChannelConnector();
+ // FIXME httpPort hardcoded to 8888
+ // connector.setPort(Integer.valueOf(serverArgs.get("httpPort")
+ // .toString()));
+ connector.setPort(8888);
+ server.setConnectors(new Connector[] { connector });
+
+ WebAppContext webappcontext = new WebAppContext();
+ webappcontext.setContextPath("");
+ webappcontext.setWar(serverArgs.get("webroot").toString());
+ // enable hot code replace
+ webappcontext.setCopyWebDir(true);
+
+ server.setHandler(webappcontext);
+
+ server.start();
+ // System.err.println("Started Jetty in "
+ // + (System.currentTimeMillis() - started) + "ms.");
+ } catch (Exception e) {
+ e.printStackTrace();
+ return null;
+ }
+
+ return "http://localhost:" + serverArgs.get("httpPort");
+ }
+
+ /**
+ * Assign default value for given key.
+ *
+ * @param map
+ * @param key
+ * @param value
+ */
+ private static void assignDefault(Map map, String key, String value) {
+ if (!map.containsKey(key)) {
+ map.put(key, value);
+ }
+ }
+
+ /**
+ * Parse all command line arguments into a map.
+ *
+ * Arguments format "key=value" are put into map.
+ *
+ * @param args
+ * @return map of arguments key value pairs.
+ */
+ protected static Map parseArguments(String[] args) {
+ Map map = new HashMap();
+ for (int i = 0; i < args.length; i++) {
+ int d = args[i].indexOf("=");
+ if (d > 0 && d < args[i].length() && args[i].startsWith("--")) {
+ String name = args[i].substring(2, d);
+ String value = args[i].substring(d + 1);
+ map.put(name, value);
+ }
+ }
+ return map;
+ }
}
diff --git a/src/com/itmill/toolkit/launcher/util/BrowserLauncher.java b/src/com/itmill/toolkit/launcher/util/BrowserLauncher.java
index 06870ce7e2..86c48556a5 100644
--- a/src/com/itmill/toolkit/launcher/util/BrowserLauncher.java
+++ b/src/com/itmill/toolkit/launcher/util/BrowserLauncher.java
@@ -9,84 +9,85 @@ import java.io.IOException;
*/
public class BrowserLauncher {
- /**
- * Open browser on specified URL.
- *
- * @param url
- */
- public static void openBrowser(String url) {
+ /**
+ * Open browser on specified URL.
+ *
+ * @param url
+ */
+ public static void openBrowser(String url) {
- Runtime runtime = Runtime.getRuntime();
- boolean started = false;
+ Runtime runtime = Runtime.getRuntime();
+ boolean started = false;
- String os = System.getProperty("os.name", "windows").toLowerCase();
+ String os = System.getProperty("os.name", "windows").toLowerCase();
- // Linux
- if (os.indexOf("linux") >= 0) {
+ // Linux
+ if (os.indexOf("linux") >= 0) {
- // Try x-www-browser
- if (!started) {
- try {
- runtime.exec("x-www-browser " + url);
- started = true;
- } catch (IOException e) {
- }
- }
+ // Try x-www-browser
+ if (!started) {
+ try {
+ runtime.exec("x-www-browser " + url);
+ started = true;
+ } catch (IOException e) {
+ }
+ }
- // Try firefox
- if (!started) {
- try {
- runtime.exec("firefox " + url);
- started = true;
- } catch (IOException e) {
- }
- }
+ // Try firefox
+ if (!started) {
+ try {
+ runtime.exec("firefox " + url);
+ started = true;
+ } catch (IOException e) {
+ }
+ }
- // Try mozilla
- if (!started) {
- try {
- runtime.exec("mozilla " + url);
- started = true;
- } catch (IOException e) {
- }
- }
+ // Try mozilla
+ if (!started) {
+ try {
+ runtime.exec("mozilla " + url);
+ started = true;
+ } catch (IOException e) {
+ }
+ }
- // Try konqueror
- if (!started) {
- try {
- runtime.exec("konqueror " + url);
- started = true;
- } catch (IOException e) {
- }
- }
- }
+ // Try konqueror
+ if (!started) {
+ try {
+ runtime.exec("konqueror " + url);
+ started = true;
+ } catch (IOException e) {
+ }
+ }
+ }
- // OS X
- if (os.indexOf("mac os x") >= 0) {
+ // OS X
+ if (os.indexOf("mac os x") >= 0) {
- // Try open
- if (!started) {
- try {
- runtime.exec("open " + url);
- started = true;
- } catch (IOException e) {
- }
- }
- }
+ // Try open
+ if (!started) {
+ try {
+ runtime.exec("open " + url);
+ started = true;
+ } catch (IOException e) {
+ }
+ }
+ }
- // Try cmd /start command on windows
- if (os.indexOf("win") >= 0) {
- if (!started) {
- try {
- runtime.exec("cmd /c start " + url);
- started = true;
- } catch (IOException e) {
- }
- }
- }
+ // Try cmd /start command on windows
+ if (os.indexOf("win") >= 0) {
+ if (!started) {
+ try {
+ runtime.exec("cmd /c start " + url);
+ started = true;
+ } catch (IOException e) {
+ }
+ }
+ }
- if (!started)
- System.out.println("Failed to open browser. Please go to " + url);
- }
+ if (!started) {
+ System.out.println("Failed to open browser. Please go to " + url);
+ }
+ }
}
diff --git a/src/com/itmill/toolkit/service/ApplicationContext.java b/src/com/itmill/toolkit/service/ApplicationContext.java
index 36c1d49b83..7c092c484d 100644
--- a/src/com/itmill/toolkit/service/ApplicationContext.java
+++ b/src/com/itmill/toolkit/service/ApplicationContext.java
@@ -45,76 +45,76 @@ import com.itmill.toolkit.Application;
*/
public interface ApplicationContext {
- /**
- * Returns application context base directory.
- *
- * Typically an application is deployed in a such way that is has
- * application directory. For web applications this directory is the root
- * directory of the web applications. In some cases application might not
- * have application directory (for example web applications running inside
- * of war).
- *
- * @return The application base directory
- */
- public File getBaseDirectory();
-
- /**
- * Gets the applications in this context.
- *
- * Gets all applications in this context. Each application context contains
- * all applications that are open for one user.
- *
- * @return Collection containing all applications in this context
- */
- public Collection getApplications();
-
- /**
- * Adds transaction listener to this context.
- *
- * @param listener
- * the listener to be added.
- * @see TransactionListener
- */
- public void addTransactionListener(TransactionListener listener);
-
- /**
- * Removes transaction listener from this context.
- *
- * @param listener
- * the listener to be removed.
- * @see TransactionListener
- */
- public void removeTransactionListener(TransactionListener listener);
-
- /**
- * Interface for listening the application transaction events.
- * Implementations of this interface can be used to listen all transactions
- * between the client and the application.
- *
- */
- public interface TransactionListener {
-
- /**
- * Invoked at the beginning of every transaction.
- *
- * @param application
- * the Application object.
- * @param transactionData
- * the Data identifying the transaction.
- */
- public void transactionStart(Application application,
- Object transactionData);
-
- /**
- * Invoked at the end of every transaction.
- *
- * @param applcation
- * the Application object.
- * @param transactionData
- * the Data identifying the transaction.
- */
- public void transactionEnd(Application application,
- Object transactionData);
-
- }
+ /**
+ * Returns application context base directory.
+ *
+ * Typically an application is deployed in a such way that is has
+ * application directory. For web applications this directory is the root
+ * directory of the web applications. In some cases application might not
+ * have application directory (for example web applications running inside
+ * of war).
+ *
+ * @return The application base directory
+ */
+ public File getBaseDirectory();
+
+ /**
+ * Gets the applications in this context.
+ *
+ * Gets all applications in this context. Each application context contains
+ * all applications that are open for one user.
+ *
+ * @return Collection containing all applications in this context
+ */
+ public Collection getApplications();
+
+ /**
+ * Adds transaction listener to this context.
+ *
+ * @param listener
+ * the listener to be added.
+ * @see TransactionListener
+ */
+ public void addTransactionListener(TransactionListener listener);
+
+ /**
+ * Removes transaction listener from this context.
+ *
+ * @param listener
+ * the listener to be removed.
+ * @see TransactionListener
+ */
+ public void removeTransactionListener(TransactionListener listener);
+
+ /**
+ * Interface for listening the application transaction events.
+ * Implementations of this interface can be used to listen all transactions
+ * between the client and the application.
+ *
+ */
+ public interface TransactionListener {
+
+ /**
+ * Invoked at the beginning of every transaction.
+ *
+ * @param application
+ * the Application object.
+ * @param transactionData
+ * the Data identifying the transaction.
+ */
+ public void transactionStart(Application application,
+ Object transactionData);
+
+ /**
+ * Invoked at the end of every transaction.
+ *
+ * @param applcation
+ * the Application object.
+ * @param transactionData
+ * the Data identifying the transaction.
+ */
+ public void transactionEnd(Application application,
+ Object transactionData);
+
+ }
}
diff --git a/src/com/itmill/toolkit/service/FileTypeResolver.java b/src/com/itmill/toolkit/service/FileTypeResolver.java
index 68030cbc15..7bdadc8b05 100644
--- a/src/com/itmill/toolkit/service/FileTypeResolver.java
+++ b/src/com/itmill/toolkit/service/FileTypeResolver.java
@@ -51,342 +51,350 @@ import com.itmill.toolkit.terminal.ThemeResource;
*/
public class FileTypeResolver {
- /**
- * Default icon given if no icon is specified for a mime-type.
- */
- static public Resource DEFAULT_ICON = new ThemeResource(
- "icon/files/file.gif");
-
- /**
- * Default mime-type.
- */
- static public String DEFAULT_MIME_TYPE = "application/octet-stream";
-
- /**
- * Initial file extension to mime-type mapping.
- */
- static private String initialExtToMIMEMap = "application/cu-seeme csm cu,"
- + "application/dsptype tsp,"
- + "application/futuresplash spl,"
- + "application/mac-binhex40 hqx,"
- + "application/msaccess mdb,"
- + "application/msword doc dot,"
- + "application/octet-stream bin,"
- + "application/oda oda,"
- + "application/pdf pdf,"
- + "application/pgp-signature pgp,"
- + "application/postscript ps ai eps,"
- + "application/rtf rtf,"
- + "application/vnd.ms-excel xls xlb,"
- + "application/vnd.ms-powerpoint ppt pps pot,"
- + "application/vnd.wap.wmlc wmlc,"
- + "application/vnd.wap.wmlscriptc wmlsc,"
- + "application/wordperfect5.1 wp5,"
- + "application/zip zip,"
- + "application/x-123 wk,"
- + "application/x-bcpio bcpio,"
- + "application/x-chess-pgn pgn,"
- + "application/x-cpio cpio,"
- + "application/x-debian-package deb,"
- + "application/x-director dcr dir dxr,"
- + "application/x-dms dms,"
- + "application/x-dvi dvi,"
- + "application/x-xfig fig,"
- + "application/x-font pfa pfb gsf pcf pcf.Z,"
- + "application/x-gnumeric gnumeric,"
- + "application/x-gtar gtar tgz taz,"
- + "application/x-hdf hdf,"
- + "application/x-httpd-php phtml pht php,"
- + "application/x-httpd-php3 php3,"
- + "application/x-httpd-php3-source phps,"
- + "application/x-httpd-php3-preprocessed php3p,"
- + "application/x-httpd-php4 php4,"
- + "application/x-ica ica,"
- + "application/x-java-archive jar,"
- + "application/x-java-serialized-object ser,"
- + "application/x-java-vm class,"
- + "application/x-javascript js,"
- + "application/x-kchart chrt,"
- + "application/x-killustrator kil,"
- + "application/x-kpresenter kpr kpt,"
- + "application/x-kspread ksp,"
- + "application/x-kword kwd kwt,"
- + "application/x-latex latex,"
- + "application/x-lha lha,"
- + "application/x-lzh lzh,"
- + "application/x-lzx lzx,"
- + "application/x-maker frm maker frame fm fb book fbdoc,"
- + "application/x-mif mif,"
- + "application/x-msdos-program com exe bat dll,"
- + "application/x-msi msi,"
- + "application/x-netcdf nc cdf,"
- + "application/x-ns-proxy-autoconfig pac,"
- + "application/x-object o,"
- + "application/x-ogg ogg,"
- + "application/x-oz-application oza,"
- + "application/x-perl pl pm,"
- + "application/x-pkcs7-crl crl,"
- + "application/x-redhat-package-manager rpm,"
- + "application/x-shar shar,"
- + "application/x-shockwave-flash swf swfl,"
- + "application/x-star-office sdd sda,"
- + "application/x-stuffit sit,"
- + "application/x-sv4cpio sv4cpio,"
- + "application/x-sv4crc sv4crc,"
- + "application/x-tar tar,"
- + "application/x-tex-gf gf,"
- + "application/x-tex-pk pk PK,"
- + "application/x-texinfo texinfo texi,"
- + "application/x-trash ~ % bak old sik,"
- + "application/x-troff t tr roff,"
- + "application/x-troff-man man,"
- + "application/x-troff-me me,"
- + "application/x-troff-ms ms,"
- + "application/x-ustar ustar,"
- + "application/x-wais-source src,"
- + "application/x-wingz wz,"
- + "application/x-x509-ca-cert crt,"
- + "audio/basic au snd,"
- + "audio/midi mid midi,"
- + "audio/mpeg mpga mpega mp2 mp3,"
- + "audio/mpegurl m3u,"
- + "audio/prs.sid sid,"
- + "audio/x-aiff aif aiff aifc,"
- + "audio/x-gsm gsm,"
- + "audio/x-pn-realaudio ra rm ram,"
- + "audio/x-scpls pls,"
- + "audio/x-wav wav,"
- + "image/bitmap bmp,"
- + "image/gif gif,"
- + "image/ief ief,"
- + "image/jpeg jpeg jpg jpe,"
- + "image/pcx pcx,"
- + "image/png png,"
- + "image/tiff tiff tif,"
- + "image/vnd.wap.wbmp wbmp,"
- + "image/x-cmu-raster ras,"
- + "image/x-coreldraw cdr,"
- + "image/x-coreldrawpattern pat,"
- + "image/x-coreldrawtemplate cdt,"
- + "image/x-corelphotopaint cpt,"
- + "image/x-jng jng,"
- + "image/x-portable-anymap pnm,"
- + "image/x-portable-bitmap pbm,"
- + "image/x-portable-graymap pgm,"
- + "image/x-portable-pixmap ppm,"
- + "image/x-rgb rgb,"
- + "image/x-xbitmap xbm,"
- + "image/x-xpixmap xpm,"
- + "image/x-xwindowdump xwd,"
- + "text/comma-separated-values csv,"
- + "text/css css,"
- + "text/html htm html xhtml,"
- + "text/mathml mml,"
- + "text/plain txt text diff,"
- + "text/richtext rtx,"
- + "text/tab-separated-values tsv,"
- + "text/vnd.wap.wml wml,"
- + "text/vnd.wap.wmlscript wmls,"
- + "text/xml xml,"
- + "text/x-c++hdr h++ hpp hxx hh,"
- + "text/x-c++src c++ cpp cxx cc,"
- + "text/x-chdr h,"
- + "text/x-csh csh,"
- + "text/x-csrc c,"
- + "text/x-java java,"
- + "text/x-moc moc,"
- + "text/x-pascal p pas,"
- + "text/x-setext etx,"
- + "text/x-sh sh,"
- + "text/x-tcl tcl tk,"
- + "text/x-tex tex ltx sty cls,"
- + "text/x-vcalendar vcs,"
- + "text/x-vcard vcf,"
- + "video/dl dl,"
- + "video/fli fli,"
- + "video/gl gl,"
- + "video/mpeg mpeg mpg mpe,"
- + "video/quicktime qt mov,"
- + "video/x-mng mng,"
- + "video/x-ms-asf asf asx,"
- + "video/x-msvideo avi,"
- + "video/x-sgi-movie movie,"
- + "x-world/x-vrml vrm vrml wrl";
-
- /**
- * File extension to MIME type mapping.
- */
- static private Hashtable extToMIMEMap = new Hashtable();
-
- /**
- * MIME type to Icon mapping.
- */
- static private Hashtable MIMEToIconMap = new Hashtable();
-
- static {
-
- // Initialize extension to MIME map
- StringTokenizer lines = new StringTokenizer(initialExtToMIMEMap, ",");
- while (lines.hasMoreTokens()) {
- String line = lines.nextToken();
- StringTokenizer exts = new StringTokenizer(line);
- String type = exts.nextToken();
- while (exts.hasMoreTokens()) {
- String ext = exts.nextToken();
- addExtension(ext, type);
- }
- }
-
- // Initialize Icons
- addIcon("inode/drive", new ThemeResource("icon/files/drive.gif"));
- addIcon("inode/directory", new ThemeResource("icon/files/folder.gif"));
- }
-
- /**
- * Gets the mime-type of a file. Currently the mime-type is resolved based
- * only on the file name extension.
- *
- * @param fileName
- * the name of the file whose mime-type is requested.
- * @return mime-type String
for the given filename
- */
- public static String getMIMEType(String fileName) {
-
- // Checks for nulls
- if (fileName == null)
- throw new NullPointerException("Filename can not be null");
-
- // Calculates the extension of the file
- int dotIndex = fileName.indexOf(".");
- while (dotIndex >= 0 && fileName.indexOf(".", dotIndex + 1) >= 0)
- dotIndex = fileName.indexOf(".", dotIndex + 1);
- dotIndex++;
-
- if (fileName.length() > dotIndex) {
- String ext = fileName.substring(dotIndex);
-
- // Return type from extension map, if found
- String type = (String) extToMIMEMap.get(ext);
- if (type != null)
- return type;
- }
-
- return DEFAULT_MIME_TYPE;
- }
-
- /**
- * Gets the descriptive icon representing file, based on the filename. First
- * the mime-type for the given filename is resolved, and then the
- * corresponding icon is fetched from the internal icon storage. If it is
- * not found the default icon is returned.
- *
- * @param fileName
- * the name of the file whose icon is requested.
- * @return the icon corresponding to the given file
- */
- public static Resource getIcon(String fileName) {
-
- String mimeType = getMIMEType(fileName);
- Resource icon = (Resource) MIMEToIconMap.get(mimeType);
- if (icon != null)
- return icon;
-
- // If nothing is known about the file-type, general file
- // icon is used
- return DEFAULT_ICON;
- }
-
- /**
- * Gets the descriptive icon representing a file. First the mime-type for
- * the given file name is resolved, and then the corresponding icon is
- * fetched from the internal icon storage. If it is not found the default
- * icon is returned.
- *
- * @param file
- * the file whose icon is requested.
- * @return the icon corresponding to the given file
- */
- public static Resource getIcon(File file) {
-
- String mimeType = getMIMEType(file);
- Resource icon = (Resource) MIMEToIconMap.get(mimeType);
- if (icon != null)
- return icon;
-
- // If nothing is known about the file-type, general file
- // icon is used
- return DEFAULT_ICON;
- }
-
- /**
- * Gets the mime-type for a file. Currently the returned file type is
- * resolved by the filename extension only.
- *
- * @param file
- * the file whose mime-type is requested.
- * @return the files mime-type String
- */
- public static String getMIMEType(File file) {
-
- // Checks for nulls
- if (file == null)
- throw new NullPointerException("File can not be null");
-
- // Drives
- if (file.getParentFile() == null)
- return "inode/drive";
-
- // Directories
- if (file.isDirectory())
- return "inode/directory";
-
- // Return type from extension
- return getMIMEType(file.getName());
- }
-
- /**
- * Adds a mime-type mapping for the given filename extension. If the
- * extension is already in the internal mapping it is overwritten.
- *
- * @param extension
- * the filename extension to be associated with
- * MIMEType
.
- * @param MIMEType
- * the new mime-type for extension
.
- */
- public static void addExtension(String extension, String MIMEType) {
- extToMIMEMap.put(extension, MIMEType);
- }
-
- /**
- * Adds a icon for the given mime-type. If the mime-type also has a
- * corresponding icon, it is replaced with the new icon.
- *
- * @param MIMEType
- * the mime-type whose icon is to be changed.
- * @param icon
- * the new icon to be associated with MIMEType
.
- */
- public static void addIcon(String MIMEType, Resource icon) {
- MIMEToIconMap.put(MIMEType, icon);
- }
-
- /**
- * Gets the internal file extension to mime-type mapping.
- *
- * @return unmodifiable map containing the current file extension to
- * mime-type mapping
- */
- public static Map getExtensionToMIMETypeMapping() {
- return Collections.unmodifiableMap(extToMIMEMap);
- }
-
- /**
- * Gets the internal mime-type to icon mapping.
- *
- * @return unmodifiable map containing the current mime-type to icon mapping
- */
- public static Map getMIMETypeToIconMapping() {
- return Collections.unmodifiableMap(MIMEToIconMap);
- }
+ /**
+ * Default icon given if no icon is specified for a mime-type.
+ */
+ static public Resource DEFAULT_ICON = new ThemeResource(
+ "icon/files/file.gif");
+
+ /**
+ * Default mime-type.
+ */
+ static public String DEFAULT_MIME_TYPE = "application/octet-stream";
+
+ /**
+ * Initial file extension to mime-type mapping.
+ */
+ static private String initialExtToMIMEMap = "application/cu-seeme csm cu,"
+ + "application/dsptype tsp,"
+ + "application/futuresplash spl,"
+ + "application/mac-binhex40 hqx,"
+ + "application/msaccess mdb,"
+ + "application/msword doc dot,"
+ + "application/octet-stream bin,"
+ + "application/oda oda,"
+ + "application/pdf pdf,"
+ + "application/pgp-signature pgp,"
+ + "application/postscript ps ai eps,"
+ + "application/rtf rtf,"
+ + "application/vnd.ms-excel xls xlb,"
+ + "application/vnd.ms-powerpoint ppt pps pot,"
+ + "application/vnd.wap.wmlc wmlc,"
+ + "application/vnd.wap.wmlscriptc wmlsc,"
+ + "application/wordperfect5.1 wp5,"
+ + "application/zip zip,"
+ + "application/x-123 wk,"
+ + "application/x-bcpio bcpio,"
+ + "application/x-chess-pgn pgn,"
+ + "application/x-cpio cpio,"
+ + "application/x-debian-package deb,"
+ + "application/x-director dcr dir dxr,"
+ + "application/x-dms dms,"
+ + "application/x-dvi dvi,"
+ + "application/x-xfig fig,"
+ + "application/x-font pfa pfb gsf pcf pcf.Z,"
+ + "application/x-gnumeric gnumeric,"
+ + "application/x-gtar gtar tgz taz,"
+ + "application/x-hdf hdf,"
+ + "application/x-httpd-php phtml pht php,"
+ + "application/x-httpd-php3 php3,"
+ + "application/x-httpd-php3-source phps,"
+ + "application/x-httpd-php3-preprocessed php3p,"
+ + "application/x-httpd-php4 php4,"
+ + "application/x-ica ica,"
+ + "application/x-java-archive jar,"
+ + "application/x-java-serialized-object ser,"
+ + "application/x-java-vm class,"
+ + "application/x-javascript js,"
+ + "application/x-kchart chrt,"
+ + "application/x-killustrator kil,"
+ + "application/x-kpresenter kpr kpt,"
+ + "application/x-kspread ksp,"
+ + "application/x-kword kwd kwt,"
+ + "application/x-latex latex,"
+ + "application/x-lha lha,"
+ + "application/x-lzh lzh,"
+ + "application/x-lzx lzx,"
+ + "application/x-maker frm maker frame fm fb book fbdoc,"
+ + "application/x-mif mif,"
+ + "application/x-msdos-program com exe bat dll,"
+ + "application/x-msi msi,"
+ + "application/x-netcdf nc cdf,"
+ + "application/x-ns-proxy-autoconfig pac,"
+ + "application/x-object o,"
+ + "application/x-ogg ogg,"
+ + "application/x-oz-application oza,"
+ + "application/x-perl pl pm,"
+ + "application/x-pkcs7-crl crl,"
+ + "application/x-redhat-package-manager rpm,"
+ + "application/x-shar shar,"
+ + "application/x-shockwave-flash swf swfl,"
+ + "application/x-star-office sdd sda,"
+ + "application/x-stuffit sit,"
+ + "application/x-sv4cpio sv4cpio,"
+ + "application/x-sv4crc sv4crc,"
+ + "application/x-tar tar,"
+ + "application/x-tex-gf gf,"
+ + "application/x-tex-pk pk PK,"
+ + "application/x-texinfo texinfo texi,"
+ + "application/x-trash ~ % bak old sik,"
+ + "application/x-troff t tr roff,"
+ + "application/x-troff-man man,"
+ + "application/x-troff-me me,"
+ + "application/x-troff-ms ms,"
+ + "application/x-ustar ustar,"
+ + "application/x-wais-source src,"
+ + "application/x-wingz wz,"
+ + "application/x-x509-ca-cert crt,"
+ + "audio/basic au snd,"
+ + "audio/midi mid midi,"
+ + "audio/mpeg mpga mpega mp2 mp3,"
+ + "audio/mpegurl m3u,"
+ + "audio/prs.sid sid,"
+ + "audio/x-aiff aif aiff aifc,"
+ + "audio/x-gsm gsm,"
+ + "audio/x-pn-realaudio ra rm ram,"
+ + "audio/x-scpls pls,"
+ + "audio/x-wav wav,"
+ + "image/bitmap bmp,"
+ + "image/gif gif,"
+ + "image/ief ief,"
+ + "image/jpeg jpeg jpg jpe,"
+ + "image/pcx pcx,"
+ + "image/png png,"
+ + "image/tiff tiff tif,"
+ + "image/vnd.wap.wbmp wbmp,"
+ + "image/x-cmu-raster ras,"
+ + "image/x-coreldraw cdr,"
+ + "image/x-coreldrawpattern pat,"
+ + "image/x-coreldrawtemplate cdt,"
+ + "image/x-corelphotopaint cpt,"
+ + "image/x-jng jng,"
+ + "image/x-portable-anymap pnm,"
+ + "image/x-portable-bitmap pbm,"
+ + "image/x-portable-graymap pgm,"
+ + "image/x-portable-pixmap ppm,"
+ + "image/x-rgb rgb,"
+ + "image/x-xbitmap xbm,"
+ + "image/x-xpixmap xpm,"
+ + "image/x-xwindowdump xwd,"
+ + "text/comma-separated-values csv,"
+ + "text/css css,"
+ + "text/html htm html xhtml,"
+ + "text/mathml mml,"
+ + "text/plain txt text diff,"
+ + "text/richtext rtx,"
+ + "text/tab-separated-values tsv,"
+ + "text/vnd.wap.wml wml,"
+ + "text/vnd.wap.wmlscript wmls,"
+ + "text/xml xml,"
+ + "text/x-c++hdr h++ hpp hxx hh,"
+ + "text/x-c++src c++ cpp cxx cc,"
+ + "text/x-chdr h,"
+ + "text/x-csh csh,"
+ + "text/x-csrc c,"
+ + "text/x-java java,"
+ + "text/x-moc moc,"
+ + "text/x-pascal p pas,"
+ + "text/x-setext etx,"
+ + "text/x-sh sh,"
+ + "text/x-tcl tcl tk,"
+ + "text/x-tex tex ltx sty cls,"
+ + "text/x-vcalendar vcs,"
+ + "text/x-vcard vcf,"
+ + "video/dl dl,"
+ + "video/fli fli,"
+ + "video/gl gl,"
+ + "video/mpeg mpeg mpg mpe,"
+ + "video/quicktime qt mov,"
+ + "video/x-mng mng,"
+ + "video/x-ms-asf asf asx,"
+ + "video/x-msvideo avi,"
+ + "video/x-sgi-movie movie,"
+ + "x-world/x-vrml vrm vrml wrl";
+
+ /**
+ * File extension to MIME type mapping.
+ */
+ static private Hashtable extToMIMEMap = new Hashtable();
+
+ /**
+ * MIME type to Icon mapping.
+ */
+ static private Hashtable MIMEToIconMap = new Hashtable();
+
+ static {
+
+ // Initialize extension to MIME map
+ StringTokenizer lines = new StringTokenizer(initialExtToMIMEMap, ",");
+ while (lines.hasMoreTokens()) {
+ String line = lines.nextToken();
+ StringTokenizer exts = new StringTokenizer(line);
+ String type = exts.nextToken();
+ while (exts.hasMoreTokens()) {
+ String ext = exts.nextToken();
+ addExtension(ext, type);
+ }
+ }
+
+ // Initialize Icons
+ addIcon("inode/drive", new ThemeResource("icon/files/drive.gif"));
+ addIcon("inode/directory", new ThemeResource("icon/files/folder.gif"));
+ }
+
+ /**
+ * Gets the mime-type of a file. Currently the mime-type is resolved based
+ * only on the file name extension.
+ *
+ * @param fileName
+ * the name of the file whose mime-type is requested.
+ * @return mime-type String
for the given filename
+ */
+ public static String getMIMEType(String fileName) {
+
+ // Checks for nulls
+ if (fileName == null) {
+ throw new NullPointerException("Filename can not be null");
+ }
+
+ // Calculates the extension of the file
+ int dotIndex = fileName.indexOf(".");
+ while (dotIndex >= 0 && fileName.indexOf(".", dotIndex + 1) >= 0) {
+ dotIndex = fileName.indexOf(".", dotIndex + 1);
+ }
+ dotIndex++;
+
+ if (fileName.length() > dotIndex) {
+ String ext = fileName.substring(dotIndex);
+
+ // Return type from extension map, if found
+ String type = (String) extToMIMEMap.get(ext);
+ if (type != null) {
+ return type;
+ }
+ }
+
+ return DEFAULT_MIME_TYPE;
+ }
+
+ /**
+ * Gets the descriptive icon representing file, based on the filename. First
+ * the mime-type for the given filename is resolved, and then the
+ * corresponding icon is fetched from the internal icon storage. If it is
+ * not found the default icon is returned.
+ *
+ * @param fileName
+ * the name of the file whose icon is requested.
+ * @return the icon corresponding to the given file
+ */
+ public static Resource getIcon(String fileName) {
+
+ String mimeType = getMIMEType(fileName);
+ Resource icon = (Resource) MIMEToIconMap.get(mimeType);
+ if (icon != null) {
+ return icon;
+ }
+
+ // If nothing is known about the file-type, general file
+ // icon is used
+ return DEFAULT_ICON;
+ }
+
+ /**
+ * Gets the descriptive icon representing a file. First the mime-type for
+ * the given file name is resolved, and then the corresponding icon is
+ * fetched from the internal icon storage. If it is not found the default
+ * icon is returned.
+ *
+ * @param file
+ * the file whose icon is requested.
+ * @return the icon corresponding to the given file
+ */
+ public static Resource getIcon(File file) {
+
+ String mimeType = getMIMEType(file);
+ Resource icon = (Resource) MIMEToIconMap.get(mimeType);
+ if (icon != null) {
+ return icon;
+ }
+
+ // If nothing is known about the file-type, general file
+ // icon is used
+ return DEFAULT_ICON;
+ }
+
+ /**
+ * Gets the mime-type for a file. Currently the returned file type is
+ * resolved by the filename extension only.
+ *
+ * @param file
+ * the file whose mime-type is requested.
+ * @return the files mime-type String
+ */
+ public static String getMIMEType(File file) {
+
+ // Checks for nulls
+ if (file == null) {
+ throw new NullPointerException("File can not be null");
+ }
+
+ // Drives
+ if (file.getParentFile() == null) {
+ return "inode/drive";
+ }
+
+ // Directories
+ if (file.isDirectory()) {
+ return "inode/directory";
+ }
+
+ // Return type from extension
+ return getMIMEType(file.getName());
+ }
+
+ /**
+ * Adds a mime-type mapping for the given filename extension. If the
+ * extension is already in the internal mapping it is overwritten.
+ *
+ * @param extension
+ * the filename extension to be associated with
+ * MIMEType
.
+ * @param MIMEType
+ * the new mime-type for extension
.
+ */
+ public static void addExtension(String extension, String MIMEType) {
+ extToMIMEMap.put(extension, MIMEType);
+ }
+
+ /**
+ * Adds a icon for the given mime-type. If the mime-type also has a
+ * corresponding icon, it is replaced with the new icon.
+ *
+ * @param MIMEType
+ * the mime-type whose icon is to be changed.
+ * @param icon
+ * the new icon to be associated with MIMEType
.
+ */
+ public static void addIcon(String MIMEType, Resource icon) {
+ MIMEToIconMap.put(MIMEType, icon);
+ }
+
+ /**
+ * Gets the internal file extension to mime-type mapping.
+ *
+ * @return unmodifiable map containing the current file extension to
+ * mime-type mapping
+ */
+ public static Map getExtensionToMIMETypeMapping() {
+ return Collections.unmodifiableMap(extToMIMEMap);
+ }
+
+ /**
+ * Gets the internal mime-type to icon mapping.
+ *
+ * @return unmodifiable map containing the current mime-type to icon mapping
+ */
+ public static Map getMIMETypeToIconMapping() {
+ return Collections.unmodifiableMap(MIMEToIconMap);
+ }
}
diff --git a/src/com/itmill/toolkit/terminal/ApplicationResource.java b/src/com/itmill/toolkit/terminal/ApplicationResource.java
index 53e1540cb6..17093f8907 100644
--- a/src/com/itmill/toolkit/terminal/ApplicationResource.java
+++ b/src/com/itmill/toolkit/terminal/ApplicationResource.java
@@ -47,51 +47,51 @@ import com.itmill.toolkit.Application;
*/
public interface ApplicationResource extends Resource {
- /**
- * Default cache time.
- */
- public static final long DEFAULT_CACHETIME = 1000 * 60 * 60 * 24;
+ /**
+ * Default cache time.
+ */
+ public static final long DEFAULT_CACHETIME = 1000 * 60 * 60 * 24;
- /**
- * Gets resource as stream.
- */
- public DownloadStream getStream();
+ /**
+ * Gets resource as stream.
+ */
+ public DownloadStream getStream();
- /**
- * Gets the application of the resource.
- */
- public Application getApplication();
+ /**
+ * Gets the application of the resource.
+ */
+ public Application getApplication();
- /**
- * Gets the virtual filename for this resource.
- *
- * @return the file name associated to this resource.
- */
- public String getFilename();
+ /**
+ * Gets the virtual filename for this resource.
+ *
+ * @return the file name associated to this resource.
+ */
+ public String getFilename();
- /**
- * Gets the length of cache expiration time.
- *
- *
- * This gives the adapter the possibility cache streams sent to the client.
- * The caching may be made in adapter or at the client if the client
- * supports caching. Default is DEFAULT_CACHETIME
.
- *
- *
- * @return Cache time in milliseconds
- */
- public long getCacheTime();
+ /**
+ * Gets the length of cache expiration time.
+ *
+ *
+ * This gives the adapter the possibility cache streams sent to the client.
+ * The caching may be made in adapter or at the client if the client
+ * supports caching. Default is DEFAULT_CACHETIME
.
+ *
+ *
+ * @return Cache time in milliseconds
+ */
+ public long getCacheTime();
- /**
- * Gets the size of the download buffer used for this resource.
- *
- *
- * If the buffer size is 0, the buffer size is decided by the terminal
- * adapter. The default value is 0.
- *
- *
- * @return int the size of the buffer in bytes.
- */
- public int getBufferSize();
+ /**
+ * Gets the size of the download buffer used for this resource.
+ *
+ *
+ * If the buffer size is 0, the buffer size is decided by the terminal
+ * adapter. The default value is 0.
+ *
+ *
+ * @return int the size of the buffer in bytes.
+ */
+ public int getBufferSize();
}
diff --git a/src/com/itmill/toolkit/terminal/ClassResource.java b/src/com/itmill/toolkit/terminal/ClassResource.java
index c53375350e..afb596f5c3 100644
--- a/src/com/itmill/toolkit/terminal/ClassResource.java
+++ b/src/com/itmill/toolkit/terminal/ClassResource.java
@@ -46,151 +46,156 @@ import com.itmill.toolkit.service.FileTypeResolver;
*/
public class ClassResource implements ApplicationResource {
- /**
- * Default buffer size for this stream resource.
- */
- private int bufferSize = 0;
-
- /**
- * Default cache time for this stream resource.
- */
- private long cacheTime = DEFAULT_CACHETIME;
-
- /**
- * Associated class used for indetifying the source of the resource.
- */
- private Class associatedClass;
-
- /**
- * Name of the resource is relative to the associated class.
- */
- private String resourceName;
-
- /**
- * Application used for serving the class.
- */
- private Application application;
-
- /**
- * Creates a new application resource instance. The resource id is relative
- * to the location of the application class.
- *
- * @param resourceName
- * the Unique identifier of the resource within the application.
- * @param application
- * the application this resource will be added to.
- */
- public ClassResource(String resourceName, Application application) {
- this.associatedClass = application.getClass();
- this.resourceName = resourceName;
- this.application = application;
- if (resourceName == null)
- throw new NullPointerException();
- application.addResource(this);
- }
-
- /**
- * Creates a new application resource instance.
- *
- * @param associatedClass
- * the class of the which the resource is associated.
- * @param resourceName
- * the Unique identifier of the resource within the application.
- * @param application
- * the application this resource will be added to.
- */
- public ClassResource(Class associatedClass, String resourceName,
- Application application) {
- this.associatedClass = associatedClass;
- this.resourceName = resourceName;
- this.application = application;
- if (resourceName == null || associatedClass == null)
- throw new NullPointerException();
- application.addResource(this);
- }
-
- /**
- * Gets the MIME type of this resource.
- *
- * @see com.itmill.toolkit.terminal.Resource#getMIMEType()
- */
- public String getMIMEType() {
- return FileTypeResolver.getMIMEType(this.resourceName);
- }
-
- /**
- * Gets the application of this resource.
- *
- * @see com.itmill.toolkit.terminal.ApplicationResource#getApplication()
- */
- public Application getApplication() {
- return application;
- }
-
- /**
- * Gets the virtual filename for this resource.
- *
- * @return the file name associated to this resource.
- * @see com.itmill.toolkit.terminal.ApplicationResource#getFilename()
- */
- public String getFilename() {
- int index = 0;
- int next = 0;
- while ((next = resourceName.indexOf('/', index)) > 0
- && next + 1 < resourceName.length())
- index = next + 1;
- return resourceName.substring(index);
- }
-
- /**
- * Gets resource as stream.
- *
- * @see com.itmill.toolkit.terminal.ApplicationResource#getStream()
- */
- public DownloadStream getStream() {
- DownloadStream ds = new DownloadStream(associatedClass
- .getResourceAsStream(resourceName), getMIMEType(),
- getFilename());
- ds.setBufferSize(getBufferSize());
- ds.setCacheTime(cacheTime);
- return ds;
- }
-
- /* documented in superclass */
- public int getBufferSize() {
- return bufferSize;
- }
-
- /**
- * Sets the size of the download buffer used for this resource.
- *
- * @param bufferSize
- * the size of the buffer in bytes.
- */
- public void setBufferSize(int bufferSize) {
- this.bufferSize = bufferSize;
- }
-
- /* documented in superclass */
- public long getCacheTime() {
- return cacheTime;
- }
-
- /**
- * Sets the length of cache expiration time.
- *
- *
- * This gives the adapter the possibility cache streams sent to the client.
- * The caching may be made in adapter or at the client if the client
- * supports caching. Zero or negavive value disbales the caching of this
- * stream.
- *
- *
- * @param cacheTime
- * the cache time in milliseconds.
- *
- */
- public void setCacheTime(long cacheTime) {
- this.cacheTime = cacheTime;
- }
+ /**
+ * Default buffer size for this stream resource.
+ */
+ private int bufferSize = 0;
+
+ /**
+ * Default cache time for this stream resource.
+ */
+ private long cacheTime = DEFAULT_CACHETIME;
+
+ /**
+ * Associated class used for indetifying the source of the resource.
+ */
+ private Class associatedClass;
+
+ /**
+ * Name of the resource is relative to the associated class.
+ */
+ private String resourceName;
+
+ /**
+ * Application used for serving the class.
+ */
+ private Application application;
+
+ /**
+ * Creates a new application resource instance. The resource id is relative
+ * to the location of the application class.
+ *
+ * @param resourceName
+ * the Unique identifier of the resource within the
+ * application.
+ * @param application
+ * the application this resource will be added to.
+ */
+ public ClassResource(String resourceName, Application application) {
+ associatedClass = application.getClass();
+ this.resourceName = resourceName;
+ this.application = application;
+ if (resourceName == null) {
+ throw new NullPointerException();
+ }
+ application.addResource(this);
+ }
+
+ /**
+ * Creates a new application resource instance.
+ *
+ * @param associatedClass
+ * the class of the which the resource is associated.
+ * @param resourceName
+ * the Unique identifier of the resource within the
+ * application.
+ * @param application
+ * the application this resource will be added to.
+ */
+ public ClassResource(Class associatedClass, String resourceName,
+ Application application) {
+ this.associatedClass = associatedClass;
+ this.resourceName = resourceName;
+ this.application = application;
+ if (resourceName == null || associatedClass == null) {
+ throw new NullPointerException();
+ }
+ application.addResource(this);
+ }
+
+ /**
+ * Gets the MIME type of this resource.
+ *
+ * @see com.itmill.toolkit.terminal.Resource#getMIMEType()
+ */
+ public String getMIMEType() {
+ return FileTypeResolver.getMIMEType(resourceName);
+ }
+
+ /**
+ * Gets the application of this resource.
+ *
+ * @see com.itmill.toolkit.terminal.ApplicationResource#getApplication()
+ */
+ public Application getApplication() {
+ return application;
+ }
+
+ /**
+ * Gets the virtual filename for this resource.
+ *
+ * @return the file name associated to this resource.
+ * @see com.itmill.toolkit.terminal.ApplicationResource#getFilename()
+ */
+ public String getFilename() {
+ int index = 0;
+ int next = 0;
+ while ((next = resourceName.indexOf('/', index)) > 0
+ && next + 1 < resourceName.length()) {
+ index = next + 1;
+ }
+ return resourceName.substring(index);
+ }
+
+ /**
+ * Gets resource as stream.
+ *
+ * @see com.itmill.toolkit.terminal.ApplicationResource#getStream()
+ */
+ public DownloadStream getStream() {
+ DownloadStream ds = new DownloadStream(associatedClass
+ .getResourceAsStream(resourceName), getMIMEType(),
+ getFilename());
+ ds.setBufferSize(getBufferSize());
+ ds.setCacheTime(cacheTime);
+ return ds;
+ }
+
+ /* documented in superclass */
+ public int getBufferSize() {
+ return bufferSize;
+ }
+
+ /**
+ * Sets the size of the download buffer used for this resource.
+ *
+ * @param bufferSize
+ * the size of the buffer in bytes.
+ */
+ public void setBufferSize(int bufferSize) {
+ this.bufferSize = bufferSize;
+ }
+
+ /* documented in superclass */
+ public long getCacheTime() {
+ return cacheTime;
+ }
+
+ /**
+ * Sets the length of cache expiration time.
+ *
+ *
+ * This gives the adapter the possibility cache streams sent to the client.
+ * The caching may be made in adapter or at the client if the client
+ * supports caching. Zero or negavive value disbales the caching of this
+ * stream.
+ *
+ *
+ * @param cacheTime
+ * the cache time in milliseconds.
+ *
+ */
+ public void setCacheTime(long cacheTime) {
+ this.cacheTime = cacheTime;
+ }
}
diff --git a/src/com/itmill/toolkit/terminal/CompositeErrorMessage.java b/src/com/itmill/toolkit/terminal/CompositeErrorMessage.java
index 469efdbf7b..8916e6291b 100644
--- a/src/com/itmill/toolkit/terminal/CompositeErrorMessage.java
+++ b/src/com/itmill/toolkit/terminal/CompositeErrorMessage.java
@@ -43,153 +43,159 @@ import java.util.List;
*/
public class CompositeErrorMessage implements ErrorMessage {
- /**
- * Array of all the errors.
- */
- private List errors;
-
- /**
- * Level of the error.
- */
- private int level;
-
- /**
- * Constructor for CompositeErrorMessage.
- *
- * @param errorMessages
- * the Array of error messages that are listed togeter. Nulls are
- * ignored, but at least one message is required.
- */
- public CompositeErrorMessage(ErrorMessage[] errorMessages) {
- errors = new ArrayList(errorMessages.length);
- level = Integer.MIN_VALUE;
-
- for (int i = 0; i < errorMessages.length; i++) {
- addErrorMessage(errorMessages[i]);
- }
-
- if (errors.size() == 0)
- throw new IllegalArgumentException(
- "Composite error message must have at least one error");
-
- }
-
- /**
- * Constructor for CompositeErrorMessage.
- *
- * @param errorMessages
- * the Collection of error messages that are listed togeter. At
- * least one message is required.
- */
- public CompositeErrorMessage(Collection errorMessages) {
- errors = new ArrayList(errorMessages.size());
- level = Integer.MIN_VALUE;
-
- for (Iterator i = errorMessages.iterator(); i.hasNext();) {
- addErrorMessage((ErrorMessage) i.next());
- }
-
- if (errors.size() == 0)
- throw new IllegalArgumentException(
- "Composite error message must have at least one error");
- }
-
- /**
- * The error level is the largest error level in
- *
- * @see com.itmill.toolkit.terminal.ErrorMessage#getErrorLevel()
- */
- public final int getErrorLevel() {
- return level;
- }
-
- /**
- * Adds a error message into this composite message. Updates the level
- * field.
- *
- * @param error
- * the error message to be added. Duplicate errors are ignored.
- */
- private void addErrorMessage(ErrorMessage error) {
- if (error != null && !errors.contains(error)) {
- this.errors.add(error);
- int l = error.getErrorLevel();
- if (l > level)
- level = l;
- }
- }
-
- /**
- * Gets Error Iterator.
- *
- * @return the error iterator.
- */
- public Iterator iterator() {
- return errors.iterator();
- }
-
- /**
- * @see com.itmill.toolkit.terminal.Paintable#paint(com.itmill.toolkit.terminal.PaintTarget)
- */
- public void paint(PaintTarget target) throws PaintException {
-
- if (errors.size() == 1)
- ((ErrorMessage) errors.iterator().next()).paint(target);
- else {
- target.startTag("error");
-
- if (level > 0 && level <= ErrorMessage.INFORMATION)
- target.addAttribute("level", "info");
- else if (level <= ErrorMessage.WARNING)
- target.addAttribute("level", "warning");
- else if (level <= ErrorMessage.ERROR)
- target.addAttribute("level", "error");
- else if (level <= ErrorMessage.CRITICAL)
- target.addAttribute("level", "critical");
- else
- target.addAttribute("level", "system");
-
- // Paint all the exceptions
- for (Iterator i = errors.iterator(); i.hasNext();) {
- ((ErrorMessage) i.next()).paint(target);
- }
-
- target.endTag("error");
- }
- }
-
- /* Documented in super interface */
- public void addListener(RepaintRequestListener listener) {
- }
-
- /* Documented in super interface */
- public void removeListener(RepaintRequestListener listener) {
- }
-
- /* Documented in super interface */
- public void requestRepaint() {
- }
-
- /* Documented in super interface */
- public void requestRepaintRequests() {
- }
-
- /**
- * Returns a comma separated list of the error messages.
- *
- * @return String, comma separated list of error messages.
- */
- public String toString() {
- String retval = "[";
- int pos = 0;
- for (Iterator i = errors.iterator(); i.hasNext();) {
- if (pos > 0)
- retval += ",";
- pos++;
- retval += i.next().toString();
- }
- retval += "]";
-
- return retval;
- }
+ /**
+ * Array of all the errors.
+ */
+ private List errors;
+
+ /**
+ * Level of the error.
+ */
+ private int level;
+
+ /**
+ * Constructor for CompositeErrorMessage.
+ *
+ * @param errorMessages
+ * the Array of error messages that are listed togeter. Nulls
+ * are ignored, but at least one message is required.
+ */
+ public CompositeErrorMessage(ErrorMessage[] errorMessages) {
+ errors = new ArrayList(errorMessages.length);
+ level = Integer.MIN_VALUE;
+
+ for (int i = 0; i < errorMessages.length; i++) {
+ addErrorMessage(errorMessages[i]);
+ }
+
+ if (errors.size() == 0) {
+ throw new IllegalArgumentException(
+ "Composite error message must have at least one error");
+ }
+
+ }
+
+ /**
+ * Constructor for CompositeErrorMessage.
+ *
+ * @param errorMessages
+ * the Collection of error messages that are listed togeter.
+ * At least one message is required.
+ */
+ public CompositeErrorMessage(Collection errorMessages) {
+ errors = new ArrayList(errorMessages.size());
+ level = Integer.MIN_VALUE;
+
+ for (Iterator i = errorMessages.iterator(); i.hasNext();) {
+ addErrorMessage((ErrorMessage) i.next());
+ }
+
+ if (errors.size() == 0) {
+ throw new IllegalArgumentException(
+ "Composite error message must have at least one error");
+ }
+ }
+
+ /**
+ * The error level is the largest error level in
+ *
+ * @see com.itmill.toolkit.terminal.ErrorMessage#getErrorLevel()
+ */
+ public final int getErrorLevel() {
+ return level;
+ }
+
+ /**
+ * Adds a error message into this composite message. Updates the level
+ * field.
+ *
+ * @param error
+ * the error message to be added. Duplicate errors are
+ * ignored.
+ */
+ private void addErrorMessage(ErrorMessage error) {
+ if (error != null && !errors.contains(error)) {
+ errors.add(error);
+ int l = error.getErrorLevel();
+ if (l > level) {
+ level = l;
+ }
+ }
+ }
+
+ /**
+ * Gets Error Iterator.
+ *
+ * @return the error iterator.
+ */
+ public Iterator iterator() {
+ return errors.iterator();
+ }
+
+ /**
+ * @see com.itmill.toolkit.terminal.Paintable#paint(com.itmill.toolkit.terminal.PaintTarget)
+ */
+ public void paint(PaintTarget target) throws PaintException {
+
+ if (errors.size() == 1) {
+ ((ErrorMessage) errors.iterator().next()).paint(target);
+ } else {
+ target.startTag("error");
+
+ if (level > 0 && level <= ErrorMessage.INFORMATION) {
+ target.addAttribute("level", "info");
+ } else if (level <= ErrorMessage.WARNING) {
+ target.addAttribute("level", "warning");
+ } else if (level <= ErrorMessage.ERROR) {
+ target.addAttribute("level", "error");
+ } else if (level <= ErrorMessage.CRITICAL) {
+ target.addAttribute("level", "critical");
+ } else {
+ target.addAttribute("level", "system");
+ }
+
+ // Paint all the exceptions
+ for (Iterator i = errors.iterator(); i.hasNext();) {
+ ((ErrorMessage) i.next()).paint(target);
+ }
+
+ target.endTag("error");
+ }
+ }
+
+ /* Documented in super interface */
+ public void addListener(RepaintRequestListener listener) {
+ }
+
+ /* Documented in super interface */
+ public void removeListener(RepaintRequestListener listener) {
+ }
+
+ /* Documented in super interface */
+ public void requestRepaint() {
+ }
+
+ /* Documented in super interface */
+ public void requestRepaintRequests() {
+ }
+
+ /**
+ * Returns a comma separated list of the error messages.
+ *
+ * @return String, comma separated list of error messages.
+ */
+ public String toString() {
+ String retval = "[";
+ int pos = 0;
+ for (Iterator i = errors.iterator(); i.hasNext();) {
+ if (pos > 0) {
+ retval += ",";
+ }
+ pos++;
+ retval += i.next().toString();
+ }
+ retval += "]";
+
+ return retval;
+ }
}
diff --git a/src/com/itmill/toolkit/terminal/DownloadStream.java b/src/com/itmill/toolkit/terminal/DownloadStream.java
index 86995036e9..4ec51c848d 100644
--- a/src/com/itmill/toolkit/terminal/DownloadStream.java
+++ b/src/com/itmill/toolkit/terminal/DownloadStream.java
@@ -43,184 +43,186 @@ import java.util.Map;
*/
public class DownloadStream {
- /**
- * Maximum cache time.
- */
- public static final long MAX_CACHETIME = Long.MAX_VALUE;
-
- /**
- * Default cache time.
- */
- public static final long DEFAULT_CACHETIME = 1000 * 60 * 60 * 24;
-
- private InputStream stream;
-
- private String contentType;
-
- private String fileName;
-
- private Map params;
-
- private long cacheTime = DEFAULT_CACHETIME;
-
- private int bufferSize = 0;
-
- /**
- * Creates a new instance of DownloadStream.
- */
- public DownloadStream(InputStream stream, String contentType,
- String fileName) {
- setStream(stream);
- setContentType(contentType);
- setFileName(fileName);
- }
-
- /**
- * Gets downloadable stream.
- *
- * @return output stream.
- */
- public InputStream getStream() {
- return this.stream;
- }
-
- /**
- * Sets the stream.
- *
- * @param stream
- * The stream to set
- */
- public void setStream(InputStream stream) {
- this.stream = stream;
- }
-
- /**
- * Gets stream content type.
- *
- * @return type of the stream content.
- */
- public String getContentType() {
- return this.contentType;
- }
-
- /**
- * Sets stream content type.
- *
- * @param contentType
- * the contentType to set
- */
- public void setContentType(String contentType) {
- this.contentType = contentType;
- }
-
- /**
- * Returns the file name.
- *
- * @return the name of the file.
- */
- public String getFileName() {
- return fileName;
- }
-
- /**
- * Sets the file name.
- *
- * @param fileName
- * the file name to set.
- */
- public void setFileName(String fileName) {
- this.fileName = fileName;
- }
-
- /**
- * Sets a paramater for download stream. Parameters are optional information
- * about the downloadable stream and their meaning depends on the used
- * adapter. For example in WebAdapter they are interpreted as HTTP response
- * headers.
- *
- * If the parameters by this name exists, the old value is replaced.
- *
- * @param name
- * the Name of the parameter to set.
- * @param value
- * the Value of the parameter to set.
- */
- public void setParameter(String name, String value) {
- if (this.params == null) {
- this.params = new HashMap();
- }
- this.params.put(name, value);
- }
-
- /**
- * Gets a paramater for download stream. Parameters are optional information
- * about the downloadable stream and their meaning depends on the used
- * adapter. For example in WebAdapter they are interpreted as HTTP response
- * headers.
- *
- * @param name
- * the Name of the parameter to set.
- * @return Value of the parameter or null if the parameter does not exist.
- */
- public String getParameter(String name) {
- if (this.params != null)
- return (String) this.params.get(name);
- return null;
- }
-
- /**
- * Gets the names of the parameters.
- *
- * @return Iterator of names or null if no parameters are set.
- */
- public Iterator getParameterNames() {
- if (this.params != null)
- return this.params.keySet().iterator();
- return null;
- }
-
- /**
- * Gets length of cache expiration time. This gives the adapter the
- * possibility cache streams sent to the client. The caching may be made in
- * adapter or at the client if the client supports caching. Default is
- * DEFAULT_CACHETIME
.
- *
- * @return Cache time in milliseconds
- */
- public long getCacheTime() {
- return cacheTime;
- }
-
- /**
- * Sets length of cache expiration time. This gives the adapter the
- * possibility cache streams sent to the client. The caching may be made in
- * adapter or at the client if the client supports caching. Zero or negavive
- * value disbales the caching of this stream.
- *
- * @param cacheTime
- * the cache time in milliseconds.
- */
- public void setCacheTime(long cacheTime) {
- this.cacheTime = cacheTime;
- }
-
- /**
- * Gets the size of the download buffer.
- *
- * @return int The size of the buffer in bytes.
- */
- public int getBufferSize() {
- return bufferSize;
- }
-
- /**
- * Sets the size of the download buffer.
- *
- * @param bufferSize
- * the size of the buffer in bytes.
- */
- public void setBufferSize(int bufferSize) {
- this.bufferSize = bufferSize;
- }
+ /**
+ * Maximum cache time.
+ */
+ public static final long MAX_CACHETIME = Long.MAX_VALUE;
+
+ /**
+ * Default cache time.
+ */
+ public static final long DEFAULT_CACHETIME = 1000 * 60 * 60 * 24;
+
+ private InputStream stream;
+
+ private String contentType;
+
+ private String fileName;
+
+ private Map params;
+
+ private long cacheTime = DEFAULT_CACHETIME;
+
+ private int bufferSize = 0;
+
+ /**
+ * Creates a new instance of DownloadStream.
+ */
+ public DownloadStream(InputStream stream, String contentType,
+ String fileName) {
+ setStream(stream);
+ setContentType(contentType);
+ setFileName(fileName);
+ }
+
+ /**
+ * Gets downloadable stream.
+ *
+ * @return output stream.
+ */
+ public InputStream getStream() {
+ return stream;
+ }
+
+ /**
+ * Sets the stream.
+ *
+ * @param stream
+ * The stream to set
+ */
+ public void setStream(InputStream stream) {
+ this.stream = stream;
+ }
+
+ /**
+ * Gets stream content type.
+ *
+ * @return type of the stream content.
+ */
+ public String getContentType() {
+ return contentType;
+ }
+
+ /**
+ * Sets stream content type.
+ *
+ * @param contentType
+ * the contentType to set
+ */
+ public void setContentType(String contentType) {
+ this.contentType = contentType;
+ }
+
+ /**
+ * Returns the file name.
+ *
+ * @return the name of the file.
+ */
+ public String getFileName() {
+ return fileName;
+ }
+
+ /**
+ * Sets the file name.
+ *
+ * @param fileName
+ * the file name to set.
+ */
+ public void setFileName(String fileName) {
+ this.fileName = fileName;
+ }
+
+ /**
+ * Sets a paramater for download stream. Parameters are optional information
+ * about the downloadable stream and their meaning depends on the used
+ * adapter. For example in WebAdapter they are interpreted as HTTP response
+ * headers.
+ *
+ * If the parameters by this name exists, the old value is replaced.
+ *
+ * @param name
+ * the Name of the parameter to set.
+ * @param value
+ * the Value of the parameter to set.
+ */
+ public void setParameter(String name, String value) {
+ if (params == null) {
+ params = new HashMap();
+ }
+ params.put(name, value);
+ }
+
+ /**
+ * Gets a paramater for download stream. Parameters are optional information
+ * about the downloadable stream and their meaning depends on the used
+ * adapter. For example in WebAdapter they are interpreted as HTTP response
+ * headers.
+ *
+ * @param name
+ * the Name of the parameter to set.
+ * @return Value of the parameter or null if the parameter does not exist.
+ */
+ public String getParameter(String name) {
+ if (params != null) {
+ return (String) params.get(name);
+ }
+ return null;
+ }
+
+ /**
+ * Gets the names of the parameters.
+ *
+ * @return Iterator of names or null if no parameters are set.
+ */
+ public Iterator getParameterNames() {
+ if (params != null) {
+ return params.keySet().iterator();
+ }
+ return null;
+ }
+
+ /**
+ * Gets length of cache expiration time. This gives the adapter the
+ * possibility cache streams sent to the client. The caching may be made in
+ * adapter or at the client if the client supports caching. Default is
+ * DEFAULT_CACHETIME
.
+ *
+ * @return Cache time in milliseconds
+ */
+ public long getCacheTime() {
+ return cacheTime;
+ }
+
+ /**
+ * Sets length of cache expiration time. This gives the adapter the
+ * possibility cache streams sent to the client. The caching may be made in
+ * adapter or at the client if the client supports caching. Zero or negavive
+ * value disbales the caching of this stream.
+ *
+ * @param cacheTime
+ * the cache time in milliseconds.
+ */
+ public void setCacheTime(long cacheTime) {
+ this.cacheTime = cacheTime;
+ }
+
+ /**
+ * Gets the size of the download buffer.
+ *
+ * @return int The size of the buffer in bytes.
+ */
+ public int getBufferSize() {
+ return bufferSize;
+ }
+
+ /**
+ * Sets the size of the download buffer.
+ *
+ * @param bufferSize
+ * the size of the buffer in bytes.
+ */
+ public void setBufferSize(int bufferSize) {
+ this.bufferSize = bufferSize;
+ }
}
diff --git a/src/com/itmill/toolkit/terminal/ErrorMessage.java b/src/com/itmill/toolkit/terminal/ErrorMessage.java
index d26c1c74a4..4153ca220a 100644
--- a/src/com/itmill/toolkit/terminal/ErrorMessage.java
+++ b/src/com/itmill/toolkit/terminal/ErrorMessage.java
@@ -39,64 +39,64 @@ package com.itmill.toolkit.terminal;
*/
public interface ErrorMessage extends Paintable {
- /**
- * Error code for system errors and bugs.
- */
- public static final int SYSTEMERROR = 5000;
-
- /**
- * Error code for critical error messages.
- */
- public static final int CRITICAL = 4000;
-
- /**
- * Error code for regular error messages.
- */
- public static final int ERROR = 3000;
-
- /**
- * Error code for warning messages.
- */
- public static final int WARNING = 2000;
-
- /**
- * Error code for informational messages.
- */
- public static final int INFORMATION = 1000;
-
- /**
- * Gets the errors level.
- *
- * @return the level of error as an integer.
- */
- public int getErrorLevel();
-
- /**
- * Error messages are inmodifiable and thus listeners are not needed. This
- * method should be implemented as empty.
- *
- * @param listener
- * the listener to be added.
- * @see com.itmill.toolkit.terminal.Paintable#addListener(Paintable.RepaintRequestListener)
- */
- public void addListener(RepaintRequestListener listener);
-
- /**
- * Error messages are inmodifiable and thus listeners are not needed. This
- * method should be implemented as empty.
- *
- * @param listener
- * the listener to be removed.
- * @see com.itmill.toolkit.terminal.Paintable#removeListener(Paintable.RepaintRequestListener)
- */
- public void removeListener(RepaintRequestListener listener);
-
- /**
- * Error messages are inmodifiable and thus listeners are not needed. This
- * method should be implemented as empty.
- *
- * @see com.itmill.toolkit.terminal.Paintable#requestRepaint()
- */
- public void requestRepaint();
+ /**
+ * Error code for system errors and bugs.
+ */
+ public static final int SYSTEMERROR = 5000;
+
+ /**
+ * Error code for critical error messages.
+ */
+ public static final int CRITICAL = 4000;
+
+ /**
+ * Error code for regular error messages.
+ */
+ public static final int ERROR = 3000;
+
+ /**
+ * Error code for warning messages.
+ */
+ public static final int WARNING = 2000;
+
+ /**
+ * Error code for informational messages.
+ */
+ public static final int INFORMATION = 1000;
+
+ /**
+ * Gets the errors level.
+ *
+ * @return the level of error as an integer.
+ */
+ public int getErrorLevel();
+
+ /**
+ * Error messages are inmodifiable and thus listeners are not needed. This
+ * method should be implemented as empty.
+ *
+ * @param listener
+ * the listener to be added.
+ * @see com.itmill.toolkit.terminal.Paintable#addListener(Paintable.RepaintRequestListener)
+ */
+ public void addListener(RepaintRequestListener listener);
+
+ /**
+ * Error messages are inmodifiable and thus listeners are not needed. This
+ * method should be implemented as empty.
+ *
+ * @param listener
+ * the listener to be removed.
+ * @see com.itmill.toolkit.terminal.Paintable#removeListener(Paintable.RepaintRequestListener)
+ */
+ public void removeListener(RepaintRequestListener listener);
+
+ /**
+ * Error messages are inmodifiable and thus listeners are not needed. This
+ * method should be implemented as empty.
+ *
+ * @see com.itmill.toolkit.terminal.Paintable#requestRepaint()
+ */
+ public void requestRepaint();
}
diff --git a/src/com/itmill/toolkit/terminal/ExternalResource.java b/src/com/itmill/toolkit/terminal/ExternalResource.java
index 6509d44534..005e97217b 100644
--- a/src/com/itmill/toolkit/terminal/ExternalResource.java
+++ b/src/com/itmill/toolkit/terminal/ExternalResource.java
@@ -44,53 +44,55 @@ import com.itmill.toolkit.service.FileTypeResolver;
*/
public class ExternalResource implements Resource {
- /**
- * Url of the download.
- */
- private String sourceURL = null;
-
- /**
- * Creates a new download component for downloading directly from given URL.
- *
- * @param sourceURL
- * the source URL.
- */
- public ExternalResource(URL sourceURL) {
- if (sourceURL == null)
- throw new RuntimeException("Source must be non-null");
-
- this.sourceURL = sourceURL.toString();
- }
-
- /**
- * Creates a new download component for downloading directly from given URL.
- *
- * @param sourceURL
- * the source URL.
- */
- public ExternalResource(String sourceURL) {
- if (sourceURL == null)
- throw new RuntimeException("Source must be non-null");
-
- this.sourceURL = sourceURL.toString();
- }
-
- /**
- * Gets the URL of the external resource.
- *
- * @return the URL of the external resource.
- */
- public String getURL() {
- return sourceURL;
- }
-
- /**
- * Gets the MIME type of the resource.
- *
- * @see com.itmill.toolkit.terminal.Resource#getMIMEType()
- */
- public String getMIMEType() {
- return FileTypeResolver.getMIMEType(getURL().toString());
- }
+ /**
+ * Url of the download.
+ */
+ private String sourceURL = null;
+
+ /**
+ * Creates a new download component for downloading directly from given URL.
+ *
+ * @param sourceURL
+ * the source URL.
+ */
+ public ExternalResource(URL sourceURL) {
+ if (sourceURL == null) {
+ throw new RuntimeException("Source must be non-null");
+ }
+
+ this.sourceURL = sourceURL.toString();
+ }
+
+ /**
+ * Creates a new download component for downloading directly from given URL.
+ *
+ * @param sourceURL
+ * the source URL.
+ */
+ public ExternalResource(String sourceURL) {
+ if (sourceURL == null) {
+ throw new RuntimeException("Source must be non-null");
+ }
+
+ this.sourceURL = sourceURL.toString();
+ }
+
+ /**
+ * Gets the URL of the external resource.
+ *
+ * @return the URL of the external resource.
+ */
+ public String getURL() {
+ return sourceURL;
+ }
+
+ /**
+ * Gets the MIME type of the resource.
+ *
+ * @see com.itmill.toolkit.terminal.Resource#getMIMEType()
+ */
+ public String getMIMEType() {
+ return FileTypeResolver.getMIMEType(getURL().toString());
+ }
}
diff --git a/src/com/itmill/toolkit/terminal/FileResource.java b/src/com/itmill/toolkit/terminal/FileResource.java
index 2ca1332f08..800e63582b 100644
--- a/src/com/itmill/toolkit/terminal/FileResource.java
+++ b/src/com/itmill/toolkit/terminal/FileResource.java
@@ -48,131 +48,131 @@ import com.itmill.toolkit.service.FileTypeResolver;
*/
public class FileResource implements ApplicationResource {
- /**
- * Default buffer size for this stream resource.
- */
- private int bufferSize = 0;
-
- /**
- * File where the downloaded content is fetched from.
- */
- private File sourceFile;
-
- /**
- * Application.
- */
- private Application application;
-
- /**
- * Default cache time for this stream resource.
- */
- private long cacheTime = DownloadStream.DEFAULT_CACHETIME;
-
- /**
- * Creates a new file resource for providing given file for client
- * terminals.
- */
- public FileResource(File sourceFile, Application application) {
- this.application = application;
- setSourceFile(sourceFile);
- application.addResource(this);
- }
-
- /**
- * Gets the resource as stream.
- *
- * @see com.itmill.toolkit.terminal.ApplicationResource#getStream()
- */
- public DownloadStream getStream() {
- try {
- DownloadStream ds = new DownloadStream(new FileInputStream(
- this.sourceFile), getMIMEType(), getFilename());
- ds.setCacheTime(cacheTime);
- return ds;
- } catch (FileNotFoundException e) {
- // No logging for non-existing files at this level.
- return null;
- }
- }
-
- /**
- * Gets the source file.
- *
- * @return the source File.
- */
- public File getSourceFile() {
- return sourceFile;
- }
-
- /**
- * Sets the source file.
- *
- * @param sourceFile
- * the source file to set.
- */
- public void setSourceFile(File sourceFile) {
- this.sourceFile = sourceFile;
- }
-
- /**
- * @see com.itmill.toolkit.terminal.ApplicationResource#getApplication()
- */
- public Application getApplication() {
- return application;
- }
-
- /**
- * @see com.itmill.toolkit.terminal.ApplicationResource#getFilename()
- */
- public String getFilename() {
- return sourceFile.getName();
- }
-
- /**
- * @see com.itmill.toolkit.terminal.Resource#getMIMEType()
- */
- public String getMIMEType() {
- return FileTypeResolver.getMIMEType(sourceFile);
- }
-
- /**
- * Gets the length of cache expiration time. This gives the adapter the
- * possibility cache streams sent to the client. The caching may be made in
- * adapter or at the client if the client supports caching. Default is
- * DownloadStream.DEFAULT_CACHETIME
.
- *
- * @return Cache time in milliseconds.
- */
- public long getCacheTime() {
- return cacheTime;
- }
-
- /**
- * Sets the length of cache expiration time. This gives the adapter the
- * possibility cache streams sent to the client. The caching may be made in
- * adapter or at the client if the client supports caching. Zero or negavive
- * value disbales the caching of this stream.
- *
- * @param cacheTime
- * the cache time in milliseconds.
- */
- public void setCacheTime(long cacheTime) {
- this.cacheTime = cacheTime;
- }
-
- /* documented in superclass */
- public int getBufferSize() {
- return bufferSize;
- }
-
- /**
- * Sets the size of the download buffer used for this resource.
- *
- * @param bufferSize
- * the size of the buffer in bytes.
- */
- public void setBufferSize(int bufferSize) {
- this.bufferSize = bufferSize;
- }
+ /**
+ * Default buffer size for this stream resource.
+ */
+ private int bufferSize = 0;
+
+ /**
+ * File where the downloaded content is fetched from.
+ */
+ private File sourceFile;
+
+ /**
+ * Application.
+ */
+ private Application application;
+
+ /**
+ * Default cache time for this stream resource.
+ */
+ private long cacheTime = DownloadStream.DEFAULT_CACHETIME;
+
+ /**
+ * Creates a new file resource for providing given file for client
+ * terminals.
+ */
+ public FileResource(File sourceFile, Application application) {
+ this.application = application;
+ setSourceFile(sourceFile);
+ application.addResource(this);
+ }
+
+ /**
+ * Gets the resource as stream.
+ *
+ * @see com.itmill.toolkit.terminal.ApplicationResource#getStream()
+ */
+ public DownloadStream getStream() {
+ try {
+ DownloadStream ds = new DownloadStream(new FileInputStream(
+ sourceFile), getMIMEType(), getFilename());
+ ds.setCacheTime(cacheTime);
+ return ds;
+ } catch (FileNotFoundException e) {
+ // No logging for non-existing files at this level.
+ return null;
+ }
+ }
+
+ /**
+ * Gets the source file.
+ *
+ * @return the source File.
+ */
+ public File getSourceFile() {
+ return sourceFile;
+ }
+
+ /**
+ * Sets the source file.
+ *
+ * @param sourceFile
+ * the source file to set.
+ */
+ public void setSourceFile(File sourceFile) {
+ this.sourceFile = sourceFile;
+ }
+
+ /**
+ * @see com.itmill.toolkit.terminal.ApplicationResource#getApplication()
+ */
+ public Application getApplication() {
+ return application;
+ }
+
+ /**
+ * @see com.itmill.toolkit.terminal.ApplicationResource#getFilename()
+ */
+ public String getFilename() {
+ return sourceFile.getName();
+ }
+
+ /**
+ * @see com.itmill.toolkit.terminal.Resource#getMIMEType()
+ */
+ public String getMIMEType() {
+ return FileTypeResolver.getMIMEType(sourceFile);
+ }
+
+ /**
+ * Gets the length of cache expiration time. This gives the adapter the
+ * possibility cache streams sent to the client. The caching may be made in
+ * adapter or at the client if the client supports caching. Default is
+ * DownloadStream.DEFAULT_CACHETIME
.
+ *
+ * @return Cache time in milliseconds.
+ */
+ public long getCacheTime() {
+ return cacheTime;
+ }
+
+ /**
+ * Sets the length of cache expiration time. This gives the adapter the
+ * possibility cache streams sent to the client. The caching may be made in
+ * adapter or at the client if the client supports caching. Zero or negavive
+ * value disbales the caching of this stream.
+ *
+ * @param cacheTime
+ * the cache time in milliseconds.
+ */
+ public void setCacheTime(long cacheTime) {
+ this.cacheTime = cacheTime;
+ }
+
+ /* documented in superclass */
+ public int getBufferSize() {
+ return bufferSize;
+ }
+
+ /**
+ * Sets the size of the download buffer used for this resource.
+ *
+ * @param bufferSize
+ * the size of the buffer in bytes.
+ */
+ public void setBufferSize(int bufferSize) {
+ this.bufferSize = bufferSize;
+ }
}
diff --git a/src/com/itmill/toolkit/terminal/KeyMapper.java b/src/com/itmill/toolkit/terminal/KeyMapper.java
index 59967f2d32..16460de64c 100644
--- a/src/com/itmill/toolkit/terminal/KeyMapper.java
+++ b/src/com/itmill/toolkit/terminal/KeyMapper.java
@@ -41,83 +41,85 @@ import java.util.Hashtable;
*/
public class KeyMapper {
- private int lastKey = 0;
-
- private Hashtable objectKeyMap = new Hashtable();
-
- private Hashtable keyObjectMap = new Hashtable();
-
- /**
- * Gets key for an object.
- *
- * @param o
- * the object.
- */
- public String key(Object o) {
-
- if (o == null)
- return "null";
-
- // If the object is already mapped, use existing key
- String key = (String) objectKeyMap.get(o);
- if (key != null)
- return key;
-
- // If the object is not yet mapped, map it
- key = String.valueOf(++lastKey);
- objectKeyMap.put(o, key);
- keyObjectMap.put(key, o);
-
- return key;
- }
-
- /**
- * Checks if the key belongs to a new id.
- *
- * Usage of new id:s are specific to components, but for example Select
- * component uses newItemId:s for selection of newly added items in
- * allowNewItems
-mode.
- *
- * @param key
- * @return true
if the key belongs to the new id,otherwise
- * false
.
- */
- public boolean isNewIdKey(String key) {
- return "NEW".equals(key);
- }
-
- /**
- * Retrieves object with the key.
- *
- * @param key
- * the name with the desired value.
- * @return the object with the key.
- */
- public Object get(String key) {
-
- return keyObjectMap.get(key);
- }
-
- /**
- * Removes object from the mapper.
- *
- * @param removeobj
- * the object to be removed.
- */
- public void remove(Object removeobj) {
- String key = (String) objectKeyMap.get(removeobj);
-
- if (key != null) {
- objectKeyMap.remove(key);
- keyObjectMap.remove(removeobj);
- }
- }
-
- /**
- * Removes all objects from the mapper.
- */
- public void removeAll() {
- objectKeyMap.clear();
- keyObjectMap.clear();
- }
+ private int lastKey = 0;
+
+ private Hashtable objectKeyMap = new Hashtable();
+
+ private Hashtable keyObjectMap = new Hashtable();
+
+ /**
+ * Gets key for an object.
+ *
+ * @param o
+ * the object.
+ */
+ public String key(Object o) {
+
+ if (o == null) {
+ return "null";
+ }
+
+ // If the object is already mapped, use existing key
+ String key = (String) objectKeyMap.get(o);
+ if (key != null) {
+ return key;
+ }
+
+ // If the object is not yet mapped, map it
+ key = String.valueOf(++lastKey);
+ objectKeyMap.put(o, key);
+ keyObjectMap.put(key, o);
+
+ return key;
+ }
+
+ /**
+ * Checks if the key belongs to a new id.
+ *
+ * Usage of new id:s are specific to components, but for example Select
+ * component uses newItemId:s for selection of newly added items in
+ * allowNewItems
-mode.
+ *
+ * @param key
+ * @return true
if the key belongs to the new id,otherwise
+ * false
.
+ */
+ public boolean isNewIdKey(String key) {
+ return "NEW".equals(key);
+ }
+
+ /**
+ * Retrieves object with the key.
+ *
+ * @param key
+ * the name with the desired value.
+ * @return the object with the key.
+ */
+ public Object get(String key) {
+
+ return keyObjectMap.get(key);
+ }
+
+ /**
+ * Removes object from the mapper.
+ *
+ * @param removeobj
+ * the object to be removed.
+ */
+ public void remove(Object removeobj) {
+ String key = (String) objectKeyMap.get(removeobj);
+
+ if (key != null) {
+ objectKeyMap.remove(key);
+ keyObjectMap.remove(removeobj);
+ }
+ }
+
+ /**
+ * Removes all objects from the mapper.
+ */
+ public void removeAll() {
+ objectKeyMap.clear();
+ keyObjectMap.clear();
+ }
}
diff --git a/src/com/itmill/toolkit/terminal/PaintException.java b/src/com/itmill/toolkit/terminal/PaintException.java
index 8d49ebc41e..2830e762a5 100644
--- a/src/com/itmill/toolkit/terminal/PaintException.java
+++ b/src/com/itmill/toolkit/terminal/PaintException.java
@@ -40,30 +40,30 @@ import java.io.IOException;
*/
public class PaintException extends IOException {
- /**
- * Serial generated by eclipse.
- */
- private static final long serialVersionUID = 3762535607221891897L;
+ /**
+ * Serial generated by eclipse.
+ */
+ private static final long serialVersionUID = 3762535607221891897L;
- /**
- * Constructs an instance of PaintExeception
with the
- * specified detail message.
- *
- * @param msg
- * the detail message.
- */
- public PaintException(String msg) {
- super(msg);
- }
+ /**
+ * Constructs an instance of PaintExeception
with the
+ * specified detail message.
+ *
+ * @param msg
+ * the detail message.
+ */
+ public PaintException(String msg) {
+ super(msg);
+ }
- /**
- * Constructs an instance of PaintExeception
from
- * IOException.
- *
- * @param exception
- * the original exception.
- */
- public PaintException(IOException exception) {
- super(exception.getMessage());
- }
+ /**
+ * Constructs an instance of PaintExeception
from
+ * IOException.
+ *
+ * @param exception
+ * the original exception.
+ */
+ public PaintException(IOException exception) {
+ super(exception.getMessage());
+ }
}
diff --git a/src/com/itmill/toolkit/terminal/PaintTarget.java b/src/com/itmill/toolkit/terminal/PaintTarget.java
index c0736d6c97..e7760c9e7f 100644
--- a/src/com/itmill/toolkit/terminal/PaintTarget.java
+++ b/src/com/itmill/toolkit/terminal/PaintTarget.java
@@ -38,349 +38,349 @@ package com.itmill.toolkit.terminal;
*/
public interface PaintTarget {
- /**
- * Prints single XMLsection.
- *
- * Prints full XML section. The section data is escaped from XML tags and
- * surrounded by XML start and end-tags.
- *
- * @param sectionTagName
- * the name of the tag.
- * @param sectionData
- * the scetion data.
- * @throws PaintException
- * if the paint operation failed.
- */
- public void addSection(String sectionTagName, String sectionData)
- throws PaintException;
+ /**
+ * Prints single XMLsection.
+ *
+ * Prints full XML section. The section data is escaped from XML tags and
+ * surrounded by XML start and end-tags.
+ *
+ * @param sectionTagName
+ * the name of the tag.
+ * @param sectionData
+ * the scetion data.
+ * @throws PaintException
+ * if the paint operation failed.
+ */
+ public void addSection(String sectionTagName, String sectionData)
+ throws PaintException;
- /**
- * Prints element start tag of a paintable section. Starts a paintable
- * section using the given tag. The PaintTarget may implement a caching
- * scheme, that checks the paintable has actually changed or can a cached
- * version be used instead. This method should call the startTag method.
- *
- * If the Paintable is found in cache and this function returns true it may
- * omit the content and close the tag, in which case cached content should
- * be used.
- *
- *
- * @param paintable
- * the paintable to start.
- * @param tag
- * the name of the start tag.
- * @return true
if paintable found in cache,
- * false
otherwise.
- * @throws PaintException
- * if the paint operation failed.
- * @see #startTag(String)
- * @since 3.1
- */
- public boolean startTag(Paintable paintable, String tag)
- throws PaintException;
+ /**
+ * Prints element start tag of a paintable section. Starts a paintable
+ * section using the given tag. The PaintTarget may implement a caching
+ * scheme, that checks the paintable has actually changed or can a cached
+ * version be used instead. This method should call the startTag method.
+ *
+ * If the Paintable is found in cache and this function returns true it may
+ * omit the content and close the tag, in which case cached content should
+ * be used.
+ *
+ *
+ * @param paintable
+ * the paintable to start.
+ * @param tag
+ * the name of the start tag.
+ * @return true
if paintable found in cache,
+ * false
otherwise.
+ * @throws PaintException
+ * if the paint operation failed.
+ * @see #startTag(String)
+ * @since 3.1
+ */
+ public boolean startTag(Paintable paintable, String tag)
+ throws PaintException;
- /**
- * Prints element start tag.
- *
- *
- * Todo:
- * Checking of input values
- *
- *
- * @param tagName
- * the name of the start tag.
- * @throws PaintException
- * if the paint operation failed.
- */
- public void startTag(String tagName) throws PaintException;
+ /**
+ * Prints element start tag.
+ *
+ *
+ * Todo:
+ * Checking of input values
+ *
+ *
+ * @param tagName
+ * the name of the start tag.
+ * @throws PaintException
+ * if the paint operation failed.
+ */
+ public void startTag(String tagName) throws PaintException;
- /**
- * Prints element end tag.
- *
- * If the parent tag is closed before every child tag is closed an
- * PaintException is raised.
- *
- * @param tagName
- * the name of the end tag.
- * @throws PaintException
- * if the paint operation failed.
- */
- public void endTag(String tagName) throws PaintException;
+ /**
+ * Prints element end tag.
+ *
+ * If the parent tag is closed before every child tag is closed an
+ * PaintException is raised.
+ *
+ * @param tagName
+ * the name of the end tag.
+ * @throws PaintException
+ * if the paint operation failed.
+ */
+ public void endTag(String tagName) throws PaintException;
- /**
- * Adds a boolean attribute to component. Atributes must be added before any
- * content is written.
- *
- * @param name
- * the Attribute name.
- * @param value
- * the Attribute value.
- *
- * @throws PaintException
- * if the paint operation failed.
- */
- public void addAttribute(String name, boolean value) throws PaintException;
+ /**
+ * Adds a boolean attribute to component. Atributes must be added before any
+ * content is written.
+ *
+ * @param name
+ * the Attribute name.
+ * @param value
+ * the Attribute value.
+ *
+ * @throws PaintException
+ * if the paint operation failed.
+ */
+ public void addAttribute(String name, boolean value) throws PaintException;
- /**
- * Adds a integer attribute to component. Atributes must be added before any
- * content is written.
- *
- * @param name
- * the Attribute name.
- * @param value
- * the Attribute value.
- *
- * @throws PaintException
- * if the paint operation failed.
- */
- public void addAttribute(String name, int value) throws PaintException;
+ /**
+ * Adds a integer attribute to component. Atributes must be added before any
+ * content is written.
+ *
+ * @param name
+ * the Attribute name.
+ * @param value
+ * the Attribute value.
+ *
+ * @throws PaintException
+ * if the paint operation failed.
+ */
+ public void addAttribute(String name, int value) throws PaintException;
- /**
- * Adds a resource attribute to component. Atributes must be added before
- * any content is written.
- *
- * @param name
- * the Attribute name
- * @param value
- * the Attribute value
- *
- * @throws PaintException
- * if the paint operation failed.
- */
- public void addAttribute(String name, Resource value) throws PaintException;
+ /**
+ * Adds a resource attribute to component. Atributes must be added before
+ * any content is written.
+ *
+ * @param name
+ * the Attribute name
+ * @param value
+ * the Attribute value
+ *
+ * @throws PaintException
+ * if the paint operation failed.
+ */
+ public void addAttribute(String name, Resource value) throws PaintException;
- /**
- * Adds a long attribute to component. Atributes must be added before any
- * content is written.
- *
- * @param name
- * the Attribute name.
- * @param value
- * the Attribute value.
- *
- * @throws PaintException
- * if the paint operation failed.
- */
- public void addAttribute(String name, long value) throws PaintException;
+ /**
+ * Adds a long attribute to component. Atributes must be added before any
+ * content is written.
+ *
+ * @param name
+ * the Attribute name.
+ * @param value
+ * the Attribute value.
+ *
+ * @throws PaintException
+ * if the paint operation failed.
+ */
+ public void addAttribute(String name, long value) throws PaintException;
- /**
- * Adds a float attribute to component. Atributes must be added before any
- * content is written.
- *
- * @param name
- * the Attribute name.
- * @param value
- * the Attribute value.
- *
- * @throws PaintException
- * if the paint operation failed.
- */
- public void addAttribute(String name, float value) throws PaintException;
+ /**
+ * Adds a float attribute to component. Atributes must be added before any
+ * content is written.
+ *
+ * @param name
+ * the Attribute name.
+ * @param value
+ * the Attribute value.
+ *
+ * @throws PaintException
+ * if the paint operation failed.
+ */
+ public void addAttribute(String name, float value) throws PaintException;
- /**
- * Adds a double attribute to component. Atributes must be added before any
- * content is written.
- *
- * @param name
- * the Attribute name.
- * @param value
- * the Attribute value.
- *
- * @throws PaintException
- * if the paint operation failed.
- */
- public void addAttribute(String name, double value) throws PaintException;
+ /**
+ * Adds a double attribute to component. Atributes must be added before any
+ * content is written.
+ *
+ * @param name
+ * the Attribute name.
+ * @param value
+ * the Attribute value.
+ *
+ * @throws PaintException
+ * if the paint operation failed.
+ */
+ public void addAttribute(String name, double value) throws PaintException;
- /**
- * Adds a string attribute to component. Atributes must be added before any
- * content is written.
- *
- * @param name
- * the Boolean attribute name.
- * @param value
- * the Boolean attribute value.
- *
- * @throws PaintException
- * if the paint operation failed.
- */
- public void addAttribute(String name, String value) throws PaintException;
+ /**
+ * Adds a string attribute to component. Atributes must be added before any
+ * content is written.
+ *
+ * @param name
+ * the Boolean attribute name.
+ * @param value
+ * the Boolean attribute value.
+ *
+ * @throws PaintException
+ * if the paint operation failed.
+ */
+ public void addAttribute(String name, String value) throws PaintException;
- /**
- * Adds a string type variable.
- *
- * @param owner
- * the Listener for variable changes.
- * @param name
- * the Variable name.
- * @param value
- * the Variable initial value.
- *
- * @throws PaintException
- * if the paint operation failed.
- */
- public void addVariable(VariableOwner owner, String name, String value)
- throws PaintException;
+ /**
+ * Adds a string type variable.
+ *
+ * @param owner
+ * the Listener for variable changes.
+ * @param name
+ * the Variable name.
+ * @param value
+ * the Variable initial value.
+ *
+ * @throws PaintException
+ * if the paint operation failed.
+ */
+ public void addVariable(VariableOwner owner, String name, String value)
+ throws PaintException;
- /**
- * Adds a int type variable.
- *
- * @param owner
- * the Listener for variable changes.
- * @param name
- * the Variable name.
- * @param value
- * the Variable initial value.
- *
- * @throws PaintException
- * if the paint operation failed.
- */
- public void addVariable(VariableOwner owner, String name, int value)
- throws PaintException;
+ /**
+ * Adds a int type variable.
+ *
+ * @param owner
+ * the Listener for variable changes.
+ * @param name
+ * the Variable name.
+ * @param value
+ * the Variable initial value.
+ *
+ * @throws PaintException
+ * if the paint operation failed.
+ */
+ public void addVariable(VariableOwner owner, String name, int value)
+ throws PaintException;
- /**
- * Adds a long type variable.
- *
- * @param owner
- * the Listener for variable changes.
- * @param name
- * the Variable name.
- * @param value
- * the Variable initial value.
- *
- * @throws PaintException
- * if the paint operation failed.
- */
- public void addVariable(VariableOwner owner, String name, long value)
- throws PaintException;
+ /**
+ * Adds a long type variable.
+ *
+ * @param owner
+ * the Listener for variable changes.
+ * @param name
+ * the Variable name.
+ * @param value
+ * the Variable initial value.
+ *
+ * @throws PaintException
+ * if the paint operation failed.
+ */
+ public void addVariable(VariableOwner owner, String name, long value)
+ throws PaintException;
- /**
- * Adds a float type variable.
- *
- * @param owner
- * the Listener for variable changes.
- * @param name
- * the Variable name.
- * @param value
- * the Variable initial value.
- *
- * @throws PaintException
- * if the paint operation failed.
- */
- public void addVariable(VariableOwner owner, String name, float value)
- throws PaintException;
+ /**
+ * Adds a float type variable.
+ *
+ * @param owner
+ * the Listener for variable changes.
+ * @param name
+ * the Variable name.
+ * @param value
+ * the Variable initial value.
+ *
+ * @throws PaintException
+ * if the paint operation failed.
+ */
+ public void addVariable(VariableOwner owner, String name, float value)
+ throws PaintException;
- /**
- * Adds a double type variable.
- *
- * @param owner
- * the Listener for variable changes.
- * @param name
- * the Variable name.
- * @param value
- * the Variable initial value.
- *
- * @throws PaintException
- * if the paint operation failed.
- */
- public void addVariable(VariableOwner owner, String name, double value)
- throws PaintException;
+ /**
+ * Adds a double type variable.
+ *
+ * @param owner
+ * the Listener for variable changes.
+ * @param name
+ * the Variable name.
+ * @param value
+ * the Variable initial value.
+ *
+ * @throws PaintException
+ * if the paint operation failed.
+ */
+ public void addVariable(VariableOwner owner, String name, double value)
+ throws PaintException;
- /**
- * Adds a boolean type variable.
- *
- * @param owner
- * the Listener for variable changes.
- * @param name
- * the Variable name.
- * @param value
- * the Variable initial value.
- *
- * @throws PaintException
- * if the paint operation failed.
- */
- public void addVariable(VariableOwner owner, String name, boolean value)
- throws PaintException;
+ /**
+ * Adds a boolean type variable.
+ *
+ * @param owner
+ * the Listener for variable changes.
+ * @param name
+ * the Variable name.
+ * @param value
+ * the Variable initial value.
+ *
+ * @throws PaintException
+ * if the paint operation failed.
+ */
+ public void addVariable(VariableOwner owner, String name, boolean value)
+ throws PaintException;
- /**
- * Adds a string array type variable.
- *
- * @param owner
- * the Listener for variable changes.
- * @param name
- * the Variable name.
- * @param value
- * the Variable initial value.
- *
- * @throws PaintException
- * if the paint operation failed.
- */
- public void addVariable(VariableOwner owner, String name, String[] value)
- throws PaintException;
+ /**
+ * Adds a string array type variable.
+ *
+ * @param owner
+ * the Listener for variable changes.
+ * @param name
+ * the Variable name.
+ * @param value
+ * the Variable initial value.
+ *
+ * @throws PaintException
+ * if the paint operation failed.
+ */
+ public void addVariable(VariableOwner owner, String name, String[] value)
+ throws PaintException;
- /**
- * Adds a upload stream type variable.
- *
- * @param owner
- * the Listener for variable changes.
- * @param name
- * the Variable name.
- *
- * @throws PaintException
- * if the paint operation failed.
- */
- public void addUploadStreamVariable(VariableOwner owner, String name)
- throws PaintException;
+ /**
+ * Adds a upload stream type variable.
+ *
+ * @param owner
+ * the Listener for variable changes.
+ * @param name
+ * the Variable name.
+ *
+ * @throws PaintException
+ * if the paint operation failed.
+ */
+ public void addUploadStreamVariable(VariableOwner owner, String name)
+ throws PaintException;
- /**
- * Prints single XML section.
- *
- * Prints full XML section. The section data must be XML and it is
- * surrounded by XML start and end-tags.
- *
- *
- * @param sectionTagName
- * the tag name.
- * @param sectionData
- * the section data to be printed.
- * @param namespace
- * the namespace.
- * @throws PaintException
- * if the paint operation failed.
- */
- public void addXMLSection(String sectionTagName, String sectionData,
- String namespace) throws PaintException;
+ /**
+ * Prints single XML section.
+ *
+ * Prints full XML section. The section data must be XML and it is
+ * surrounded by XML start and end-tags.
+ *
+ *
+ * @param sectionTagName
+ * the tag name.
+ * @param sectionData
+ * the section data to be printed.
+ * @param namespace
+ * the namespace.
+ * @throws PaintException
+ * if the paint operation failed.
+ */
+ public void addXMLSection(String sectionTagName, String sectionData,
+ String namespace) throws PaintException;
- /**
- * Adds UIDL directly. The UIDL must be valid in accordance with the
- * UIDL.dtd
- *
- * @param uidl
- * the UIDL to be added.
- * @throws PaintException
- * if the paint operation failed.
- */
- public void addUIDL(java.lang.String uidl) throws PaintException;
+ /**
+ * Adds UIDL directly. The UIDL must be valid in accordance with the
+ * UIDL.dtd
+ *
+ * @param uidl
+ * the UIDL to be added.
+ * @throws PaintException
+ * if the paint operation failed.
+ */
+ public void addUIDL(java.lang.String uidl) throws PaintException;
- /**
- * Adds text node. All the contents of the text are XML-escaped.
- *
- * @param text
- * the Text to add
- * @throws PaintException
- * if the paint operation failed.
- */
- void addText(String text) throws PaintException;
+ /**
+ * Adds text node. All the contents of the text are XML-escaped.
+ *
+ * @param text
+ * the Text to add
+ * @throws PaintException
+ * if the paint operation failed.
+ */
+ void addText(String text) throws PaintException;
- /**
- * Adds CDATA node to target UIDL-tree.
- *
- * @param text
- * the Character data to add
- * @throws PaintException
- * if the paint operation failed.
- * @since 3.1
- */
- void addCharacterData(String text) throws PaintException;
+ /**
+ * Adds CDATA node to target UIDL-tree.
+ *
+ * @param text
+ * the Character data to add
+ * @throws PaintException
+ * if the paint operation failed.
+ * @since 3.1
+ */
+ void addCharacterData(String text) throws PaintException;
- public void addAttribute(String string, Object[] keys);
+ public void addAttribute(String string, Object[] keys);
}
diff --git a/src/com/itmill/toolkit/terminal/Paintable.java b/src/com/itmill/toolkit/terminal/Paintable.java
index 29e01e0bf5..3c89923632 100644
--- a/src/com/itmill/toolkit/terminal/Paintable.java
+++ b/src/com/itmill/toolkit/terminal/Paintable.java
@@ -42,111 +42,112 @@ import java.util.EventObject;
*/
public interface Paintable extends java.util.EventListener {
- /**
- *
- * Paints the paintable into a UIDL stream. This method creates the UIDL
- * sequence describing it and outputs it to the given UIDL stream.
- *
- *
- *
- * It is called when the contents of the component should be painted in
- * response to the component first being shown or having been altered so
- * that its visual representation is changed.
- *
- *
- * @param target
- * the target UIDL stream where the component should paint itself
- * to.
- * @throws PaintException
- * if the paint operation failed.
- */
- public void paint(PaintTarget target) throws PaintException;
-
- /**
- * Requests that the paintable should be repainted as soon as possible.
- */
- public void requestRepaint();
-
- /**
- * Repaint request event is thrown when the paintable needs to be repainted.
- * This is typically done when the paint
method would return
- * dissimilar UIDL from the previous call of the method.
- */
- public class RepaintRequestEvent extends EventObject {
-
- /**
- * Serial generated by eclipse.
- */
- private static final long serialVersionUID = 3256725095530442805L;
-
- /**
- * Constructs a new event.
- *
- * @param source
- * the paintable needing repaint.
- */
- public RepaintRequestEvent(Paintable source) {
- super(source);
- }
-
- /**
- * Gets the paintable needing repainting.
- *
- * @return Paintable for which the paint
method will
- * return dissimilar UIDL from the previous call of the method.
- */
- public Paintable getPaintable() {
- return (Paintable) getSource();
- }
- }
-
- /**
- * Listens repaint requests. The repaintRequested
method is
- * called when the paintable needs to be repainted. This is typically done
- * when the paint
method would return dissimilar UIDL from
- * the previous call of the method.
- */
- public interface RepaintRequestListener {
-
- /**
- * Receives repaint request events.
- *
- * @param event
- * the repaint request event specifying the paintable source.
- */
- public void repaintRequested(RepaintRequestEvent event);
- }
-
- /**
- * Adds repaint request listener. In order to assure that no repaint
- * requests are missed, the new repaint listener should paint the paintable
- * right after adding itself as listener.
- *
- * @param listener
- * the listener to be added.
- */
- public void addListener(RepaintRequestListener listener);
-
- /**
- * Removes repaint request listener.
- *
- * @param listener
- * the listener to be removed.
- */
- public void removeListener(RepaintRequestListener listener);
-
- /**
- * Request sending of repaint events on any further visible changes.
- * Normally the paintable only send up to one repaint request for listeners
- * after paint as the paintable as the paintable assumes that the listeners
- * already know about the repaint need. This method resets the assumtion.
- * Paint implicitly does the assumtion reset functionality implemented by
- * this method.
- *
- * This method is normally used only by the terminals to note paintables
- * about implicit repaints (painting the component without actually invoking
- * paint method).
- *
- */
- public void requestRepaintRequests();
+ /**
+ *
+ * Paints the paintable into a UIDL stream. This method creates the UIDL
+ * sequence describing it and outputs it to the given UIDL stream.
+ *
+ *
+ *
+ * It is called when the contents of the component should be painted in
+ * response to the component first being shown or having been altered so
+ * that its visual representation is changed.
+ *
+ *
+ * @param target
+ * the target UIDL stream where the component should paint
+ * itself to.
+ * @throws PaintException
+ * if the paint operation failed.
+ */
+ public void paint(PaintTarget target) throws PaintException;
+
+ /**
+ * Requests that the paintable should be repainted as soon as possible.
+ */
+ public void requestRepaint();
+
+ /**
+ * Repaint request event is thrown when the paintable needs to be repainted.
+ * This is typically done when the paint
method would return
+ * dissimilar UIDL from the previous call of the method.
+ */
+ public class RepaintRequestEvent extends EventObject {
+
+ /**
+ * Serial generated by eclipse.
+ */
+ private static final long serialVersionUID = 3256725095530442805L;
+
+ /**
+ * Constructs a new event.
+ *
+ * @param source
+ * the paintable needing repaint.
+ */
+ public RepaintRequestEvent(Paintable source) {
+ super(source);
+ }
+
+ /**
+ * Gets the paintable needing repainting.
+ *
+ * @return Paintable for which the paint
method will
+ * return dissimilar UIDL from the previous call of the method.
+ */
+ public Paintable getPaintable() {
+ return (Paintable) getSource();
+ }
+ }
+
+ /**
+ * Listens repaint requests. The repaintRequested
method is
+ * called when the paintable needs to be repainted. This is typically done
+ * when the paint
method would return dissimilar UIDL from
+ * the previous call of the method.
+ */
+ public interface RepaintRequestListener {
+
+ /**
+ * Receives repaint request events.
+ *
+ * @param event
+ * the repaint request event specifying the paintable
+ * source.
+ */
+ public void repaintRequested(RepaintRequestEvent event);
+ }
+
+ /**
+ * Adds repaint request listener. In order to assure that no repaint
+ * requests are missed, the new repaint listener should paint the paintable
+ * right after adding itself as listener.
+ *
+ * @param listener
+ * the listener to be added.
+ */
+ public void addListener(RepaintRequestListener listener);
+
+ /**
+ * Removes repaint request listener.
+ *
+ * @param listener
+ * the listener to be removed.
+ */
+ public void removeListener(RepaintRequestListener listener);
+
+ /**
+ * Request sending of repaint events on any further visible changes.
+ * Normally the paintable only send up to one repaint request for listeners
+ * after paint as the paintable as the paintable assumes that the listeners
+ * already know about the repaint need. This method resets the assumtion.
+ * Paint implicitly does the assumtion reset functionality implemented by
+ * this method.
+ *
+ * This method is normally used only by the terminals to note paintables
+ * about implicit repaints (painting the component without actually invoking
+ * paint method).
+ *
+ */
+ public void requestRepaintRequests();
}
diff --git a/src/com/itmill/toolkit/terminal/ParameterHandler.java b/src/com/itmill/toolkit/terminal/ParameterHandler.java
index 1f847ae1c0..8d8ab0ca17 100644
--- a/src/com/itmill/toolkit/terminal/ParameterHandler.java
+++ b/src/com/itmill/toolkit/terminal/ParameterHandler.java
@@ -50,32 +50,32 @@ import java.util.Map;
*/
public interface ParameterHandler {
- /**
- *
- * Handles the given parameters. The parameters are given as inmodifieable
- * name to value map. All parameters names are of type:
- * {@link java.lang.String}. All the parameter values are arrays of
- * strings.
- *
- *
- * @param parameters
- * the Inmodifiable name to value[] mapping.
- *
- */
- public void handleParameters(Map parameters);
+ /**
+ *
+ * Handles the given parameters. The parameters are given as inmodifieable
+ * name to value map. All parameters names are of type:
+ * {@link java.lang.String}. All the parameter values are arrays of
+ * strings.
+ *
+ *
+ * @param parameters
+ * the Inmodifiable name to value[] mapping.
+ *
+ */
+ public void handleParameters(Map parameters);
- /**
- * ParameterHandler error event.
- */
- public interface ErrorEvent extends Terminal.ErrorEvent {
+ /**
+ * ParameterHandler error event.
+ */
+ public interface ErrorEvent extends Terminal.ErrorEvent {
- /**
- * Gets the source ParameterHandler.
- *
- * @return the source Parameter Handler.
- */
- public ParameterHandler getParameterHandler();
+ /**
+ * Gets the source ParameterHandler.
+ *
+ * @return the source Parameter Handler.
+ */
+ public ParameterHandler getParameterHandler();
- }
+ }
}
diff --git a/src/com/itmill/toolkit/terminal/Resource.java b/src/com/itmill/toolkit/terminal/Resource.java
index 28578ee022..8dc86e2d86 100644
--- a/src/com/itmill/toolkit/terminal/Resource.java
+++ b/src/com/itmill/toolkit/terminal/Resource.java
@@ -39,10 +39,10 @@ package com.itmill.toolkit.terminal;
*/
public interface Resource {
- /**
- * Gets the MIME type of the resource.
- *
- * @return the MIME type of the resource.
- */
- public String getMIMEType();
+ /**
+ * Gets the MIME type of the resource.
+ *
+ * @return the MIME type of the resource.
+ */
+ public String getMIMEType();
}
diff --git a/src/com/itmill/toolkit/terminal/Scrollable.java b/src/com/itmill/toolkit/terminal/Scrollable.java
index de88dbce13..f320a4d2a8 100644
--- a/src/com/itmill/toolkit/terminal/Scrollable.java
+++ b/src/com/itmill/toolkit/terminal/Scrollable.java
@@ -41,80 +41,80 @@ package com.itmill.toolkit.terminal;
*/
public interface Scrollable {
- /**
- * Gets scroll X offset.
- *
- *
- * Scrolling offset is the number of pixels this scrollable has been
- * scrolled to left.
- *
- *
- * @return Horizontal scrolling position in pixels.
- */
- public int getScrollOffsetX();
+ /**
+ * Gets scroll X offset.
+ *
+ *
+ * Scrolling offset is the number of pixels this scrollable has been
+ * scrolled to left.
+ *
+ *
+ * @return Horizontal scrolling position in pixels.
+ */
+ public int getScrollOffsetX();
- /**
- * Sets scroll X offset.
- *
- *
- * Scrolling offset is the number of pixels this scrollable has been
- * scrolled to left.
- *
- *
- * @param pixelsScrolledLeft
- * the xOffset.
- */
- public void setScrollOffsetX(int pixelsScrolledLeft);
+ /**
+ * Sets scroll X offset.
+ *
+ *
+ * Scrolling offset is the number of pixels this scrollable has been
+ * scrolled to left.
+ *
+ *
+ * @param pixelsScrolledLeft
+ * the xOffset.
+ */
+ public void setScrollOffsetX(int pixelsScrolledLeft);
- /**
- * Gets scroll Y offset.
- *
- *
- * Scrolling offset is the number of pixels this scrollable has been
- * scrolled to down.
- *
- *
- * @return Vertical scrolling position in pixels.
- */
- public int getScrollOffsetY();
+ /**
+ * Gets scroll Y offset.
+ *
+ *
+ * Scrolling offset is the number of pixels this scrollable has been
+ * scrolled to down.
+ *
+ *
+ * @return Vertical scrolling position in pixels.
+ */
+ public int getScrollOffsetY();
- /**
- * Sets scroll Y offset.
- *
- *
- * Scrolling offset is the number of pixels this scrollable has been
- * scrolled to down.
- *
- *
- * @param pixelsScrolledDown
- * the yOffset.
- */
- public void setScrollOffsetY(int pixelsScrolledDown);
+ /**
+ * Sets scroll Y offset.
+ *
+ *
+ * Scrolling offset is the number of pixels this scrollable has been
+ * scrolled to down.
+ *
+ *
+ * @param pixelsScrolledDown
+ * the yOffset.
+ */
+ public void setScrollOffsetY(int pixelsScrolledDown);
- /**
- * Is the scrolling enabled.
- *
- *
- * Enabling scrolling allows the user to scroll the scrollable view
- * interactively
- *
- *
- * @return true
if the scrolling is allowed, otherwise
- * false
.
- */
- public boolean isScrollable();
+ /**
+ * Is the scrolling enabled.
+ *
+ *
+ * Enabling scrolling allows the user to scroll the scrollable view
+ * interactively
+ *
+ *
+ * @return true
if the scrolling is allowed, otherwise
+ * false
.
+ */
+ public boolean isScrollable();
- /**
- * Enables or disables scrolling..
- *
- *
- * Enabling scrolling allows the user to scroll the scrollable view
- * interactively
- *
- *
- * @param isScrollingEnabled
- * true if the scrolling is allowed.
- */
- public void setScrollable(boolean isScrollingEnabled);
+ /**
+ * Enables or disables scrolling..
+ *
+ *
+ * Enabling scrolling allows the user to scroll the scrollable view
+ * interactively
+ *
+ *
+ * @param isScrollingEnabled
+ * true if the scrolling is allowed.
+ */
+ public void setScrollable(boolean isScrollingEnabled);
}
diff --git a/src/com/itmill/toolkit/terminal/Sizeable.java b/src/com/itmill/toolkit/terminal/Sizeable.java
index 230440aa50..decacf3fa4 100644
--- a/src/com/itmill/toolkit/terminal/Sizeable.java
+++ b/src/com/itmill/toolkit/terminal/Sizeable.java
@@ -39,153 +39,153 @@ package com.itmill.toolkit.terminal;
*/
public interface Sizeable {
- /**
- * Unit code representing pixels.
- */
- public static final int UNITS_PIXELS = 0;
-
- /**
- * Unit code representing points (1/72nd of an inch).
- */
- public static final int UNITS_POINTS = 1;
-
- /**
- * Unit code representing picas (12 points).
- */
- public static final int UNITS_PICAS = 2;
-
- /**
- * Unit code representing the font-size of the relevant font.
- */
- public static final int UNITS_EM = 3;
-
- /**
- * Unit code representing the x-height of the relevant font.
- */
- public static final int UNITS_EX = 4;
-
- /**
- * Unit code representing millimetres.
- */
- public static final int UNITS_MM = 5;
-
- /**
- * Unit code representing centimetres.
- */
- public static final int UNITS_CM = 6;
-
- /**
- * Unit code representing inches.
- */
- public static final int UNITS_INCH = 7;
-
- /**
- * Unit code representing in percentage of the containing element defined by
- * terminal.
- */
- public static final int UNITS_PERCENTAGE = 8;
-
- /**
- * Unit code representing in rows of text. This unit is only applicaple to
- * some components can it's meaning is specified by component
- * implementation.
- */
- public static final int UNITS_ROWS = 9;
-
- /**
- * Textual representations of units symbols. Supported units and their
- * symbols are:
- *
- * UNITS_PIXELS
: "px"
- * UNITS_POINTS
: "pt"
- * UNITS_PICAS
: "pc"
- * UNITS_EM
: "em"
- * UNITS_EX
: "ex"
- * UNITS_MM
: "mm"
- * UNITS_CM
. "cm"
- * UNITS_INCH
: "in"
- * UNITS_PERCENTAGE
: "%"
- * UNITS_ROWS
: "rows"
- *
- * These can be used like Sizeable.UNIT_SYMBOLS[UNITS_PIXELS]
.
- */
- public static final String[] UNIT_SYMBOLS = { "px", "pt", "pc", "em", "ex",
- "mm", "cm", "in", "%", "rows" };
-
- /**
- * Gets the width of the object. Negative number implies unspecified size
- * (terminal is free to set the size).
- *
- * @return width of the object in units specified by widthUnits property.
- */
- public int getWidth();
-
- /**
- * Sets the width of the object. Negative number implies unspecified size
- * (terminal is free to set the size).
- *
- * @param width
- * the width of the object in units specified by widthUnits
- * property.
- */
- public void setWidth(int width);
-
- /**
- * Gets the height of the object. Negative number implies unspecified size
- * (terminal is free to set the size).
- *
- * @return height of the object in units specified by heightUnits property.
- */
- public int getHeight();
-
- /**
- * Sets the height of the object. Negative number implies unspecified size
- * (terminal is free to set the size).
- *
- * @param height
- * the height of the object in units specified by heightUnits
- * property.
- */
- public void setHeight(int height);
-
- /**
- * Gets the width property units.
- *
- * @return units used in width property.
- */
- public int getWidthUnits();
-
- /**
- * Sets the width property units.
- *
- * @param units
- * the units used in width property.
- */
- public void setWidthUnits(int units);
-
- /**
- * Gets the height property units.
- *
- * @return units used in height property.
- */
- public int getHeightUnits();
-
- /**
- * Sets the height property units.
- *
- * @param units
- * the units used in height property.
- */
- public void setHeightUnits(int units);
-
- /**
- * Sets the size to 100% x 100%.
- */
- public void setSizeFull();
-
- /**
- * Clears any size settings.
- */
- public void setSizeUndefined();
+ /**
+ * Unit code representing pixels.
+ */
+ public static final int UNITS_PIXELS = 0;
+
+ /**
+ * Unit code representing points (1/72nd of an inch).
+ */
+ public static final int UNITS_POINTS = 1;
+
+ /**
+ * Unit code representing picas (12 points).
+ */
+ public static final int UNITS_PICAS = 2;
+
+ /**
+ * Unit code representing the font-size of the relevant font.
+ */
+ public static final int UNITS_EM = 3;
+
+ /**
+ * Unit code representing the x-height of the relevant font.
+ */
+ public static final int UNITS_EX = 4;
+
+ /**
+ * Unit code representing millimetres.
+ */
+ public static final int UNITS_MM = 5;
+
+ /**
+ * Unit code representing centimetres.
+ */
+ public static final int UNITS_CM = 6;
+
+ /**
+ * Unit code representing inches.
+ */
+ public static final int UNITS_INCH = 7;
+
+ /**
+ * Unit code representing in percentage of the containing element defined by
+ * terminal.
+ */
+ public static final int UNITS_PERCENTAGE = 8;
+
+ /**
+ * Unit code representing in rows of text. This unit is only applicaple to
+ * some components can it's meaning is specified by component
+ * implementation.
+ */
+ public static final int UNITS_ROWS = 9;
+
+ /**
+ * Textual representations of units symbols. Supported units and their
+ * symbols are:
+ *
+ * UNITS_PIXELS
: "px"
+ * UNITS_POINTS
: "pt"
+ * UNITS_PICAS
: "pc"
+ * UNITS_EM
: "em"
+ * UNITS_EX
: "ex"
+ * UNITS_MM
: "mm"
+ * UNITS_CM
. "cm"
+ * UNITS_INCH
: "in"
+ * UNITS_PERCENTAGE
: "%"
+ * UNITS_ROWS
: "rows"
+ *
+ * These can be used like Sizeable.UNIT_SYMBOLS[UNITS_PIXELS]
.
+ */
+ public static final String[] UNIT_SYMBOLS = { "px", "pt", "pc", "em", "ex",
+ "mm", "cm", "in", "%", "rows" };
+
+ /**
+ * Gets the width of the object. Negative number implies unspecified size
+ * (terminal is free to set the size).
+ *
+ * @return width of the object in units specified by widthUnits property.
+ */
+ public int getWidth();
+
+ /**
+ * Sets the width of the object. Negative number implies unspecified size
+ * (terminal is free to set the size).
+ *
+ * @param width
+ * the width of the object in units specified by widthUnits
+ * property.
+ */
+ public void setWidth(int width);
+
+ /**
+ * Gets the height of the object. Negative number implies unspecified size
+ * (terminal is free to set the size).
+ *
+ * @return height of the object in units specified by heightUnits property.
+ */
+ public int getHeight();
+
+ /**
+ * Sets the height of the object. Negative number implies unspecified size
+ * (terminal is free to set the size).
+ *
+ * @param height
+ * the height of the object in units specified by heightUnits
+ * property.
+ */
+ public void setHeight(int height);
+
+ /**
+ * Gets the width property units.
+ *
+ * @return units used in width property.
+ */
+ public int getWidthUnits();
+
+ /**
+ * Sets the width property units.
+ *
+ * @param units
+ * the units used in width property.
+ */
+ public void setWidthUnits(int units);
+
+ /**
+ * Gets the height property units.
+ *
+ * @return units used in height property.
+ */
+ public int getHeightUnits();
+
+ /**
+ * Sets the height property units.
+ *
+ * @param units
+ * the units used in height property.
+ */
+ public void setHeightUnits(int units);
+
+ /**
+ * Sets the size to 100% x 100%.
+ */
+ public void setSizeFull();
+
+ /**
+ * Clears any size settings.
+ */
+ public void setSizeUndefined();
}
diff --git a/src/com/itmill/toolkit/terminal/StreamResource.java b/src/com/itmill/toolkit/terminal/StreamResource.java
index d7a467d95a..523741089d 100644
--- a/src/com/itmill/toolkit/terminal/StreamResource.java
+++ b/src/com/itmill/toolkit/terminal/StreamResource.java
@@ -46,191 +46,193 @@ import com.itmill.toolkit.service.FileTypeResolver;
*/
public class StreamResource implements ApplicationResource {
- /**
- * Source stream the downloaded content is fetched from.
- */
- private StreamSource streamSource = null;
-
- /**
- * Explicit mime-type.
- */
- private String MIMEType = null;
-
- /**
- * Filename.
- */
- private String filename;
-
- /**
- * Application.
- */
- private Application application;
-
- /**
- * Default buffer size for this stream resource.
- */
- private int bufferSize = 0;
-
- /**
- * Default cache time for this stream resource.
- */
- private long cacheTime = DEFAULT_CACHETIME;
-
- /**
- * Creates a new stream resource for downloading from stream.
- *
- * @param streamSource
- * the source Stream.
- * @param filename
- * the name of the file.
- * @param application
- * the Application object.
- */
- public StreamResource(StreamSource streamSource, String filename,
- Application application) {
-
- this.application = application;
- setFilename(filename);
- setStreamSource(streamSource);
-
- // Register to application
- application.addResource(this);
-
- }
-
- /**
- * @see com.itmill.toolkit.terminal.Resource#getMIMEType()
- */
- public String getMIMEType() {
- if (MIMEType != null)
- return MIMEType;
- return FileTypeResolver.getMIMEType(filename);
- }
-
- /**
- * Sets the mime type of the resource.
- *
- * @param MIMEType
- * the MIME type to be set.
- */
- public void setMIMEType(String MIMEType) {
- this.MIMEType = MIMEType;
- }
-
- /**
- * Returns the source for this StreamResource
. StreamSource
- * is queried when the resource is about to be streamed to the client.
- *
- * @return Source of the StreamResource.
- */
- public StreamSource getStreamSource() {
- return streamSource;
- }
-
- /**
- * Sets the source for this StreamResource
.
- * StreamSource
is queried when the resource is about to be
- * streamed to the client.
- *
- * @param streamSource
- * the source to set.
- */
- public void setStreamSource(StreamSource streamSource) {
- this.streamSource = streamSource;
- }
-
- /**
- * Gets the filename.
- *
- * @return the filename.
- */
- public String getFilename() {
- return filename;
- }
-
- /**
- * Sets the filename.
- *
- * @param filename
- * the filename to set.
- */
- public void setFilename(String filename) {
- this.filename = filename;
- }
-
- /**
- * @see com.itmill.toolkit.terminal.ApplicationResource#getApplication()
- */
- public Application getApplication() {
- return application;
- }
-
- /**
- * @see com.itmill.toolkit.terminal.ApplicationResource#getStream()
- */
- public DownloadStream getStream() {
- StreamSource ss = getStreamSource();
- if (ss == null)
- return null;
- DownloadStream ds = new DownloadStream(ss.getStream(), getMIMEType(),
- getFilename());
- ds.setBufferSize(getBufferSize());
- ds.setCacheTime(cacheTime);
- return ds;
- }
-
- /**
- * Interface implemented by the source of a StreamResource.
- *
- * @author IT Mill Ltd.
- * @version
- * @VERSION@
- * @since 3.0
- */
- public interface StreamSource {
-
- /**
- * Returns new input stream that is used for reading the resource.
- */
- public InputStream getStream();
- }
-
- /* documented in superclass */
- public int getBufferSize() {
- return bufferSize;
- }
-
- /**
- * Sets the size of the download buffer used for this resource.
- *
- * @param bufferSize
- * the size of the buffer in bytes.
- */
- public void setBufferSize(int bufferSize) {
- this.bufferSize = bufferSize;
- }
-
- /* documented in superclass */
- public long getCacheTime() {
- return cacheTime;
- }
-
- /**
- * Sets the length of cache expiration time.
- *
- *
- * This gives the adapter the possibility cache streams sent to the client.
- * The caching may be made in adapter or at the client if the client
- * supports caching. Zero or negavive value disbales the caching of this
- * stream.
- *
- *
- * @param cacheTime
- * the cache time in milliseconds.
- *
- */
- public void setCacheTime(long cacheTime) {
- this.cacheTime = cacheTime;
- }
+ /**
+ * Source stream the downloaded content is fetched from.
+ */
+ private StreamSource streamSource = null;
+
+ /**
+ * Explicit mime-type.
+ */
+ private String MIMEType = null;
+
+ /**
+ * Filename.
+ */
+ private String filename;
+
+ /**
+ * Application.
+ */
+ private Application application;
+
+ /**
+ * Default buffer size for this stream resource.
+ */
+ private int bufferSize = 0;
+
+ /**
+ * Default cache time for this stream resource.
+ */
+ private long cacheTime = DEFAULT_CACHETIME;
+
+ /**
+ * Creates a new stream resource for downloading from stream.
+ *
+ * @param streamSource
+ * the source Stream.
+ * @param filename
+ * the name of the file.
+ * @param application
+ * the Application object.
+ */
+ public StreamResource(StreamSource streamSource, String filename,
+ Application application) {
+
+ this.application = application;
+ setFilename(filename);
+ setStreamSource(streamSource);
+
+ // Register to application
+ application.addResource(this);
+
+ }
+
+ /**
+ * @see com.itmill.toolkit.terminal.Resource#getMIMEType()
+ */
+ public String getMIMEType() {
+ if (MIMEType != null) {
+ return MIMEType;
+ }
+ return FileTypeResolver.getMIMEType(filename);
+ }
+
+ /**
+ * Sets the mime type of the resource.
+ *
+ * @param MIMEType
+ * the MIME type to be set.
+ */
+ public void setMIMEType(String MIMEType) {
+ this.MIMEType = MIMEType;
+ }
+
+ /**
+ * Returns the source for this StreamResource
. StreamSource
+ * is queried when the resource is about to be streamed to the client.
+ *
+ * @return Source of the StreamResource.
+ */
+ public StreamSource getStreamSource() {
+ return streamSource;
+ }
+
+ /**
+ * Sets the source for this StreamResource
.
+ * StreamSource
is queried when the resource is about to be
+ * streamed to the client.
+ *
+ * @param streamSource
+ * the source to set.
+ */
+ public void setStreamSource(StreamSource streamSource) {
+ this.streamSource = streamSource;
+ }
+
+ /**
+ * Gets the filename.
+ *
+ * @return the filename.
+ */
+ public String getFilename() {
+ return filename;
+ }
+
+ /**
+ * Sets the filename.
+ *
+ * @param filename
+ * the filename to set.
+ */
+ public void setFilename(String filename) {
+ this.filename = filename;
+ }
+
+ /**
+ * @see com.itmill.toolkit.terminal.ApplicationResource#getApplication()
+ */
+ public Application getApplication() {
+ return application;
+ }
+
+ /**
+ * @see com.itmill.toolkit.terminal.ApplicationResource#getStream()
+ */
+ public DownloadStream getStream() {
+ StreamSource ss = getStreamSource();
+ if (ss == null) {
+ return null;
+ }
+ DownloadStream ds = new DownloadStream(ss.getStream(), getMIMEType(),
+ getFilename());
+ ds.setBufferSize(getBufferSize());
+ ds.setCacheTime(cacheTime);
+ return ds;
+ }
+
+ /**
+ * Interface implemented by the source of a StreamResource.
+ *
+ * @author IT Mill Ltd.
+ * @version
+ * @VERSION@
+ * @since 3.0
+ */
+ public interface StreamSource {
+
+ /**
+ * Returns new input stream that is used for reading the resource.
+ */
+ public InputStream getStream();
+ }
+
+ /* documented in superclass */
+ public int getBufferSize() {
+ return bufferSize;
+ }
+
+ /**
+ * Sets the size of the download buffer used for this resource.
+ *
+ * @param bufferSize
+ * the size of the buffer in bytes.
+ */
+ public void setBufferSize(int bufferSize) {
+ this.bufferSize = bufferSize;
+ }
+
+ /* documented in superclass */
+ public long getCacheTime() {
+ return cacheTime;
+ }
+
+ /**
+ * Sets the length of cache expiration time.
+ *
+ *
+ * This gives the adapter the possibility cache streams sent to the client.
+ * The caching may be made in adapter or at the client if the client
+ * supports caching. Zero or negavive value disbales the caching of this
+ * stream.
+ *
+ *
+ * @param cacheTime
+ * the cache time in milliseconds.
+ *
+ */
+ public void setCacheTime(long cacheTime) {
+ this.cacheTime = cacheTime;
+ }
}
diff --git a/src/com/itmill/toolkit/terminal/SystemError.java b/src/com/itmill/toolkit/terminal/SystemError.java
index 90c045c18c..0fbace4337 100644
--- a/src/com/itmill/toolkit/terminal/SystemError.java
+++ b/src/com/itmill/toolkit/terminal/SystemError.java
@@ -44,107 +44,107 @@ import java.io.StringWriter;
*/
public class SystemError extends RuntimeException implements ErrorMessage {
- /**
- * Serial generated by eclipse.
- */
- private static final long serialVersionUID = 3256445789512675891L;
-
- /**
- * The cause of the system error. The cause is stored separately as JDK 1.3
- * does not support causes natively.
- */
- private Throwable cause = null;
-
- /**
- * Constructor for SystemError with error message specified.
- *
- * @param message
- * the Textual error description.
- */
- public SystemError(String message) {
- super(message);
- }
-
- /**
- * Constructor for SystemError with causing exception and error message.
- *
- * @param message
- * the Textual error description.
- * @param cause
- * the throwable causing the system error.
- */
- public SystemError(String message, Throwable cause) {
- super(message);
- this.cause = cause;
- }
-
- /**
- * Constructor for SystemError with cause.
- *
- * @param cause
- * the throwable causing the system error.
- */
- public SystemError(Throwable cause) {
- this.cause = cause;
- }
-
- /**
- * @see com.itmill.toolkit.terminal.ErrorMessage#getErrorLevel()
- */
- public final int getErrorLevel() {
- return ErrorMessage.SYSTEMERROR;
- }
-
- /**
- * @see com.itmill.toolkit.terminal.Paintable#paint(com.itmill.toolkit.terminal.PaintTarget)
- */
- public void paint(PaintTarget target) throws PaintException {
-
- target.startTag("error");
- target.addAttribute("level", "system");
-
- // Paint the error message
- String message = getLocalizedMessage();
- if (message != null) {
- target.addSection("h2", message);
- }
-
- // Paint the exception
- if (cause != null) {
- target.addSection("h3", "Exception");
- StringWriter buffer = new StringWriter();
- cause.printStackTrace(new PrintWriter(buffer));
- target.addSection("pre", buffer.toString());
- }
-
- target.endTag("error");
-
- }
-
- /**
- * Gets cause for the error.
- *
- * @return the cause.
- * @see java.lang.Throwable#getCause()
- */
- public Throwable getCause() {
- return cause;
- }
-
- /* Documented in super interface */
- public void addListener(RepaintRequestListener listener) {
- }
-
- /* Documented in super interface */
- public void removeListener(RepaintRequestListener listener) {
- }
-
- /* Documented in super interface */
- public void requestRepaint() {
- }
-
- /* Documented in super interface */
- public void requestRepaintRequests() {
- }
+ /**
+ * Serial generated by eclipse.
+ */
+ private static final long serialVersionUID = 3256445789512675891L;
+
+ /**
+ * The cause of the system error. The cause is stored separately as JDK 1.3
+ * does not support causes natively.
+ */
+ private Throwable cause = null;
+
+ /**
+ * Constructor for SystemError with error message specified.
+ *
+ * @param message
+ * the Textual error description.
+ */
+ public SystemError(String message) {
+ super(message);
+ }
+
+ /**
+ * Constructor for SystemError with causing exception and error message.
+ *
+ * @param message
+ * the Textual error description.
+ * @param cause
+ * the throwable causing the system error.
+ */
+ public SystemError(String message, Throwable cause) {
+ super(message);
+ this.cause = cause;
+ }
+
+ /**
+ * Constructor for SystemError with cause.
+ *
+ * @param cause
+ * the throwable causing the system error.
+ */
+ public SystemError(Throwable cause) {
+ this.cause = cause;
+ }
+
+ /**
+ * @see com.itmill.toolkit.terminal.ErrorMessage#getErrorLevel()
+ */
+ public final int getErrorLevel() {
+ return ErrorMessage.SYSTEMERROR;
+ }
+
+ /**
+ * @see com.itmill.toolkit.terminal.Paintable#paint(com.itmill.toolkit.terminal.PaintTarget)
+ */
+ public void paint(PaintTarget target) throws PaintException {
+
+ target.startTag("error");
+ target.addAttribute("level", "system");
+
+ // Paint the error message
+ String message = getLocalizedMessage();
+ if (message != null) {
+ target.addSection("h2", message);
+ }
+
+ // Paint the exception
+ if (cause != null) {
+ target.addSection("h3", "Exception");
+ StringWriter buffer = new StringWriter();
+ cause.printStackTrace(new PrintWriter(buffer));
+ target.addSection("pre", buffer.toString());
+ }
+
+ target.endTag("error");
+
+ }
+
+ /**
+ * Gets cause for the error.
+ *
+ * @return the cause.
+ * @see java.lang.Throwable#getCause()
+ */
+ public Throwable getCause() {
+ return cause;
+ }
+
+ /* Documented in super interface */
+ public void addListener(RepaintRequestListener listener) {
+ }
+
+ /* Documented in super interface */
+ public void removeListener(RepaintRequestListener listener) {
+ }
+
+ /* Documented in super interface */
+ public void requestRepaint() {
+ }
+
+ /* Documented in super interface */
+ public void requestRepaintRequests() {
+ }
}
diff --git a/src/com/itmill/toolkit/terminal/Terminal.java b/src/com/itmill/toolkit/terminal/Terminal.java
index e8054d2e88..a31e31c6db 100644
--- a/src/com/itmill/toolkit/terminal/Terminal.java
+++ b/src/com/itmill/toolkit/terminal/Terminal.java
@@ -38,50 +38,50 @@ package com.itmill.toolkit.terminal;
*/
public interface Terminal {
- /**
- * Gets the name of the default theme.
- *
- * @return the Name of the terminal window.
- */
- public String getDefaultTheme();
+ /**
+ * Gets the name of the default theme.
+ *
+ * @return the Name of the terminal window.
+ */
+ public String getDefaultTheme();
- /**
- * Gets the width of the terminal window in pixels.
- *
- * @return the Width of the terminal window.
- */
- public int getScreenWidth();
+ /**
+ * Gets the width of the terminal window in pixels.
+ *
+ * @return the Width of the terminal window.
+ */
+ public int getScreenWidth();
- /**
- * Gets the height of the terminal window in pixels.
- *
- * @return the Height of the terminal window.
- */
- public int getScreenHeight();
+ /**
+ * Gets the height of the terminal window in pixels.
+ *
+ * @return the Height of the terminal window.
+ */
+ public int getScreenHeight();
- /**
- * Terminal error event.
- */
- public interface ErrorEvent {
+ /**
+ * Terminal error event.
+ */
+ public interface ErrorEvent {
- /**
- * Gets the contained throwable.
- */
- public Throwable getThrowable();
+ /**
+ * Gets the contained throwable.
+ */
+ public Throwable getThrowable();
- }
+ }
- /**
- * Terminal error listener interface.
- */
- public interface ErrorListener {
+ /**
+ * Terminal error listener interface.
+ */
+ public interface ErrorListener {
- /**
- * Invoked when terminal error occurs.
- *
- * @param event
- * the fired event.
- */
- public void terminalError(Terminal.ErrorEvent event);
- }
+ /**
+ * Invoked when terminal error occurs.
+ *
+ * @param event
+ * the fired event.
+ */
+ public void terminalError(Terminal.ErrorEvent event);
+ }
}
diff --git a/src/com/itmill/toolkit/terminal/ThemeResource.java b/src/com/itmill/toolkit/terminal/ThemeResource.java
index 566e5b71ab..c8f80ba56a 100644
--- a/src/com/itmill/toolkit/terminal/ThemeResource.java
+++ b/src/com/itmill/toolkit/terminal/ThemeResource.java
@@ -43,70 +43,73 @@ import com.itmill.toolkit.service.FileTypeResolver;
*/
public class ThemeResource implements Resource {
- /**
- * Id of the terminal managed resource.
- */
- private String resourceID = null;
-
- /**
- * Creates a resource.
- *
- * @param resourceId
- * the Id of the resource.
- */
- public ThemeResource(String resourceId) {
- if (resourceId == null)
- throw new NullPointerException("Resource ID must not be null");
- if (resourceId.length() == 0)
- throw new IllegalArgumentException("Resource ID can not be empty");
- if (resourceId.charAt(0) == '/')
- throw new IllegalArgumentException(
- "Resource ID must be relative (can not begin with /)");
-
- this.resourceID = resourceId;
- }
-
- /**
- * Tests if the given object equals this Resource.
- *
- * @param obj
- * the object to be tested for equality.
- * @return true
if the given object equals this Icon,
- * false
if not.
- * @see java.lang.Object#equals(Object)
- */
- public boolean equals(Object obj) {
- return obj instanceof ThemeResource
- && resourceID.equals(((ThemeResource) obj).resourceID);
- }
-
- /**
- * @see java.lang.Object#hashCode()
- */
- public int hashCode() {
- return resourceID.hashCode();
- }
-
- /**
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return resourceID.toString();
- }
-
- /**
- * Gets the resource id.
- *
- * @return the resource id.
- */
- public String getResourceId() {
- return resourceID;
- }
-
- /**
- * @see com.itmill.toolkit.terminal.Resource#getMIMEType()
- */
- public String getMIMEType() {
- return FileTypeResolver.getMIMEType(getResourceId());
- }
+ /**
+ * Id of the terminal managed resource.
+ */
+ private String resourceID = null;
+
+ /**
+ * Creates a resource.
+ *
+ * @param resourceId
+ * the Id of the resource.
+ */
+ public ThemeResource(String resourceId) {
+ if (resourceId == null) {
+ throw new NullPointerException("Resource ID must not be null");
+ }
+ if (resourceId.length() == 0) {
+ throw new IllegalArgumentException("Resource ID can not be empty");
+ }
+ if (resourceId.charAt(0) == '/') {
+ throw new IllegalArgumentException(
+ "Resource ID must be relative (can not begin with /)");
+ }
+
+ resourceID = resourceId;
+ }
+
+ /**
+ * Tests if the given object equals this Resource.
+ *
+ * @param obj
+ * the object to be tested for equality.
+ * @return true
if the given object equals this Icon,
+ * false
if not.
+ * @see java.lang.Object#equals(Object)
+ */
+ public boolean equals(Object obj) {
+ return obj instanceof ThemeResource
+ && resourceID.equals(((ThemeResource) obj).resourceID);
+ }
+
+ /**
+ * @see java.lang.Object#hashCode()
+ */
+ public int hashCode() {
+ return resourceID.hashCode();
+ }
+
+ /**
+ * @see java.lang.Object#toString()
+ */
+ public String toString() {
+ return resourceID.toString();
+ }
+
+ /**
+ * Gets the resource id.
+ *
+ * @return the resource id.
+ */
+ public String getResourceId() {
+ return resourceID;
+ }
+
+ /**
+ * @see com.itmill.toolkit.terminal.Resource#getMIMEType()
+ */
+ public String getMIMEType() {
+ return FileTypeResolver.getMIMEType(getResourceId());
+ }
}
diff --git a/src/com/itmill/toolkit/terminal/URIHandler.java b/src/com/itmill/toolkit/terminal/URIHandler.java
index 9883606c2a..5b4bf67d58 100644
--- a/src/com/itmill/toolkit/terminal/URIHandler.java
+++ b/src/com/itmill/toolkit/terminal/URIHandler.java
@@ -45,30 +45,30 @@ import java.net.URL;
*/
public interface URIHandler {
- /**
- * Handles a given relative URI. If the URI handling wants to emit a
- * downloadable stream it can return download stream object. If no emitting
- * stream is necessary, null should be returned instead.
- *
- * @param context
- * the URl.
- * @param relativeUri
- * the relative uri.
- * @return the download stream object.
- */
- public DownloadStream handleURI(URL context, String relativeUri);
+ /**
+ * Handles a given relative URI. If the URI handling wants to emit a
+ * downloadable stream it can return download stream object. If no emitting
+ * stream is necessary, null should be returned instead.
+ *
+ * @param context
+ * the URl.
+ * @param relativeUri
+ * the relative uri.
+ * @return the download stream object.
+ */
+ public DownloadStream handleURI(URL context, String relativeUri);
- /**
- * URIHandler error event.
- */
- public interface ErrorEvent extends Terminal.ErrorEvent {
+ /**
+ * URIHandler error event.
+ */
+ public interface ErrorEvent extends Terminal.ErrorEvent {
- /**
- * Gets the source URIHandler.
- *
- * @return the URIHandler.
- */
- public URIHandler getURIHandler();
+ /**
+ * Gets the source URIHandler.
+ *
+ * @return the URIHandler.
+ */
+ public URIHandler getURIHandler();
- }
+ }
}
diff --git a/src/com/itmill/toolkit/terminal/UploadStream.java b/src/com/itmill/toolkit/terminal/UploadStream.java
index 5a63ac4139..b0a9cf85c9 100644
--- a/src/com/itmill/toolkit/terminal/UploadStream.java
+++ b/src/com/itmill/toolkit/terminal/UploadStream.java
@@ -42,32 +42,32 @@ import java.io.InputStream;
*/
public interface UploadStream {
- /**
- * Gets the name of the stream.
- *
- * @return the name of the stream.
- */
- public String getStreamName();
+ /**
+ * Gets the name of the stream.
+ *
+ * @return the name of the stream.
+ */
+ public String getStreamName();
- /**
- * Gets the input stream.
- *
- * @return the Input stream.
- */
- public InputStream getStream();
+ /**
+ * Gets the input stream.
+ *
+ * @return the Input stream.
+ */
+ public InputStream getStream();
- /**
- * Gets the input stream content type.
- *
- * @return the content type of the input stream.
- */
- public String getContentType();
+ /**
+ * Gets the input stream content type.
+ *
+ * @return the content type of the input stream.
+ */
+ public String getContentType();
- /**
- * Gets stream content name. Stream content name usually differs from the
- * actual stream name. It is used to identify the content of the stream.
- *
- * @return the Name of the stream content.
- */
- public String getContentName();
+ /**
+ * Gets stream content name. Stream content name usually differs from the
+ * actual stream name. It is used to identify the content of the stream.
+ *
+ * @return the Name of the stream content.
+ */
+ public String getContentName();
}
diff --git a/src/com/itmill/toolkit/terminal/UserError.java b/src/com/itmill/toolkit/terminal/UserError.java
index 53b44fded8..6915f07378 100644
--- a/src/com/itmill/toolkit/terminal/UserError.java
+++ b/src/com/itmill/toolkit/terminal/UserError.java
@@ -39,127 +39,129 @@ package com.itmill.toolkit.terminal;
*/
public class UserError implements ErrorMessage {
- /**
- * Content mode, where the error contains only plain text.
- */
- public static final int CONTENT_TEXT = 0;
-
- /**
- * Content mode, where the error contains preformatted text.
- */
- public static final int CONTENT_PREFORMATTED = 1;
-
- /**
- * Formatted content mode, where the contents is XML restricted to the UIDL
- * 1.0 formatting markups.
- */
- public static final int CONTENT_UIDL = 2;
-
- /**
- * Content mode.
- */
- private int mode = CONTENT_TEXT;
-
- /**
- * Message in content mode.
- */
- private String msg;
-
- /**
- * Error level.
- */
- private int level = ErrorMessage.ERROR;
-
- /**
- * Creates a textual error message of level ERROR.
- *
- * @param textErrorMessage
- * the text of the error message.
- */
- public UserError(String textErrorMessage) {
- this.msg = textErrorMessage;
- }
-
- /**
- * Creates a error message with level and content mode.
- *
- * @param message
- * the error message.
- * @param contentMode
- * the content Mode.
- * @param errorLevel
- * the level of error.
- */
- public UserError(String message, int contentMode, int errorLevel) {
-
- // Check the parameters
- if (contentMode < 0 || contentMode > 2)
- throw new java.lang.IllegalArgumentException(
- "Unsupported content mode: " + contentMode);
-
- this.msg = message;
- this.mode = contentMode;
- this.level = errorLevel;
- }
-
- /* Documenten in interface */
- public int getErrorLevel() {
- return level;
- }
-
- /* Documenten in interface */
- public void addListener(RepaintRequestListener listener) {
- }
-
- /* Documenten in interface */
- public void removeListener(RepaintRequestListener listener) {
- }
-
- /* Documenten in interface */
- public void requestRepaint() {
- }
-
- /* Documenten in interface */
- public void paint(PaintTarget target) throws PaintException {
-
- target.startTag("error");
-
- // Error level
- if (level >= ErrorMessage.SYSTEMERROR)
- target.addAttribute("level", "system");
- else if (level >= ErrorMessage.CRITICAL)
- target.addAttribute("level", "critical");
- else if (level >= ErrorMessage.ERROR)
- target.addAttribute("level", "error");
- else if (level >= ErrorMessage.WARNING)
- target.addAttribute("level", "warning");
- else
- target.addAttribute("level", "info");
-
- // Paint the message
- switch (mode) {
- case CONTENT_TEXT:
- target.addText(msg);
- break;
- case CONTENT_UIDL:
- target.addUIDL(msg);
- break;
- case CONTENT_PREFORMATTED:
- target.startTag("pre");
- target.addText(msg);
- target.endTag("pre");
- }
-
- target.endTag("error");
- }
-
- /* Documenten in interface */
- public void requestRepaintRequests() {
- }
-
- /* Documented in superclass */
- public String toString() {
- return msg;
- }
+ /**
+ * Content mode, where the error contains only plain text.
+ */
+ public static final int CONTENT_TEXT = 0;
+
+ /**
+ * Content mode, where the error contains preformatted text.
+ */
+ public static final int CONTENT_PREFORMATTED = 1;
+
+ /**
+ * Formatted content mode, where the contents is XML restricted to the UIDL
+ * 1.0 formatting markups.
+ */
+ public static final int CONTENT_UIDL = 2;
+
+ /**
+ * Content mode.
+ */
+ private int mode = CONTENT_TEXT;
+
+ /**
+ * Message in content mode.
+ */
+ private String msg;
+
+ /**
+ * Error level.
+ */
+ private int level = ErrorMessage.ERROR;
+
+ /**
+ * Creates a textual error message of level ERROR.
+ *
+ * @param textErrorMessage
+ * the text of the error message.
+ */
+ public UserError(String textErrorMessage) {
+ msg = textErrorMessage;
+ }
+
+ /**
+ * Creates a error message with level and content mode.
+ *
+ * @param message
+ * the error message.
+ * @param contentMode
+ * the content Mode.
+ * @param errorLevel
+ * the level of error.
+ */
+ public UserError(String message, int contentMode, int errorLevel) {
+
+ // Check the parameters
+ if (contentMode < 0 || contentMode > 2) {
+ throw new java.lang.IllegalArgumentException(
+ "Unsupported content mode: " + contentMode);
+ }
+
+ msg = message;
+ mode = contentMode;
+ level = errorLevel;
+ }
+
+ /* Documenten in interface */
+ public int getErrorLevel() {
+ return level;
+ }
+
+ /* Documenten in interface */
+ public void addListener(RepaintRequestListener listener) {
+ }
+
+ /* Documenten in interface */
+ public void removeListener(RepaintRequestListener listener) {
+ }
+
+ /* Documenten in interface */
+ public void requestRepaint() {
+ }
+
+ /* Documenten in interface */
+ public void paint(PaintTarget target) throws PaintException {
+
+ target.startTag("error");
+
+ // Error level
+ if (level >= ErrorMessage.SYSTEMERROR) {
+ target.addAttribute("level", "system");
+ } else if (level >= ErrorMessage.CRITICAL) {
+ target.addAttribute("level", "critical");
+ } else if (level >= ErrorMessage.ERROR) {
+ target.addAttribute("level", "error");
+ } else if (level >= ErrorMessage.WARNING) {
+ target.addAttribute("level", "warning");
+ } else {
+ target.addAttribute("level", "info");
+ }
+
+ // Paint the message
+ switch (mode) {
+ case CONTENT_TEXT:
+ target.addText(msg);
+ break;
+ case CONTENT_UIDL:
+ target.addUIDL(msg);
+ break;
+ case CONTENT_PREFORMATTED:
+ target.startTag("pre");
+ target.addText(msg);
+ target.endTag("pre");
+ }
+
+ target.endTag("error");
+ }
+
+ /* Documenten in interface */
+ public void requestRepaintRequests() {
+ }
+
+ /* Documented in superclass */
+ public String toString() {
+ return msg;
+ }
}
diff --git a/src/com/itmill/toolkit/terminal/VariableOwner.java b/src/com/itmill/toolkit/terminal/VariableOwner.java
index b730125d34..93bdb7d780 100644
--- a/src/com/itmill/toolkit/terminal/VariableOwner.java
+++ b/src/com/itmill/toolkit/terminal/VariableOwner.java
@@ -61,90 +61,93 @@ import java.util.Set;
*/
public interface VariableOwner {
- /**
- * Dependencies are not needed anymore as HTML-mode is deprecated in Toolkit 5.
- * *
- * @return Set of VariableOwners
this component directly
- * depend on, null
if this component does not depend
- * on anybody.
- * @deprecated
- */
- public Set getDirectDependencies();
-
- /**
- * Called when one or more variables handled by the implementing class are
- * changed.
- *
- * @param source
- * the Source of the variable change. This is the origin of the
- * event. For example in Web Adapter this is the request.
- * @param variables
- * the Mapping from variable names to new variable values.
- */
- public void changeVariables(Object source, Map variables);
-
- /**
- * Dependencies are not needed anymore as HTML-mode is deprecated in Toolkit 5.
- *
- * @param depended
- * the VariableOwner
component who this component
- * depends on.
- * @deprecated
- */
- public void dependsOn(VariableOwner depended);
-
- /**
- * Dependencies are not needed anymore as HTML-mode is deprecated in Toolkit 5.
- *
- * @param depended
- * the component to be removed from this component's dependency
- * list.
- * @deprecated
- */
- public void removeDirectDependency(VariableOwner depended);
-
- /**
- *
- * Tests if the variable owner is enabled or not. The terminal should not
- * send any variable changes to disabled variable owners.
- *
- *
- * @return true
if the variable owner is enabled,
- * false
if not
- */
- public boolean isEnabled();
-
- /**
- *
- * Tests if the variable owner is in immediate mode or not. Being in
- * immediate mode means that all variable changes are required to be sent
- * back from the terminal immediately when they occur.
- *
- *
- *
- * Note: VariableOwner
does not include a
- * set- method for the immediateness property. This is because not all
- * VariableOwners wish to offer the functionality. Such VariableOwners are
- * never in the immediate mode, thus they always return false
- * in {@link #isImmediate()}.
- *
- *
- * @return true
if the component is in immediate mode,
- * false
if not.
- */
- public boolean isImmediate();
-
- /**
- * VariableOwner error event.
- */
- public interface ErrorEvent extends Terminal.ErrorEvent {
-
- /**
- * Gets the source VariableOwner.
- *
- * @return the variable owner.
- */
- public VariableOwner getVariableOwner();
-
- }
+ /**
+ * Dependencies are not needed anymore as HTML-mode is deprecated in Toolkit
+ * 5. *
+ *
+ * @return Set of VariableOwners
this component directly
+ * depend on, null
if this component does not depend
+ * on anybody.
+ * @deprecated
+ */
+ public Set getDirectDependencies();
+
+ /**
+ * Called when one or more variables handled by the implementing class are
+ * changed.
+ *
+ * @param source
+ * the Source of the variable change. This is the origin of
+ * the event. For example in Web Adapter this is the request.
+ * @param variables
+ * the Mapping from variable names to new variable values.
+ */
+ public void changeVariables(Object source, Map variables);
+
+ /**
+ * Dependencies are not needed anymore as HTML-mode is deprecated in Toolkit
+ * 5.
+ *
+ * @param depended
+ * the VariableOwner
component who this
+ * component depends on.
+ * @deprecated
+ */
+ public void dependsOn(VariableOwner depended);
+
+ /**
+ * Dependencies are not needed anymore as HTML-mode is deprecated in Toolkit
+ * 5.
+ *
+ * @param depended
+ * the component to be removed from this component's
+ * dependency list.
+ * @deprecated
+ */
+ public void removeDirectDependency(VariableOwner depended);
+
+ /**
+ *
+ * Tests if the variable owner is enabled or not. The terminal should not
+ * send any variable changes to disabled variable owners.
+ *
+ *
+ * @return true
if the variable owner is enabled,
+ * false
if not
+ */
+ public boolean isEnabled();
+
+ /**
+ *
+ * Tests if the variable owner is in immediate mode or not. Being in
+ * immediate mode means that all variable changes are required to be sent
+ * back from the terminal immediately when they occur.
+ *
+ *
+ *
+ * Note: VariableOwner
does not include a
+ * set- method for the immediateness property. This is because not all
+ * VariableOwners wish to offer the functionality. Such VariableOwners are
+ * never in the immediate mode, thus they always return false
+ * in {@link #isImmediate()}.
+ *
+ *
+ * @return true
if the component is in immediate mode,
+ * false
if not.
+ */
+ public boolean isImmediate();
+
+ /**
+ * VariableOwner error event.
+ */
+ public interface ErrorEvent extends Terminal.ErrorEvent {
+
+ /**
+ * Gets the source VariableOwner.
+ *
+ * @return the variable owner.
+ */
+ public VariableOwner getVariableOwner();
+
+ }
}
diff --git a/src/com/itmill/toolkit/terminal/gwt/client/ApplicationConnection.java b/src/com/itmill/toolkit/terminal/gwt/client/ApplicationConnection.java
index cce50f4888..035b62efa9 100755
--- a/src/com/itmill/toolkit/terminal/gwt/client/ApplicationConnection.java
+++ b/src/com/itmill/toolkit/terminal/gwt/client/ApplicationConnection.java
@@ -30,550 +30,552 @@ import com.itmill.toolkit.terminal.gwt.client.ui.IView;
*/
public class ApplicationConnection {
- private String appUri;
+ private String appUri;
- private HashMap resourcesMap = new HashMap();
+ private HashMap resourcesMap = new HashMap();
- private static Console console;
+ private static Console console;
- private Vector pendingVariables = new Vector();
-
- private HashMap idToPaintable = new HashMap();
-
- private HashMap paintableToId = new HashMap();
-
- private final WidgetSet widgetSet;
-
- private ContextMenu contextMenu = null;
-
- private Timer loadTimer;
- private Element loadElement;
-
- private IView view;
-
- public ApplicationConnection(WidgetSet widgetSet) {
- this.widgetSet = widgetSet;
- appUri = getAppUri();
-
- if (isDebugMode()) {
- console = new DebugConsole(this);
- } else {
- console = new NullConsole();
- }
-
- makeUidlRequest("repaintAll=1");
-
- // TODO remove hardcoded id name
- view = new IView("itmill-ajax-window");
-
- }
-
- public static Console getConsole() {
- return console;
- }
-
- private native static boolean isDebugMode()
- /*-{
- var uri = $wnd.location;
- var re = /debug[^\/]*$/;
- return re.test(uri);
- }-*/;
-
- public native String getAppUri()
- /*-{
- var u = $wnd.itmill.appUri;
- if (u.indexOf("/") != 0 && u.indexOf("http") != 0) {
- var b = $wnd.location.href;
- var i = b.length-1;
- while (b.charAt(i) != "/" && i>0) i--;
- b = b.substring(0,i+1);
- u = b + u;
- }
- return u;
- }-*/;
-
- private native String getPathInfo()
- /*-{
- return $wnd.itmill.pathInfo;
- }-*/;
-
- private native String getThemeUri()
- /*-{
- return $wnd.itmill.themeUri;
- }-*/;
-
- private void makeUidlRequest(String requestData) {
-
- // place loading indicator
- showLoadingIndicator();
-
- console.log("Making UIDL Request with params: " + requestData);
- String uri = appUri + "/UIDL" + getPathInfo();
- RequestBuilder rb = new RequestBuilder(RequestBuilder.POST, uri);
- rb.setHeader("Content-Type",
- "application/x-www-form-urlencoded; charset=utf-8");
- try {
- rb.sendRequest(requestData, new RequestCallback() {
- public void onError(Request request, Throwable exception) {
- // TODO Better reporting to user
- console.error("Got error");
- }
-
- public void onResponseReceived(Request request,
- Response response) {
- handleReceivedJSONMessage(response);
- }
-
- });
-
- } catch (RequestException e) {
- // TODO Better reporting to user
- console.error(e.getMessage());
- }
- }
-
- private void showLoadingIndicator() {
- loadTimer = new Timer() {
- public void run() {
- // show initial throbber
- if (loadElement == null) {
- loadElement = DOM.createDiv();
- DOM.setStyleAttribute(loadElement, "position", "absolute");
- DOM.appendChild(view.getElement(), loadElement);
- }
- DOM.setElementProperty(loadElement, "className",
- "i-loading-indicator");
- DOM.setStyleAttribute(loadElement, "display", "block");
- // Position
- DOM.setStyleAttribute(loadElement, "top", (view
- .getAbsoluteTop() + 6)
- + "px");
- DOM.setStyleAttribute(loadElement, "left",
- (view.getAbsoluteLeft()
- + view.getOffsetWidth()
- - DOM.getElementPropertyInt(loadElement,
- "offsetWidth") - 5)
- + "px");
-
- // Initialize other timers
- Timer delay = new Timer() {
- public void run() {
- DOM.setElementProperty(loadElement, "className",
- "i-loading-indicator-delay");
- }
- };
- // Second one kicks in at 1500ms
- delay.schedule(1200);
-
- Timer wait = new Timer() {
- public void run() {
- DOM.setElementProperty(loadElement, "className",
- "i-loading-indicator-wait");
- }
- };
- // Third one kicks in at 5000ms
- wait.schedule(4700);
- }
- };
- // First one kicks in at 300ms
- loadTimer.schedule(300);
- }
-
- private void hideLoadingIndicator() {
- if (loadTimer != null)
- loadTimer.cancel();
- if (loadElement != null)
- DOM.setStyleAttribute(loadElement, "display", "none");
- }
-
- private void handleReceivedJSONMessage(Response response) {
- hideLoadingIndicator();
-
- Date start = new Date();
- String jsonText = response.getText().substring(3) + "}";
- JSONValue json;
- try {
- json = JSONParser.parse(jsonText);
- } catch (com.google.gwt.json.client.JSONException e) {
- console.log(e.getMessage() + " - Original JSON-text:");
- console.log(jsonText);
- return;
- }
- // Handle redirect
- JSONObject redirect = (JSONObject) ((JSONObject) json).get("redirect");
- if (redirect != null) {
- JSONString url = (JSONString) redirect.get("url");
- if (url != null) {
- console.log("redirecting to " + url.stringValue());
- redirect(url.stringValue());
- return;
- }
- }
-
- // Store resources
- JSONObject resources = (JSONObject) ((JSONObject) json)
- .get("resources");
- for (Iterator i = resources.keySet().iterator(); i.hasNext();) {
- String key = (String) i.next();
- resourcesMap.put(key, ((JSONString) resources.get(key))
- .stringValue());
- }
-
- // Store locale data
- if (((JSONObject) json).containsKey("locales")) {
- JSONArray l = (JSONArray) ((JSONObject) json).get("locales");
- for (int i = 0; i < l.size(); i++) {
- LocaleService.addLocale((JSONObject) l.get(i));
- }
- }
-
- // Process changes
- JSONArray changes = (JSONArray) ((JSONObject) json).get("changes");
- for (int i = 0; i < changes.size(); i++) {
- try {
- UIDL change = new UIDL((JSONArray) changes.get(i));
- try {
- console.dirUIDL(change);
- } catch (Exception e) {
- console.log(e.getMessage());
- // TODO: dir doesn't work in any browser although it should
- // work (works in hosted mode)
- // it partially did at some part but now broken.
- }
- UIDL uidl = change.getChildUIDL(0);
- Paintable paintable = getPaintable(uidl.getId());
- if (paintable != null) {
- paintable.updateFromUIDL(uidl, this);
- } else {
- if (!uidl.getTag().equals("window")) {
- System.out.println("Received update for "
- + uidl.getTag()
- + ", but there is no such paintable ("
- + uidl.getId() + ") rendered.");
- } else {
- view.updateFromUIDL(uidl, this);
- }
- }
- } catch (Throwable e) {
- e.printStackTrace();
- }
- }
-
- if (((JSONObject) json).containsKey("meta")) {
- JSONObject meta = ((JSONObject) json).get("meta").isObject();
- if (meta.containsKey("focus")) {
- String focusPid = meta.get("focus").isString().stringValue();
- Paintable toBeFocused = getPaintable(focusPid);
- if (toBeFocused instanceof HasFocus) {
- HasFocus toBeFocusedWidget = (HasFocus) toBeFocused;
- toBeFocusedWidget.setFocus(true);
- }
- }
- }
-
- long prosessingTime = (new Date().getTime()) - start.getTime();
- console.log(" Processing time was " + String.valueOf(prosessingTime)
- + "ms for " + jsonText.length() + " characters of JSON");
- console.log("Referenced paintables: " + idToPaintable.size());
-
- }
-
- // Redirect browser
- private static native void redirect(String url)
- /*-{
- $wnd.location = url;
- }-*/;
-
- public void registerPaintable(String id, Paintable paintable) {
- idToPaintable.put(id, paintable);
- paintableToId.put(paintable, id);
- }
-
- public void unregisterPaintable(Paintable p) {
- idToPaintable.remove(paintableToId.get(p));
- paintableToId.remove(p);
-
- if (p instanceof HasWidgets) {
- unregisterChildPaintables((HasWidgets) p);
- }
- }
-
- public void unregisterChildPaintables(HasWidgets container) {
- Iterator it = container.iterator();
- while (it.hasNext()) {
- Widget w = (Widget) it.next();
- if (w instanceof Paintable) {
- unregisterPaintable((Paintable) w);
- }
- if (w instanceof HasWidgets) {
- unregisterChildPaintables((HasWidgets) w);
- }
- }
- }
-
- /**
- * Returns Paintable element by its id
- *
- * @param id
- * Paintable ID
- */
- public Paintable getPaintable(String id) {
- return (Paintable) idToPaintable.get(id);
- }
-
- private void addVariableToQueue(String paintableId, String variableName,
- String encodedValue, boolean immediate, char type) {
- String id = paintableId + "_" + variableName + "_" + type;
- for (int i = 0; i < pendingVariables.size(); i += 2) {
- if ((pendingVariables.get(i)).equals(id)) {
- pendingVariables.remove(i);
- pendingVariables.remove(i);
- break;
- }
- }
- pendingVariables.add(id);
- pendingVariables.add(encodedValue);
- if (immediate) {
- sendPendingVariableChanges();
- }
- }
-
- public void sendPendingVariableChanges() {
- StringBuffer req = new StringBuffer();
-
- req.append("changes=");
- for (int i = 0; i < pendingVariables.size(); i++) {
- if (i > 0) {
- req.append("\u0001");
- }
- req.append(pendingVariables.get(i));
- }
-
- pendingVariables.clear();
- makeUidlRequest(req.toString());
- }
-
- private static native String escapeString(String value)
- /*-{
- return encodeURIComponent(value);
- }-*/;
-
- public void updateVariable(String paintableId, String variableName,
- String newValue, boolean immediate) {
- addVariableToQueue(paintableId, variableName, escapeString(newValue),
- immediate, 's');
- }
-
- public void updateVariable(String paintableId, String variableName,
- int newValue, boolean immediate) {
- addVariableToQueue(paintableId, variableName, "" + newValue, immediate,
- 'i');
- }
-
- public void updateVariable(String paintableId, String variableName,
- long newValue, boolean immediate) {
- addVariableToQueue(paintableId, variableName, "" + newValue, immediate,
- 'l');
- }
-
- public void updateVariable(String paintableId, String variableName,
- float newValue, boolean immediate) {
- addVariableToQueue(paintableId, variableName, "" + newValue, immediate,
- 'f');
- }
-
- public void updateVariable(String paintableId, String variableName,
- double newValue, boolean immediate) {
- addVariableToQueue(paintableId, variableName, "" + newValue, immediate,
- 'd');
- }
-
- public void updateVariable(String paintableId, String variableName,
- boolean newValue, boolean immediate) {
- addVariableToQueue(paintableId, variableName, newValue ? "true"
- : "false", immediate, 'b');
- }
-
- public void updateVariable(String paintableId, String variableName,
- Object[] values, boolean immediate) {
- StringBuffer buf = new StringBuffer();
- for (int i = 0; i < values.length; i++) {
- if (i > 0) {
- buf.append(",");
- }
- buf.append(escapeString(values[i].toString()));
- }
- addVariableToQueue(paintableId, variableName, buf.toString(),
- immediate, 'a');
- }
-
- public static Container getParentLayout(Widget component) {
- Widget parent = component.getParent();
- while (parent != null && !(parent instanceof Container)) {
- parent = parent.getParent();
- }
- if (parent != null && ((Container) parent).hasChildComponent(component)) {
- return (Container) parent;
- }
- return null;
- }
-
- /**
- * Update generic component features.
- *
- * Selecting correct implementation
- *
- *
- * The implementation of a component depends on many properties, including
- * styles, component features, etc. Sometimes the user changes those
- * properties after the component has been created. Calling this method in
- * the beginning of your updateFromUIDL -method automatically replaces your
- * component with more appropriate if the requested implementation changes.
- *
- *
- * Caption, icon, error messages and description
- *
- *
- * Component can delegate management of caption, icon, error messages and
- * description to parent layout. This is optional an should be decided by
- * component author
- *
- *
- * Component visibility and disabling
- *
- * This method will manage component visibility automatically and if
- * component is an instanceof FocusWidget, also handle component disabling
- * when needed.
- *
- * @param currentWidget
- * Current widget that might need replacement
- * @param uidl
- * UIDL to be painted
- * @param manageCaption
- * True if you want to delegate caption, icon, description and
- * error message management to parent.
- *
- * @return Returns true iff no further painting is needed by caller
- */
- public boolean updateComponent(Widget component, UIDL uidl,
- boolean manageCaption) {
-
- // If the server request that a cached instance should be used, do
- // nothing
- if (uidl.getBooleanAttribute("cached")) {
- return true;
- }
-
- // Visibility
- boolean visible = !uidl.getBooleanAttribute("invisible");
- component.setVisible(visible);
- if (!visible) {
- return true;
- }
-
- // Switch to correct implementation if needed
- if (!widgetSet.isCorrectImplementation(component, uidl)) {
- Container parent = getParentLayout(component);
- if (parent != null) {
- Widget w = widgetSet.createWidget(uidl);
- parent.replaceChildComponent(component, w);
- registerPaintable(uidl.getId(), (Paintable) w);
- ((Paintable) w).updateFromUIDL(uidl, this);
- return true;
- }
- }
-
- // Set captions
- // TODO Manage Error messages
- if (manageCaption) {
- Container parent = getParentLayout(component);
- if (parent != null) {
- parent.updateCaption((Paintable) component, uidl);
- }
- }
-
- // Styles + disabled & readonly
- component.setStyleName(component.getStylePrimaryName());
-
- // first disabling and read-only status
- boolean enabled = true;
- if (uidl.hasAttribute("disabled")) {
- enabled = !uidl.getBooleanAttribute("disabled");
- } else if (uidl.hasAttribute("readonly")) {
- enabled = !uidl.getBooleanAttribute("readonly");
- }
- if (component instanceof FocusWidget) {
- ((FocusWidget) component).setEnabled(enabled);
- }
- if (!enabled) {
- component.addStyleName("i-disabled");
- } else {
- component.removeStyleName("i-disabled");
- }
-
- // add additional styles as css classes, prefixed with component default
- // stylename
- if (uidl.hasAttribute("style")) {
- String[] styles = uidl.getStringAttribute("style").split(" ");
- for (int i = 0; i < styles.length; i++) {
- component.addStyleDependentName(styles[i]);
- }
- }
-
- return false;
- }
-
- /**
- * Get either existing or new widget for given UIDL.
- *
- * If corresponding paintable has been previously painted, return it.
- * Otherwise create and register a new widget from UIDL. Caller must update
- * the returned widget from UIDL after it has been connected to parent.
- *
- * @param uidl
- * UIDL to create widget from.
- * @return Either existing or new widget corresponding to UIDL.
- */
- public Widget getWidget(UIDL uidl) {
- String id = uidl.getId();
- Widget w = (Widget) getPaintable(id);
- if (w != null) {
- return w;
- }
- w = widgetSet.createWidget(uidl);
- registerPaintable(id, (Paintable) w);
- return w;
- }
-
- public String getResource(String name) {
- return (String) resourcesMap.get(name);
- }
-
- /**
- * Singleton method to get instance of app's context menu.
- *
- * @return IContextMenu object
- */
- public ContextMenu getContextMenu() {
- if (contextMenu == null) {
- contextMenu = new ContextMenu();
- }
- return contextMenu;
- }
-
- /**
- * Translates custom protocols in UIRL URI's to be recognizable by browser.
- * All uri's from UIDL should be routed via this method before giving them
- * to browser due URI's in UIDL may contain custom protocols like theme://.
- *
- * @param toolkitUri
- * toolkit URI from uidl
- * @return translated URI ready for browser
- */
- public String translateToolkitUri(String toolkitUri) {
- if (toolkitUri.startsWith("theme")) {
- toolkitUri = getThemeUri() + toolkitUri.substring(7);
- }
- return toolkitUri;
- }
+ private Vector pendingVariables = new Vector();
+
+ private HashMap idToPaintable = new HashMap();
+
+ private HashMap paintableToId = new HashMap();
+
+ private final WidgetSet widgetSet;
+
+ private ContextMenu contextMenu = null;
+
+ private Timer loadTimer;
+ private Element loadElement;
+
+ private IView view;
+
+ public ApplicationConnection(WidgetSet widgetSet) {
+ this.widgetSet = widgetSet;
+ appUri = getAppUri();
+
+ if (isDebugMode()) {
+ console = new DebugConsole(this);
+ } else {
+ console = new NullConsole();
+ }
+
+ makeUidlRequest("repaintAll=1");
+
+ // TODO remove hardcoded id name
+ view = new IView("itmill-ajax-window");
+
+ }
+
+ public static Console getConsole() {
+ return console;
+ }
+
+ private native static boolean isDebugMode()
+ /*-{
+ var uri = $wnd.location;
+ var re = /debug[^\/]*$/;
+ return re.test(uri);
+ }-*/;
+
+ public native String getAppUri()
+ /*-{
+ var u = $wnd.itmill.appUri;
+ if (u.indexOf("/") != 0 && u.indexOf("http") != 0) {
+ var b = $wnd.location.href;
+ var i = b.length-1;
+ while (b.charAt(i) != "/" && i>0) i--;
+ b = b.substring(0,i+1);
+ u = b + u;
+ }
+ return u;
+ }-*/;
+
+ private native String getPathInfo()
+ /*-{
+ return $wnd.itmill.pathInfo;
+ }-*/;
+
+ private native String getThemeUri()
+ /*-{
+ return $wnd.itmill.themeUri;
+ }-*/;
+
+ private void makeUidlRequest(String requestData) {
+
+ // place loading indicator
+ showLoadingIndicator();
+
+ console.log("Making UIDL Request with params: " + requestData);
+ String uri = appUri + "/UIDL" + getPathInfo();
+ RequestBuilder rb = new RequestBuilder(RequestBuilder.POST, uri);
+ rb.setHeader("Content-Type",
+ "application/x-www-form-urlencoded; charset=utf-8");
+ try {
+ rb.sendRequest(requestData, new RequestCallback() {
+ public void onError(Request request, Throwable exception) {
+ // TODO Better reporting to user
+ console.error("Got error");
+ }
+
+ public void onResponseReceived(Request request,
+ Response response) {
+ handleReceivedJSONMessage(response);
+ }
+
+ });
+
+ } catch (RequestException e) {
+ // TODO Better reporting to user
+ console.error(e.getMessage());
+ }
+ }
+
+ private void showLoadingIndicator() {
+ loadTimer = new Timer() {
+ public void run() {
+ // show initial throbber
+ if (loadElement == null) {
+ loadElement = DOM.createDiv();
+ DOM.setStyleAttribute(loadElement, "position", "absolute");
+ DOM.appendChild(view.getElement(), loadElement);
+ }
+ DOM.setElementProperty(loadElement, "className",
+ "i-loading-indicator");
+ DOM.setStyleAttribute(loadElement, "display", "block");
+ // Position
+ DOM.setStyleAttribute(loadElement, "top", (view
+ .getAbsoluteTop() + 6)
+ + "px");
+ DOM.setStyleAttribute(loadElement, "left",
+ (view.getAbsoluteLeft()
+ + view.getOffsetWidth()
+ - DOM.getElementPropertyInt(loadElement,
+ "offsetWidth") - 5)
+ + "px");
+
+ // Initialize other timers
+ Timer delay = new Timer() {
+ public void run() {
+ DOM.setElementProperty(loadElement, "className",
+ "i-loading-indicator-delay");
+ }
+ };
+ // Second one kicks in at 1500ms
+ delay.schedule(1200);
+
+ Timer wait = new Timer() {
+ public void run() {
+ DOM.setElementProperty(loadElement, "className",
+ "i-loading-indicator-wait");
+ }
+ };
+ // Third one kicks in at 5000ms
+ wait.schedule(4700);
+ }
+ };
+ // First one kicks in at 300ms
+ loadTimer.schedule(300);
+ }
+
+ private void hideLoadingIndicator() {
+ if (loadTimer != null) {
+ loadTimer.cancel();
+ }
+ if (loadElement != null) {
+ DOM.setStyleAttribute(loadElement, "display", "none");
+ }
+ }
+
+ private void handleReceivedJSONMessage(Response response) {
+ hideLoadingIndicator();
+
+ Date start = new Date();
+ String jsonText = response.getText().substring(3) + "}";
+ JSONValue json;
+ try {
+ json = JSONParser.parse(jsonText);
+ } catch (com.google.gwt.json.client.JSONException e) {
+ console.log(e.getMessage() + " - Original JSON-text:");
+ console.log(jsonText);
+ return;
+ }
+ // Handle redirect
+ JSONObject redirect = (JSONObject) ((JSONObject) json).get("redirect");
+ if (redirect != null) {
+ JSONString url = (JSONString) redirect.get("url");
+ if (url != null) {
+ console.log("redirecting to " + url.stringValue());
+ redirect(url.stringValue());
+ return;
+ }
+ }
+
+ // Store resources
+ JSONObject resources = (JSONObject) ((JSONObject) json)
+ .get("resources");
+ for (Iterator i = resources.keySet().iterator(); i.hasNext();) {
+ String key = (String) i.next();
+ resourcesMap.put(key, ((JSONString) resources.get(key))
+ .stringValue());
+ }
+
+ // Store locale data
+ if (((JSONObject) json).containsKey("locales")) {
+ JSONArray l = (JSONArray) ((JSONObject) json).get("locales");
+ for (int i = 0; i < l.size(); i++) {
+ LocaleService.addLocale((JSONObject) l.get(i));
+ }
+ }
+
+ // Process changes
+ JSONArray changes = (JSONArray) ((JSONObject) json).get("changes");
+ for (int i = 0; i < changes.size(); i++) {
+ try {
+ UIDL change = new UIDL((JSONArray) changes.get(i));
+ try {
+ console.dirUIDL(change);
+ } catch (Exception e) {
+ console.log(e.getMessage());
+ // TODO: dir doesn't work in any browser although it should
+ // work (works in hosted mode)
+ // it partially did at some part but now broken.
+ }
+ UIDL uidl = change.getChildUIDL(0);
+ Paintable paintable = getPaintable(uidl.getId());
+ if (paintable != null) {
+ paintable.updateFromUIDL(uidl, this);
+ } else {
+ if (!uidl.getTag().equals("window")) {
+ System.out.println("Received update for "
+ + uidl.getTag()
+ + ", but there is no such paintable ("
+ + uidl.getId() + ") rendered.");
+ } else {
+ view.updateFromUIDL(uidl, this);
+ }
+ }
+ } catch (Throwable e) {
+ e.printStackTrace();
+ }
+ }
+
+ if (((JSONObject) json).containsKey("meta")) {
+ JSONObject meta = ((JSONObject) json).get("meta").isObject();
+ if (meta.containsKey("focus")) {
+ String focusPid = meta.get("focus").isString().stringValue();
+ Paintable toBeFocused = getPaintable(focusPid);
+ if (toBeFocused instanceof HasFocus) {
+ HasFocus toBeFocusedWidget = (HasFocus) toBeFocused;
+ toBeFocusedWidget.setFocus(true);
+ }
+ }
+ }
+
+ long prosessingTime = (new Date().getTime()) - start.getTime();
+ console.log(" Processing time was " + String.valueOf(prosessingTime)
+ + "ms for " + jsonText.length() + " characters of JSON");
+ console.log("Referenced paintables: " + idToPaintable.size());
+
+ }
+
+ // Redirect browser
+ private static native void redirect(String url)
+ /*-{
+ $wnd.location = url;
+ }-*/;
+
+ public void registerPaintable(String id, Paintable paintable) {
+ idToPaintable.put(id, paintable);
+ paintableToId.put(paintable, id);
+ }
+
+ public void unregisterPaintable(Paintable p) {
+ idToPaintable.remove(paintableToId.get(p));
+ paintableToId.remove(p);
+
+ if (p instanceof HasWidgets) {
+ unregisterChildPaintables((HasWidgets) p);
+ }
+ }
+
+ public void unregisterChildPaintables(HasWidgets container) {
+ Iterator it = container.iterator();
+ while (it.hasNext()) {
+ Widget w = (Widget) it.next();
+ if (w instanceof Paintable) {
+ unregisterPaintable((Paintable) w);
+ }
+ if (w instanceof HasWidgets) {
+ unregisterChildPaintables((HasWidgets) w);
+ }
+ }
+ }
+
+ /**
+ * Returns Paintable element by its id
+ *
+ * @param id
+ * Paintable ID
+ */
+ public Paintable getPaintable(String id) {
+ return (Paintable) idToPaintable.get(id);
+ }
+
+ private void addVariableToQueue(String paintableId, String variableName,
+ String encodedValue, boolean immediate, char type) {
+ String id = paintableId + "_" + variableName + "_" + type;
+ for (int i = 0; i < pendingVariables.size(); i += 2) {
+ if ((pendingVariables.get(i)).equals(id)) {
+ pendingVariables.remove(i);
+ pendingVariables.remove(i);
+ break;
+ }
+ }
+ pendingVariables.add(id);
+ pendingVariables.add(encodedValue);
+ if (immediate) {
+ sendPendingVariableChanges();
+ }
+ }
+
+ public void sendPendingVariableChanges() {
+ StringBuffer req = new StringBuffer();
+
+ req.append("changes=");
+ for (int i = 0; i < pendingVariables.size(); i++) {
+ if (i > 0) {
+ req.append("\u0001");
+ }
+ req.append(pendingVariables.get(i));
+ }
+
+ pendingVariables.clear();
+ makeUidlRequest(req.toString());
+ }
+
+ private static native String escapeString(String value)
+ /*-{
+ return encodeURIComponent(value);
+ }-*/;
+
+ public void updateVariable(String paintableId, String variableName,
+ String newValue, boolean immediate) {
+ addVariableToQueue(paintableId, variableName, escapeString(newValue),
+ immediate, 's');
+ }
+
+ public void updateVariable(String paintableId, String variableName,
+ int newValue, boolean immediate) {
+ addVariableToQueue(paintableId, variableName, "" + newValue, immediate,
+ 'i');
+ }
+
+ public void updateVariable(String paintableId, String variableName,
+ long newValue, boolean immediate) {
+ addVariableToQueue(paintableId, variableName, "" + newValue, immediate,
+ 'l');
+ }
+
+ public void updateVariable(String paintableId, String variableName,
+ float newValue, boolean immediate) {
+ addVariableToQueue(paintableId, variableName, "" + newValue, immediate,
+ 'f');
+ }
+
+ public void updateVariable(String paintableId, String variableName,
+ double newValue, boolean immediate) {
+ addVariableToQueue(paintableId, variableName, "" + newValue, immediate,
+ 'd');
+ }
+
+ public void updateVariable(String paintableId, String variableName,
+ boolean newValue, boolean immediate) {
+ addVariableToQueue(paintableId, variableName, newValue ? "true"
+ : "false", immediate, 'b');
+ }
+
+ public void updateVariable(String paintableId, String variableName,
+ Object[] values, boolean immediate) {
+ StringBuffer buf = new StringBuffer();
+ for (int i = 0; i < values.length; i++) {
+ if (i > 0) {
+ buf.append(",");
+ }
+ buf.append(escapeString(values[i].toString()));
+ }
+ addVariableToQueue(paintableId, variableName, buf.toString(),
+ immediate, 'a');
+ }
+
+ public static Container getParentLayout(Widget component) {
+ Widget parent = component.getParent();
+ while (parent != null && !(parent instanceof Container)) {
+ parent = parent.getParent();
+ }
+ if (parent != null && ((Container) parent).hasChildComponent(component)) {
+ return (Container) parent;
+ }
+ return null;
+ }
+
+ /**
+ * Update generic component features.
+ *
+ * Selecting correct implementation
+ *
+ *
+ * The implementation of a component depends on many properties, including
+ * styles, component features, etc. Sometimes the user changes those
+ * properties after the component has been created. Calling this method in
+ * the beginning of your updateFromUIDL -method automatically replaces your
+ * component with more appropriate if the requested implementation changes.
+ *
+ *
+ * Caption, icon, error messages and description
+ *
+ *
+ * Component can delegate management of caption, icon, error messages and
+ * description to parent layout. This is optional an should be decided by
+ * component author
+ *
+ *
+ * Component visibility and disabling
+ *
+ * This method will manage component visibility automatically and if
+ * component is an instanceof FocusWidget, also handle component disabling
+ * when needed.
+ *
+ * @param currentWidget
+ * Current widget that might need replacement
+ * @param uidl
+ * UIDL to be painted
+ * @param manageCaption
+ * True if you want to delegate caption, icon, description
+ * and error message management to parent.
+ *
+ * @return Returns true iff no further painting is needed by caller
+ */
+ public boolean updateComponent(Widget component, UIDL uidl,
+ boolean manageCaption) {
+
+ // If the server request that a cached instance should be used, do
+ // nothing
+ if (uidl.getBooleanAttribute("cached")) {
+ return true;
+ }
+
+ // Visibility
+ boolean visible = !uidl.getBooleanAttribute("invisible");
+ component.setVisible(visible);
+ if (!visible) {
+ return true;
+ }
+
+ // Switch to correct implementation if needed
+ if (!widgetSet.isCorrectImplementation(component, uidl)) {
+ Container parent = getParentLayout(component);
+ if (parent != null) {
+ Widget w = widgetSet.createWidget(uidl);
+ parent.replaceChildComponent(component, w);
+ registerPaintable(uidl.getId(), (Paintable) w);
+ ((Paintable) w).updateFromUIDL(uidl, this);
+ return true;
+ }
+ }
+
+ // Set captions
+ // TODO Manage Error messages
+ if (manageCaption) {
+ Container parent = getParentLayout(component);
+ if (parent != null) {
+ parent.updateCaption((Paintable) component, uidl);
+ }
+ }
+
+ // Styles + disabled & readonly
+ component.setStyleName(component.getStylePrimaryName());
+
+ // first disabling and read-only status
+ boolean enabled = true;
+ if (uidl.hasAttribute("disabled")) {
+ enabled = !uidl.getBooleanAttribute("disabled");
+ } else if (uidl.hasAttribute("readonly")) {
+ enabled = !uidl.getBooleanAttribute("readonly");
+ }
+ if (component instanceof FocusWidget) {
+ ((FocusWidget) component).setEnabled(enabled);
+ }
+ if (!enabled) {
+ component.addStyleName("i-disabled");
+ } else {
+ component.removeStyleName("i-disabled");
+ }
+
+ // add additional styles as css classes, prefixed with component default
+ // stylename
+ if (uidl.hasAttribute("style")) {
+ String[] styles = uidl.getStringAttribute("style").split(" ");
+ for (int i = 0; i < styles.length; i++) {
+ component.addStyleDependentName(styles[i]);
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Get either existing or new widget for given UIDL.
+ *
+ * If corresponding paintable has been previously painted, return it.
+ * Otherwise create and register a new widget from UIDL. Caller must update
+ * the returned widget from UIDL after it has been connected to parent.
+ *
+ * @param uidl
+ * UIDL to create widget from.
+ * @return Either existing or new widget corresponding to UIDL.
+ */
+ public Widget getWidget(UIDL uidl) {
+ String id = uidl.getId();
+ Widget w = (Widget) getPaintable(id);
+ if (w != null) {
+ return w;
+ }
+ w = widgetSet.createWidget(uidl);
+ registerPaintable(id, (Paintable) w);
+ return w;
+ }
+
+ public String getResource(String name) {
+ return (String) resourcesMap.get(name);
+ }
+
+ /**
+ * Singleton method to get instance of app's context menu.
+ *
+ * @return IContextMenu object
+ */
+ public ContextMenu getContextMenu() {
+ if (contextMenu == null) {
+ contextMenu = new ContextMenu();
+ }
+ return contextMenu;
+ }
+
+ /**
+ * Translates custom protocols in UIRL URI's to be recognizable by browser.
+ * All uri's from UIDL should be routed via this method before giving them
+ * to browser due URI's in UIDL may contain custom protocols like theme://.
+ *
+ * @param toolkitUri
+ * toolkit URI from uidl
+ * @return translated URI ready for browser
+ */
+ public String translateToolkitUri(String toolkitUri) {
+ if (toolkitUri.startsWith("theme")) {
+ toolkitUri = getThemeUri() + toolkitUri.substring(7);
+ }
+ return toolkitUri;
+ }
}
diff --git a/src/com/itmill/toolkit/terminal/gwt/client/Console.java b/src/com/itmill/toolkit/terminal/gwt/client/Console.java
index 048e6aa925..37c911032d 100644
--- a/src/com/itmill/toolkit/terminal/gwt/client/Console.java
+++ b/src/com/itmill/toolkit/terminal/gwt/client/Console.java
@@ -2,12 +2,12 @@ package com.itmill.toolkit.terminal.gwt.client;
public interface Console {
- public abstract void log(String msg);
+ public abstract void log(String msg);
- public abstract void error(String msg);
+ public abstract void error(String msg);
- public abstract void printObject(Object msg);
+ public abstract void printObject(Object msg);
- public abstract void dirUIDL(UIDL u);
+ public abstract void dirUIDL(UIDL u);
}
\ No newline at end of file
diff --git a/src/com/itmill/toolkit/terminal/gwt/client/Container.java b/src/com/itmill/toolkit/terminal/gwt/client/Container.java
index 174e44f516..5e0fe8df31 100644
--- a/src/com/itmill/toolkit/terminal/gwt/client/Container.java
+++ b/src/com/itmill/toolkit/terminal/gwt/client/Container.java
@@ -4,45 +4,45 @@ import com.google.gwt.user.client.ui.Widget;
public interface Container extends Paintable {
- /**
- * Replace child of this layout with another component.
- *
- * Each layout must be able to switch children. To to this, one must just
- * give references to a current and new child. Note that the Layout is not
- * responsible for registering Paintable into ApplicationConnection, but it
- * is responsible is for unregistering it.
- *
- * @param oldComponent
- * Child to be replaced
- * @param newComponent
- * Child that replaces the oldComponent
- */
- void replaceChildComponent(Widget oldComponent, Widget newComponent);
+ /**
+ * Replace child of this layout with another component.
+ *
+ * Each layout must be able to switch children. To to this, one must just
+ * give references to a current and new child. Note that the Layout is not
+ * responsible for registering Paintable into ApplicationConnection, but it
+ * is responsible is for unregistering it.
+ *
+ * @param oldComponent
+ * Child to be replaced
+ * @param newComponent
+ * Child that replaces the oldComponent
+ */
+ void replaceChildComponent(Widget oldComponent, Widget newComponent);
- /**
- * Is a given component child of this layout.
- *
- * @param component
- * Component to test.
- * @return true iff component is a child of this layout.
- */
- boolean hasChildComponent(Widget component);
+ /**
+ * Is a given component child of this layout.
+ *
+ * @param component
+ * Component to test.
+ * @return true iff component is a child of this layout.
+ */
+ boolean hasChildComponent(Widget component);
- /**
- * Update child components caption, description and error message.
- *
- *
- * Each component is responsible for maintaining its caption, description
- * and error message. In most cases components doesn't want to do that and
- * those elements reside outside of the component. Because of this layouts
- * must provide service for it's childen to show those elements for them.
- *
- *
- * @param component
- * Child component for which service is requested.
- * @param uidl
- * UIDL of the child component.
- */
- void updateCaption(Paintable component, UIDL uidl);
+ /**
+ * Update child components caption, description and error message.
+ *
+ *
+ * Each component is responsible for maintaining its caption, description
+ * and error message. In most cases components doesn't want to do that and
+ * those elements reside outside of the component. Because of this layouts
+ * must provide service for it's childen to show those elements for them.
+ *
+ *
+ * @param component
+ * Child component for which service is requested.
+ * @param uidl
+ * UIDL of the child component.
+ */
+ void updateCaption(Paintable component, UIDL uidl);
}
diff --git a/src/com/itmill/toolkit/terminal/gwt/client/ContainerResizedListener.java b/src/com/itmill/toolkit/terminal/gwt/client/ContainerResizedListener.java
index 7248b1d921..22d92355d1 100644
--- a/src/com/itmill/toolkit/terminal/gwt/client/ContainerResizedListener.java
+++ b/src/com/itmill/toolkit/terminal/gwt/client/ContainerResizedListener.java
@@ -5,12 +5,12 @@ package com.itmill.toolkit.terminal.gwt.client;
* relative sizes and who need some additional sizing logic.
*/
public interface ContainerResizedListener {
- /**
- * This function is run when container box has been resized. Object
- * implementing ContainerResizedListener is responsible to call the same
- * function on its ancestors that implement NeedsLayout in case their
- * container has resized. runAnchestorsLayout(HasWidgets parent) function
- * from Util class may be a good helper for this.
- */
- public void iLayout();
+ /**
+ * This function is run when container box has been resized. Object
+ * implementing ContainerResizedListener is responsible to call the same
+ * function on its ancestors that implement NeedsLayout in case their
+ * container has resized. runAnchestorsLayout(HasWidgets parent) function
+ * from Util class may be a good helper for this.
+ */
+ public void iLayout();
}
diff --git a/src/com/itmill/toolkit/terminal/gwt/client/DateLocale.java b/src/com/itmill/toolkit/terminal/gwt/client/DateLocale.java
index fec5417a01..7cc4ace944 100644
--- a/src/com/itmill/toolkit/terminal/gwt/client/DateLocale.java
+++ b/src/com/itmill/toolkit/terminal/gwt/client/DateLocale.java
@@ -1,64 +1,65 @@
package com.itmill.toolkit.terminal.gwt.client;
public class DateLocale extends
- com.itmill.toolkit.terminal.gwt.client.util.DateLocale {
+ com.itmill.toolkit.terminal.gwt.client.util.DateLocale {
- private static String locale;
+ private static String locale;
- public DateLocale() {
- locale = LocaleService.getDefaultLocale();
- }
+ public DateLocale() {
+ locale = LocaleService.getDefaultLocale();
+ }
- public static void setLocale(String l) {
- if (LocaleService.getAvailableLocales().contains(locale))
- locale = l;
- else
- // TODO redirect to console
- System.out.println("Tried to use an unloaded locale \"" + locale
- + "\". Using default in stead (" + locale + ")");
- }
+ public static void setLocale(String l) {
+ if (LocaleService.getAvailableLocales().contains(locale)) {
+ locale = l;
+ } else {
+ // TODO redirect to console
+ System.out.println("Tried to use an unloaded locale \"" + locale
+ + "\". Using default in stead (" + locale + ")");
+ }
+ }
- public static String getAM() {
- try {
- return LocaleService.getAmPmStrings(locale)[0];
- } catch (LocaleNotLoadedException e) {
- // TODO redirect to console
- System.out.println("Tried to use an unloaded locale \"" + locale
- + "\".");
- return "AM";
- }
- }
+ public static String getAM() {
+ try {
+ return LocaleService.getAmPmStrings(locale)[0];
+ } catch (LocaleNotLoadedException e) {
+ // TODO redirect to console
+ System.out.println("Tried to use an unloaded locale \"" + locale
+ + "\".");
+ return "AM";
+ }
+ }
- public static String getPM() {
- try {
- return LocaleService.getAmPmStrings(locale)[1];
- } catch (LocaleNotLoadedException e) {
- // TODO redirect to console
- System.out.println("Tried to use an unloaded locale \"" + locale
- + "\".");
- return "PM";
- }
- }
+ public static String getPM() {
+ try {
+ return LocaleService.getAmPmStrings(locale)[1];
+ } catch (LocaleNotLoadedException e) {
+ // TODO redirect to console
+ System.out.println("Tried to use an unloaded locale \"" + locale
+ + "\".");
+ return "PM";
+ }
+ }
- public String[] getWEEKDAY_LONG() {
- try {
- return LocaleService.getDayNames(locale);
- } catch (LocaleNotLoadedException e) {
- // TODO redirect to console
- System.out.println("Tried to use an unloaded locale \"" + locale
- + "\".");
- return null;
- }
- }
+ public String[] getWEEKDAY_LONG() {
+ try {
+ return LocaleService.getDayNames(locale);
+ } catch (LocaleNotLoadedException e) {
+ // TODO redirect to console
+ System.out.println("Tried to use an unloaded locale \"" + locale
+ + "\".");
+ return null;
+ }
+ }
- public String[] getWEEKDAY_SHORT() {
- try {
- return LocaleService.getShortDayNames(locale);
- } catch (LocaleNotLoadedException e) {
- // TODO redirect to console
- System.out.println("Tried to use an unloaded locale \"" + locale
- + "\".");
- return null;
- }
- }
+ public String[] getWEEKDAY_SHORT() {
+ try {
+ return LocaleService.getShortDayNames(locale);
+ } catch (LocaleNotLoadedException e) {
+ // TODO redirect to console
+ System.out.println("Tried to use an unloaded locale \"" + locale
+ + "\".");
+ return null;
+ }
+ }
}
diff --git a/src/com/itmill/toolkit/terminal/gwt/client/DateTimeService.java b/src/com/itmill/toolkit/terminal/gwt/client/DateTimeService.java
index 9d4b28a555..02d77730f9 100644
--- a/src/com/itmill/toolkit/terminal/gwt/client/DateTimeService.java
+++ b/src/com/itmill/toolkit/terminal/gwt/client/DateTimeService.java
@@ -2,8 +2,6 @@ package com.itmill.toolkit.terminal.gwt.client;
import java.util.Date;
-import com.itmill.toolkit.terminal.gwt.client.ui.IDateField;
-
/**
* This class provides date/time parsing services to all components on the
* client side.
@@ -12,239 +10,242 @@ import com.itmill.toolkit.terminal.gwt.client.ui.IDateField;
*
*/
public class DateTimeService {
- public static int RESOLUTION_YEAR = 0;
- public static int RESOLUTION_MONTH = 1;
- public static int RESOLUTION_DAY = 2;
- public static int RESOLUTION_HOUR = 3;
- public static int RESOLUTION_MIN = 4;
- public static int RESOLUTION_SEC = 5;
- public static int RESOLUTION_MSEC = 6;
-
- private String currentLocale;
-
- private static int[] maxDaysInMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30,
- 31, 30, 31 };
-
- /**
- * Creates a new date time service with the application default locale.
- */
- public DateTimeService() {
- currentLocale = LocaleService.getDefaultLocale();
- }
-
- /**
- * Creates a new date time service with a given locale.
- *
- * @param locale
- * e.g. fi, en etc.
- * @throws LocaleNotLoadedException
- */
- public DateTimeService(String locale) throws LocaleNotLoadedException {
- setLocale(locale);
- }
-
- public void setLocale(String locale) throws LocaleNotLoadedException {
- if (LocaleService.getAvailableLocales().contains(locale))
- currentLocale = locale;
- else
- throw new LocaleNotLoadedException(locale);
- }
-
- public String getLocale() {
- return currentLocale;
- }
-
- public String getMonth(int month) {
- try {
- return LocaleService.getMonthNames(currentLocale)[month];
- } catch (LocaleNotLoadedException e) {
- // TODO redirect to console
- System.out.println(e + ":" + e.getMessage());
- }
- return null;
- }
-
- public String getShortMonth(int month) {
- try {
- return LocaleService.getShortMonthNames(currentLocale)[month];
- } catch (LocaleNotLoadedException e) {
- // TODO redirect to console
- System.out.println(e + ":" + e.getMessage());
- }
- return null;
- }
-
- public String getDay(int day) {
- try {
- return LocaleService.getDayNames(currentLocale)[day];
- } catch (LocaleNotLoadedException e) {
- // TODO redirect to console
- System.out.println(e + ":" + e.getMessage());
- }
- return null;
- }
-
- public String getShortDay(int day) {
- try {
- return LocaleService.getShortDayNames(currentLocale)[day];
- } catch (LocaleNotLoadedException e) {
- // TODO redirect to console
- System.out.println(e + ":" + e.getMessage());
- }
- return null;
- }
-
- public int getFirstDayOfWeek() {
- try {
- return LocaleService.getFirstDayOfWeek(currentLocale);
- } catch (LocaleNotLoadedException e) {
- // TODO redirect to console
- System.out.println(e + ":" + e.getMessage());
- }
- return 0;
- }
-
- public boolean isTwelveHourClock() {
- try {
- return LocaleService.isTwelveHourClock(currentLocale);
- } catch (LocaleNotLoadedException e) {
- // TODO redirect to console
- System.out.println(e + ":" + e.getMessage());
- }
- return false;
- }
-
- public String getClockDelimeter() {
- try {
- return LocaleService.getClockDelimiter(currentLocale);
- } catch (LocaleNotLoadedException e) {
- // TODO redirect to console
- System.out.println(e + ":" + e.getMessage());
- }
- return ":";
- }
-
- public String[] getAmPmStrings() {
- try {
- return LocaleService.getAmPmStrings(currentLocale);
- } catch (LocaleNotLoadedException e) {
- // TODO redirect to console
- System.out.println(e + ":" + e.getMessage());
- }
- String[] temp = new String[2];
- temp[0] = "AM";
- temp[1] = "PM";
- return temp;
- }
-
- public int getStartWeekDay(Date date) {
- Date dateForFirstOfThisMonth = new Date(date.getYear(),
- date.getMonth(), 1);
- int firstDay;
- try {
- firstDay = LocaleService.getFirstDayOfWeek(currentLocale);
- } catch (LocaleNotLoadedException e) {
- firstDay = 0;
- // TODO redirect to console
- System.out.println(e + ":" + e.getMessage());
- }
- int start = dateForFirstOfThisMonth.getDay() - firstDay;
- if (start < 0)
- start = 6;
- return start;
- }
-
- public String getDateFormat() {
- try {
- return LocaleService.getDateFormat(currentLocale);
- } catch (LocaleNotLoadedException e) {
- // TODO redirect to console
- System.out.println(e + ":" + e.getMessage());
- }
- return "M/d/yy";
- }
-
- public static int getNumberOfDaysInMonth(Date date) {
- int month = date.getMonth();
- if (month == 1 && true == isLeapYear(date))
- return 29;
- return maxDaysInMonth[month];
- }
-
- public static boolean isLeapYear(Date date) {
- // Instantiate the date for 1st March of that year
- Date firstMarch = new Date(date.getYear(), 2, 1);
-
- // Go back 1 day
- long firstMarchTime = firstMarch.getTime();
- long lastDayTimeFeb = firstMarchTime - (24 * 60 * 60 * 1000); // NUM_MILLISECS_A_DAY
-
- // Instantiate new Date with this time
- Date febLastDay = new Date(lastDayTimeFeb);
-
- // Check for date in this new instance
- return (29 == febLastDay.getDate()) ? true : false;
- }
-
- public static boolean isSameDay(Date d1, Date d2) {
- return (getDayInt(d1) == getDayInt(d2));
- }
-
- public static boolean isInRange(Date date, Date rangeStart, Date rangeEnd,
- int resolution) {
- Date s;
- Date e;
- if (rangeStart.after(rangeEnd)) {
- s = rangeEnd;
- e = rangeStart;
- } else {
- e = rangeEnd;
- s = rangeStart;
- }
- long start = s.getYear() * 10000000000l;
- long end = e.getYear() * 10000000000l;
- long target = date.getYear() * 10000000000l;
-
- if (resolution == RESOLUTION_YEAR) {
- return (start <= target && end >= target);
- }
- start += s.getMonth() * 100000000;
- end += e.getMonth() * 100000000;
- target += date.getMonth() * 100000000;
- if (resolution == RESOLUTION_MONTH) {
- return (start <= target && end >= target);
- }
- start += s.getDate() * 1000000;
- end += e.getDate() * 1000000;
- target += date.getDate() * 1000000;
- if (resolution == RESOLUTION_DAY) {
- return (start <= target && end >= target);
- }
- start += s.getHours() * 10000;
- end += e.getHours() * 10000;
- target += date.getHours() * 10000;
- if (resolution == RESOLUTION_HOUR) {
- return (start <= target && end >= target);
- }
- start += s.getMinutes() * 100;
- end += e.getMinutes() * 100;
- target += date.getMinutes() * 100;
- if (resolution == RESOLUTION_MIN) {
- return (start <= target && end >= target);
- }
- start += s.getSeconds();
- end += e.getSeconds();
- target += date.getSeconds();
- return (start <= target && end >= target);
-
- }
-
- private static int getDayInt(Date date) {
- int y = date.getYear();
- int m = date.getMonth();
- int d = date.getDate();
-
- return ((y + 1900) * 10000 + m * 100 + d) * 1000000000;
- }
+ public static int RESOLUTION_YEAR = 0;
+ public static int RESOLUTION_MONTH = 1;
+ public static int RESOLUTION_DAY = 2;
+ public static int RESOLUTION_HOUR = 3;
+ public static int RESOLUTION_MIN = 4;
+ public static int RESOLUTION_SEC = 5;
+ public static int RESOLUTION_MSEC = 6;
+
+ private String currentLocale;
+
+ private static int[] maxDaysInMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30,
+ 31, 30, 31 };
+
+ /**
+ * Creates a new date time service with the application default locale.
+ */
+ public DateTimeService() {
+ currentLocale = LocaleService.getDefaultLocale();
+ }
+
+ /**
+ * Creates a new date time service with a given locale.
+ *
+ * @param locale
+ * e.g. fi, en etc.
+ * @throws LocaleNotLoadedException
+ */
+ public DateTimeService(String locale) throws LocaleNotLoadedException {
+ setLocale(locale);
+ }
+
+ public void setLocale(String locale) throws LocaleNotLoadedException {
+ if (LocaleService.getAvailableLocales().contains(locale)) {
+ currentLocale = locale;
+ } else {
+ throw new LocaleNotLoadedException(locale);
+ }
+ }
+
+ public String getLocale() {
+ return currentLocale;
+ }
+
+ public String getMonth(int month) {
+ try {
+ return LocaleService.getMonthNames(currentLocale)[month];
+ } catch (LocaleNotLoadedException e) {
+ // TODO redirect to console
+ System.out.println(e + ":" + e.getMessage());
+ }
+ return null;
+ }
+
+ public String getShortMonth(int month) {
+ try {
+ return LocaleService.getShortMonthNames(currentLocale)[month];
+ } catch (LocaleNotLoadedException e) {
+ // TODO redirect to console
+ System.out.println(e + ":" + e.getMessage());
+ }
+ return null;
+ }
+
+ public String getDay(int day) {
+ try {
+ return LocaleService.getDayNames(currentLocale)[day];
+ } catch (LocaleNotLoadedException e) {
+ // TODO redirect to console
+ System.out.println(e + ":" + e.getMessage());
+ }
+ return null;
+ }
+
+ public String getShortDay(int day) {
+ try {
+ return LocaleService.getShortDayNames(currentLocale)[day];
+ } catch (LocaleNotLoadedException e) {
+ // TODO redirect to console
+ System.out.println(e + ":" + e.getMessage());
+ }
+ return null;
+ }
+
+ public int getFirstDayOfWeek() {
+ try {
+ return LocaleService.getFirstDayOfWeek(currentLocale);
+ } catch (LocaleNotLoadedException e) {
+ // TODO redirect to console
+ System.out.println(e + ":" + e.getMessage());
+ }
+ return 0;
+ }
+
+ public boolean isTwelveHourClock() {
+ try {
+ return LocaleService.isTwelveHourClock(currentLocale);
+ } catch (LocaleNotLoadedException e) {
+ // TODO redirect to console
+ System.out.println(e + ":" + e.getMessage());
+ }
+ return false;
+ }
+
+ public String getClockDelimeter() {
+ try {
+ return LocaleService.getClockDelimiter(currentLocale);
+ } catch (LocaleNotLoadedException e) {
+ // TODO redirect to console
+ System.out.println(e + ":" + e.getMessage());
+ }
+ return ":";
+ }
+
+ public String[] getAmPmStrings() {
+ try {
+ return LocaleService.getAmPmStrings(currentLocale);
+ } catch (LocaleNotLoadedException e) {
+ // TODO redirect to console
+ System.out.println(e + ":" + e.getMessage());
+ }
+ String[] temp = new String[2];
+ temp[0] = "AM";
+ temp[1] = "PM";
+ return temp;
+ }
+
+ public int getStartWeekDay(Date date) {
+ Date dateForFirstOfThisMonth = new Date(date.getYear(),
+ date.getMonth(), 1);
+ int firstDay;
+ try {
+ firstDay = LocaleService.getFirstDayOfWeek(currentLocale);
+ } catch (LocaleNotLoadedException e) {
+ firstDay = 0;
+ // TODO redirect to console
+ System.out.println(e + ":" + e.getMessage());
+ }
+ int start = dateForFirstOfThisMonth.getDay() - firstDay;
+ if (start < 0) {
+ start = 6;
+ }
+ return start;
+ }
+
+ public String getDateFormat() {
+ try {
+ return LocaleService.getDateFormat(currentLocale);
+ } catch (LocaleNotLoadedException e) {
+ // TODO redirect to console
+ System.out.println(e + ":" + e.getMessage());
+ }
+ return "M/d/yy";
+ }
+
+ public static int getNumberOfDaysInMonth(Date date) {
+ int month = date.getMonth();
+ if (month == 1 && true == isLeapYear(date)) {
+ return 29;
+ }
+ return maxDaysInMonth[month];
+ }
+
+ public static boolean isLeapYear(Date date) {
+ // Instantiate the date for 1st March of that year
+ Date firstMarch = new Date(date.getYear(), 2, 1);
+
+ // Go back 1 day
+ long firstMarchTime = firstMarch.getTime();
+ long lastDayTimeFeb = firstMarchTime - (24 * 60 * 60 * 1000); // NUM_MILLISECS_A_DAY
+
+ // Instantiate new Date with this time
+ Date febLastDay = new Date(lastDayTimeFeb);
+
+ // Check for date in this new instance
+ return (29 == febLastDay.getDate()) ? true : false;
+ }
+
+ public static boolean isSameDay(Date d1, Date d2) {
+ return (getDayInt(d1) == getDayInt(d2));
+ }
+
+ public static boolean isInRange(Date date, Date rangeStart, Date rangeEnd,
+ int resolution) {
+ Date s;
+ Date e;
+ if (rangeStart.after(rangeEnd)) {
+ s = rangeEnd;
+ e = rangeStart;
+ } else {
+ e = rangeEnd;
+ s = rangeStart;
+ }
+ long start = s.getYear() * 10000000000l;
+ long end = e.getYear() * 10000000000l;
+ long target = date.getYear() * 10000000000l;
+
+ if (resolution == RESOLUTION_YEAR) {
+ return (start <= target && end >= target);
+ }
+ start += s.getMonth() * 100000000;
+ end += e.getMonth() * 100000000;
+ target += date.getMonth() * 100000000;
+ if (resolution == RESOLUTION_MONTH) {
+ return (start <= target && end >= target);
+ }
+ start += s.getDate() * 1000000;
+ end += e.getDate() * 1000000;
+ target += date.getDate() * 1000000;
+ if (resolution == RESOLUTION_DAY) {
+ return (start <= target && end >= target);
+ }
+ start += s.getHours() * 10000;
+ end += e.getHours() * 10000;
+ target += date.getHours() * 10000;
+ if (resolution == RESOLUTION_HOUR) {
+ return (start <= target && end >= target);
+ }
+ start += s.getMinutes() * 100;
+ end += e.getMinutes() * 100;
+ target += date.getMinutes() * 100;
+ if (resolution == RESOLUTION_MIN) {
+ return (start <= target && end >= target);
+ }
+ start += s.getSeconds();
+ end += e.getSeconds();
+ target += date.getSeconds();
+ return (start <= target && end >= target);
+
+ }
+
+ private static int getDayInt(Date date) {
+ int y = date.getYear();
+ int m = date.getMonth();
+ int d = date.getDate();
+
+ return ((y + 1900) * 10000 + m * 100 + d) * 1000000000;
+ }
}
diff --git a/src/com/itmill/toolkit/terminal/gwt/client/DebugConsole.java b/src/com/itmill/toolkit/terminal/gwt/client/DebugConsole.java
index 8f6a1c822d..4b9d2b799a 100755
--- a/src/com/itmill/toolkit/terminal/gwt/client/DebugConsole.java
+++ b/src/com/itmill/toolkit/terminal/gwt/client/DebugConsole.java
@@ -11,69 +11,69 @@ import com.itmill.toolkit.terminal.gwt.client.ui.IWindow;
public final class DebugConsole extends IWindow implements Console {
- private Panel panel;
+ private Panel panel;
- public DebugConsole(ApplicationConnection client) {
- super();
- this.client = client;
- panel = new FlowPanel();
- ScrollPanel p = new ScrollPanel();
- p.add(panel);
- this.setWidget(p);
- this.setCaption("Debug window");
- minimize();
- show();
- }
+ public DebugConsole(ApplicationConnection client) {
+ super();
+ this.client = client;
+ panel = new FlowPanel();
+ ScrollPanel p = new ScrollPanel();
+ p.add(panel);
+ setWidget(p);
+ setCaption("Debug window");
+ minimize();
+ show();
+ }
- private void minimize() {
- // TODO stack to bottom (create window manager of some sort)
- setPixelSize(60, 60);
- setPopupPosition(Window.getClientWidth()
- - (60 + IWindow.BORDER_WIDTH_HORIZONTAL), Window
- .getClientHeight()
- - (80 + IWindow.BORDER_WIDTH_VERTICAL));
- }
+ private void minimize() {
+ // TODO stack to bottom (create window manager of some sort)
+ setPixelSize(60, 60);
+ setPopupPosition(Window.getClientWidth()
+ - (60 + IWindow.BORDER_WIDTH_HORIZONTAL), Window
+ .getClientHeight()
+ - (80 + IWindow.BORDER_WIDTH_VERTICAL));
+ }
- /*
- * (non-Javadoc)
- *
- * @see com.itmill.toolkit.terminal.gwt.client.Console#log(java.lang.String)
- */
- public void log(String msg) {
- panel.add(new HTML(msg));
- System.out.println(msg);
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.itmill.toolkit.terminal.gwt.client.Console#log(java.lang.String)
+ */
+ public void log(String msg) {
+ panel.add(new HTML(msg));
+ System.out.println(msg);
+ }
- /*
- * (non-Javadoc)
- *
- * @see com.itmill.toolkit.terminal.gwt.client.Console#error(java.lang.String)
- */
- public void error(String msg) {
- panel.add((new HTML(msg)));
- System.out.println(msg);
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.itmill.toolkit.terminal.gwt.client.Console#error(java.lang.String)
+ */
+ public void error(String msg) {
+ panel.add((new HTML(msg)));
+ System.out.println(msg);
+ }
- /*
- * (non-Javadoc)
- *
- * @see com.itmill.toolkit.terminal.gwt.client.Console#printObject(java.lang.Object)
- */
- public void printObject(Object msg) {
- panel.add((new Label(msg.toString())));
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.itmill.toolkit.terminal.gwt.client.Console#printObject(java.lang.Object)
+ */
+ public void printObject(Object msg) {
+ panel.add((new Label(msg.toString())));
+ }
- /*
- * (non-Javadoc)
- *
- * @see com.itmill.toolkit.terminal.gwt.client.Console#dirUIDL(com.itmill.toolkit.terminal.gwt.client.UIDL)
- */
- public void dirUIDL(UIDL u) {
- panel.add(u.print_r());
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.itmill.toolkit.terminal.gwt.client.Console#dirUIDL(com.itmill.toolkit.terminal.gwt.client.UIDL)
+ */
+ public void dirUIDL(UIDL u) {
+ panel.add(u.print_r());
+ }
- public void setSize(Event event, boolean updateVariables) {
- super.setSize(event, false);
- }
+ public void setSize(Event event, boolean updateVariables) {
+ super.setSize(event, false);
+ }
}
diff --git a/src/com/itmill/toolkit/terminal/gwt/client/LocaleNotLoadedException.java b/src/com/itmill/toolkit/terminal/gwt/client/LocaleNotLoadedException.java
index 1f1e805d0a..2ff8e09948 100644
--- a/src/com/itmill/toolkit/terminal/gwt/client/LocaleNotLoadedException.java
+++ b/src/com/itmill/toolkit/terminal/gwt/client/LocaleNotLoadedException.java
@@ -2,12 +2,12 @@ package com.itmill.toolkit.terminal.gwt.client;
public class LocaleNotLoadedException extends Exception {
- /**
- * Serial generated by Eclipse.
- */
- private static final long serialVersionUID = 2005227056545210838L;
+ /**
+ * Serial generated by Eclipse.
+ */
+ private static final long serialVersionUID = 2005227056545210838L;
- public LocaleNotLoadedException(String locale) {
- super(locale);
- }
+ public LocaleNotLoadedException(String locale) {
+ super(locale);
+ }
}
diff --git a/src/com/itmill/toolkit/terminal/gwt/client/LocaleService.java b/src/com/itmill/toolkit/terminal/gwt/client/LocaleService.java
index 31fe42d167..5a266aed91 100644
--- a/src/com/itmill/toolkit/terminal/gwt/client/LocaleService.java
+++ b/src/com/itmill/toolkit/terminal/gwt/client/LocaleService.java
@@ -19,163 +19,174 @@ import com.google.gwt.json.client.JSONString;
*/
public class LocaleService {
- private static Map cache = new HashMap();
- private static String defaultLocale;
-
- public static void addLocale(JSONObject json) {
- String key = ((JSONString) json.get("name")).stringValue();
- if (cache.containsKey(key))
- cache.remove(key);
- cache.put(key, json);
- if (cache.size() == 1)
- setDefaultLocale(key);
- }
-
- public static void setDefaultLocale(String locale) {
- defaultLocale = locale;
- }
-
- public static String getDefaultLocale() {
- return defaultLocale;
- }
-
- public static Set getAvailableLocales() {
- return cache.keySet();
- }
-
- public static String[] getMonthNames(String locale)
- throws LocaleNotLoadedException {
- if (cache.containsKey(locale)) {
- JSONObject l = (JSONObject) cache.get(locale);
- JSONArray mn = (JSONArray) l.get("mn");
- String[] temp = new String[12];
- temp[0] = ((JSONString) mn.get(0)).stringValue();
- temp[1] = ((JSONString) mn.get(1)).stringValue();
- temp[2] = ((JSONString) mn.get(2)).stringValue();
- temp[3] = ((JSONString) mn.get(3)).stringValue();
- temp[4] = ((JSONString) mn.get(4)).stringValue();
- temp[5] = ((JSONString) mn.get(5)).stringValue();
- temp[6] = ((JSONString) mn.get(6)).stringValue();
- temp[7] = ((JSONString) mn.get(7)).stringValue();
- temp[8] = ((JSONString) mn.get(8)).stringValue();
- temp[9] = ((JSONString) mn.get(9)).stringValue();
- temp[10] = ((JSONString) mn.get(10)).stringValue();
- temp[11] = ((JSONString) mn.get(11)).stringValue();
- return temp;
- } else
- throw new LocaleNotLoadedException(locale);
- }
-
- public static String[] getShortMonthNames(String locale)
- throws LocaleNotLoadedException {
- if (cache.containsKey(locale)) {
- JSONObject l = (JSONObject) cache.get(locale);
- JSONArray smn = (JSONArray) l.get("smn");
- String[] temp = new String[12];
- temp[0] = ((JSONString) smn.get(0)).stringValue();
- temp[1] = ((JSONString) smn.get(1)).stringValue();
- temp[2] = ((JSONString) smn.get(2)).stringValue();
- temp[3] = ((JSONString) smn.get(3)).stringValue();
- temp[4] = ((JSONString) smn.get(4)).stringValue();
- temp[5] = ((JSONString) smn.get(5)).stringValue();
- temp[6] = ((JSONString) smn.get(6)).stringValue();
- temp[7] = ((JSONString) smn.get(7)).stringValue();
- temp[8] = ((JSONString) smn.get(8)).stringValue();
- temp[9] = ((JSONString) smn.get(9)).stringValue();
- temp[10] = ((JSONString) smn.get(10)).stringValue();
- temp[11] = ((JSONString) smn.get(11)).stringValue();
- return temp;
- } else
- throw new LocaleNotLoadedException(locale);
- }
-
- public static String[] getDayNames(String locale)
- throws LocaleNotLoadedException {
- if (cache.containsKey(locale)) {
- JSONObject l = (JSONObject) cache.get(locale);
- JSONArray dn = (JSONArray) l.get("dn");
- String[] temp = new String[7];
- temp[0] = ((JSONString) dn.get(0)).stringValue();
- temp[1] = ((JSONString) dn.get(1)).stringValue();
- temp[2] = ((JSONString) dn.get(2)).stringValue();
- temp[3] = ((JSONString) dn.get(3)).stringValue();
- temp[4] = ((JSONString) dn.get(4)).stringValue();
- temp[5] = ((JSONString) dn.get(5)).stringValue();
- temp[6] = ((JSONString) dn.get(6)).stringValue();
- return temp;
- } else
- throw new LocaleNotLoadedException(locale);
- }
-
- public static String[] getShortDayNames(String locale)
- throws LocaleNotLoadedException {
- if (cache.containsKey(locale)) {
- JSONObject l = (JSONObject) cache.get(locale);
- JSONArray sdn = (JSONArray) l.get("sdn");
- String[] temp = new String[7];
- temp[0] = ((JSONString) sdn.get(0)).stringValue();
- temp[1] = ((JSONString) sdn.get(1)).stringValue();
- temp[2] = ((JSONString) sdn.get(2)).stringValue();
- temp[3] = ((JSONString) sdn.get(3)).stringValue();
- temp[4] = ((JSONString) sdn.get(4)).stringValue();
- temp[5] = ((JSONString) sdn.get(5)).stringValue();
- temp[6] = ((JSONString) sdn.get(6)).stringValue();
- return temp;
- } else
- throw new LocaleNotLoadedException(locale);
- }
-
- public static int getFirstDayOfWeek(String locale)
- throws LocaleNotLoadedException {
- if (cache.containsKey(locale)) {
- JSONObject l = (JSONObject) cache.get(locale);
- JSONNumber fdow = (JSONNumber) l.get("fdow");
- return (int) fdow.getValue();
- } else
- throw new LocaleNotLoadedException(locale);
- }
-
- public static String getDateFormat(String locale)
- throws LocaleNotLoadedException {
- if (cache.containsKey(locale)) {
- JSONObject l = (JSONObject) cache.get(locale);
- JSONString df = (JSONString) l.get("df");
- return df.stringValue();
- } else
- throw new LocaleNotLoadedException(locale);
- }
-
- public static boolean isTwelveHourClock(String locale)
- throws LocaleNotLoadedException {
- if (cache.containsKey(locale)) {
- JSONObject l = (JSONObject) cache.get(locale);
- JSONBoolean thc = (JSONBoolean) l.get("thc");
- return thc.booleanValue();
- } else
- throw new LocaleNotLoadedException(locale);
- }
-
- public static String getClockDelimiter(String locale)
- throws LocaleNotLoadedException {
- if (cache.containsKey(locale)) {
- JSONObject l = (JSONObject) cache.get(locale);
- JSONString hmd = (JSONString) l.get("hmd");
- return hmd.stringValue();
- } else
- throw new LocaleNotLoadedException(locale);
- }
-
- public static String[] getAmPmStrings(String locale)
- throws LocaleNotLoadedException {
- if (cache.containsKey(locale)) {
- JSONObject l = (JSONObject) cache.get(locale);
- JSONArray ampm = (JSONArray) l.get("ampm");
- String[] temp = new String[2];
- temp[0] = ((JSONString) ampm.get(0)).stringValue();
- temp[1] = ((JSONString) ampm.get(1)).stringValue();
- return temp;
- } else
- throw new LocaleNotLoadedException(locale);
- }
+ private static Map cache = new HashMap();
+ private static String defaultLocale;
+
+ public static void addLocale(JSONObject json) {
+ String key = ((JSONString) json.get("name")).stringValue();
+ if (cache.containsKey(key)) {
+ cache.remove(key);
+ }
+ cache.put(key, json);
+ if (cache.size() == 1) {
+ setDefaultLocale(key);
+ }
+ }
+
+ public static void setDefaultLocale(String locale) {
+ defaultLocale = locale;
+ }
+
+ public static String getDefaultLocale() {
+ return defaultLocale;
+ }
+
+ public static Set getAvailableLocales() {
+ return cache.keySet();
+ }
+
+ public static String[] getMonthNames(String locale)
+ throws LocaleNotLoadedException {
+ if (cache.containsKey(locale)) {
+ JSONObject l = (JSONObject) cache.get(locale);
+ JSONArray mn = (JSONArray) l.get("mn");
+ String[] temp = new String[12];
+ temp[0] = ((JSONString) mn.get(0)).stringValue();
+ temp[1] = ((JSONString) mn.get(1)).stringValue();
+ temp[2] = ((JSONString) mn.get(2)).stringValue();
+ temp[3] = ((JSONString) mn.get(3)).stringValue();
+ temp[4] = ((JSONString) mn.get(4)).stringValue();
+ temp[5] = ((JSONString) mn.get(5)).stringValue();
+ temp[6] = ((JSONString) mn.get(6)).stringValue();
+ temp[7] = ((JSONString) mn.get(7)).stringValue();
+ temp[8] = ((JSONString) mn.get(8)).stringValue();
+ temp[9] = ((JSONString) mn.get(9)).stringValue();
+ temp[10] = ((JSONString) mn.get(10)).stringValue();
+ temp[11] = ((JSONString) mn.get(11)).stringValue();
+ return temp;
+ } else {
+ throw new LocaleNotLoadedException(locale);
+ }
+ }
+
+ public static String[] getShortMonthNames(String locale)
+ throws LocaleNotLoadedException {
+ if (cache.containsKey(locale)) {
+ JSONObject l = (JSONObject) cache.get(locale);
+ JSONArray smn = (JSONArray) l.get("smn");
+ String[] temp = new String[12];
+ temp[0] = ((JSONString) smn.get(0)).stringValue();
+ temp[1] = ((JSONString) smn.get(1)).stringValue();
+ temp[2] = ((JSONString) smn.get(2)).stringValue();
+ temp[3] = ((JSONString) smn.get(3)).stringValue();
+ temp[4] = ((JSONString) smn.get(4)).stringValue();
+ temp[5] = ((JSONString) smn.get(5)).stringValue();
+ temp[6] = ((JSONString) smn.get(6)).stringValue();
+ temp[7] = ((JSONString) smn.get(7)).stringValue();
+ temp[8] = ((JSONString) smn.get(8)).stringValue();
+ temp[9] = ((JSONString) smn.get(9)).stringValue();
+ temp[10] = ((JSONString) smn.get(10)).stringValue();
+ temp[11] = ((JSONString) smn.get(11)).stringValue();
+ return temp;
+ } else {
+ throw new LocaleNotLoadedException(locale);
+ }
+ }
+
+ public static String[] getDayNames(String locale)
+ throws LocaleNotLoadedException {
+ if (cache.containsKey(locale)) {
+ JSONObject l = (JSONObject) cache.get(locale);
+ JSONArray dn = (JSONArray) l.get("dn");
+ String[] temp = new String[7];
+ temp[0] = ((JSONString) dn.get(0)).stringValue();
+ temp[1] = ((JSONString) dn.get(1)).stringValue();
+ temp[2] = ((JSONString) dn.get(2)).stringValue();
+ temp[3] = ((JSONString) dn.get(3)).stringValue();
+ temp[4] = ((JSONString) dn.get(4)).stringValue();
+ temp[5] = ((JSONString) dn.get(5)).stringValue();
+ temp[6] = ((JSONString) dn.get(6)).stringValue();
+ return temp;
+ } else {
+ throw new LocaleNotLoadedException(locale);
+ }
+ }
+
+ public static String[] getShortDayNames(String locale)
+ throws LocaleNotLoadedException {
+ if (cache.containsKey(locale)) {
+ JSONObject l = (JSONObject) cache.get(locale);
+ JSONArray sdn = (JSONArray) l.get("sdn");
+ String[] temp = new String[7];
+ temp[0] = ((JSONString) sdn.get(0)).stringValue();
+ temp[1] = ((JSONString) sdn.get(1)).stringValue();
+ temp[2] = ((JSONString) sdn.get(2)).stringValue();
+ temp[3] = ((JSONString) sdn.get(3)).stringValue();
+ temp[4] = ((JSONString) sdn.get(4)).stringValue();
+ temp[5] = ((JSONString) sdn.get(5)).stringValue();
+ temp[6] = ((JSONString) sdn.get(6)).stringValue();
+ return temp;
+ } else {
+ throw new LocaleNotLoadedException(locale);
+ }
+ }
+
+ public static int getFirstDayOfWeek(String locale)
+ throws LocaleNotLoadedException {
+ if (cache.containsKey(locale)) {
+ JSONObject l = (JSONObject) cache.get(locale);
+ JSONNumber fdow = (JSONNumber) l.get("fdow");
+ return (int) fdow.getValue();
+ } else {
+ throw new LocaleNotLoadedException(locale);
+ }
+ }
+
+ public static String getDateFormat(String locale)
+ throws LocaleNotLoadedException {
+ if (cache.containsKey(locale)) {
+ JSONObject l = (JSONObject) cache.get(locale);
+ JSONString df = (JSONString) l.get("df");
+ return df.stringValue();
+ } else {
+ throw new LocaleNotLoadedException(locale);
+ }
+ }
+
+ public static boolean isTwelveHourClock(String locale)
+ throws LocaleNotLoadedException {
+ if (cache.containsKey(locale)) {
+ JSONObject l = (JSONObject) cache.get(locale);
+ JSONBoolean thc = (JSONBoolean) l.get("thc");
+ return thc.booleanValue();
+ } else {
+ throw new LocaleNotLoadedException(locale);
+ }
+ }
+
+ public static String getClockDelimiter(String locale)
+ throws LocaleNotLoadedException {
+ if (cache.containsKey(locale)) {
+ JSONObject l = (JSONObject) cache.get(locale);
+ JSONString hmd = (JSONString) l.get("hmd");
+ return hmd.stringValue();
+ } else {
+ throw new LocaleNotLoadedException(locale);
+ }
+ }
+
+ public static String[] getAmPmStrings(String locale)
+ throws LocaleNotLoadedException {
+ if (cache.containsKey(locale)) {
+ JSONObject l = (JSONObject) cache.get(locale);
+ JSONArray ampm = (JSONArray) l.get("ampm");
+ String[] temp = new String[2];
+ temp[0] = ((JSONString) ampm.get(0)).stringValue();
+ temp[1] = ((JSONString) ampm.get(1)).stringValue();
+ return temp;
+ } else {
+ throw new LocaleNotLoadedException(locale);
+ }
+ }
}
diff --git a/src/com/itmill/toolkit/terminal/gwt/client/NullConsole.java b/src/com/itmill/toolkit/terminal/gwt/client/NullConsole.java
index 055251cf45..ec81a7b11f 100644
--- a/src/com/itmill/toolkit/terminal/gwt/client/NullConsole.java
+++ b/src/com/itmill/toolkit/terminal/gwt/client/NullConsole.java
@@ -7,16 +7,16 @@ package com.itmill.toolkit.terminal.gwt.client;
*/
public class NullConsole implements Console {
- public void dirUIDL(UIDL u) {
- }
+ public void dirUIDL(UIDL u) {
+ }
- public void error(String msg) {
- }
+ public void error(String msg) {
+ }
- public void log(String msg) {
- }
+ public void log(String msg) {
+ }
- public void printObject(Object msg) {
- }
+ public void printObject(Object msg) {
+ }
}
diff --git a/src/com/itmill/toolkit/terminal/gwt/client/Paintable.java b/src/com/itmill/toolkit/terminal/gwt/client/Paintable.java
index 4f29946569..bfe73243dc 100644
--- a/src/com/itmill/toolkit/terminal/gwt/client/Paintable.java
+++ b/src/com/itmill/toolkit/terminal/gwt/client/Paintable.java
@@ -2,5 +2,5 @@ package com.itmill.toolkit.terminal.gwt.client;
public interface Paintable {
- public void updateFromUIDL(UIDL uidl, ApplicationConnection client);
+ public void updateFromUIDL(UIDL uidl, ApplicationConnection client);
}
diff --git a/src/com/itmill/toolkit/terminal/gwt/client/StyleConstants.java b/src/com/itmill/toolkit/terminal/gwt/client/StyleConstants.java
index c562082e4e..c7a752e5ff 100644
--- a/src/com/itmill/toolkit/terminal/gwt/client/StyleConstants.java
+++ b/src/com/itmill/toolkit/terminal/gwt/client/StyleConstants.java
@@ -1,10 +1,10 @@
package com.itmill.toolkit.terminal.gwt.client;
public class StyleConstants {
-
- public static final String LAYOUT_MARGIN_TOP = "i-layoutmargin-top";
- public static final String LAYOUT_MARGIN_RIGHT = "i-layoutmargin-right";
- public static final String LAYOUT_MARGIN_BOTTOM = "i-layoutmargin-bottom";
- public static final String LAYOUT_MARGIN_LEFT = "i-layoutmargin-left";
+
+ public static final String LAYOUT_MARGIN_TOP = "i-layoutmargin-top";
+ public static final String LAYOUT_MARGIN_RIGHT = "i-layoutmargin-right";
+ public static final String LAYOUT_MARGIN_BOTTOM = "i-layoutmargin-bottom";
+ public static final String LAYOUT_MARGIN_LEFT = "i-layoutmargin-left";
}
diff --git a/src/com/itmill/toolkit/terminal/gwt/client/UIDL.java b/src/com/itmill/toolkit/terminal/gwt/client/UIDL.java
index d03bae840d..14ad0c6a31 100644
--- a/src/com/itmill/toolkit/terminal/gwt/client/UIDL.java
+++ b/src/com/itmill/toolkit/terminal/gwt/client/UIDL.java
@@ -17,422 +17,450 @@ import com.google.gwt.user.client.ui.TreeListener;
public class UIDL {
- JSONArray json;
-
- public UIDL(JSONArray json) {
- this.json = json;
- }
-
- public String getId() {
- JSONValue val = ((JSONObject) json.get(1)).get("id");
- if (val == null)
- return null;
- return ((JSONString) val).stringValue();
- }
-
- public String getTag() {
- return ((JSONString) json.get(0)).stringValue();
- }
-
- public String getStringAttribute(String name) {
- JSONValue val = ((JSONObject) json.get(1)).get(name);
- if (val == null)
- return null;
- return ((JSONString) val).stringValue();
- }
-
- public Set getAttributeNames() {
- HashSet attrs = new HashSet(((JSONObject) json.get(1)).keySet());
- attrs.remove("v");
- return attrs;
- }
-
- public int getIntAttribute(String name) {
- JSONValue val = ((JSONObject) json.get(1)).get(name);
- if (val == null)
- return 0;
- double num = ((JSONNumber) val).getValue();
- return (int) num;
- }
-
- public long getLongAttribute(String name) {
- JSONValue val = ((JSONObject) json.get(1)).get(name);
- if (val == null)
- return 0;
- double num = ((JSONNumber) val).getValue();
- return (long) num;
- }
-
- public float getFloatAttribute(String name) {
- JSONValue val = ((JSONObject) json.get(1)).get(name);
- if (val == null)
- return 0;
- double num = ((JSONNumber) val).getValue();
- return (float) num;
- }
-
- public double getDoubleAttribute(String name) {
- JSONValue val = ((JSONObject) json.get(1)).get(name);
- if (val == null)
- return 0;
- double num = ((JSONNumber) val).getValue();
- return (double) num;
- }
-
- public boolean getBooleanAttribute(String name) {
- JSONValue val = ((JSONObject) json.get(1)).get(name);
- if (val == null)
- return false;
- return ((JSONBoolean) val).booleanValue();
- }
-
- public String[] getStringArrayAttribute(String name) {
- JSONArray a = (JSONArray) ((JSONObject) json.get(1)).get(name);
- String[] s = new String[a.size()];
- for (int i = 0; i < a.size(); i++)
- s[i] = ((JSONString) a.get(i)).stringValue();
- return s;
- }
-
- public int[] getIntArrayAttribute(String name) {
- JSONArray a = (JSONArray) ((JSONObject) json.get(1)).get(name);
- int[] s = new int[a.size()];
- for (int i = 0; i < a.size(); i++)
- s[i] = Integer.parseInt(((JSONString) a.get(i)).stringValue());
- return s;
- }
-
- public HashSet getStringArrayAttributeAsSet(String string) {
- JSONArray a = getArrayVariable(string);
- HashSet s = new HashSet();
- for (int i = 0; i < a.size(); i++)
- s.add(((JSONString) a.get(i)).stringValue());
- return s;
- }
-
- /**
- * Get attributes value as string whateever the type is
- *
- * @param name
- * @return string presentation of attribute
- */
- private String getAttribute(String name) {
- return json.get(1).isObject().get(name).toString();
- }
-
- public boolean hasAttribute(String name) {
- return ((JSONObject) json.get(1)).get(name) != null;
- }
-
- public UIDL getChildUIDL(int i) {
-
- JSONValue c = json.get(i + 2);
- if (c == null)
- return null;
- if (c.isArray() != null)
- return new UIDL(c.isArray());
- throw new IllegalStateException("Child node " + i
- + " is not of type UIDL");
- }
-
- public String getChildString(int i) {
-
- JSONValue c = json.get(i + 2);
- if (c.isString() != null)
- return ((JSONString) c).stringValue();
- throw new IllegalStateException("Child node " + i
- + " is not of type String");
- }
-
- public Iterator getChildIterator() {
-
- return new Iterator() {
-
- int index = 2;
-
- public void remove() {
- throw new UnsupportedOperationException();
- }
-
- public Object next() {
-
- if (json.size() > index) {
- JSONValue c = json.get(index++);
- if (c.isString() != null)
- return c.isString().stringValue();
- else if (c.isArray() != null)
- return new UIDL(c.isArray());
- else if (c.isObject() != null)
- return new XML(c.isObject());
- else
- throw new IllegalStateException("Illegal child " + c
- + " in tag " + getTag() + " at index " + index);
- }
- return null;
- }
-
- public boolean hasNext() {
- return json.size() > index;
- }
-
- };
- }
-
- public int getNumberOfChildren() {
- return json.size() - 2;
- }
-
- public String toString() {
- String s = "<" + getTag();
-
- for (Iterator i = getAttributeNames().iterator(); i.hasNext();) {
- String name = i.next().toString();
- s += " " + name + "=";
- JSONValue v = ((JSONObject) json.get(1)).get(name);
- if (v.isString() != null)
- s += v;
- else
- s += "\"" + v + "\"";
- }
-
- s += ">\n";
-
- Iterator i = getChildIterator();
- while (i.hasNext()) {
- Object c = i.next();
- s += c.toString();
- }
-
- s += "" + getTag() + ">\n";
-
- return s;
- }
-
- public String getChildrenAsXML() {
- String s = "";
- Iterator i = getChildIterator();
- while (i.hasNext()) {
- Object c = i.next();
- s += c.toString();
- }
- return s;
- }
-
- public UIDLBrowser print_r() {
- return new UIDLBrowser();
- }
-
- private class UIDLBrowser extends Tree {
- public UIDLBrowser() {
-
- DOM.setStyleAttribute(getElement(), "position", "");
-
- final TreeItem root = new TreeItem(getTag());
- addItem(root);
- root.addItem("");
- addTreeListener(new TreeListener() {
-
- public void onTreeItemStateChanged(TreeItem item) {
- if (item == root) {
- removeItem(root);
- UIDLBrowser.this.removeTreeListener(this);
- addItem(dir());
- Iterator it = treeItemIterator();
- while (it.hasNext())
- ((TreeItem) it.next()).setState(true);
- }
- }
-
- public void onTreeItemSelected(TreeItem item) {
- }
-
- });
-
- }
-
- protected boolean isKeyboardNavigationEnabled(TreeItem currentItem) {
- return false;
- }
-
- }
-
- public TreeItem dir() {
-
- String nodeName = getTag();
- for (Iterator i = getAttributeNames().iterator(); i.hasNext();) {
- String name = i.next().toString();
- String value = getAttribute(name);
- nodeName += " " + name + "=" + value;
- }
- TreeItem item = new TreeItem(nodeName);
-
- try {
- TreeItem tmp = null;
- for (Iterator i = getVariableHash().keySet().iterator(); i
- .hasNext();) {
- String name = i.next().toString();
- String value = "";
- try {
- value = getStringVariable(name);
- } catch (Exception e) {
- try {
- JSONArray a = getArrayVariable(name);
- value = a.toString();
- } catch (Exception e2) {
- try {
- int intVal = getIntVariable(name);
- value = String.valueOf(intVal);
- } catch (Exception e3) {
- value = "unknown";
- }
- }
- }
- if (tmp == null)
- tmp = new TreeItem("variables");
- tmp.addItem(name + "=" + value);
- }
- if (tmp != null)
- item.addItem(tmp);
- } catch (Exception e) {
- // Ingonered, no variables
- }
-
- Iterator i = getChildIterator();
- while (i.hasNext()) {
- Object child = i.next();
- try {
- UIDL c = (UIDL) child;
- item.addItem(c.dir());
-
- } catch (Exception e) {
- item.addItem(child.toString());
- }
- }
- return item;
- }
-
- private JSONObject getVariableHash() {
- JSONObject v = (JSONObject) ((JSONObject) json.get(1)).get("v");
- if (v == null)
- throw new IllegalArgumentException("No variables defined in tag.");
- return v;
- }
-
- public boolean hasVariable(String name) {
- Object v = null;
- try {
- v = getVariableHash().get(name);
- } catch (IllegalArgumentException e) {
- }
- return v != null;
- }
-
- public String getStringVariable(String name) {
- JSONString t = (JSONString) getVariableHash().get(name);
- if (t == null)
- throw new IllegalArgumentException("No such variable: " + name);
- return t.stringValue();
- }
-
- public int getIntVariable(String name) {
- JSONNumber t = (JSONNumber) getVariableHash().get(name);
- if (t == null)
- throw new IllegalArgumentException("No such variable: " + name);
- return (int) t.getValue();
- }
-
- public long getLongVariable(String name) {
- JSONNumber t = (JSONNumber) getVariableHash().get(name);
- if (t == null)
- throw new IllegalArgumentException("No such variable: " + name);
- return (long) t.getValue();
- }
-
- public float getFloatVariable(String name) {
- JSONNumber t = (JSONNumber) getVariableHash().get(name);
- if (t == null)
- throw new IllegalArgumentException("No such variable: " + name);
- return (float) t.getValue();
- }
-
- public double getDoubleVariable(String name) {
- JSONNumber t = (JSONNumber) getVariableHash().get(name);
- if (t == null)
- throw new IllegalArgumentException("No such variable: " + name);
- return (double) t.getValue();
- }
-
- public boolean getBooleanVariable(String name) {
- JSONBoolean t = (JSONBoolean) getVariableHash().get(name);
- if (t == null)
- throw new IllegalArgumentException("No such variable: " + name);
- return t.booleanValue();
- }
-
- private JSONArray getArrayVariable(String name) {
- JSONArray t = (JSONArray) getVariableHash().get(name);
- if (t == null)
- throw new IllegalArgumentException("No such variable: " + name);
- return t;
- }
-
- public String[] getStringArrayVariable(String name) {
- JSONArray a = getArrayVariable(name);
- String[] s = new String[a.size()];
- for (int i = 0; i < a.size(); i++)
- s[i] = ((JSONString) a.get(i)).stringValue();
- return s;
- }
-
- public Set getStringArrayVariableAsSet(String name) {
- JSONArray a = getArrayVariable(name);
- HashSet s = new HashSet();
- for (int i = 0; i < a.size(); i++)
- s.add(((JSONString) a.get(i)).stringValue());
- return s;
- }
-
- public int[] getIntArrayVariable(String name) {
- JSONArray a = getArrayVariable(name);
- int[] s = new int[a.size()];
- for (int i = 0; i < a.size(); i++) {
- JSONValue v = a.get(i);
- s[i] = v.isNumber() != null ? (int) ((JSONNumber) v).getValue()
- : Integer.parseInt(v.toString());
- }
- return s;
- }
-
- public class XML {
- JSONObject x;
-
- private XML(JSONObject x) {
- this.x = x;
- }
-
- public String getXMLAsString() {
- StringBuffer sb = new StringBuffer();
- for (Iterator it = x.keySet().iterator(); it.hasNext();) {
- String tag = (String) it.next();
- sb.append("<");
- sb.append(tag);
- sb.append(">");
- sb.append(x.get(tag).isString().stringValue());
- sb.append("");
- sb.append(tag);
- sb.append(">");
- }
- return sb.toString();
- }
- }
-
- public int getChidlCount() {
- return json.size() - 2;
- }
-
- public UIDL getErrors() {
- JSONArray a = (JSONArray) ((JSONObject) json.get(1)).get("error");
- return new UIDL(a);
- }
+ JSONArray json;
+
+ public UIDL(JSONArray json) {
+ this.json = json;
+ }
+
+ public String getId() {
+ JSONValue val = ((JSONObject) json.get(1)).get("id");
+ if (val == null) {
+ return null;
+ }
+ return ((JSONString) val).stringValue();
+ }
+
+ public String getTag() {
+ return ((JSONString) json.get(0)).stringValue();
+ }
+
+ public String getStringAttribute(String name) {
+ JSONValue val = ((JSONObject) json.get(1)).get(name);
+ if (val == null) {
+ return null;
+ }
+ return ((JSONString) val).stringValue();
+ }
+
+ public Set getAttributeNames() {
+ HashSet attrs = new HashSet(((JSONObject) json.get(1)).keySet());
+ attrs.remove("v");
+ return attrs;
+ }
+
+ public int getIntAttribute(String name) {
+ JSONValue val = ((JSONObject) json.get(1)).get(name);
+ if (val == null) {
+ return 0;
+ }
+ double num = ((JSONNumber) val).getValue();
+ return (int) num;
+ }
+
+ public long getLongAttribute(String name) {
+ JSONValue val = ((JSONObject) json.get(1)).get(name);
+ if (val == null) {
+ return 0;
+ }
+ double num = ((JSONNumber) val).getValue();
+ return (long) num;
+ }
+
+ public float getFloatAttribute(String name) {
+ JSONValue val = ((JSONObject) json.get(1)).get(name);
+ if (val == null) {
+ return 0;
+ }
+ double num = ((JSONNumber) val).getValue();
+ return (float) num;
+ }
+
+ public double getDoubleAttribute(String name) {
+ JSONValue val = ((JSONObject) json.get(1)).get(name);
+ if (val == null) {
+ return 0;
+ }
+ double num = ((JSONNumber) val).getValue();
+ return num;
+ }
+
+ public boolean getBooleanAttribute(String name) {
+ JSONValue val = ((JSONObject) json.get(1)).get(name);
+ if (val == null) {
+ return false;
+ }
+ return ((JSONBoolean) val).booleanValue();
+ }
+
+ public String[] getStringArrayAttribute(String name) {
+ JSONArray a = (JSONArray) ((JSONObject) json.get(1)).get(name);
+ String[] s = new String[a.size()];
+ for (int i = 0; i < a.size(); i++) {
+ s[i] = ((JSONString) a.get(i)).stringValue();
+ }
+ return s;
+ }
+
+ public int[] getIntArrayAttribute(String name) {
+ JSONArray a = (JSONArray) ((JSONObject) json.get(1)).get(name);
+ int[] s = new int[a.size()];
+ for (int i = 0; i < a.size(); i++) {
+ s[i] = Integer.parseInt(((JSONString) a.get(i)).stringValue());
+ }
+ return s;
+ }
+
+ public HashSet getStringArrayAttributeAsSet(String string) {
+ JSONArray a = getArrayVariable(string);
+ HashSet s = new HashSet();
+ for (int i = 0; i < a.size(); i++) {
+ s.add(((JSONString) a.get(i)).stringValue());
+ }
+ return s;
+ }
+
+ /**
+ * Get attributes value as string whateever the type is
+ *
+ * @param name
+ * @return string presentation of attribute
+ */
+ private String getAttribute(String name) {
+ return json.get(1).isObject().get(name).toString();
+ }
+
+ public boolean hasAttribute(String name) {
+ return ((JSONObject) json.get(1)).get(name) != null;
+ }
+
+ public UIDL getChildUIDL(int i) {
+
+ JSONValue c = json.get(i + 2);
+ if (c == null) {
+ return null;
+ }
+ if (c.isArray() != null) {
+ return new UIDL(c.isArray());
+ }
+ throw new IllegalStateException("Child node " + i
+ + " is not of type UIDL");
+ }
+
+ public String getChildString(int i) {
+
+ JSONValue c = json.get(i + 2);
+ if (c.isString() != null) {
+ return ((JSONString) c).stringValue();
+ }
+ throw new IllegalStateException("Child node " + i
+ + " is not of type String");
+ }
+
+ public Iterator getChildIterator() {
+
+ return new Iterator() {
+
+ int index = 2;
+
+ public void remove() {
+ throw new UnsupportedOperationException();
+ }
+
+ public Object next() {
+
+ if (json.size() > index) {
+ JSONValue c = json.get(index++);
+ if (c.isString() != null) {
+ return c.isString().stringValue();
+ } else if (c.isArray() != null) {
+ return new UIDL(c.isArray());
+ } else if (c.isObject() != null) {
+ return new XML(c.isObject());
+ } else {
+ throw new IllegalStateException("Illegal child " + c
+ + " in tag " + getTag() + " at index " + index);
+ }
+ }
+ return null;
+ }
+
+ public boolean hasNext() {
+ return json.size() > index;
+ }
+
+ };
+ }
+
+ public int getNumberOfChildren() {
+ return json.size() - 2;
+ }
+
+ public String toString() {
+ String s = "<" + getTag();
+
+ for (Iterator i = getAttributeNames().iterator(); i.hasNext();) {
+ String name = i.next().toString();
+ s += " " + name + "=";
+ JSONValue v = ((JSONObject) json.get(1)).get(name);
+ if (v.isString() != null) {
+ s += v;
+ } else {
+ s += "\"" + v + "\"";
+ }
+ }
+
+ s += ">\n";
+
+ Iterator i = getChildIterator();
+ while (i.hasNext()) {
+ Object c = i.next();
+ s += c.toString();
+ }
+
+ s += "" + getTag() + ">\n";
+
+ return s;
+ }
+
+ public String getChildrenAsXML() {
+ String s = "";
+ Iterator i = getChildIterator();
+ while (i.hasNext()) {
+ Object c = i.next();
+ s += c.toString();
+ }
+ return s;
+ }
+
+ public UIDLBrowser print_r() {
+ return new UIDLBrowser();
+ }
+
+ private class UIDLBrowser extends Tree {
+ public UIDLBrowser() {
+
+ DOM.setStyleAttribute(getElement(), "position", "");
+
+ final TreeItem root = new TreeItem(getTag());
+ addItem(root);
+ root.addItem("");
+ addTreeListener(new TreeListener() {
+
+ public void onTreeItemStateChanged(TreeItem item) {
+ if (item == root) {
+ removeItem(root);
+ UIDLBrowser.this.removeTreeListener(this);
+ addItem(dir());
+ Iterator it = treeItemIterator();
+ while (it.hasNext()) {
+ ((TreeItem) it.next()).setState(true);
+ }
+ }
+ }
+
+ public void onTreeItemSelected(TreeItem item) {
+ }
+
+ });
+
+ }
+
+ protected boolean isKeyboardNavigationEnabled(TreeItem currentItem) {
+ return false;
+ }
+
+ }
+
+ public TreeItem dir() {
+
+ String nodeName = getTag();
+ for (Iterator i = getAttributeNames().iterator(); i.hasNext();) {
+ String name = i.next().toString();
+ String value = getAttribute(name);
+ nodeName += " " + name + "=" + value;
+ }
+ TreeItem item = new TreeItem(nodeName);
+
+ try {
+ TreeItem tmp = null;
+ for (Iterator i = getVariableHash().keySet().iterator(); i
+ .hasNext();) {
+ String name = i.next().toString();
+ String value = "";
+ try {
+ value = getStringVariable(name);
+ } catch (Exception e) {
+ try {
+ JSONArray a = getArrayVariable(name);
+ value = a.toString();
+ } catch (Exception e2) {
+ try {
+ int intVal = getIntVariable(name);
+ value = String.valueOf(intVal);
+ } catch (Exception e3) {
+ value = "unknown";
+ }
+ }
+ }
+ if (tmp == null) {
+ tmp = new TreeItem("variables");
+ }
+ tmp.addItem(name + "=" + value);
+ }
+ if (tmp != null) {
+ item.addItem(tmp);
+ }
+ } catch (Exception e) {
+ // Ingonered, no variables
+ }
+
+ Iterator i = getChildIterator();
+ while (i.hasNext()) {
+ Object child = i.next();
+ try {
+ UIDL c = (UIDL) child;
+ item.addItem(c.dir());
+
+ } catch (Exception e) {
+ item.addItem(child.toString());
+ }
+ }
+ return item;
+ }
+
+ private JSONObject getVariableHash() {
+ JSONObject v = (JSONObject) ((JSONObject) json.get(1)).get("v");
+ if (v == null) {
+ throw new IllegalArgumentException("No variables defined in tag.");
+ }
+ return v;
+ }
+
+ public boolean hasVariable(String name) {
+ Object v = null;
+ try {
+ v = getVariableHash().get(name);
+ } catch (IllegalArgumentException e) {
+ }
+ return v != null;
+ }
+
+ public String getStringVariable(String name) {
+ JSONString t = (JSONString) getVariableHash().get(name);
+ if (t == null) {
+ throw new IllegalArgumentException("No such variable: " + name);
+ }
+ return t.stringValue();
+ }
+
+ public int getIntVariable(String name) {
+ JSONNumber t = (JSONNumber) getVariableHash().get(name);
+ if (t == null) {
+ throw new IllegalArgumentException("No such variable: " + name);
+ }
+ return (int) t.getValue();
+ }
+
+ public long getLongVariable(String name) {
+ JSONNumber t = (JSONNumber) getVariableHash().get(name);
+ if (t == null) {
+ throw new IllegalArgumentException("No such variable: " + name);
+ }
+ return (long) t.getValue();
+ }
+
+ public float getFloatVariable(String name) {
+ JSONNumber t = (JSONNumber) getVariableHash().get(name);
+ if (t == null) {
+ throw new IllegalArgumentException("No such variable: " + name);
+ }
+ return (float) t.getValue();
+ }
+
+ public double getDoubleVariable(String name) {
+ JSONNumber t = (JSONNumber) getVariableHash().get(name);
+ if (t == null) {
+ throw new IllegalArgumentException("No such variable: " + name);
+ }
+ return t.getValue();
+ }
+
+ public boolean getBooleanVariable(String name) {
+ JSONBoolean t = (JSONBoolean) getVariableHash().get(name);
+ if (t == null) {
+ throw new IllegalArgumentException("No such variable: " + name);
+ }
+ return t.booleanValue();
+ }
+
+ private JSONArray getArrayVariable(String name) {
+ JSONArray t = (JSONArray) getVariableHash().get(name);
+ if (t == null) {
+ throw new IllegalArgumentException("No such variable: " + name);
+ }
+ return t;
+ }
+
+ public String[] getStringArrayVariable(String name) {
+ JSONArray a = getArrayVariable(name);
+ String[] s = new String[a.size()];
+ for (int i = 0; i < a.size(); i++) {
+ s[i] = ((JSONString) a.get(i)).stringValue();
+ }
+ return s;
+ }
+
+ public Set getStringArrayVariableAsSet(String name) {
+ JSONArray a = getArrayVariable(name);
+ HashSet s = new HashSet();
+ for (int i = 0; i < a.size(); i++) {
+ s.add(((JSONString) a.get(i)).stringValue());
+ }
+ return s;
+ }
+
+ public int[] getIntArrayVariable(String name) {
+ JSONArray a = getArrayVariable(name);
+ int[] s = new int[a.size()];
+ for (int i = 0; i < a.size(); i++) {
+ JSONValue v = a.get(i);
+ s[i] = v.isNumber() != null ? (int) ((JSONNumber) v).getValue()
+ : Integer.parseInt(v.toString());
+ }
+ return s;
+ }
+
+ public class XML {
+ JSONObject x;
+
+ private XML(JSONObject x) {
+ this.x = x;
+ }
+
+ public String getXMLAsString() {
+ StringBuffer sb = new StringBuffer();
+ for (Iterator it = x.keySet().iterator(); it.hasNext();) {
+ String tag = (String) it.next();
+ sb.append("<");
+ sb.append(tag);
+ sb.append(">");
+ sb.append(x.get(tag).isString().stringValue());
+ sb.append("");
+ sb.append(tag);
+ sb.append(">");
+ }
+ return sb.toString();
+ }
+ }
+
+ public int getChidlCount() {
+ return json.size() - 2;
+ }
+
+ public UIDL getErrors() {
+ JSONArray a = (JSONArray) ((JSONObject) json.get(1)).get("error");
+ return new UIDL(a);
+ }
}
diff --git a/src/com/itmill/toolkit/terminal/gwt/client/Util.java b/src/com/itmill/toolkit/terminal/gwt/client/Util.java
index e440e28f84..a1fad8258d 100644
--- a/src/com/itmill/toolkit/terminal/gwt/client/Util.java
+++ b/src/com/itmill/toolkit/terminal/gwt/client/Util.java
@@ -8,74 +8,74 @@ import com.google.gwt.user.client.ui.Widget;
public class Util {
- /**
- * Helper method for debugging purposes.
- *
- * Stops execution on firefox browsers on a breakpoint.
- *
- */
- public static native void browserDebugger() /*-{
- if(window.console)
- debugger;
- }-*/;
+ /**
+ * Helper method for debugging purposes.
+ *
+ * Stops execution on firefox browsers on a breakpoint.
+ *
+ */
+ public static native void browserDebugger() /*-{
+ if(window.console)
+ debugger;
+ }-*/;
- /**
- * Detects if current browser is IE.
- *
- * @return true if IE
- */
- public static native boolean isIE() /*-{
- var browser=$wnd.navigator.appName;
- if (browser=="Microsoft Internet Explorer") {
- return true;
- }
- return false;
- }-*/;
+ /**
+ * Detects if current browser is IE.
+ *
+ * @return true if IE
+ */
+ public static native boolean isIE() /*-{
+ var browser=$wnd.navigator.appName;
+ if (browser=="Microsoft Internet Explorer") {
+ return true;
+ }
+ return false;
+ }-*/;
- /**
- * Detects if current browser is IE6.
- *
- * @return true if IE6
- */
- public static native boolean isIE6() /*-{
- var browser=$wnd.navigator.appName;
- if (browser=="Microsoft Internet Explorer") {
- var ua = navigator.userAgent;
- var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
- if (re.exec(ua) != null)
- rv = parseFloat(RegExp.$1);
- if(rv == 6) return true;
- }
- return false;
- }-*/;
+ /**
+ * Detects if current browser is IE6.
+ *
+ * @return true if IE6
+ */
+ public static native boolean isIE6() /*-{
+ var browser=$wnd.navigator.appName;
+ if (browser=="Microsoft Internet Explorer") {
+ var ua = navigator.userAgent;
+ var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
+ if (re.exec(ua) != null)
+ rv = parseFloat(RegExp.$1);
+ if(rv == 6) return true;
+ }
+ return false;
+ }-*/;
- /**
- * Nulls oncontextmenu function on given element. We need to manually clear
- * context menu events due bad browsers memory leaks, since GWT don't
- * support them.
- *
- * @param el
- */
- public native static void removeContextMenuEvent(Element el) /*-{
- el.oncontextmenu = null;
- }-*/;
+ /**
+ * Nulls oncontextmenu function on given element. We need to manually clear
+ * context menu events due bad browsers memory leaks, since GWT don't
+ * support them.
+ *
+ * @param el
+ */
+ public native static void removeContextMenuEvent(Element el) /*-{
+ el.oncontextmenu = null;
+ }-*/;
- /**
- * Traverses recursively ancestors until ContainerResizedListener child
- * widget is found. They will delegate it futher if needed.
- *
- * @param container
- */
- public static void runDescendentsLayout(HasWidgets container) {
- Iterator childWidgets = container.iterator();
- while (childWidgets.hasNext()) {
- Widget child = (Widget) childWidgets.next();
- if (child instanceof ContainerResizedListener) {
- ((ContainerResizedListener) child).iLayout();
- } else if (child instanceof HasWidgets) {
- HasWidgets childContainer = (HasWidgets) child;
- runDescendentsLayout(childContainer);
- }
- }
- }
+ /**
+ * Traverses recursively ancestors until ContainerResizedListener child
+ * widget is found. They will delegate it futher if needed.
+ *
+ * @param container
+ */
+ public static void runDescendentsLayout(HasWidgets container) {
+ Iterator childWidgets = container.iterator();
+ while (childWidgets.hasNext()) {
+ Widget child = (Widget) childWidgets.next();
+ if (child instanceof ContainerResizedListener) {
+ ((ContainerResizedListener) child).iLayout();
+ } else if (child instanceof HasWidgets) {
+ HasWidgets childContainer = (HasWidgets) child;
+ runDescendentsLayout(childContainer);
+ }
+ }
+ }
}
diff --git a/src/com/itmill/toolkit/terminal/gwt/client/WidgetSet.java b/src/com/itmill/toolkit/terminal/gwt/client/WidgetSet.java
index aaa77a91ab..c975830252 100644
--- a/src/com/itmill/toolkit/terminal/gwt/client/WidgetSet.java
+++ b/src/com/itmill/toolkit/terminal/gwt/client/WidgetSet.java
@@ -5,25 +5,25 @@ import com.google.gwt.user.client.ui.Widget;
public interface WidgetSet extends EntryPoint {
- /**
- * Create an uninitialized component that best matches given UIDL.
- *
- * @param uidl
- * UIDL to be painted with returned component.
- * @return New uninitialized and unregistered component that can paint given
- * UIDL.
- */
- public Widget createWidget(UIDL uidl);
+ /**
+ * Create an uninitialized component that best matches given UIDL.
+ *
+ * @param uidl
+ * UIDL to be painted with returned component.
+ * @return New uninitialized and unregistered component that can paint given
+ * UIDL.
+ */
+ public Widget createWidget(UIDL uidl);
- /**
- * Test if the given component implementation conforms to UIDL.
- *
- * @param currentWidget
- * Current implementation of the component
- * @param uidl
- * UIDL to test against
- * @return true iff createWidget would return a new component of the same
- * class than currentWidget
- */
- public boolean isCorrectImplementation(Widget currentWidget, UIDL uidl);
+ /**
+ * Test if the given component implementation conforms to UIDL.
+ *
+ * @param currentWidget
+ * Current implementation of the component
+ * @param uidl
+ * UIDL to test against
+ * @return true iff createWidget would return a new component of the same
+ * class than currentWidget
+ */
+ public boolean isCorrectImplementation(Widget currentWidget, UIDL uidl);
}
diff --git a/src/com/itmill/toolkit/terminal/gwt/client/ui/Action.java b/src/com/itmill/toolkit/terminal/gwt/client/ui/Action.java
index dce4342fbe..58d7d679c0 100644
--- a/src/com/itmill/toolkit/terminal/gwt/client/ui/Action.java
+++ b/src/com/itmill/toolkit/terminal/gwt/client/ui/Action.java
@@ -8,47 +8,47 @@ import com.itmill.toolkit.terminal.gwt.client.ApplicationConnection;
*/
public abstract class Action implements Command {
- protected ActionOwner owner;
-
- protected String iconUrl = null;
-
- protected String caption = "";
-
- public Action(ActionOwner owner) {
- this.owner = owner;
- }
-
- /**
- * Executed when action fired
- */
- public abstract void execute();
-
- public String getHTML() {
- StringBuffer sb = new StringBuffer();
- sb.append("");
- if (getIconUrl() != null) {
- sb.append("");
- }
- sb.append(getCaption());
- sb.append("");
- return sb.toString();
- }
-
- public String getCaption() {
- return caption;
- }
-
- public void setCaption(String caption) {
- this.caption = caption;
- }
-
- public String getIconUrl() {
- return iconUrl;
- }
-
- public void setIconUrl(String url) {
- iconUrl = url;
- }
+ protected ActionOwner owner;
+
+ protected String iconUrl = null;
+
+ protected String caption = "";
+
+ public Action(ActionOwner owner) {
+ this.owner = owner;
+ }
+
+ /**
+ * Executed when action fired
+ */
+ public abstract void execute();
+
+ public String getHTML() {
+ StringBuffer sb = new StringBuffer();
+ sb.append("");
+ if (getIconUrl() != null) {
+ sb.append("");
+ }
+ sb.append(getCaption());
+ sb.append("");
+ return sb.toString();
+ }
+
+ public String getCaption() {
+ return caption;
+ }
+
+ public void setCaption(String caption) {
+ this.caption = caption;
+ }
+
+ public String getIconUrl() {
+ return iconUrl;
+ }
+
+ public void setIconUrl(String url) {
+ iconUrl = url;
+ }
}
/**
@@ -57,12 +57,12 @@ public abstract class Action implements Command {
*/
interface ActionOwner {
- /**
- * @return Array of IActions
- */
- public Action[] getActions();
+ /**
+ * @return Array of IActions
+ */
+ public Action[] getActions();
- public ApplicationConnection getClient();
+ public ApplicationConnection getClient();
- public String getPaintableId();
+ public String getPaintableId();
}
\ No newline at end of file
diff --git a/src/com/itmill/toolkit/terminal/gwt/client/ui/AlignmentInfo.java b/src/com/itmill/toolkit/terminal/gwt/client/ui/AlignmentInfo.java
index d2967e1593..0a2f48ab00 100644
--- a/src/com/itmill/toolkit/terminal/gwt/client/ui/AlignmentInfo.java
+++ b/src/com/itmill/toolkit/terminal/gwt/client/ui/AlignmentInfo.java
@@ -2,71 +2,71 @@ package com.itmill.toolkit.terminal.gwt.client.ui;
public class AlignmentInfo {
- public static final int ALIGNMENT_LEFT = 1;
- public static final int ALIGNMENT_RIGHT = 2;
- public static final int ALIGNMENT_TOP = 4;
- public static final int ALIGNMENT_BOTTOM = 8;
- public static final int ALIGNMENT_HORIZONTAL_CENTER = 16;
- public static final int ALIGNMENT_VERTICAL_CENTER = 32;
-
- private int bitMask;
-
- public AlignmentInfo(int bitMask) {
- this.bitMask = bitMask;
- }
-
- public AlignmentInfo(int horizontal, int vertical) {
- setAlignment(horizontal, vertical);
- }
-
- public void setAlignment(int horiz, int vert) {
- bitMask = horiz + vert;
- }
-
- public int getBitMask() {
- return bitMask;
- }
-
- public boolean isTop() {
- return (bitMask & ALIGNMENT_TOP) == ALIGNMENT_TOP;
- }
-
- public boolean isBottom() {
- return (bitMask & ALIGNMENT_BOTTOM) == ALIGNMENT_BOTTOM;
- }
-
- public boolean isLeft() {
- return (bitMask & ALIGNMENT_LEFT) == ALIGNMENT_LEFT;
- }
-
- public boolean isRight() {
- return (bitMask & ALIGNMENT_RIGHT) == ALIGNMENT_RIGHT;
- }
-
- public boolean isVerticalCenter() {
- return (bitMask & ALIGNMENT_VERTICAL_CENTER) == ALIGNMENT_VERTICAL_CENTER;
- }
-
- public boolean isHorizontalCenter() {
- return (bitMask & ALIGNMENT_HORIZONTAL_CENTER) == ALIGNMENT_HORIZONTAL_CENTER;
- }
-
- public String getVerticalAlignment() {
- if (isBottom()) {
- return "bottom";
- } else if (isVerticalCenter()) {
- return "middle";
- }
- return "top";
- }
-
- public String getHorizontalAlignment() {
- if (isRight()) {
- return "right";
- } else if (isHorizontalCenter()) {
- return "center";
- }
- return "left";
- }
+ public static final int ALIGNMENT_LEFT = 1;
+ public static final int ALIGNMENT_RIGHT = 2;
+ public static final int ALIGNMENT_TOP = 4;
+ public static final int ALIGNMENT_BOTTOM = 8;
+ public static final int ALIGNMENT_HORIZONTAL_CENTER = 16;
+ public static final int ALIGNMENT_VERTICAL_CENTER = 32;
+
+ private int bitMask;
+
+ public AlignmentInfo(int bitMask) {
+ this.bitMask = bitMask;
+ }
+
+ public AlignmentInfo(int horizontal, int vertical) {
+ setAlignment(horizontal, vertical);
+ }
+
+ public void setAlignment(int horiz, int vert) {
+ bitMask = horiz + vert;
+ }
+
+ public int getBitMask() {
+ return bitMask;
+ }
+
+ public boolean isTop() {
+ return (bitMask & ALIGNMENT_TOP) == ALIGNMENT_TOP;
+ }
+
+ public boolean isBottom() {
+ return (bitMask & ALIGNMENT_BOTTOM) == ALIGNMENT_BOTTOM;
+ }
+
+ public boolean isLeft() {
+ return (bitMask & ALIGNMENT_LEFT) == ALIGNMENT_LEFT;
+ }
+
+ public boolean isRight() {
+ return (bitMask & ALIGNMENT_RIGHT) == ALIGNMENT_RIGHT;
+ }
+
+ public boolean isVerticalCenter() {
+ return (bitMask & ALIGNMENT_VERTICAL_CENTER) == ALIGNMENT_VERTICAL_CENTER;
+ }
+
+ public boolean isHorizontalCenter() {
+ return (bitMask & ALIGNMENT_HORIZONTAL_CENTER) == ALIGNMENT_HORIZONTAL_CENTER;
+ }
+
+ public String getVerticalAlignment() {
+ if (isBottom()) {
+ return "bottom";
+ } else if (isVerticalCenter()) {
+ return "middle";
+ }
+ return "top";
+ }
+
+ public String getHorizontalAlignment() {
+ if (isRight()) {
+ return "right";
+ } else if (isHorizontalCenter()) {
+ return "center";
+ }
+ return "left";
+ }
}
diff --git a/src/com/itmill/toolkit/terminal/gwt/client/ui/CalendarEntry.java b/src/com/itmill/toolkit/terminal/gwt/client/ui/CalendarEntry.java
index 075f68cbf6..edf0de98bd 100644
--- a/src/com/itmill/toolkit/terminal/gwt/client/ui/CalendarEntry.java
+++ b/src/com/itmill/toolkit/terminal/gwt/client/ui/CalendarEntry.java
@@ -5,118 +5,118 @@ import java.util.Date;
import com.itmill.toolkit.terminal.gwt.client.DateTimeService;
public class CalendarEntry {
- private String styleName;
- private Date start;
- private Date end;
- private String title;
- private String description;
- private boolean notime;
-
- public CalendarEntry(String styleName, Date start, Date end, String title,
- String description, boolean notime) {
- this.styleName = styleName;
- if (notime) {
- Date d = new Date(start.getTime());
- d.setSeconds(0);
- d.setMinutes(0);
- this.start = d;
- if (end != null) {
- d = new Date(end.getTime());
- d.setSeconds(0);
- d.setMinutes(0);
- this.end = d;
- } else {
- end = start;
- }
- } else {
- this.start = start;
- this.end = end;
- }
- this.title = title;
- this.description = description;
- this.notime = notime;
- }
-
- public CalendarEntry(String styleName, Date start, Date end, String title,
- String description) {
- this(styleName, start, end, title, description, false);
- }
-
- public String getStyleName() {
- return styleName;
- }
-
- public Date getStart() {
- return start;
- }
-
- public void setStart(Date start) {
- this.start = start;
- }
-
- public Date getEnd() {
- return end;
- }
-
- public void setEnd(Date end) {
- this.end = end;
- }
-
- public String getTitle() {
- return title;
- }
-
- public void setTitle(String title) {
- this.title = title;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public boolean isNotime() {
- return notime;
- }
-
- public void setNotime(boolean notime) {
- this.notime = notime;
- }
-
- public String getStringForDate(Date d) {
- // TODO format from DateTimeService
- String s = "";
- if (!notime) {
- if (!DateTimeService.isSameDay(d, start)) {
- s += (start.getYear() + 1900) + "." + (start.getMonth() + 1)
- + "." + start.getDate() + " ";
- }
- int i = start.getHours();
- s += (i < 10 ? "0" : "") + i;
- s += ":";
- i = start.getMinutes();
- s += (i < 10 ? "0" : "") + i;
- if (!start.equals(end)) {
- s += " - ";
- if (!DateTimeService.isSameDay(start, end)) {
- s += (end.getYear() + 1900) + "." + (end.getMonth() + 1)
- + "." + end.getDate() + " ";
- }
- i = end.getHours();
- s += (i < 10 ? "0" : "") + i;
- s += ":";
- i = end.getMinutes();
- s += (i < 10 ? "0" : "") + i;
- }
- s += " ";
- }
- if (title!=null) {
- s += title;
- }
- return s;
- }
+ private String styleName;
+ private Date start;
+ private Date end;
+ private String title;
+ private String description;
+ private boolean notime;
+
+ public CalendarEntry(String styleName, Date start, Date end, String title,
+ String description, boolean notime) {
+ this.styleName = styleName;
+ if (notime) {
+ Date d = new Date(start.getTime());
+ d.setSeconds(0);
+ d.setMinutes(0);
+ this.start = d;
+ if (end != null) {
+ d = new Date(end.getTime());
+ d.setSeconds(0);
+ d.setMinutes(0);
+ this.end = d;
+ } else {
+ end = start;
+ }
+ } else {
+ this.start = start;
+ this.end = end;
+ }
+ this.title = title;
+ this.description = description;
+ this.notime = notime;
+ }
+
+ public CalendarEntry(String styleName, Date start, Date end, String title,
+ String description) {
+ this(styleName, start, end, title, description, false);
+ }
+
+ public String getStyleName() {
+ return styleName;
+ }
+
+ public Date getStart() {
+ return start;
+ }
+
+ public void setStart(Date start) {
+ this.start = start;
+ }
+
+ public Date getEnd() {
+ return end;
+ }
+
+ public void setEnd(Date end) {
+ this.end = end;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public boolean isNotime() {
+ return notime;
+ }
+
+ public void setNotime(boolean notime) {
+ this.notime = notime;
+ }
+
+ public String getStringForDate(Date d) {
+ // TODO format from DateTimeService
+ String s = "";
+ if (!notime) {
+ if (!DateTimeService.isSameDay(d, start)) {
+ s += (start.getYear() + 1900) + "." + (start.getMonth() + 1)
+ + "." + start.getDate() + " ";
+ }
+ int i = start.getHours();
+ s += (i < 10 ? "0" : "") + i;
+ s += ":";
+ i = start.getMinutes();
+ s += (i < 10 ? "0" : "") + i;
+ if (!start.equals(end)) {
+ s += " - ";
+ if (!DateTimeService.isSameDay(start, end)) {
+ s += (end.getYear() + 1900) + "." + (end.getMonth() + 1)
+ + "." + end.getDate() + " ";
+ }
+ i = end.getHours();
+ s += (i < 10 ? "0" : "") + i;
+ s += ":";
+ i = end.getMinutes();
+ s += (i < 10 ? "0" : "") + i;
+ }
+ s += " ";
+ }
+ if (title != null) {
+ s += title;
+ }
+ return s;
+ }
}
\ No newline at end of file
diff --git a/src/com/itmill/toolkit/terminal/gwt/client/ui/CalendarPanel.java b/src/com/itmill/toolkit/terminal/gwt/client/ui/CalendarPanel.java
index 0fc60e25dc..216bf95a3a 100644
--- a/src/com/itmill/toolkit/terminal/gwt/client/ui/CalendarPanel.java
+++ b/src/com/itmill/toolkit/terminal/gwt/client/ui/CalendarPanel.java
@@ -19,413 +19,428 @@ import com.itmill.toolkit.terminal.gwt.client.DateTimeService;
import com.itmill.toolkit.terminal.gwt.client.LocaleService;
public class CalendarPanel extends FlexTable implements MouseListener,
- ClickListener {
-
- private IDateField datefield;
-
- private IEventButton prevYear;
-
- private IEventButton nextYear;
-
- private IEventButton prevMonth;
-
- private IEventButton nextMonth;
-
- private Time time;
-
- private Date minDate = null;
-
- private Date maxDate = null;
-
- private CalendarEntrySource entrySource;
-
- /* Needed to identify resolution changes */
- private int resolution = IDateField.RESOLUTION_YEAR;
-
- /* Needed to identify locale changes */
- private String locale = LocaleService.getDefaultLocale();
-
- public CalendarPanel(IDateField parent) {
- datefield = parent;
- setStyleName(datefield.CLASSNAME + "-calendarpanel");
- // buildCalendar(true);
- addTableListener(new DateClickListener(this));
- }
-
- public CalendarPanel(IDateField parent, Date min, Date max) {
- datefield = parent;
- setStyleName(datefield.CLASSNAME + "-calendarpanel");
- // buildCalendar(true);
- addTableListener(new DateClickListener(this));
- }
-
- private void buildCalendar(boolean forceRedraw) {
- boolean needsMonth = datefield.getCurrentResolution() > IDateField.RESOLUTION_YEAR;
- boolean needsBody = datefield.getCurrentResolution() >= IDateField.RESOLUTION_DAY;
- boolean needsTime = datefield.getCurrentResolution() >= IDateField.RESOLUTION_HOUR;
- buildCalendarHeader(forceRedraw, needsMonth);
- clearCalendarBody(!needsBody);
- if (needsBody)
- buildCalendarBody();
- if (needsTime)
- buildTime(forceRedraw);
- else if (time != null) {
- remove(time);
- time = null;
- }
- }
-
- private void clearCalendarBody(boolean remove) {
- if (!remove) {
- for (int row = 2; row < 8; row++) {
- for (int col = 0; col < 7; col++) {
- setHTML(row, col, " ");
- }
- }
- } else if (getRowCount() > 2) {
- while (getRowCount() > 2)
- removeRow(2);
- }
- }
-
- private void buildCalendarHeader(boolean forceRedraw, boolean needsMonth) {
- // Can't draw a calendar without a date
- if (datefield.getCurrentDate() == null)
- datefield.setCurrentDate(new Date());
-
- if (forceRedraw) {
- if (prevMonth == null) { // Only do once
- prevYear = new IEventButton();
- prevYear.setHTML("«");
- prevYear.setStyleName("i-button-prevyear");
- nextYear = new IEventButton();
- nextYear.setHTML("»");
- nextYear.setStyleName("i-button-nextyear");
- prevYear.addMouseListener(this);
- nextYear.addMouseListener(this);
- prevYear.addClickListener(this);
- nextYear.addClickListener(this);
- setWidget(0, 0, prevYear);
- setWidget(0, 4, nextYear);
-
- if (needsMonth) {
- prevMonth = new IEventButton();
- prevMonth.setHTML("‹");
- prevMonth.setStyleName("i-button-prevmonth");
- nextMonth = new IEventButton();
- nextMonth.setHTML("›");
- nextMonth.setStyleName("i-button-nextmonth");
- prevMonth.addMouseListener(this);
- nextMonth.addMouseListener(this);
- prevMonth.addClickListener(this);
- nextMonth.addClickListener(this);
- setWidget(0, 3, nextMonth);
- setWidget(0, 1, prevMonth);
- }
-
- getFlexCellFormatter().setColSpan(0, 2, 3);
- getRowFormatter().addStyleName(0,
- datefield.CLASSNAME + "-calendarpanel-header");
- } else if (!needsMonth) {
- // Remove month traverse buttons
- prevMonth.removeClickListener(this);
- prevMonth.removeMouseListener(this);
- nextMonth.removeClickListener(this);
- nextMonth.removeMouseListener(this);
- remove(prevMonth);
- remove(nextMonth);
- prevMonth = null;
- nextMonth = null;
- }
-
- // Print weekday names
- int firstDay = datefield.getDateTimeService().getFirstDayOfWeek();
- for (int i = 0; i < 7; i++) {
- int day = i + firstDay;
- if (day > 6)
- day = 0;
- if (datefield.getCurrentResolution() > IDateField.RESOLUTION_MONTH)
- setHTML(1, i, ""
- + datefield.getDateTimeService().getShortDay(day)
- + "");
- else
- setHTML(1, i, "");
- }
- }
-
- String monthName = needsMonth ? datefield.getDateTimeService()
- .getMonth(datefield.getCurrentDate().getMonth()) : "";
- int year = datefield.getCurrentDate().getYear() + 1900;
- setHTML(0, 2, "" + monthName + " " + year
- + "");
- }
-
- private void buildCalendarBody() {
- Date date = datefield.getCurrentDate();
- if (date == null)
- date = new Date();
- int startWeekDay = datefield.getDateTimeService().getStartWeekDay(date);
- int numDays = DateTimeService.getNumberOfDaysInMonth(date);
- int dayCount = 0;
- Date today = new Date();
- Date curr = new Date(date.getTime());
- for (int row = 2; row < 8; row++) {
- for (int col = 0; col < 7; col++) {
- if (!(row == 2 && col < startWeekDay)) {
- if (dayCount < numDays) {
- int selectedDate = ++dayCount;
- String title = "";
- if (this.entrySource != null) {
- curr.setDate(dayCount);
- List entries = this.entrySource.getEntries(curr,
- IDateField.RESOLUTION_DAY);
- if (entries != null) {
- for (Iterator it = entries.iterator(); it
- .hasNext();) {
- CalendarEntry entry = (CalendarEntry) it
- .next();
- title += (title.length() > 0 ? ", " : "")
- + entry.getStringForDate(curr);
- }
- }
- }
- String baseclass = datefield.CLASSNAME
- + "-calendarpanel-day";
- String cssClass = baseclass;
- if (!isEnabledDate(curr)) {
- cssClass += " " + baseclass + "-disabled";
- }
- if (date.getDate() == dayCount) {
- cssClass += " " + baseclass + "-selected";
- }
- if (today.getDate() == dayCount
- && today.getMonth() == date.getMonth()
- && today.getYear() == date.getYear()) {
- cssClass += " " + baseclass + "-today";
- }
- if (title.length() > 0)
- cssClass += " " + baseclass + "-entry";
- setHTML(row, col, ""
- + selectedDate + "");
- } else {
- break;
- }
-
- }
- }
- }
- }
-
- private void buildTime(boolean forceRedraw) {
- if (time == null) {
- time = new Time(datefield);
- setText(8, 0, ""); // Add new row
- getFlexCellFormatter().setColSpan(8, 0, 7);
- setWidget(8, 0, time);
- }
- time.updateTime(forceRedraw);
- }
-
- /**
- *
- * @param forceRedraw
- * Build all from scratch, in case of e.g. locale changes
- */
- public void updateCalendar() {
- // Locale and resolution changes force a complete redraw
- buildCalendar(locale != datefield.getCurrentLocale()
- || resolution != datefield.getCurrentResolution());
- if (datefield instanceof ITextualDate)
- ((ITextualDate) datefield).buildDate();
- locale = datefield.getCurrentLocale();
- resolution = datefield.getCurrentResolution();
- }
-
- public void onClick(Widget sender) {
- processClickEvent(sender);
- }
-
- private boolean isEnabledDate(Date date) {
- if ((this.minDate != null && date.before(this.minDate))
- || (this.maxDate != null && date.after(this.maxDate))) {
- return false;
- }
- return true;
- }
-
- private void processClickEvent(Widget sender) {
- if (!datefield.isEnabled() || datefield.isReadonly())
- return;
-
- if (sender == prevYear) {
- datefield.getCurrentDate().setYear(
- datefield.getCurrentDate().getYear() - 1);
- datefield.getClient().updateVariable(datefield.getId(), "year",
- datefield.getCurrentDate().getYear() + 1900,
- datefield.isImmediate());
- updateCalendar();
- } else if (sender == nextYear) {
- datefield.getCurrentDate().setYear(
- datefield.getCurrentDate().getYear() + 1);
- datefield.getClient().updateVariable(datefield.getId(), "year",
- datefield.getCurrentDate().getYear() + 1900,
- datefield.isImmediate());
- updateCalendar();
- } else if (sender == prevMonth) {
- datefield.getCurrentDate().setMonth(
- datefield.getCurrentDate().getMonth() - 1);
- datefield.getClient().updateVariable(datefield.getId(), "month",
- datefield.getCurrentDate().getMonth() + 1,
- datefield.isImmediate());
- updateCalendar();
- } else if (sender == nextMonth) {
- datefield.getCurrentDate().setMonth(
- datefield.getCurrentDate().getMonth() + 1);
- datefield.getClient().updateVariable(datefield.getId(), "month",
- datefield.getCurrentDate().getMonth() + 1,
- datefield.isImmediate());
- updateCalendar();
- }
- }
-
- private Timer timer;
-
- public void onMouseDown(final Widget sender, int x, int y) {
- if (sender instanceof IEventButton) {
- timer = new Timer() {
- public void run() {
- processClickEvent(sender);
- }
- };
- timer.scheduleRepeating(100);
- }
- }
-
- public void onMouseEnter(Widget sender) {
- }
-
- public void onMouseLeave(Widget sender) {
- if (timer != null)
- timer.cancel();
- }
-
- public void onMouseMove(Widget sender, int x, int y) {
- }
-
- public void onMouseUp(Widget sender, int x, int y) {
- if (timer != null)
- timer.cancel();
- }
-
- private class IEventButton extends IButton implements SourcesMouseEvents {
-
- private MouseListenerCollection mouseListeners;
-
- public IEventButton() {
- super();
- sinkEvents(Event.FOCUSEVENTS | Event.KEYEVENTS | Event.ONCLICK
- | Event.MOUSEEVENTS);
- }
-
- public void addMouseListener(MouseListener listener) {
- if (mouseListeners == null) {
- mouseListeners = new MouseListenerCollection();
- }
- mouseListeners.add(listener);
- }
-
- public void removeMouseListener(MouseListener listener) {
- if (mouseListeners != null)
- mouseListeners.remove(listener);
- }
-
- public void onBrowserEvent(Event event) {
- super.onBrowserEvent(event);
- switch (DOM.eventGetType(event)) {
- case Event.ONMOUSEDOWN:
- case Event.ONMOUSEUP:
- case Event.ONMOUSEMOVE:
- case Event.ONMOUSEOVER:
- case Event.ONMOUSEOUT:
- if (mouseListeners != null) {
- mouseListeners.fireMouseEvent(this, event);
- }
- break;
- }
- }
- }
-
- private class DateClickListener implements TableListener {
-
- private CalendarPanel cal;
-
- public DateClickListener(CalendarPanel panel) {
- cal = panel;
- }
-
- public void onCellClicked(SourcesTableEvents sender, int row, int col) {
- if (sender != cal || row < 2 || row > 7
- || !cal.datefield.isEnabled() || cal.datefield.isReadonly())
- return;
-
- String text = cal.getText(row, col);
- if (text.equals(" "))
- return;
-
- try {
- Integer day = new Integer(text);
- Date newDate = new Date(cal.datefield.getCurrentDate().getTime());
- newDate.setDate(day.intValue());
- if (!isEnabledDate(newDate)) {
- return;
- }
- cal.datefield.getCurrentDate().setTime(newDate.getTime());
- cal.datefield.getClient().updateVariable(cal.datefield.getId(),
- "day", cal.datefield.getCurrentDate().getDate(),
- cal.datefield.isImmediate());
-
- updateCalendar();
- } catch(NumberFormatException e) {
- // Not a number, ignore and stop here
- return;
- }
- }
-
- }
-
- public void setLimits(Date min, Date max) {
- if (min != null) {
- Date d = new Date(min.getTime());
- d.setHours(0);
- d.setMinutes(0);
- d.setSeconds(1);
- this.minDate = d;
- } else {
- this.minDate = null;
- }
- if (max != null) {
- Date d = new Date(max.getTime());
- d.setHours(24);
- d.setMinutes(59);
- d.setSeconds(59);
- this.maxDate = d;
- } else {
- this.maxDate = null;
- }
- }
-
- public void setCalendarEntrySource(CalendarEntrySource entrySource) {
- this.entrySource = entrySource;
- }
-
- public CalendarEntrySource getCalendarEntrySource() {
- return this.entrySource;
- }
-
- public interface CalendarEntrySource {
- public List getEntries(Date date, int resolution);
- }
+ ClickListener {
+
+ private IDateField datefield;
+
+ private IEventButton prevYear;
+
+ private IEventButton nextYear;
+
+ private IEventButton prevMonth;
+
+ private IEventButton nextMonth;
+
+ private Time time;
+
+ private Date minDate = null;
+
+ private Date maxDate = null;
+
+ private CalendarEntrySource entrySource;
+
+ /* Needed to identify resolution changes */
+ private int resolution = IDateField.RESOLUTION_YEAR;
+
+ /* Needed to identify locale changes */
+ private String locale = LocaleService.getDefaultLocale();
+
+ public CalendarPanel(IDateField parent) {
+ datefield = parent;
+ setStyleName(IDateField.CLASSNAME + "-calendarpanel");
+ // buildCalendar(true);
+ addTableListener(new DateClickListener(this));
+ }
+
+ public CalendarPanel(IDateField parent, Date min, Date max) {
+ datefield = parent;
+ setStyleName(IDateField.CLASSNAME + "-calendarpanel");
+ // buildCalendar(true);
+ addTableListener(new DateClickListener(this));
+ }
+
+ private void buildCalendar(boolean forceRedraw) {
+ boolean needsMonth = datefield.getCurrentResolution() > IDateField.RESOLUTION_YEAR;
+ boolean needsBody = datefield.getCurrentResolution() >= IDateField.RESOLUTION_DAY;
+ boolean needsTime = datefield.getCurrentResolution() >= IDateField.RESOLUTION_HOUR;
+ buildCalendarHeader(forceRedraw, needsMonth);
+ clearCalendarBody(!needsBody);
+ if (needsBody) {
+ buildCalendarBody();
+ }
+ if (needsTime) {
+ buildTime(forceRedraw);
+ } else if (time != null) {
+ remove(time);
+ time = null;
+ }
+ }
+
+ private void clearCalendarBody(boolean remove) {
+ if (!remove) {
+ for (int row = 2; row < 8; row++) {
+ for (int col = 0; col < 7; col++) {
+ setHTML(row, col, " ");
+ }
+ }
+ } else if (getRowCount() > 2) {
+ while (getRowCount() > 2) {
+ removeRow(2);
+ }
+ }
+ }
+
+ private void buildCalendarHeader(boolean forceRedraw, boolean needsMonth) {
+ // Can't draw a calendar without a date
+ if (datefield.getCurrentDate() == null) {
+ datefield.setCurrentDate(new Date());
+ }
+
+ if (forceRedraw) {
+ if (prevMonth == null) { // Only do once
+ prevYear = new IEventButton();
+ prevYear.setHTML("«");
+ prevYear.setStyleName("i-button-prevyear");
+ nextYear = new IEventButton();
+ nextYear.setHTML("»");
+ nextYear.setStyleName("i-button-nextyear");
+ prevYear.addMouseListener(this);
+ nextYear.addMouseListener(this);
+ prevYear.addClickListener(this);
+ nextYear.addClickListener(this);
+ setWidget(0, 0, prevYear);
+ setWidget(0, 4, nextYear);
+
+ if (needsMonth) {
+ prevMonth = new IEventButton();
+ prevMonth.setHTML("‹");
+ prevMonth.setStyleName("i-button-prevmonth");
+ nextMonth = new IEventButton();
+ nextMonth.setHTML("›");
+ nextMonth.setStyleName("i-button-nextmonth");
+ prevMonth.addMouseListener(this);
+ nextMonth.addMouseListener(this);
+ prevMonth.addClickListener(this);
+ nextMonth.addClickListener(this);
+ setWidget(0, 3, nextMonth);
+ setWidget(0, 1, prevMonth);
+ }
+
+ getFlexCellFormatter().setColSpan(0, 2, 3);
+ getRowFormatter().addStyleName(0,
+ IDateField.CLASSNAME + "-calendarpanel-header");
+ } else if (!needsMonth) {
+ // Remove month traverse buttons
+ prevMonth.removeClickListener(this);
+ prevMonth.removeMouseListener(this);
+ nextMonth.removeClickListener(this);
+ nextMonth.removeMouseListener(this);
+ remove(prevMonth);
+ remove(nextMonth);
+ prevMonth = null;
+ nextMonth = null;
+ }
+
+ // Print weekday names
+ int firstDay = datefield.getDateTimeService().getFirstDayOfWeek();
+ for (int i = 0; i < 7; i++) {
+ int day = i + firstDay;
+ if (day > 6) {
+ day = 0;
+ }
+ if (datefield.getCurrentResolution() > IDateField.RESOLUTION_MONTH) {
+ setHTML(1, i, ""
+ + datefield.getDateTimeService().getShortDay(day)
+ + "");
+ } else {
+ setHTML(1, i, "");
+ }
+ }
+ }
+
+ String monthName = needsMonth ? datefield.getDateTimeService()
+ .getMonth(datefield.getCurrentDate().getMonth()) : "";
+ int year = datefield.getCurrentDate().getYear() + 1900;
+ setHTML(0, 2, "" + monthName + " " + year
+ + "");
+ }
+
+ private void buildCalendarBody() {
+ Date date = datefield.getCurrentDate();
+ if (date == null) {
+ date = new Date();
+ }
+ int startWeekDay = datefield.getDateTimeService().getStartWeekDay(date);
+ int numDays = DateTimeService.getNumberOfDaysInMonth(date);
+ int dayCount = 0;
+ Date today = new Date();
+ Date curr = new Date(date.getTime());
+ for (int row = 2; row < 8; row++) {
+ for (int col = 0; col < 7; col++) {
+ if (!(row == 2 && col < startWeekDay)) {
+ if (dayCount < numDays) {
+ int selectedDate = ++dayCount;
+ String title = "";
+ if (entrySource != null) {
+ curr.setDate(dayCount);
+ List entries = entrySource.getEntries(curr,
+ IDateField.RESOLUTION_DAY);
+ if (entries != null) {
+ for (Iterator it = entries.iterator(); it
+ .hasNext();) {
+ CalendarEntry entry = (CalendarEntry) it
+ .next();
+ title += (title.length() > 0 ? ", " : "")
+ + entry.getStringForDate(curr);
+ }
+ }
+ }
+ String baseclass = IDateField.CLASSNAME
+ + "-calendarpanel-day";
+ String cssClass = baseclass;
+ if (!isEnabledDate(curr)) {
+ cssClass += " " + baseclass + "-disabled";
+ }
+ if (date.getDate() == dayCount) {
+ cssClass += " " + baseclass + "-selected";
+ }
+ if (today.getDate() == dayCount
+ && today.getMonth() == date.getMonth()
+ && today.getYear() == date.getYear()) {
+ cssClass += " " + baseclass + "-today";
+ }
+ if (title.length() > 0) {
+ cssClass += " " + baseclass + "-entry";
+ }
+ setHTML(row, col, ""
+ + selectedDate + "");
+ } else {
+ break;
+ }
+
+ }
+ }
+ }
+ }
+
+ private void buildTime(boolean forceRedraw) {
+ if (time == null) {
+ time = new Time(datefield);
+ setText(8, 0, ""); // Add new row
+ getFlexCellFormatter().setColSpan(8, 0, 7);
+ setWidget(8, 0, time);
+ }
+ time.updateTime(forceRedraw);
+ }
+
+ /**
+ *
+ * @param forceRedraw
+ * Build all from scratch, in case of e.g. locale changes
+ */
+ public void updateCalendar() {
+ // Locale and resolution changes force a complete redraw
+ buildCalendar(locale != datefield.getCurrentLocale()
+ || resolution != datefield.getCurrentResolution());
+ if (datefield instanceof ITextualDate) {
+ ((ITextualDate) datefield).buildDate();
+ }
+ locale = datefield.getCurrentLocale();
+ resolution = datefield.getCurrentResolution();
+ }
+
+ public void onClick(Widget sender) {
+ processClickEvent(sender);
+ }
+
+ private boolean isEnabledDate(Date date) {
+ if ((minDate != null && date.before(minDate))
+ || (maxDate != null && date.after(maxDate))) {
+ return false;
+ }
+ return true;
+ }
+
+ private void processClickEvent(Widget sender) {
+ if (!datefield.isEnabled() || datefield.isReadonly()) {
+ return;
+ }
+
+ if (sender == prevYear) {
+ datefield.getCurrentDate().setYear(
+ datefield.getCurrentDate().getYear() - 1);
+ datefield.getClient().updateVariable(datefield.getId(), "year",
+ datefield.getCurrentDate().getYear() + 1900,
+ datefield.isImmediate());
+ updateCalendar();
+ } else if (sender == nextYear) {
+ datefield.getCurrentDate().setYear(
+ datefield.getCurrentDate().getYear() + 1);
+ datefield.getClient().updateVariable(datefield.getId(), "year",
+ datefield.getCurrentDate().getYear() + 1900,
+ datefield.isImmediate());
+ updateCalendar();
+ } else if (sender == prevMonth) {
+ datefield.getCurrentDate().setMonth(
+ datefield.getCurrentDate().getMonth() - 1);
+ datefield.getClient().updateVariable(datefield.getId(), "month",
+ datefield.getCurrentDate().getMonth() + 1,
+ datefield.isImmediate());
+ updateCalendar();
+ } else if (sender == nextMonth) {
+ datefield.getCurrentDate().setMonth(
+ datefield.getCurrentDate().getMonth() + 1);
+ datefield.getClient().updateVariable(datefield.getId(), "month",
+ datefield.getCurrentDate().getMonth() + 1,
+ datefield.isImmediate());
+ updateCalendar();
+ }
+ }
+
+ private Timer timer;
+
+ public void onMouseDown(final Widget sender, int x, int y) {
+ if (sender instanceof IEventButton) {
+ timer = new Timer() {
+ public void run() {
+ processClickEvent(sender);
+ }
+ };
+ timer.scheduleRepeating(100);
+ }
+ }
+
+ public void onMouseEnter(Widget sender) {
+ }
+
+ public void onMouseLeave(Widget sender) {
+ if (timer != null) {
+ timer.cancel();
+ }
+ }
+
+ public void onMouseMove(Widget sender, int x, int y) {
+ }
+
+ public void onMouseUp(Widget sender, int x, int y) {
+ if (timer != null) {
+ timer.cancel();
+ }
+ }
+
+ private class IEventButton extends IButton implements SourcesMouseEvents {
+
+ private MouseListenerCollection mouseListeners;
+
+ public IEventButton() {
+ super();
+ sinkEvents(Event.FOCUSEVENTS | Event.KEYEVENTS | Event.ONCLICK
+ | Event.MOUSEEVENTS);
+ }
+
+ public void addMouseListener(MouseListener listener) {
+ if (mouseListeners == null) {
+ mouseListeners = new MouseListenerCollection();
+ }
+ mouseListeners.add(listener);
+ }
+
+ public void removeMouseListener(MouseListener listener) {
+ if (mouseListeners != null) {
+ mouseListeners.remove(listener);
+ }
+ }
+
+ public void onBrowserEvent(Event event) {
+ super.onBrowserEvent(event);
+ switch (DOM.eventGetType(event)) {
+ case Event.ONMOUSEDOWN:
+ case Event.ONMOUSEUP:
+ case Event.ONMOUSEMOVE:
+ case Event.ONMOUSEOVER:
+ case Event.ONMOUSEOUT:
+ if (mouseListeners != null) {
+ mouseListeners.fireMouseEvent(this, event);
+ }
+ break;
+ }
+ }
+ }
+
+ private class DateClickListener implements TableListener {
+
+ private CalendarPanel cal;
+
+ public DateClickListener(CalendarPanel panel) {
+ cal = panel;
+ }
+
+ public void onCellClicked(SourcesTableEvents sender, int row, int col) {
+ if (sender != cal || row < 2 || row > 7
+ || !cal.datefield.isEnabled() || cal.datefield.isReadonly()) {
+ return;
+ }
+
+ String text = cal.getText(row, col);
+ if (text.equals(" ")) {
+ return;
+ }
+
+ try {
+ Integer day = new Integer(text);
+ Date newDate = new Date(cal.datefield.getCurrentDate()
+ .getTime());
+ newDate.setDate(day.intValue());
+ if (!isEnabledDate(newDate)) {
+ return;
+ }
+ cal.datefield.getCurrentDate().setTime(newDate.getTime());
+ cal.datefield.getClient().updateVariable(cal.datefield.getId(),
+ "day", cal.datefield.getCurrentDate().getDate(),
+ cal.datefield.isImmediate());
+
+ updateCalendar();
+ } catch (NumberFormatException e) {
+ // Not a number, ignore and stop here
+ return;
+ }
+ }
+
+ }
+
+ public void setLimits(Date min, Date max) {
+ if (min != null) {
+ Date d = new Date(min.getTime());
+ d.setHours(0);
+ d.setMinutes(0);
+ d.setSeconds(1);
+ minDate = d;
+ } else {
+ minDate = null;
+ }
+ if (max != null) {
+ Date d = new Date(max.getTime());
+ d.setHours(24);
+ d.setMinutes(59);
+ d.setSeconds(59);
+ maxDate = d;
+ } else {
+ maxDate = null;
+ }
+ }
+
+ public void setCalendarEntrySource(CalendarEntrySource entrySource) {
+ this.entrySource = entrySource;
+ }
+
+ public CalendarEntrySource getCalendarEntrySource() {
+ return entrySource;
+ }
+
+ public interface CalendarEntrySource {
+ public List getEntries(Date date, int resolution);
+ }
}
diff --git a/src/com/itmill/toolkit/terminal/gwt/client/ui/ICheckBox.java b/src/com/itmill/toolkit/terminal/gwt/client/ui/ICheckBox.java
index 50e1b76e6d..8d80561231 100644
--- a/src/com/itmill/toolkit/terminal/gwt/client/ui/ICheckBox.java
+++ b/src/com/itmill/toolkit/terminal/gwt/client/ui/ICheckBox.java
@@ -11,91 +11,93 @@ import com.itmill.toolkit.terminal.gwt.client.Paintable;
import com.itmill.toolkit.terminal.gwt.client.UIDL;
public class ICheckBox extends com.google.gwt.user.client.ui.CheckBox implements
- Paintable {
-
- public static final String CLASSNAME = "i-checkbox";
-
- String id;
-
- boolean immediate;
-
- ApplicationConnection client;
-
- private Element errorIndicatorElement;
-
- private ErrorMessage errorMessage;
-
- public ICheckBox() {
- setStyleName(CLASSNAME);
- addClickListener(new ClickListener() {
-
- public void onClick(Widget sender) {
- if (id == null || client == null)
- return;
- client.updateVariable(id, "state", isChecked(), immediate);
- }
-
- });
-
- }
-
- public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
- // Save details
- this.client = client;
- id = uidl.getId();
-
- // Ensure correct implementation
- if (client.updateComponent(this, uidl, false))
- return;
-
- if (uidl.hasAttribute("error")) {
- UIDL errorUidl = uidl.getErrors();
-
- if (errorIndicatorElement == null) {
- errorIndicatorElement = DOM.createDiv();
- DOM.sinkEvents(errorIndicatorElement, Event.MOUSEEVENTS);
- DOM.setElementProperty(errorIndicatorElement, "className",
- "i-errorindicator");
- DOM.appendChild(getElement(), errorIndicatorElement);
- }
- if (errorMessage == null)
- errorMessage = new ErrorMessage();
- errorMessage.updateFromUIDL(errorUidl);
-
- } else if (errorIndicatorElement != null) {
- DOM.setStyleAttribute(errorIndicatorElement, "display", "none");
- }
-
- if(uidl.hasAttribute("description")) {
- setTitle(uidl.getStringAttribute("description"));
- }
-
-
- // Set text
- setText(uidl.getStringAttribute("caption"));
- setChecked(uidl.getBooleanVariable("state"));
- immediate = uidl.getBooleanAttribute("immediate");
- }
-
- public void onBrowserEvent(Event event) {
- super.onBrowserEvent(event);
- Element target = DOM.eventGetTarget(event);
- if (errorIndicatorElement != null
- && DOM.compare(target, errorIndicatorElement)) {
- switch (DOM.eventGetType(event)) {
- case Event.ONMOUSEOVER:
- errorMessage.showAt(errorIndicatorElement);
- break;
- case Event.ONMOUSEOUT:
- errorMessage.hide();
- break;
- case Event.ONCLICK:
- ApplicationConnection.getConsole().log(
- DOM.getInnerHTML(errorMessage.getElement()));
- default:
- break;
- }
- }
-
- }
+ Paintable {
+
+ public static final String CLASSNAME = "i-checkbox";
+
+ String id;
+
+ boolean immediate;
+
+ ApplicationConnection client;
+
+ private Element errorIndicatorElement;
+
+ private ErrorMessage errorMessage;
+
+ public ICheckBox() {
+ setStyleName(CLASSNAME);
+ addClickListener(new ClickListener() {
+
+ public void onClick(Widget sender) {
+ if (id == null || client == null) {
+ return;
+ }
+ client.updateVariable(id, "state", isChecked(), immediate);
+ }
+
+ });
+
+ }
+
+ public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
+ // Save details
+ this.client = client;
+ id = uidl.getId();
+
+ // Ensure correct implementation
+ if (client.updateComponent(this, uidl, false)) {
+ return;
+ }
+
+ if (uidl.hasAttribute("error")) {
+ UIDL errorUidl = uidl.getErrors();
+
+ if (errorIndicatorElement == null) {
+ errorIndicatorElement = DOM.createDiv();
+ DOM.sinkEvents(errorIndicatorElement, Event.MOUSEEVENTS);
+ DOM.setElementProperty(errorIndicatorElement, "className",
+ "i-errorindicator");
+ DOM.appendChild(getElement(), errorIndicatorElement);
+ }
+ if (errorMessage == null) {
+ errorMessage = new ErrorMessage();
+ }
+ errorMessage.updateFromUIDL(errorUidl);
+
+ } else if (errorIndicatorElement != null) {
+ DOM.setStyleAttribute(errorIndicatorElement, "display", "none");
+ }
+
+ if (uidl.hasAttribute("description")) {
+ setTitle(uidl.getStringAttribute("description"));
+ }
+
+ // Set text
+ setText(uidl.getStringAttribute("caption"));
+ setChecked(uidl.getBooleanVariable("state"));
+ immediate = uidl.getBooleanAttribute("immediate");
+ }
+
+ public void onBrowserEvent(Event event) {
+ super.onBrowserEvent(event);
+ Element target = DOM.eventGetTarget(event);
+ if (errorIndicatorElement != null
+ && DOM.compare(target, errorIndicatorElement)) {
+ switch (DOM.eventGetType(event)) {
+ case Event.ONMOUSEOVER:
+ errorMessage.showAt(errorIndicatorElement);
+ break;
+ case Event.ONMOUSEOUT:
+ errorMessage.hide();
+ break;
+ case Event.ONCLICK:
+ ApplicationConnection.getConsole().log(
+ DOM.getInnerHTML(errorMessage.getElement()));
+ default:
+ break;
+ }
+ }
+
+ }
}
diff --git a/src/com/itmill/toolkit/terminal/gwt/client/ui/ICustomComponent.java b/src/com/itmill/toolkit/terminal/gwt/client/ui/ICustomComponent.java
index e75adb340d..73deb42e18 100644
--- a/src/com/itmill/toolkit/terminal/gwt/client/ui/ICustomComponent.java
+++ b/src/com/itmill/toolkit/terminal/gwt/client/ui/ICustomComponent.java
@@ -8,28 +8,28 @@ import com.itmill.toolkit.terminal.gwt.client.UIDL;
public class ICustomComponent extends SimplePanel implements Paintable {
- private static final String CLASSNAME = "i-customcomponent";
-
- public ICustomComponent() {
- super();
- setStyleName(CLASSNAME);
- }
-
- public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
-
- UIDL child = uidl.getChildUIDL(0);
- if (child != null) {
- Paintable p = (Paintable) client.getWidget(child);
- if (p != getWidget()) {
- if (getWidget() != null) {
- client.unregisterPaintable((Paintable) getWidget());
- clear();
- }
- setWidget((Widget) p);
- }
- p.updateFromUIDL(child, client);
- }
-
- }
+ private static final String CLASSNAME = "i-customcomponent";
+
+ public ICustomComponent() {
+ super();
+ setStyleName(CLASSNAME);
+ }
+
+ public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
+
+ UIDL child = uidl.getChildUIDL(0);
+ if (child != null) {
+ Paintable p = (Paintable) client.getWidget(child);
+ if (p != getWidget()) {
+ if (getWidget() != null) {
+ client.unregisterPaintable((Paintable) getWidget());
+ clear();
+ }
+ setWidget((Widget) p);
+ }
+ p.updateFromUIDL(child, client);
+ }
+
+ }
}
diff --git a/src/com/itmill/toolkit/terminal/gwt/client/ui/ICustomLayout.java b/src/com/itmill/toolkit/terminal/gwt/client/ui/ICustomLayout.java
index 7b8264b8eb..38637e6bed 100644
--- a/src/com/itmill/toolkit/terminal/gwt/client/ui/ICustomLayout.java
+++ b/src/com/itmill/toolkit/terminal/gwt/client/ui/ICustomLayout.java
@@ -23,425 +23,425 @@ import com.itmill.toolkit.terminal.gwt.client.Util;
*
*/
public class ICustomLayout extends ComplexPanel implements Paintable,
- Container, ContainerResizedListener {
-
- public static final String CLASSNAME = "i-customlayout";
-
- /** Location-name to containing element in DOM map */
- private HashMap locationToElement = new HashMap();
-
- /** Location-name to contained widget map */
- private HashMap locationToWidget = new HashMap();
-
- /** Widget to captionwrapper map */
- private HashMap widgetToCaptionWrapper = new HashMap();
-
- /** Currently rendered style */
- String currentTemplate;
-
- /** Unexecuted scripts loaded from the template */
- private String scripts = "";
-
- /** Paintable ID of this paintable */
- private String pid;
-
- private ApplicationConnection client;
-
- public ICustomLayout() {
- setElement(DOM.createDiv());
- // Clear any unwanted styling
- DOM.setStyleAttribute(getElement(), "border", "none");
- DOM.setStyleAttribute(getElement(), "margin", "0");
- DOM.setStyleAttribute(getElement(), "padding", "0");
- DOM.setStyleAttribute(getElement(), "overflow", "hidden");
- setStyleName(CLASSNAME);
- }
-
- /**
- * Sets widget to given location.
- *
- * If location already contains a widget it will be removed.
- *
- * @param widget
- * Widget to be set into location.
- * @param location
- * location name where widget will be added
- *
- * @throws IllegalArgumentException
- * if no such location is found in the layout.
- */
- public void setWidget(Widget widget, String location) {
-
- if (widget == null) {
- return;
- }
-
- // If no given location is found in the layout, and exception is throws
- Element elem = (Element) locationToElement.get(location);
- if (elem == null && hasTemplate()) {
- throw new IllegalArgumentException("No location " + location
- + " found");
- }
-
- // Get previous widget
- Widget previous = (Widget) locationToWidget.get(location);
- // NOP if given widget already exists in this location
- if (previous == widget) {
- return;
- }
- remove(previous);
-
- // if template is missing add element in order
- if (!hasTemplate()) {
- elem = getElement();
- }
-
- // Add widget to location
- super.add(widget, elem);
- locationToWidget.put(location, widget);
- }
-
- /** Update the layout from UIDL */
- public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
- this.client = client;
- // Client manages general cases
- if (client.updateComponent(this, uidl, false)) {
- return;
- }
-
- // Update PID
- pid = uidl.getId();
- if (!hasTemplate()) {
- // Update HTML template only once
- initializeHTML(uidl, client);
- }
-
- // Set size
- if (uidl.hasAttribute("width")) {
- setWidth(uidl.getStringAttribute("width"));
- } else {
- setWidth("100%");
- }
- if (uidl.hasAttribute("height")) {
- setHeight(uidl.getStringAttribute("height"));
- } else {
- setHeight("100%");
- }
-
- // Evaluate scripts
- eval(scripts);
- scripts = null;
-
- // For all contained widgets
- for (Iterator i = uidl.getChildIterator(); i.hasNext();) {
- UIDL uidlForChild = (UIDL) i.next();
- if (uidlForChild.getTag().equals("location")) {
- String location = uidlForChild.getStringAttribute("name");
- Widget child = client.getWidget(uidlForChild.getChildUIDL(0));
- try {
- setWidget(child, location);
- ((Paintable) child).updateFromUIDL(uidlForChild
- .getChildUIDL(0), client);
- } catch (IllegalArgumentException e) {
- // If no location is found, this component is not visible
- }
- }
- }
-
- iLayout();
- }
-
- /** Initialize HTML-layout. */
- private void initializeHTML(UIDL uidl, ApplicationConnection client) {
-
- String newTemplate = uidl.getStringAttribute("template");
-
- // Get the HTML-template from client
- String template = client
- .getResource("layouts/" + newTemplate + ".html");
- if (template == null) {
- template = "Layout file layouts/"
- + newTemplate
- + ".html is missing. Components will be drawn for debug purposes.";
- } else {
- currentTemplate = newTemplate;
- }
-
- // Connect body of the template to DOM
- template = extractBodyAndScriptsFromTemplate(template);
- DOM.setInnerHTML(getElement(), template);
-
- // Remap locations to elements
- locationToElement.clear();
- scanForLocations(getElement());
-
- // Remap image srcs in layout
- Widget parent = getParent();
- while (parent != null && !(parent instanceof IView)) {
- parent = parent.getParent();
- }
- if (parent != null && ((IView) parent).getTheme() != null) {
- String prefix;
- if (uriEndsWithSlash()) {
- prefix = "../ITMILL/themes/";
- } else {
- prefix = "ITMILL/themes/";
- }
- prefixImgSrcs(getElement(), prefix + ((IView) parent).getTheme()
- + "/layouts/");
- } else {
- throw (new IllegalStateException(
- "Could not find IView; maybe updateFromUIDL() was called before attaching the widget?"));
- }
-
- publishResizedFunction(DOM.getFirstChild(getElement()));
-
- }
-
- private native boolean uriEndsWithSlash() /*-{
- var path = $wnd.location.pathname;
- if(path.charAt(path.length - 1) == "/")
- return true;
- return false;
- }-*/;
-
- private boolean hasTemplate() {
- if (currentTemplate == null) {
- return false;
- } else {
- return true;
- }
- }
-
- /** Collect locations from template */
- private void scanForLocations(Element elem) {
-
- String location = getLocation(elem);
- if (location != null) {
- locationToElement.put(location, elem);
- DOM.setInnerHTML(elem, "");
- } else {
- int len = DOM.getChildCount(elem);
- for (int i = 0; i < len; i++) {
- scanForLocations(DOM.getChild(elem, i));
- }
- }
- }
-
- /** Get the location attribute for given element */
- private static native String getLocation(Element elem) /*-{
- return elem.getAttribute("location");
- }-*/;
-
- /** Evaluate given script in browser document */
- private static native void eval(String script) /*-{
- try {
- if (script != null)
- eval("{ var document = $doc; var window = $wnd; "+ script + "}");
- } catch (e) {
- }
- }-*/;
-
- /** Prefix all img tag srcs with given prefix. */
- private static native void prefixImgSrcs(Element e, String srcPrefix) /*-{
- try {
- var divs = e.getElementsByTagName("img");
- var base = "" + $doc.location;
- var l = base.length-1;
- while (l >= 0 && base.charAt(l) != "/") l--;
- base = base.substring(0,l+1);
- for (var i = 0; i < divs.length; i++) {
- var div = divs[i];
- var src = div.getAttribute("src");
- if (src.indexOf(base) == 0) div.setAttribute("src",base + srcPrefix + src.substring(base.length));
- else if (src.indexOf("http") != 0) div.setAttribute("src",srcPrefix + src);
- }
- } catch (e) { alert(e + " " + srcPrefix);}
- }-*/;
-
- /**
- * Extract body part and script tags from raw html-template.
- *
- * Saves contents of all script-tags to private property: scripts. Returns
- * contents of the body part for the html without script-tags. Also replaces
- * all _UID_ tags with an unique id-string.
- *
- * @param html
- * Original HTML-template received from server
- * @return html that is used to create the HTMLPanel.
- */
- private String extractBodyAndScriptsFromTemplate(String html) {
-
- // Replace UID:s
- html = html.replaceAll("_UID_", pid + "__");
-
- // Exctract script-tags
- scripts = "";
- int endOfPrevScript = 0;
- int nextPosToCheck = 0;
- String lc = html.toLowerCase();
- String res = "";
- int scriptStart = lc.indexOf("", scriptStart);
- scripts += html.substring(scriptStart + 1, j) + ";";
- nextPosToCheck = endOfPrevScript = j + "".length();
- scriptStart = lc.indexOf("", scriptStart);
+ scripts += html.substring(scriptStart + 1, j) + ";";
+ nextPosToCheck = endOfPrevScript = j + "".length();
+ scriptStart = lc.indexOf("