code
stringlengths
67
466k
docstring
stringlengths
1
13.2k
public void setButtonLabelInfo(String encodedLabelInfo) { CommandButtonLabelInfo newLabelInfo = CommandButtonLabelInfo.valueOf(encodedLabelInfo); setLabelInfo(newLabelInfo); }
Sets the label information for the command using the given encoded label descriptor. @param encodedLabelInfo The encoded label descriptor. May be null or empty. @see CommandButtonLabelInfo#valueOf(String)
public void setLabelInfo(CommandButtonLabelInfo labelInfo) { if (labelInfo == null) { labelInfo = CommandButtonLabelInfo.BLANK_BUTTON_LABEL; } CommandButtonLabelInfo old = this.labelInfo; this.labelInfo = labelInfo; firePropertyChange(LABEL_INFO_PROPERTY, old, this.labelInfo); }
{@inheritDoc}
public void setIconInfo(CommandButtonIconInfo iconInfo) { if (iconInfo == null) { iconInfo = CommandButtonIconInfo.BLANK_ICON_INFO; } CommandButtonIconInfo old = this.iconInfo; this.iconInfo = iconInfo; firePropertyChange(ICON_INFO_PROPERTY, old, this.iconInfo); }
{@inheritDoc}
public void setLargeIconInfo(CommandButtonIconInfo largeIconInfo) { if (largeIconInfo == null) { largeIconInfo = CommandButtonIconInfo.BLANK_ICON_INFO; } CommandButtonIconInfo old = this.largeIconInfo; this.largeIconInfo = largeIconInfo; firePropertyChange(LARGE_ICON_INFO_PROPERTY, old, this.largeIconInfo); }
{@inheritDoc}
public void setIcon(Icon icon) { Icon old = null; if (iconInfo == CommandButtonIconInfo.BLANK_ICON_INFO) { if (icon != null) { // New IconInfo fires event setIconInfo(new CommandButtonIconInfo(icon)); } } else { old = iconInfo.getIcon(); this.iconInfo.setIcon(icon); } firePropertyChange(ICON_PROPERTY, old, icon); }
Set the main default icon to be associated with the command. @param icon The main default icon. May be null.
public void setLargeIcon(Icon icon) { Icon old = null; if (largeIconInfo == CommandButtonIconInfo.BLANK_ICON_INFO) { if (icon != null) { // new IconInfo fires event setLargeIconInfo(new CommandButtonIconInfo(icon)); } } else { old = largeIconInfo.getIcon(); this.largeIconInfo.setIcon(icon); } firePropertyChange(LARGE_ICON_PROPERTY, old, icon); }
Sets the main default large icon for the command. @param icon The large icon. May be null.
public void configureIconInfo(AbstractButton button, boolean useLargeIcons) { Assert.notNull(button, "button"); if (useLargeIcons) { largeIconInfo.configure(button); } else { iconInfo.configure(button); } }
Configures the given button with the icon information contained in this descriptor. @param button The button to be configured. Must not be null. @param useLargeIcons Set to true to configure the button with large icons. False will use default size icons. @throws IllegalArgumentException if {@code button} is null.
public void configureColor(AbstractButton button) { Assert.notNull(button, "button"); if (foreground != null) { button.setForeground(foreground); } if (background != null) { button.setBackground(background); } }
Configures the given button with colours for background and foreground if available. @param button The button to be configured. Must not be null.
public void configure(AbstractButton button, AbstractCommand command, CommandButtonConfigurer configurer) { Assert.notNull(button, "button"); Assert.notNull(configurer, "configurer"); configurer.configure(button, command, this); }
Configures the given button and command using the given configurer and the information contained in this instance. @param button The button to be configured. Must not be null. @param command The command to be configured. May be null. @param configurer The configurer. Must not be null. @throws IllegalArgumentException if {@code button} or {@code configurer} are null.
public void configure(Action action) { Assert.notNull(action, "The swing action to configure is required"); action.putValue(Action.NAME, getText()); action.putValue(Action.MNEMONIC_KEY, new Integer(getMnemonic())); action.putValue(Action.SMALL_ICON, getIcon()); action.putValue("LargeIcon", getLargeIcon()); action.putValue(Action.ACCELERATOR_KEY, getAccelerator()); action.putValue(Action.SHORT_DESCRIPTION, caption); action.putValue(Action.LONG_DESCRIPTION, description); }
Configures the given action with the information contained in this descriptor. @param action The action to be configured. Must not be null. @throws IllegalArgumentException if {@code action} is null.
public void setAuthorized( boolean authorized ) { if( isAuthorized() != authorized ) { this.authorized = authorized; // We need to apply a change to our enabled state depending on our // new authorized state. if( authorized ) { // install the last requested enabled state setEnabled(maskedEnabledState); } else { // Record the current enabled state and then disable maskedEnabledState = isEnabled(); internalSetEnabled(false); } } }
Set the authorized state. Setting authorized to false will override any call to {@link #setEnabled(boolean)}. As long as this object is unauthorized, it can not be enabled. @param authorized Pass <code>true</code> if the object is to be authorized
private Image loadImage(Resource path) throws IOException { URL url = path.getURL(); if (url == null) { logger.warn("Unable to locate splash screen in classpath at: " + path); return null; } return Toolkit.getDefaultToolkit().createImage(url); }
Load image from path. @param path Path to image. @return Image @throws java.io.IOException @throws NullPointerException if {@code path} is null.
protected Component createContentPane() { Image image = getImage(); if (image != null) { return new ImageCanvas(image); } return null; }
Returns a component that displays an image in a canvas.
public static boolean loadPageLayoutData(DockingManager manager, String pageId, Perspective perspective){ manager.beginLoadLayoutData(); try{ if(isValidLayout(manager, pageId, perspective)){ String pageLayout = MessageFormat.format(PAGE_LAYOUT, pageId, perspective.getId()); manager.loadLayoutDataFrom(pageLayout); return true; } else{ manager.loadLayoutData(); return false; } } catch(Exception e){ manager.loadLayoutData(); return false; } }
Loads a the previously saved layout for the current page. If no previously persisted layout exists for the given page the built in default layout is used. @param manager The docking manager to use @param pageId The page to get the layout for @return a boolean saying if the layout requested was previously saved
public static void savePageLayoutData(DockingManager manager, String pageId, String perspectiveId){ manager.saveLayoutDataAs(MessageFormat.format(PAGE_LAYOUT, pageId, perspectiveId)); }
Saves the current page layout. @param manager The current docking manager @param pageId The page to saved the layout for
public final void setViewDescriptor(ViewDescriptor viewDescriptor) { Assert.notNull(viewDescriptor, "viewDescriptor"); setId(viewDescriptor.getId()); setLabel(viewDescriptor.getShowViewCommandLabel()); setIcon(viewDescriptor.getIcon()); setCaption(viewDescriptor.getCaption()); this.viewDescriptor = viewDescriptor; }
Sets the descriptor for the view that is to be opened by this command object. This command object will be assigned the id, label, icon, and caption from the given view descriptor. @param viewDescriptor The view descriptor, cannot be null. @throws IllegalArgumentException if {@code viewDescriptor} is null.
public Perspective getCurrentPerspective(){ String key = MessageFormat.format(CURRENT_PERSPECTIVE_KEY, new Object[]{pageName}); String id = prefs.get(key, DEFAULT_PERSPECTIVE_KEY); Iterator it = perspectives.iterator(); while(it.hasNext()){ Perspective perspective = (Perspective)it.next(); if(id.equals(perspective.getId())){ return perspective; } } return NullPerspective.NULL_PERSPECTIVE; }
Returns the current perspective, or the NullPerspective instance if no current perspective is defined.
protected void doExecuteCommand() { Widget widget = super.getWidget(); Assert.isInstanceOf(AbstractDataEditorWidget.class, widget); AbstractDataEditorWidget dataEditorWidget = (AbstractDataEditorWidget)widget; Object dataEditorParameters = getParameter(DefaultDataEditorWidget.PARAMETER_MAP); if(dataEditorParameters != null) { dataEditorWidget.executeFilter((Map<String, Object>)dataEditorParameters); } super.doExecuteCommand(); }
{@inheritDoc} Open de dataeditor.
public void setMessage(String message) { this.message = message; if (errorMessage == null) { logger.debug("Setting status bar message to \"" + message + "\""); messageLabel.setText(this.message); } }
Sets the message text to be displayed on the status bar. @param message the message to be set, if <code>null</code>, the status line is cleared.
public void setErrorMessage(String errorMessage) { if (errorMessage == null) { logger.debug("Resetting the status bar message color to normal"); messageLabel.setForeground(SystemColor.controlText); this.errorMessage = null; setMessage(message); } else { logger.debug("Setting the status bar messsage color to red"); messageLabel.setForeground(Color.RED); logger.debug("Setting status bar error message to \"" + errorMessage + "\""); this.errorMessage = errorMessage; messageLabel.setText(this.errorMessage); } }
Sets the error message text to be displayed on the status bar. <p> Error messages are shown over the standard message, and in a red color. @param errorMessage the error message to be set, if <code>null</code>, the error message is cleared, and the standard message is shown again
protected JLabel createMessageLabel() { JLabel messageLabel = new JLabel(" "); messageLabel.setName("message"); Border bevelBorder = BorderFactory.createBevelBorder(BevelBorder.LOWERED, UIManager .getColor("controlHighlight"), UIManager.getColor("controlShadow")); Border emptyBorder = BorderFactory.createEmptyBorder(1, 3, 1, 3); messageLabel.setBorder(BorderFactory.createCompoundBorder(bevelBorder, emptyBorder)); return messageLabel; }
Create the <code>JLabel</code> used to render the messages. <p> Can safely be overridden to customize the label @return the <code>JLabel</code>
@Override public Boolean installOverlay(JComponent targetComponent, JComponent overlay) { this.installOverlay(targetComponent, overlay, SwingConstants.NORTH_WEST, DefaultOverlayService.DEFAULT_INSETS); return Boolean.TRUE; }
{@inheritDoc} @see #installOverlay(JComponent, JComponent, int, Insets)
@Override public Boolean installOverlay(JComponent targetComponent, JComponent overlay, int position, Insets insets) { if (insets == null) { // TODO FIXME insets = new Insets(0, 0, 0, 0); } InterceptorOverlayHelper.attachOverlay(overlay, targetComponent, position, insets.left, insets.top); return Boolean.TRUE; }
{@inheritDoc}
public Boolean uninstallOverlay(JComponent targetComponent, JComponent overlay) { this.uninstallOverlay(targetComponent, overlay, null); return Boolean.TRUE; }
{@inheritDoc} @see #uninstallOverlay(JComponent, JComponent, Insets)
@Override public Boolean uninstallOverlay(JComponent targetComponent, JComponent overlay, Insets insets) { overlay.setVisible(Boolean.FALSE); return Boolean.TRUE; }
{@inheritDoc}
@Override public Boolean hideOverlay(JComponent targetComponent, JComponent overlay) { overlay.setVisible(Boolean.FALSE); return Boolean.TRUE; }
{@inheritDoc}
@Override public Boolean showOverlay(JComponent targetComponent, JComponent overlay) { overlay.setVisible(Boolean.TRUE); return Boolean.TRUE; }
{@inheritDoc}
private synchronized Image loadImage(InputStream stream) throws IOException { Toolkit toolkit = Toolkit.getDefaultToolkit(); byte data[] = FileCopyUtils.copyToByteArray(stream); Image image = toolkit.createImage(data); imageLoaded = false; imageError = false; // fully loads the image into memory toolkit.prepareImage(image, -1, -1, this); while (!imageLoaded && !imageError) { try { wait(); } catch (InterruptedException ex) { } } if (imageError) { throw new IOException("Error preparing image from resource."); } return image; }
Load an image from the underlying resource's input stream. Constructs a new <code>Image</code> object from the data read from the input stream on each call. <p> This method loads the image fully into memory. This improves UI responsiveness when the image is needed by the GUI event-dispatching thread. @param stream The input stream. @return The resulting <code>Image</code> object. @throws java.io.IOException If an error occurred while reading from the stream.
protected void registerPostProcessorAction(String actionId) { if( postProcessorActionIds.contains( actionId ) ) { throw new IllegalArgumentException( "Post-processor Action '" + actionId + "' is already registered" ); } postProcessorActionIds.add( actionId ); }
Register a post-processor action. The action id specified must not conflict with any other action registered. Subclasses that provide additional post-processor actions MUST call this method to register them. @param actionId Id of post-processor action to register
protected void updateControlledObject(Authorizable controlledObject, boolean authorized) { if( logger.isDebugEnabled() ) { logger.debug( "setAuthorized( " + authorized + ") on: " + controlledObject ); } controlledObject.setAuthorized( authorized ); runPostProcessorActions( controlledObject, authorized ); }
Update a controlled object based on the given authorization state. @param controlledObject Object being controlled @param authorized state that has been installed on controlledObject
protected void runPostProcessorActions(Object controlledObject, boolean authorized) { String actions = getPostProcessorActionsToRun(); if( logger.isDebugEnabled() ) { logger.debug( "Run post-processors actions: " + actions ); } String[] actionIds = StringUtils.commaDelimitedListToStringArray(actions); for( int i = 0; i < actionIds.length; i++ ) { doPostProcessorAction( actionIds[i], controlledObject, authorized ); } }
Run all the requested post-processor actions. @param controlledObject Object being controlled @param authorized state that has been installed on controlledObject
protected void doPostProcessorAction(String actionId, Object controlledObject, boolean authorized) { if( VISIBLE_TRACKS_AUTHORIZED_ACTION.equals( actionId ) ) { setVisibilityOnControlledObject( controlledObject, authorized ); } }
Post-process a controlled object after its authorization state has been updated. Subclasses that override this method MUST ensure that this method is called id they do not process the given action id. @param actionId Id of the post-processor action to run @param controlledObject Object being controlled @param authorized state that has been installed on controlledObject
private void setVisibilityOnControlledObject(Object controlledObject, boolean authorized) { try { Method method = controlledObject.getClass().getMethod( "setVisible", new Class[] { boolean.class } ); method.invoke( controlledObject, new Object[] { new Boolean( authorized ) } ); } catch( NoSuchMethodException ignored ) { System.out.println( "NO setVisible method on object: " + controlledObject ); // No method to call, so nothing to do } catch( IllegalAccessException ignored ) { logger.error( "Could not call setVisible", ignored ); } catch( InvocationTargetException ignored ) { logger.error( "Could not call setVisible", ignored ); } }
Set the visible property on a controlled action according to the provided authorization.
protected boolean shouldAuthorize(Authentication authentication) { Assert.state(getAccessDecisionManager() != null, "The AccessDecisionManager can not be null!"); boolean authorize = false; try { if( authentication != null ) { Object securedObject = getSecuredObject(); List<ConfigAttribute> cad = getConfigAttributeDefinition( securedObject ); getAccessDecisionManager().decide( authentication, getSecuredObject(), cad ); authorize = true; } } catch( AccessDeniedException e ) { // This means the secured objects should not be authorized } return authorize; }
Determine if our controlled objects should be authorized based on the provided authentication token. @param authentication token @return true if should authorize
public Object removeControlledObject(Authorizable object) { Object removed = null; for( Iterator iter = controlledObjects.iterator(); iter.hasNext(); ) { WeakReference ref = (WeakReference) iter.next(); Authorizable controlledObject = (Authorizable) ref.get(); if( controlledObject == null ) { // Has been GCed, remove from our list iter.remove(); } else if( controlledObject.equals( object ) ) { removed = controlledObject; iter.remove(); } } return removed; }
Remove an object from our controlled set. @param object to remove @return object removed or null if not found
public void afterPropertiesSet() throws Exception { // Ensure that all post-processors requested are registered String[] actions = StringUtils.commaDelimitedListToStringArray( getPostProcessorActionsToRun() ); for( int i = 0; i < actions.length; i++ ) { if( !postProcessorActionIds.contains( actions[i] ) ) { throw new IllegalArgumentException( "Requested post-processor action '" + actions[i] + "' is not registered." ); } } }
Validate our configuration. @throws Exception
public boolean close(){ if(super.close()){ dockableHolder.dispose(); dockableHolder.removeWindowFocusListener(this); WindowListener[] listeners = dockableHolder.getWindowListeners(); for (WindowListener listener : listeners) { dockableHolder.removeWindowListener(listener); } Lm.setParent(null); dockableHolder.removeAll(); dockableHolder.getRootPane().removeAll(); dockableHolder = null; return true; } else{ return false; } }
Overridden close method to avoid memory leaks by Mikael Valot
protected void setActivePage(ApplicationPage page) { getPage().getControl(); loadLayoutData(page.getId()); ((JideApplicationPage)getPage()).updateShowViewCommands(); }
Sets the active page by loading that page's components and applying the layout. Also updates the show view command menu to list the views within the page.
public static void throwIfNull(Object propertyValue, String propertyName, Class beanClass) { if (propertyValue == null) { throw new PropertyNotSetException(beanClass, propertyName); } }
Throws an instance of this exception if the given {@code propertyValue} is null. @param propertyValue The value of the property. @param propertyName The name of the property. @param beanClass The class on which the property is supposed to be set. @throws PropertyNotSetException if {@code propertyValue} is null.
public void setForm(AbstractForm form) { this.form = form; if(getId() == null) { setId(form.getId()); } }
Set the inner form that needs decorating.
private Icon getEditIcon() { Icon icon = null; if (getFormId() != null) { icon = getApplicationConfig().iconSource().getIcon(getFormId() + ".shuttleList.edit"); } if (icon == null) { icon = getApplicationConfig().iconSource().getIcon("shuttleList.edit"); } return icon; }
Using the application services, check for: formId.shuttleList.edit if not there shuttleList.edit @return an Icon
protected int[] indicesOf(final Object itemSet) { int[] ret = null; if (itemSet instanceof Collection) { Collection collection = (Collection) itemSet; ret = new int[collection.size()]; int i = 0; for (Iterator iter = collection.iterator(); iter.hasNext(); i++) { ret[i] = indexOf(iter.next()); } } else if (itemSet == null) { ret = new int[0]; } else if (itemSet.getClass().isArray()) { Object[] items = (Object[]) itemSet; ret = new int[items.length]; for (int i = 0; i < items.length; i++) { ret[i] = indexOf(items[i]); } } else { throw new IllegalArgumentException("itemSet must be eithe an Array or a Collection"); } return ret; }
Return an array of indices in the selectableItems for each element in the provided set. The set can be either a Collection or an Array. @param itemSet Either an array or a Collection of items @return array of indices of the elements in itemSet within the selectableItems
protected boolean arraysEqual(Object[] a1, Object[] a2) { if (a1 != null && a2 != null && a1.length == a2.length) { // Loop over each element and compare them using our comparator for (int i = 0; i < a1.length; i++) { if (!equalByComparator(a1[i], a2[i])) { return false; } } return true; } else if (a1 == null && a2 == null) { return true; } return false; }
Compare two arrays for equality using the configured comparator. @param a1 First array to compare @param a2 Second array to compare @return boolean true if they are equal
protected boolean collectionsEqual(Collection a1, Collection a2) { if (a1 != null && a2 != null && a1.size() == a2.size()) { // Loop over each element and compare them using our comparator Iterator iterA1 = a1.iterator(); Iterator iterA2 = a2.iterator(); while (iterA1.hasNext()) { if (!equalByComparator(iterA1.next(), iterA2.next())) { return false; } } } else if (a1 == null && a2 == null) { return true; } return false; }
Compare two collections for equality using the configured comparator. Element order must be the same for the collections to compare equal. @param a1 First collection to compare @param a2 Second collection to compare @return boolean true if they are equal
private boolean equalByComparator(Object o1, Object o2) { return comparator == null ? o1.equals(o2) : comparator.compare(o1, o2) == 0; }
Using the configured comparator (or equals if not configured), determine if two objects are equal. @param o1 Object to compare @param o2 Object to compare @return boolean true if objects are equal
public void addGuarded(Guarded newGuarded, int mask) { this.guardedEntries.put(newGuarded, new Integer(mask)); newGuarded.setEnabled(stateMatchesMask(getFormModelState(), mask)); }
Adds a guarded object to be guarded by this FormGuard @param newGuarded object to be guarded @param mask indicating which state of the formModel should enable the guarded obhject
public boolean removeGuarded(Guarded toRemove) { Object mask = this.guardedEntries.remove(toRemove); return mask != null; }
Removes the guarded object from the management of this FormGuard. @param toRemove object that no longer should be managed @return <code>false</code> if the object toRemove was not present in the list of managed guarded objects.
public static DockableState fixVLDockingBug(DockingDesktop dockingDesktop, Dockable dockable) { Assert.notNull(dockingDesktop, "dockingDesktop"); Assert.notNull(dockable, "dockable"); final DockingContext dockingContext = dockingDesktop.getContext(); final DockKey dockKey = dockable.getDockKey(); DockableState dockableState = dockingDesktop.getDockableState(dockable); final Boolean thisFixApplies = (dockingContext.getDockableByKey(dockKey.getKey()) != null); if ((thisFixApplies) && (dockableState == null)) { dockingDesktop.registerDockable(dockable); dockableState = dockingDesktop.getDockableState(dockable); // dockKey.setLocation(dockableState.getLocation()); Assert.notNull(dockableState, "dockableState"); } return dockableState; }
Fixes an VLDocking bug consisting on dockables that belong to a docking desktop have no state on it. @param dockable the dockable candidate. @return its dockable state. If none then registers the dockable again and ensures dockable state is not null.
public static String activationKey(String key, Boolean active) { Assert.notNull(key, "key"); Assert.notNull(active, "active"); final int index = key.lastIndexOf(VLDockingUtils.DOT); final String overlay = active ? VLDockingUtils.ACTIVE_INFIX : VLDockingUtils.INACTIVE_INFIX; // return StringUtils.overlay(key, overlay, index, index); return key; //TODO }
Transforms a UI object key into an activation aware key name. @param key the key. @param active <code>true</code> for <em>active</em> UI keys and <code>false</code> for inactive. @return the transformed key.
public static DockViewTitleBar nullSafeFindDockViewTitleBar(Component component) { final DockViewTitleBar dockViewTitleBar; if (component != null) { dockViewTitleBar = VLDockingUtils.findDockViewTitleBar(component); } else { dockViewTitleBar = null; } return dockViewTitleBar; }
Null safe version of {@link #findDockViewTitleBar(java.awt.Component)}. @param component the component. @return the dock view title bar. @see #findDockViewTitleBar(java.awt.Component)
public static DockViewTitleBar findDockViewTitleBar(Component component) { Assert.notNull(component, "component"); final SingleDockableContainer sdc = DockingUtilities.findSingleDockableContainerAncestor(component); final DockViewTitleBar dockViewTitleBar; if (sdc == null) { dockViewTitleBar = null; } else if (sdc instanceof DockView) { dockViewTitleBar = ((DockView) sdc).getTitleBar(); } else if (sdc instanceof AutoHideExpandPanel) { dockViewTitleBar = ((AutoHideExpandPanel) sdc).getTitleBar(); } else { dockViewTitleBar = null; } return dockViewTitleBar; }
Find the dock view title bar associated to the dockable container of a given component (if any). @param component the component. @return the dock view title bar.
public void onApplicationEvent(ApplicationEvent event) { if ((event instanceof LoginEvent) && (event.getSource() != LoginEvent.NO_AUTHENTICATION)) handleLoginEvent((LoginEvent) event); else if ((event instanceof LogoutEvent)) handleLogoutEvent((LogoutEvent) event); }
Handle events that influence the session/user context.
protected void handleLoginEvent(LoginEvent event) { ApplicationSessionInitializer asi = getApplicationSessionInitializer(); if (asi != null) { asi.initializeUser(); Map<String, Object> userAttributes = asi.getUserAttributes(); if (userAttributes != null) { setUserAttributes(userAttributes); } } Authentication auth = (Authentication) event.getSource(); propertyChangeSupport.firePropertyChange(USER, null, auth); }
When a correct login occurs, read all relevant userinformation into session. @param event the loginEvent that triggered this handler.
protected void handleLogoutEvent(LogoutEvent event) { clearUser(); Authentication auth = (Authentication) event.getSource(); propertyChangeSupport.firePropertyChange(USER, auth, null); }
When a logout occurs, remove all user related information from the session. @param event the logoutEvent that triggered this handler.
public void initializeSession() { ApplicationSessionInitializer asi = getApplicationSessionInitializer(); if (asi != null) { asi.initializeSession(); Map<String, Object> sessionAttributes = asi.getSessionAttributes(); if (sessionAttributes != null) { setSessionAttributes(sessionAttributes); } propertyChangeSupport.firePropertyChange(SESSION_ATTRIBUTES, null, sessionAttributes); } }
Initialize the session attributes.
public Object getUserAttribute(String key, Object defaultValue) { Object attributeValue = this.userAttributes.get(key); if (attributeValue == null) attributeValue = defaultValue; return attributeValue; }
Get a value from the user attributes map. @param key name of the attribute @param defaultValue a default value to return if no value is found. @return the attribute value
public void setUserAttribute(String key, Object newValue) { Object oldValue = userAttributes.put(key, newValue); propertyChangeSupport.firePropertyChange(key, oldValue, newValue); propertyChangeSupport.firePropertyChange(USER_ATTRIBUTES, null, userAttributes); }
Add a key/value pair to the user attributes map. @param key a unique string code. @param newValue the associated value.
public void setUserAttributes(Map<String, Object> attributes) { userAttributes.putAll(attributes); propertyChangeSupport.firePropertyChange(USER_ATTRIBUTES, null, userAttributes); }
Add the given key/value pairs to the user attributes. @param attributes a map of key/value pairs.
public Object getSessionAttribute(String key, Object defaultValue) { Object attributeValue = this.sessionAttributes.get(key); if (attributeValue == null) attributeValue = defaultValue; return attributeValue; }
Get a value from the session attributes map. @param key a unique string code @param defaultValue the default value if not found @return The session attibute or the default value if not found
public void setSessionAttribute(String key, Object newValue) { Object oldValue = sessionAttributes.put(key, newValue); propertyChangeSupport.firePropertyChange(key, oldValue, newValue); propertyChangeSupport.firePropertyChange(SESSION_ATTRIBUTES, null, sessionAttributes); }
Add a key/value pair to the session attributes map. @param key a unique string code. @param newValue the associated value.
public void setSessionAttributes(Map<String, Object> attributes) { this.sessionAttributes.putAll(attributes); propertyChangeSupport.firePropertyChange(SESSION_ATTRIBUTES, null, sessionAttributes); }
Add the given key/value pairs to the session attributes. @param attributes a map of key/value pairs.
public Object getAttribute(String key, Object defaultValue) { Object attributeValue = getUserAttribute(key, null); if (attributeValue != null) return attributeValue; attributeValue = getSessionAttribute(key, null); if (attributeValue != null) return attributeValue; return defaultValue; }
Get a value from the user OR session attributes map. @param key name of the attribute @param defaultValue a default value to return if no value is found. @return the attribute value
private void installPrePackagedUIManagerDefaults() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); UIManager.put("Tree.line", "Angled"); UIManager.put("Tree.leafIcon", null); UIManager.put("Tree.closedIcon", null); UIManager.put("Tree.openIcon", null); UIManager.put("Tree.rightChildIndent", new Integer(10)); } catch (Exception e) { throw new ApplicationException("Unable to set defaults", e); } }
Initializes the UIManager defaults to values based on recommended, best-practices user interface design. This should generally be called once by an initializing application class.
@Override public final void propertyChange(PropertyChangeEvent evt) { if ("lookAndFeel".equals(evt.getPropertyName())) { this.onLookAndFeelChange((LookAndFeel) evt.getOldValue(), (LookAndFeel) evt.getNewValue()); } }
{@inheritDoc}
private JTable installSearchable(JTable table) { final TableSearchable tableSearchable = SearchableUtils.installSearchable(table); // Search for all columns tableSearchable.setMainIndex(-1); return table; }
Installs a <code>Searchable</code> into the given table. @param table the target table. @return the target table.
private <T extends JTextComponent> T installSearchable(T textComponent) { SearchableUtils.installSearchable(textComponent); return textComponent; }
Installs a <code>Searchable</code> into the given text component. @param <T> the type of the text component. @param textComponent the target text component. @return the text component.
@Override public void processComponent(String propertyName, JComponent component) { if (component instanceof JComboBox) { this.installSearchable((JComboBox) component); } else if (component instanceof JList) { this.installSearchable((JList) component); } else if (component instanceof JTable) { this.installSearchable((JTable) component); } else if (component instanceof JTextComponent) { this.installSearchable((JTextComponent) component); } }
Installs a <code>Searchable</code> into the given component. @param propertyName the property name. @param component the target component.
public GridBagLayoutFormBuilder appendLabeledField(String propertyName, int colSpan) { return appendLabeledField(propertyName, LabelOrientation.LEFT, colSpan); }
Appends a label and field to the end of the current line. <p /> The label will be to the left of the field, and be right-justified. <br /> The field will "grow" horizontally as space allows. <p /> @param propertyName the name of the property to create the controls for @param colSpan the number of columns the field should span @return "this" to make it easier to string together append calls
public GridBagLayoutFormBuilder appendLabeledField(String propertyName, LabelOrientation labelOrientation, int colSpan) { final JComponent field = createDefaultBinding(propertyName).getControl(); return appendLabeledField(propertyName, field, labelOrientation, colSpan); }
Appends a label and field to the end of the current line. <p /> The label will be to the left of the field, and be right-justified. <br /> The field will "grow" horizontally as space allows. <p /> @param propertyName the name of the property to create the controls for @param colSpan the number of columns the field should span @return "this" to make it easier to string together append calls
public GridBagLayoutFormBuilder appendLabeledField(String propertyName, final JComponent field, LabelOrientation labelOrientation) { return appendLabeledField(propertyName, field, labelOrientation, 1); }
Appends a label and field to the end of the current line. <p /> The label will be to the left of the field, and be right-justified. <br /> The field will "grow" horizontally as space allows. <p /> @param propertyName the name of the property to create the controls for @return "this" to make it easier to string together append calls
public GridBagLayoutFormBuilder appendLabeledField(String propertyName, final JComponent field, LabelOrientation labelOrientation, int colSpan) { return appendLabeledField(propertyName, field, labelOrientation, colSpan, 1, true, false); }
Appends a label and field to the end of the current line. <p /> The label will be to the left of the field, and be right-justified. <br /> The field will "grow" horizontally as space allows. <p /> @param propertyName the name of the property to create the controls for @param colSpan the number of columns the field should span @return "this" to make it easier to string together append calls @see FormComponentInterceptor#processLabel(String, JComponent)
public GridBagLayoutFormBuilder appendLabeledField(String propertyName, final JComponent field, LabelOrientation labelOrientation, int colSpan, int rowSpan, boolean expandX, boolean expandY) { builder.appendLabeledField(propertyName, field, labelOrientation, colSpan, rowSpan, expandX, expandY); return this; }
Appends a label and field to the end of the current line. <p /> The label will be to the left of the field, and be right-justified. <br /> The field will "grow" horizontally as space allows. <p /> @param propertyName the name of the property to create the controls for @param colSpan the number of columns the field should span @return "this" to make it easier to string together append calls @see FormComponentInterceptor#processLabel(String, JComponent)
public void addPropertyChangeListener(PropertyChangeListener listener) { if (listener instanceof PropertyChangeListenerProxy) { PropertyChangeListenerProxy proxy = (PropertyChangeListenerProxy) listener; addPropertyChangeListener(proxy.getPropertyName(), (PropertyChangeListener) proxy.getListener()); } else { if (listeners == null) { listeners = new EventListenerList(); } listeners.add(PropertyChangeListener.class, listener); } }
Add a PropertyChangeListener to the listener list. The listener is registered for all properties. @param listener The PropertyChangeListener to be added
public PropertyChangeListener[] getPropertyChangeListeners() { List returnList = new ArrayList(); // Add all the PropertyChangeListeners if (listeners != null) { returnList.addAll(Arrays.asList(listeners.getListeners(PropertyChangeListener.class))); } // Add all the PropertyChangeListenerProxys if (children != null) { Iterator iterator = children.keySet().iterator(); while (iterator.hasNext()) { String key = (String) iterator.next(); PropertyChangeSupport child = (PropertyChangeSupport) children.get(key); PropertyChangeListener[] childListeners = child.getPropertyChangeListeners(); for (int index = childListeners.length - 1; index >= 0; index--) { returnList.add(new PropertyChangeListenerProxy(key, childListeners[index])); } } } return (PropertyChangeListener[]) returnList.toArray(new PropertyChangeListener[returnList.size()]); }
Returns an array of all the listeners that were added to the SwingPropertyChangeSupport object with addPropertyChangeListener(). <p> If some listeners have been added with a named property, then the returned array will be a mixture of PropertyChangeListeners and <code>PropertyChangeListenerProxy</code>s. If the calling method is interested in distinguishing the listeners then it must test each element to see if it's a <code>PropertyChangeListenerProxy</code> perform the cast and examine the parameter. <pre> PropertyChangeListener[] listeners = support.getPropertyChangeListeners(); for (int i = 0; i &lt; listeners.length; i++) { if (listeners[i] instanceof PropertyChangeListenerProxy) { PropertyChangeListenerProxy proxy = (PropertyChangeListenerProxy) listeners[i]; if (proxy.getPropertyName().equals(&quot;foo&quot;)) { // proxy is a PropertyChangeListener which was associated // with the property named &quot;foo&quot; } } } </pre> @see java.beans.PropertyChangeListenerProxy @see java.beans.PropertyChangeSupport#getPropertyChangeListeners @return all of the <code>PropertyChangeListener</code> s added or an empty array if no listeners have been added @since 1.4
public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { if (children == null) { children = new HashMap(); } PropertyChangeSupport child = (PropertyChangeSupport) children.get(propertyName); if (child == null) { child = new PropertyChangeSupport(source); children.put(propertyName, child); } child.addPropertyChangeListener(listener); }
Add a PropertyChangeListener for a specific property. The listener will be invoked only when a call on firePropertyChange names that specific property. @param propertyName The name of the property to listen on. @param listener The PropertyChangeListener to be added
public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) { if (children == null) { return; } PropertyChangeSupport child = (PropertyChangeSupport) children.get(propertyName); if (child == null) { return; } child.removePropertyChangeListener(listener); }
Remove a PropertyChangeListener for a specific property. @param propertyName The name of the property that was listened on. @param listener The PropertyChangeListener to be removed
public PropertyChangeListener[] getPropertyChangeListeners(String propertyName) { List returnList = new ArrayList(); if (children != null) { PropertyChangeSupport support = (PropertyChangeSupport) children.get(propertyName); if (support != null) { returnList.addAll(Arrays.asList(support.getPropertyChangeListeners())); } } return (PropertyChangeListener[]) (returnList.toArray(new PropertyChangeListener[0])); }
Returns an array of all the listeners which have been associated with the named property. @return all of the <code>PropertyChangeListeners</code> associated with the named property or an empty array if no listeners have been added
public void firePropertyChange(String propertyName, Object oldValue, Object newValue) { firePropertyChange(new PropertyChangeEvent(source, propertyName, oldValue, newValue)); }
Report a bound property update to any registered listeners. No event is fired if old and new are equal and non-null. @param propertyName The programmatic name of the property that was changed. @param oldValue The old value of the property. @param newValue The new value of the property.
public void firePropertyChange(PropertyChangeEvent evt) { Object oldValue = evt.getOldValue(); Object newValue = evt.getNewValue(); if (ObjectUtils.nullSafeEquals(oldValue, newValue)) { return; } String propertyName = evt.getPropertyName(); PropertyChangeSupport child = null; if (children != null) { if (children != null && propertyName != null) { child = (PropertyChangeSupport) children.get(propertyName); } } if (listeners != null) { Object[] listenerList = listeners.getListenerList(); for (int i = 0; i <= listenerList.length - 2; i += 2) { if (listenerList[i] == PropertyChangeListener.class) { ((PropertyChangeListener) listenerList[i + 1]).propertyChange(evt); } } } if (child != null) { child.firePropertyChange(evt); } }
Fire an existing PropertyChangeEvent to any registered listeners. No event is fired if the given event's old and new values are equal and non-null. @param evt The PropertyChangeEvent object.
public boolean hasListeners(String propertyName) { if (listeners != null && listeners.getListenerCount(PropertyChangeListener.class) > 0) { // there is a generic listener return true; } if (children != null) { PropertyChangeSupport child = (PropertyChangeSupport) children.get(propertyName); if (child != null) { // The child will always have a listeners ArrayList. return child.hasListeners(propertyName); } } return false; }
Check if there are any listeners for a specific property. @param propertyName the property name. @return true if there are ore or more listeners for the given property
protected void broadcastAuthentication(Authentication authentication) { if( logger.isDebugEnabled() ) logger.debug( "BROADCAST authentication: token=" + authentication ); // Save this for any new beans that we post-process currentAuthentication = authentication; final Iterator iter = getBeansToUpdate( AuthenticationAware.class ).iterator(); while( iter.hasNext() ) { ((AuthenticationAware) iter.next()).setAuthenticationToken( authentication ); } }
Broadcast an authentication event to all the AuthenticationAware beans. @param authentication token
protected void broadcastLogin(Authentication authentication) { if( logger.isDebugEnabled() ) logger.debug( "BROADCAST login: token=" + authentication ); final Iterator iter = getBeansToUpdate( LoginAware.class ).iterator(); while( iter.hasNext() ) { ((LoginAware) iter.next()).userLogin( authentication ); } }
Broadcast a Login event to all the LoginAware beans. @param authentication token
protected void broadcastLogout(Authentication authentication) { if( logger.isDebugEnabled() ) logger.debug( "BROADCAST logout: token=" + authentication ); final Iterator iter = getBeansToUpdate( LoginAware.class ).iterator(); while( iter.hasNext() ) { ((LoginAware) iter.next()).userLogout( authentication ); } }
Broadcast a Logout event to all the LoginAware beans. @param authentication token
protected List getBeansToUpdate(Class beanType) { final ApplicationContext ac = getApplicationContext(); final List listeners = new ArrayList(); if( ac != null ) { if( logger.isDebugEnabled() ) logger.debug( "Constructing list of beans to notify; bean type=" + beanType.getName() ); final Map map = ac.getBeansOfType( beanType, false, true ); if( logger.isDebugEnabled() ) logger.debug( "bean map: " + map ); listeners.addAll( map.values() ); listeners.addAll( getNonSingletonListeners( beanType ) ); } if( logger.isDebugEnabled() ) logger.debug( "List of beans to notify:" + listeners ); return listeners; }
Construct the list of all the beans we need to update. @param beanType Type of bean to locate @return List of all beans to udpate.
protected List getNonSingletonListeners(Class beanType) { final List listeners = new ArrayList(); synchronized(nonSingletonListeners) { for( Iterator iter = nonSingletonListeners.iterator(); iter.hasNext(); ) { final Object bean = ((WeakReference) iter.next()).get(); if( bean == null ) { if( logger.isDebugEnabled() ) logger.debug( "REMOVED garbage collected AuthorizationAware non-singleton from list." ); iter.remove(); } else if( beanType.isAssignableFrom( bean.getClass() ) ) { listeners.add( bean ); } } } return listeners; }
Get the list of non-singleton beans we have registered that still exist. Update our registration list if any have been GC'ed. Only return beans of the requested type. @param beanType Type of bean to locate @return list of extant non-singleton beans to notify
protected void addToNonSingletonListeners(final Object bean) { if( logger.isDebugEnabled() ) logger.debug( "Adding Authentication/LoginAware bean to list of non-singleton listeners: bean='" + bean ); nonSingletonListeners.add( new WeakReference( bean ) ); }
Add a non-singleton bean instance to our list for later notification. @param bean
public void onApplicationEvent(ApplicationEvent event) { // All events we care about are subtypes of ClientSecurityEvent if( event instanceof ClientSecurityEvent ) { Authentication authentication = (Authentication) event.getSource(); if( logger.isDebugEnabled() ) { logger.debug( "RECEIVED ClientSecurityEvent: " + event ); logger.debug( "Authentication token: " + authentication ); } // Note that we need to inspect the new authentication token and see if it is // NO_AUTHENTICATION. If so, then we need to use null instead. This little // dance is required because the source of an event can't actually be null. if( authentication == ClientSecurityEvent.NO_AUTHENTICATION ) { if( logger.isDebugEnabled() ) { logger.debug( "Converted NO_AUTHENTICATION to null" ); } authentication = null; } // And dispatch according to the event type. if( event instanceof AuthenticationEvent ) { broadcastAuthentication( authentication ); } else if( event instanceof LoginEvent ) { broadcastLogin( authentication ); } else if( event instanceof LogoutEvent ) { broadcastLogout( authentication ); } else { if( logger.isDebugEnabled() ) { logger.debug( "Unsupported event not processed" ); } } } }
/* (non-Javadoc) @see org.springframework.context.ApplicationListener#onApplicationEvent(org.springframework.context.ApplicationEvent)
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if( bean instanceof AuthenticationAware || bean instanceof LoginAware ) { // If the bean isn't a singleton, then add it to our list if( beanName == null || !getApplicationContext().containsBean( beanName ) || !getApplicationContext().isSingleton( beanName ) ) { addToNonSingletonListeners( bean ); } // Install the last known authentication token if( bean instanceof AuthenticationAware ) { if( logger.isDebugEnabled() ) logger.debug( "NOTIFY bean '" + bean + "' of new authorization for '" + currentAuthentication + "'" ); AuthenticationAware aab = (AuthenticationAware) bean; aab.setAuthenticationToken(currentAuthentication); } } return bean; }
/* (non-Javadoc) @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessBeforeInitialization(java.lang.Object, java.lang.String)
protected JTextComponent getTextComponent( JComponent component ) { if( component instanceof JSpinner ) { JSpinner spinner = (JSpinner) component; if( spinner.getEditor() instanceof JSpinner.DefaultEditor ) { return ((JSpinner.DefaultEditor) spinner.getEditor()).getTextField(); } else if( spinner.getEditor() instanceof JTextField ) { return (JTextField) spinner.getEditor(); } else { logger.warn("Cannot use JSpinner editor of type " + spinner.getEditor().getClass()); return null; } } else if(component instanceof JTextComponent) { return (JTextComponent) component; } else { return null; } }
Converts the given component to a <code>JTextComponent</code>. This can be a simple cast if the component is already a text component, or an embedded component (for example a JSpinner). <p> This method is protected, and can be overridden when necessary. @param component the component @return a <code>JTextComponent</code>, or <code>null</code>
public void addPage(DialogPage page) { pages.add(page); if (autoConfigureChildPages) { String id = getId() + "." + page.getId(); ValkyrieRepository.getInstance().getApplicationConfig().applicationObjectConfigurer().configure(page, id); } }
Adds a DialogPage to the list of pages managed by this CompositeDialogPage. @param page the page to add
public DialogPage addForm(Form form) { DialogPage page = createDialogPage(form); addPage(page); return page; }
Adds a new page to the list of pages managed by this CompositeDialogPage. The page is created by wrapping the form page in a FormBackedDialogPage. @param form the form page to be insterted @return the DialogPage that wraps formPage
public void addPages(DialogPage[] pages) { for (int i = 0; i < pages.length; i++) { addPage(pages[i]); } }
Adds an array DialogPage to the list of pages managed by this CompositeDialogPage. @param pages the pages to add
public void setActivePage(DialogPage activePage) { DialogPage oldPage = this.activePage; Assert.isTrue(activePage == null || pages.contains(activePage)); if (oldPage == activePage) { return; } this.activePage = activePage; updateMessage(); if (oldPage != null) { updatePageLabels(oldPage); } if (activePage != null) { updatePageLabels(activePage); } }
Sets the active page of this CompositeDialogPage. @param activePage the page to be made active. Must be one of the child pages.
protected void prepareDialogPage(DialogPage page) { page.addPropertyChangeListener(childChangeHandler); JComponent c = page.getControl(); GuiStandardUtils.attachDialogBorder(c); Dimension size = c.getPreferredSize(); if (size.width > largestPageWidth) { largestPageWidth = size.width; } if (size.height > largestPageHeight) { largestPageHeight = size.height; } }
Prepare a dialog page - Add our property listeners and configure the control's look. @param page to process
protected String decoratePageTitle(DialogPage page, String title) { return LabelUtils.htmlBlock("<center>" + title + "<sup><font size=-3 color=red>" + (page.isPageComplete() ? "" : "*")); }
Decorates the page title of the given <code>DialogPage</code>. <p> Can be overridden to provide additional decorations. <p> The default implementation returns a html with an indication whether the page is complete or incomplete @param page the page @param title the title @return the decorated page title
public boolean managesCommand(String commandId) { //FIXME isn't this supposed to recursively check subcommands if command is a commandgroup? if (commandId == null) { return false; } return commandId.equals(this.command.getId()); }
{@inheritDoc}
protected JMenuItem findMenu(AbstractCommand attachedCommand, List abstractButtons) { if (abstractButtons == null) { return null; } for (Iterator it = abstractButtons.iterator(); it.hasNext();) { AbstractButton button = (AbstractButton)it.next(); if (button instanceof JMenuItem && attachedCommand.isAttached(button)) { it.remove(); return (JMenuItem)button; } } return null; }
Searches the given list of {@link AbstractButton}s for one that is an instance of a {@link JMenuItem} and has the given command attached to it. If found, the menu item will be removed from the list. @param attachedCommand The command that we are checking to see if it attached to any item in the list. @param abstractButtons The collection of {@link AbstractButton}s that will be checked to see if they have the given command attached to them. May be null or empty. @return The element from the list that the given command is attached to, or null if no such element could be found.
protected AbstractButton findButton(AbstractCommand attachedCommand, List buttons) { if (buttons == null) { return null; } for (Iterator it = buttons.iterator(); it.hasNext();) { AbstractButton button = (AbstractButton)it.next(); if (!(button instanceof JMenuItem) && attachedCommand.isAttached(button)) { it.remove(); return button; } } return null; }
Searches the given list of {@link AbstractButton}s for one that is not an instance of a {@link JMenuItem} and has the given command attached to it. If found, the button will be removed from the list. @param attachedCommand The command that we are checking to see if it attached to any item in the list. @param abstractButtons The collection of {@link AbstractButton}s that will be checked to see if they have the given command attached to them. May be null or empty. @return The element from the list that the given command is attached to, or null if no such element could be found.
protected void prepareValueModel(ValueModel valueModel) { if (valueModel instanceof BufferedValueModel) { ((BufferedValueModel) valueModel).setCommitTrigger(commitTrigger); } // If the value model that we were built on is "dirty trackable" then we // need to monitor it for changes in its dirty state if (valueModel instanceof DirtyTrackingValueModel) { ((DirtyTrackingValueModel) valueModel).addPropertyChangeListener(DIRTY_PROPERTY, childStateChangeHandler); } }
Prepare the provided value model for use in this form model. @param valueModel to prepare
private void setDeliverValueChangeEvents(boolean enable) { formObjectHolder.setDeliverValueChangeEvents(enable); for (Object o : mediatingValueModels.values()) { FormModelMediatingValueModel valueModel = (FormModelMediatingValueModel) o; valueModel.setDeliverValueChangeEvents(enable); } }
Disconnect view from data in MediatingValueModels @param enable <code>true</code> if events should be delivered.