code
stringlengths
67
466k
docstring
stringlengths
1
13.2k
public void setParent(HierarchicalFormModel parent) { Assert.notNull(parent, "parent"); this.parent = parent; this.parent.addPropertyChangeListener(ENABLED_PROPERTY, parentStateChangeHandler); this.parent.addPropertyChangeListener(READONLY_PROPERTY, parentStateChangeHandler); enabledUpdated(); readOnlyUpdated(); }
{@inheritDoc} When the parent is set, the enabled and read-only states are bound and updated as needed.
public void addChild(HierarchicalFormModel child) { Assert.notNull(child, "child"); if (child.getParent() == this) return; Assert.isTrue(child.getParent() == null, "Child form model '" + child + "' already has a parent"); child.setParent(this); children.add(child); child.addPropertyChangeListener(DIRTY_PROPERTY, childStateChangeHandler); child.addPropertyChangeListener(COMMITTABLE_PROPERTY, childStateChangeHandler); if (child.isDirty()) { dirtyValueAndFormModels.add(child); dirtyUpdated(); } }
Add child to this FormModel. Dirty and committable changes are forwarded to parent model. @param child FormModel to add as child.
public void removeChild(HierarchicalFormModel child) { Assert.notNull(child, "child"); child.removeParent(); children.remove(child); child.removePropertyChangeListener(DIRTY_PROPERTY, childStateChangeHandler); child.removePropertyChangeListener(COMMITTABLE_PROPERTY, childStateChangeHandler); // when dynamically adding/removing childModels take care of // dirtymessages: // removing child that was dirty: remove from dirty map and update dirty // state if (dirtyValueAndFormModels.remove(child)) dirtyUpdated(); }
Remove a child FormModel. Dirty and committable listeners are removed. When child was dirty, remove the formModel from the dirty list and update the dirty state. @param child FormModel to remove from childlist.
protected ValueModel createValueModel(String formProperty) { Assert.notNull(formProperty, "formProperty"); if (logger.isDebugEnabled()) { logger.debug("Creating " + (buffered ? "buffered" : "") + " value model for form property '" + formProperty + "'."); } return buffered ? new BufferedValueModel(propertyAccessStrategy.getPropertyValueModel(formProperty)) : propertyAccessStrategy.getPropertyValueModel(formProperty); }
Creates a new value mode for the the given property. Usually delegates to the underlying property access strategy but subclasses may provide alternative value model creation strategies.
public void registerPropertyConverter(String propertyName, Converter toConverter, Converter fromConverter) { DefaultConversionService propertyConversionService = (DefaultConversionService) propertyConversionServices .get(propertyName); propertyConversionService.addConverter(toConverter); propertyConversionService.addConverter(fromConverter); }
Register converters for a given property name. @param propertyName name of property on which to register converters @param toConverter Convert from source to target type @param fromConverter Convert from target to source type
public ValueModel add(String propertyName, ValueModel valueModel, FieldMetadata metadata) { fieldMetadata.put(propertyName, metadata); valueModel = preProcessNewValueModel(propertyName, valueModel); propertyValueModels.put(propertyName, valueModel); if (logger.isDebugEnabled()) { logger.debug("Registering '" + propertyName + "' form property, property value model=" + valueModel); } postProcessNewValueModel(propertyName, valueModel); return valueModel; }
{@inheritDoc}
public void revert() { for (Iterator i = children.iterator(); i.hasNext();) { ((FormModel) i.next()).revert(); } // this will cause all buffered value models to revert commitTrigger.revert(); // this will then go back and revert all unbuffered value models for (Iterator i = mediatingValueModels.values().iterator(); i.hasNext();) { ((DirtyTrackingValueModel) i.next()).revertToOriginal(); } }
Revert state. If formModel has children, these will be reverted first. CommitTrigger is used to revert bufferedValueModels while revertToOriginal() is called upon FormMediatingValueModels.
protected void dirtyUpdated() { boolean dirty = isDirty(); if (hasChanged(oldDirty, dirty)) { oldDirty = dirty; firePropertyChange(DIRTY_PROPERTY, !dirty, dirty); } }
Fires the necessary property change event for changes to the dirty property. Must be called whenever the value of dirty is changed.
protected void readOnlyUpdated() { boolean localReadOnly = isReadOnly(); if (hasChanged(oldReadOnly, localReadOnly)) { oldReadOnly = localReadOnly; firePropertyChange(READONLY_PROPERTY, !localReadOnly, localReadOnly); } }
Fires the necessary property change event for changes to the readOnly property. Must be called whenever the value of readOnly is changed.
protected void enabledUpdated() { boolean enabled = isEnabled(); if (hasChanged(oldEnabled, enabled)) { oldEnabled = enabled; firePropertyChange(ENABLED_PROPERTY, !enabled, enabled); } }
Fires the necessary property change event for changes to the enabled property. Must be called whenever the value of enabled is changed.
protected void committableUpdated() { boolean committable = isCommittable(); if (hasChanged(oldCommittable, committable)) { oldCommittable = committable; firePropertyChange(COMMITTABLE_PROPERTY, !committable, committable); } }
Fires the necessary property change event for changes to the committable property. Must be called whenever the value of committable is changed.
protected void parentStateChanged(PropertyChangeEvent evt) { if (ENABLED_PROPERTY.equals(evt.getPropertyName())) { enabledUpdated(); } else if (READONLY_PROPERTY.equals(evt.getPropertyName())) { readOnlyUpdated(); } }
Events from the parent form model that have side-effects on this form model should be handled here. This includes: <ul> <li><em>Enabled state:</em> when parent gets disabled, child should be disabled as well. If parent is enabled, child should go back to its original state.</li> <li><em>Read-only state:</em> when a parent is set read-only, child should be read-only as well. If parent is set editable, child should go back to its original state.</li> </ul>
protected void childStateChanged(PropertyChangeEvent evt) { if (FormModel.DIRTY_PROPERTY.equals(evt.getPropertyName())) { Object source = evt.getSource(); if (source instanceof FieldMetadata) { FieldMetadata metadata = (FieldMetadata) source; if (metadata.isDirty()) { dirtyValueAndFormModels.add(metadata); } else { dirtyValueAndFormModels.remove(metadata); } } else if (source instanceof FormModel) { FormModel formModel = (FormModel) source; if (formModel.isDirty()) { dirtyValueAndFormModels.add(formModel); } else { dirtyValueAndFormModels.remove(formModel); } } else { DirtyTrackingValueModel valueModel = (DirtyTrackingValueModel) source; if (valueModel.isDirty()) { dirtyValueAndFormModels.add(valueModel); } else { dirtyValueAndFormModels.remove(valueModel); } } dirtyUpdated(); } else if (COMMITTABLE_PROPERTY.equals(evt.getPropertyName())) { committableUpdated(); } }
Events from the child form model or value models that have side-effects on this form model should be handled here. This includes: <ul> <li><em>Dirty state:</em> when a child is dirty, the parent should be dirty.</li> <li><em>Committable state:</em> when a child is committable, the parent might be committable as well. The committable state of the parent should be taken into account and revised when a child sends this event.</li> </ul> Note that we include value models and their metadata as being children. As these are low level models, they cannot be parents and therefore don't show up in {@link AbstractFormModel#parentStateChanged(PropertyChangeEvent)}.
public ObservableList createBoundListModel(String formProperty) { final ConfigurableFormModel formModel = ((ConfigurableFormModel)getFormModel()); ValueModel valueModel = formModel.getValueModel(formProperty); if (!(valueModel instanceof BufferedCollectionValueModel)) { // XXX: HACK! valueModel = new BufferedCollectionValueModel((((DefaultFormModel) formModel).getFormObjectPropertyAccessStrategy()).getPropertyValueModel( formProperty), formModel.getFieldMetadata(formProperty).getPropertyType()); formModel.add(formProperty, valueModel); } return (ObservableList)valueModel.getValue(); }
This method will most likely move over to FormModel @deprecated
public Binding createBoundList(String selectionFormProperty, Object selectableItems) { return createBoundList(selectionFormProperty, new ValueHolder(selectableItems)); }
Binds the values specified in the collection contained within <code>selectableItems</code> to a {@link JList}, with any user selection being placed in the form property referred to by <code>selectionFormProperty</code>. Each item in the list will be rendered as a String. Note that the selection in the bound list will track any changes to the <code>selectionFormProperty</code>. This is especially useful to preselect items in the list - if <code>selectionFormProperty</code> is not empty when the list is bound, then its content will be used for the initial selection. This method uses default behavior to determine the selection mode of the resulting <code>JList</code>: if <code>selectionFormProperty</code> refers to a {@link java.util.Collection} type property, then {@link javax.swing.ListSelectionModel#MULTIPLE_INTERVAL_SELECTION} will be used, otherwise {@link javax.swing.ListSelectionModel#SINGLE_SELECTION} will be used. @param selectionFormProperty form property to hold user's selection. This property must either be compatible with the item objects contained in <code>selectableItemsHolder</code> (in which case only single selection makes sense), or must be a <code>Collection</code> type, which allows for multiple selection. @param selectableItems a Collection or array containing the items with which to populate the list. @return
public Binding createBoundList(String selectionFormProperty, ValueModel selectableItemsHolder, String renderedProperty) { return createBoundList(selectionFormProperty, selectableItemsHolder, renderedProperty, null); }
Binds the values specified in the collection contained within <code>selectableItemsHolder</code> to a {@link JList}, with any user selection being placed in the form property referred to by <code>selectionFormProperty</code>. Each item in the list will be rendered by looking up a property on the item by the name contained in <code>renderedProperty</code>, retrieving the value of the property, and rendering that value in the UI. Note that the selection in the bound list will track any changes to the <code>selectionFormProperty</code>. This is especially useful to preselect items in the list - if <code>selectionFormProperty</code> is not empty when the list is bound, then its content will be used for the initial selection. This method uses default behavior to determine the selection mode of the resulting <code>JList</code>: if <code>selectionFormProperty</code> refers to a {@link java.util.Collection} type property, then {@link javax.swing.ListSelectionModel#MULTIPLE_INTERVAL_SELECTION} will be used, otherwise {@link javax.swing.ListSelectionModel#SINGLE_SELECTION} will be used. @param selectionFormProperty form property to hold user's selection. This property must either be compatible with the item objects contained in <code>selectableItemsHolder</code> (in which case only single selection makes sense), or must be a <code>Collection</code> type, which allows for multiple selection. @param selectableItemsHolder <code>ValueModel</code> containing the items with which to populate the list. @param renderedProperty the property to be queried for each item in the list, the result of which will be used to render that item in the UI @return
public Binding createBoundList(String selectionFormProperty, Object selectableItems, String renderedProperty, Integer forceSelectMode) { final Map context = new HashMap(); if (forceSelectMode != null) { context.put(ListBinder.SELECTION_MODE_KEY, forceSelectMode); } context.put(ListBinder.SELECTABLE_ITEMS_KEY, selectableItems); if (renderedProperty != null) { context.put(ListBinder.RENDERER_KEY, new BeanPropertyValueListRenderer(renderedProperty)); context.put(ListBinder.COMPARATOR_KEY, new PropertyComparator(renderedProperty, true, true)); } return createBinding(JList.class, selectionFormProperty, context); }
Binds the value(s) specified in <code>selectableItems</code> to a {@link JList}, with any user selection being placed in the form property referred to by <code>selectionFormProperty</code>. Each item in the list will be rendered by looking up a property on the item by the name contained in <code>renderedProperty</code>, retrieving the value of the property, and rendering that value in the UI. Note that the selection in the bound list will track any changes to the <code>selectionFormProperty</code>. This is especially useful to preselect items in the list - if <code>selectionFormProperty</code> is not empty when the list is bound, then its content will be used for the initial selection. @param selectionFormProperty form property to hold user's selection. This property must either be compatible with the item objects contained in <code>selectableItemsHolder</code> (in which case only single selection makes sense), or must be a <code>Collection</code> type, which allows for multiple selection. @param selectableItems <code>Object</code> containing the item(s) with which to populate the list. Can be an instance Collection, Object[], a ValueModel or Object @param renderedProperty the property to be queried for each item in the list, the result of which will be used to render that item in the UI. May be null, in which case the selectable items will be rendered as strings. @param forceSelectMode forces the list selection mode. Must be one of the constants defined in {@link javax.swing.ListSelectionModel} or <code>null</code> for default behavior. If <code>null</code>, then {@link javax.swing.ListSelectionModel#MULTIPLE_INTERVAL_SELECTION} will be used if <code>selectionFormProperty</code> refers to a {@link java.util.Collection} type property, otherwise {@link javax.swing.ListSelectionModel#SINGLE_SELECTION} will be used. @return
public Binding createBoundShuttleList( String selectionFormProperty, ValueModel selectableItemsHolder, String renderedProperty ) { Map context = ShuttleListBinder.createBindingContext(getFormModel(), selectionFormProperty, selectableItemsHolder, renderedProperty); return createBinding(ShuttleList.class, selectionFormProperty, context); }
Binds the values specified in the collection contained within <code>selectableItemsHolder</code> to a {@link ShuttleList}, with any user selection being placed in the form property referred to by <code>selectionFormProperty</code>. Each item in the list will be rendered by looking up a property on the item by the name contained in <code>renderedProperty</code>, retrieving the value of the property, and rendering that value in the UI. <p> Note that the selection in the bound list will track any changes to the <code>selectionFormProperty</code>. This is especially useful to preselect items in the list - if <code>selectionFormProperty</code> is not empty when the list is bound, then its content will be used for the initial selection. @param selectionFormProperty form property to hold user's selection. This property must be a <code>Collection</code> or array type. @param selectableItemsHolder <code>ValueModel</code> containing the items with which to populate the list. @param renderedProperty the property to be queried for each item in the list, the result of which will be used to render that item in the UI. May be null, in which case the selectable items will be rendered as strings. @return constructed {@link Binding}. Note that the bound control is of type {@link ShuttleList}. Access this component to set specific display properties.
public Binding createBoundShuttleList( String selectionFormProperty, Object selectableItems, String renderedProperty ) { return createBoundShuttleList(selectionFormProperty, new ValueHolder(selectableItems), renderedProperty); }
Binds the values specified in the collection contained within <code>selectableItems</code> (which will be wrapped in a {@link ValueHolder} to a {@link ShuttleList}, with any user selection being placed in the form property referred to by <code>selectionFormProperty</code>. Each item in the list will be rendered by looking up a property on the item by the name contained in <code>renderedProperty</code>, retrieving the value of the property, and rendering that value in the UI. <p> Note that the selection in the bound list will track any changes to the <code>selectionFormProperty</code>. This is especially useful to preselect items in the list - if <code>selectionFormProperty</code> is not empty when the list is bound, then its content will be used for the initial selection. @param selectionFormProperty form property to hold user's selection. This property must be a <code>Collection</code> or array type. @param selectableItems Collection or array containing the items with which to populate the selectable list (this object will be wrapped in a ValueHolder). @param renderedProperty the property to be queried for each item in the list, the result of which will be used to render that item in the UI. May be null, in which case the selectable items will be rendered as strings. @return constructed {@link Binding}. Note that the bound control is of type {@link ShuttleList}. Access this component to set specific display properties.
public Binding createBoundShuttleList( String selectionFormProperty, Object selectableItems ) { return createBoundShuttleList(selectionFormProperty, new ValueHolder(selectableItems), null); }
Binds the values specified in the collection contained within <code>selectableItems</code> (which will be wrapped in a {@link ValueHolder} to a {@link ShuttleList}, with any user selection being placed in the form property referred to by <code>selectionFormProperty</code>. Each item in the list will be rendered as a String. <p> Note that the selection in the bound list will track any changes to the <code>selectionFormProperty</code>. This is especially useful to preselect items in the list - if <code>selectionFormProperty</code> is not empty when the list is bound, then its content will be used for the initial selection. @param selectionFormProperty form property to hold user's selection. This property must be a <code>Collection</code> or array type. @param selectableItems Collection or array containing the items with which to populate the selectable list (this object will be wrapped in a ValueHolder). @return constructed {@link Binding}. Note that the bound control is of type {@link ShuttleList}. Access this component to set specific display properties.
public Binding createBinding(String propertyPath, String binderId, Map context) { Assert.notNull(context, "Context must not be null"); Binder binder = ((SwingBinderSelectionStrategy)getBinderSelectionStrategy()).getIdBoundBinder(binderId); Binding binding = binder.bind(getFormModel(), propertyPath, context); interceptBinding(binding); return binding; }
Create a binding based on a specific binder id. @param propertyPath Path to property @param binderId Id of the binder @param context Context data (can be empty map) @return Specific binding
private JComponent createPanelWithDecoration() { StringBuffer columnLayout = new StringBuffer(); if (this.leftDecoration != null) columnLayout.insert(0, "[]"); columnLayout.append("[grow]"); if (this.rightDecoration != null) columnLayout.append("[]"); JPanel panel = new JPanel(new MigLayout("insets 0", columnLayout.toString(), "")) { public void requestFocus() { NumberBinding.this.numberField.requestFocus(); } }; if (this.leftDecoration != null) { panel.add(new JLabel(this.leftDecoration)); } panel.add(this.numberField, "grow"); if (this.rightDecoration != null) { panel.add(new JLabel(this.rightDecoration)); } return panel; }
Create a panel with (possibly) decorations on both sides. TODO This leaves one problem: when validating and eg coloring/adding overlay the panel is used instead of the inputfield. There could be an interface that returns the correct component to be handled while validating. @return a decorated component which contains the inputfield.
public final Object getDetailObject(Object selectedObject, boolean forceLoad) { if (forceLoad || !isDetailObject(selectedObject)) return loadDetailObject(selectedObject); return selectedObject; }
A basic implementation that directs the necessary logic to {@link #isDetailObject(Object)} and {@link #loadDetailObject(Object)}.
public static Key<CounterShardOperationData> key(final Key<CounterShardData> counterShardDataKey, final UUID id) { Preconditions.checkNotNull(counterShardDataKey); Preconditions.checkNotNull(id); return Key.create(counterShardDataKey, CounterShardOperationData.class, id.toString()); }
Create a {@link Key} of type {@link CounterShardOperationData}. Keys for this entity are "parented" by a {@link Key} of type {@link CounterShardOperationData}. @param counterShardDataKey @param id @return
private boolean canPasteFromClipboard() { try { return textComponent.getTransferHandler().canImport( textComponent, Toolkit.getDefaultToolkit().getSystemClipboard().getContents(textComponent) .getTransferDataFlavors()); } catch (IllegalStateException e) { /* * as the javadoc of Clipboard.getContents state: the * IllegalStateException can be thrown when the clipboard is not * available (i.e. in use by another application), so we return * false. */ return false; } }
Try not to call this method to much as SystemClipboard#getContents() relatively slow.
@XmlElementDecl(namespace = "http://nav.no/melding/virksomhet/henvendelsebehandling/behandlingsresultat/v1", name = "henvendelse") public JAXBElement<XMLHenvendelse> createHenvendelse(XMLHenvendelse value) { return new JAXBElement<XMLHenvendelse>(_Henvendelse_QNAME, XMLHenvendelse.class, null, value); }
Create an instance of {@link JAXBElement }{@code <}{@link XMLHenvendelse }{@code >}}
public static Goro from(final IBinder binder) { if (binder instanceof GoroService.GoroBinder) { return ((GoroService.GoroBinder) binder).goro(); } throw new IllegalArgumentException("Cannot get Goro from " + binder); }
Gives access to Goro instance that is provided by a service. @param binder Goro service binder @return Goro instance provided by the service
public static Goro createWithDelegate(final Executor delegateExecutor) { GoroImpl goro = new GoroImpl(); goro.queues.setDelegateExecutor(delegateExecutor); return goro; }
Creates a new Goro instance which uses the specified executor to delegate tasks. @param delegateExecutor executor Goro delegates tasks to @return instance of Goro
public static BoundGoro bindAndAutoReconnectWith(final Context context) { if (context == null) { throw new IllegalArgumentException("Context cannot be null"); } return new BoundGoroImpl(context, null); }
Creates a Goro implementation that binds to {@link com.stanfy.enroscar.goro.GoroService} in order to run scheduled tasks in service context. <p> This method is functionally identical to </p> <pre> BoundGoro goro = Goro.bindWith(context, new BoundGoro.OnUnexpectedDisconnection() { public void onServiceDisconnected(BoundGoro goro) { goro.bind(); } }); </pre> @param context context that will bind to the service @return Goro implementation that binds to {@link GoroService}. @see #bindWith(Context, BoundGoro.OnUnexpectedDisconnection)
public static BoundGoro bindWith(final Context context, final BoundGoro.OnUnexpectedDisconnection handler) { if (context == null) { throw new IllegalArgumentException("Context cannot be null"); } if (handler == null) { throw new IllegalArgumentException("Disconnection handler cannot be null"); } return new BoundGoroImpl(context, handler); }
Creates a Goro implementation that binds to {@link GoroService} in order to run scheduled tasks in service context. {@code BoundGoro} exposes {@code bind()} and {@code unbind()} methods that you can use to connect to and disconnect from the worker service in other component lifecycle callbacks (like {@code onStart}/{@code onStop} in {@code Activity} or {@code onCreate}/{@code onDestory} in {@code Service}). <p> The worker service ({@code GoroService}) normally stops when all {@code BoundGoro} instances unbind and all the pending tasks in {@code Goro} queues are handled. But it can also be stopped by the system server (due to a user action in Settings app or application update). In this case {@code BoundGoro} created with this method will notify the supplied handler about the event. </p> @param context context that will bind to the service @param handler callback to invoke if worker service is unexpectedly stopped by the system server @return Goro implementation that binds to {@link GoroService}.
private void addCustomGridded(AbstractButton button) { builder.getLayout().appendRow(this.rowSpec); builder.getLayout().addGroupedRow(builder.getRow()); button.putClientProperty("jgoodies.isNarrow", Boolean.TRUE); builder.add(button); builder.nextRow(); }
Handle the custom RowSpec. @param button
private void loadData() { contacts.add(makeContact("Larry", "Streepy", "123 Some St.", "Apt. #26C", "New York", "NY", "10010", ContactType.BUSINESS, "Lorem ipsum...")); contacts.add(makeContact("Keith", "Donald", "456 WebFlow Rd.", "2", "Cooltown", "NY", "10001", ContactType.BUSINESS, "Lorem ipsum...")); contacts.add(makeContact("Steve", "Brothers", "10921 The Other Street", "", "Denver", "CO", "81234-2121", ContactType.PERSONAL, "Lorem ipsum...")); contacts.add(makeContact("Carlos", "Mencia", "4321 Comedy Central", "", "Hollywood", "CA", "91020", ContactType.PERSONAL, "Lorem ipsum...")); contacts.add(makeContact("Jim", "Jones", "1001 Another Place", "", "Dallas", "TX", "71212", ContactType.PERSONAL, "Lorem ipsum...")); contacts.add(makeContact("Jenny", "Jones", "1001 Another Place", "", "Dallas", "TX", "75201", ContactType.PERSONAL, "Lorem ipsum...")); contacts.add(makeContact("Greg", "Jones", "9 Some Other Place", "Apt. 12D", "Chicago", "IL", "60601", ContactType.PERSONAL, "Lorem ipsum...")); }
Load our initial data.
private Contact makeContact(String first, String last, String address1, String address2, String city, String state, String zip, ContactType contactType, String memo) { Contact contact = new Contact(); contact.setId(nextId++); contact.setContactType(contactType); contact.setFirstName(first); contact.setLastName(last); contact.setMemo(memo); Address address = contact.getAddress(); address.setAddress1(address1); address.setAddress2(address2); address.setCity(city); address.setState(state); address.setZip(zip); contact.setTodoItems(getTodoItemList()); return contact; }
Make a Contact object with the given data. @return Contact object
public void setEnabled(boolean enabled) { super.setEnabled(enabled); for (Iterator members = getMemberList().iterator(); members.hasNext();) { GroupMember groupMember = (GroupMember)members.next(); groupMember.setEnabled(enabled); } }
Enable/disable the entire group. @param enabled enable/disable this group.
public AbstractCommand find(String memberPath) { if (logger.isDebugEnabled()) { logger.debug("Searching for command with nested path '" + memberPath + "'"); } String[] paths = StringUtils.delimitedListToStringArray(memberPath, "/"); CommandGroup currentGroup = this; // fileGroup/newGroup/newJavaProject for (int i = 0; i < paths.length; i++) { String memberId = paths[i]; if (i < paths.length - 1) { // must be a nested group currentGroup = currentGroup.findCommandGroupMember(memberId); } else { // is last path element; can be a group or action return currentGroup.findCommandMember(memberId); } } return null; }
Search for and return the command contained by this group with the specified path. Nested paths should be deliniated by the "/" character; for example, "fileGroup/newGroup/simpleFileCommand". The returned command may be a group or an action command. @param memberPath the path of the command, with nested levels deliniated by the "/" path separator. @return the command at the specified member path, or <code>null</code> if no was command found.
public void execute() { Iterator it = memberList.iterator(); while (it.hasNext()) { GroupMember member = (GroupMember) it.next(); member.getCommand().execute(); } }
Executes all the members of this group.
public JComponent createButtonBar(Size minimumButtonSize) { return createButtonBar(minimumButtonSize, GuiStandardUtils.createTopAndBottomBorder(UIConstants.TWO_SPACES)); }
Create a button bar with buttons for all the commands in this group. Adds a border top and bottom of 2 spaces. @param minimumButtonSize if null, then there is no minimum size @return never null
public JComponent createButtonBar(final ColumnSpec columnSpec, final RowSpec rowSpec) { return createButtonBar(columnSpec, rowSpec, null); }
Create a button bar with buttons for all the commands in this. @param columnSpec Custom columnSpec for each column containing a button, can be <code>null</code>. @param rowSpec Custom rowspec for the buttonbar, can be <code>null</code>. @return never null
public JComponent createButtonBar(final Size minimumButtonSize, final Border border) { return createButtonBar(minimumButtonSize == null ? null : new ColumnSpec(minimumButtonSize), null, border); }
Create a button bar with buttons for all the commands in this. @param minimumButtonSize if null, then there is no minimum size @param border if null, then don't use a border @return never null
public JComponent createButtonBar(final ColumnSpec columnSpec, final RowSpec rowSpec, final Border border) { final ButtonBarGroupContainerPopulator container = new ButtonBarGroupContainerPopulator(); container.setColumnSpec(columnSpec); container.setRowSpec(rowSpec); addCommandsToGroupContainer(container); return GuiStandardUtils.attachBorder(container.getButtonBar(), border); }
Create a button bar with buttons for all the commands in this. @param columnSpec Custom columnSpec for each column containing a button, can be <code>null</code>. @param rowSpec Custom rowspec for the buttonbar, can be <code>null</code>. @param border if null, then don't use a border @return never null
public JComponent createButtonStack(final Size minimumButtonSize) { return createButtonStack(minimumButtonSize, GuiStandardUtils.createLeftAndRightBorder(UIConstants.TWO_SPACES)); }
Create a button stack with buttons for all the commands. Adds a border left and right of 2 spaces. @param minimumButtonSize Minimum size of the buttons (can be null) @return never null
public JComponent createButtonStack(final Size minimumButtonSize, final Border border) { return createButtonStack(minimumButtonSize == null ? null : new ColumnSpec(minimumButtonSize), null, border); }
Create a button stack with buttons for all the commands. @param minimumButtonSize Minimum size of the buttons (can be <code>null</code>) @param border Border to set around the stack. @return never null
public JComponent createButtonStack(final ColumnSpec columnSpec, final RowSpec rowSpec) { return createButtonStack(columnSpec, rowSpec, null); }
Create a button stack with buttons for all the commands. @param columnSpec Custom columnSpec for the stack, can be <code>null</code>. @param rowSpec Custom rowspec for each row containing a button can be <code>null</code>. @return never null
public JComponent createButtonStack(final ColumnSpec columnSpec, final RowSpec rowSpec, final Border border) { final ButtonStackGroupContainerPopulator container = new ButtonStackGroupContainerPopulator(); container.setColumnSpec(columnSpec); container.setRowSpec(rowSpec); addCommandsToGroupContainer(container); return GuiStandardUtils.attachBorder(container.getButtonStack(), border); }
Create a button stack with buttons for all the commands. @param columnSpec Custom columnSpec for the stack, can be <code>null</code>. @param rowSpec Custom rowspec for each row containing a button can be <code>null</code>. @param border Border to set around the stack. @return never null
protected void addCommandsToGroupContainer(final GroupContainerPopulator groupContainerPopulator) { final Iterator members = getMemberList().iterator(); while (members.hasNext()) { final GroupMember member = (GroupMember) members.next(); if (member.getCommand() instanceof CommandGroup) { member.fill(groupContainerPopulator, getButtonFactory(), getPullDownMenuButtonConfigurer(), Collections.EMPTY_LIST); } else { member.fill(groupContainerPopulator, getButtonFactory(), getDefaultButtonConfigurer(), Collections.EMPTY_LIST); } } groupContainerPopulator.onPopulated(); }
Create a container with the given GroupContainerPopulator which will hold the members of this group. @param groupContainerPopulator
public void setSecurityControllerMap(Map map) { for( Iterator i = map.entrySet().iterator(); i.hasNext(); ) { Map.Entry entry = (Map.Entry) i.next(); registerSecurityControllerAlias( (String) entry.getKey(), (SecurityController) entry.getValue() ); } }
/* (non-Javadoc) @see org.springframework.richclient.security.SecurityControllerManager#setSecurityControllerMap(java.util.Map)
public SecurityController getSecurityController(String id) { SecurityController sc = (SecurityController) securityControllerMap.get( id ); if( sc == null ) { // Try for a named bean try { sc = applicationContext.getBean( id, SecurityController.class ); } catch( NoSuchBeanDefinitionException e ) { // Try for a fallback sc = getFallbackSecurityController(); } } return sc; }
Get the security controller for the given id. If the id is registered in our map, then return the registered controller. If not, then try to obtain a bean with the given id if it implements the SecurityController interface. @param id of controller to retrieve @return controller, null if not found
public Object call(Object comparable1, Object comparable2) { int result = COMPARATOR.compare(comparable1, comparable2); if (result < 0) { return comparable1; } else if (result > 0) { return comparable2; } return comparable1; }
Return the minimum of two Comparable objects. @param comparable1 the first comparable @param comparable2 the second comparable @return the minimum
protected JComponent getInnerComponent(JComponent component) { if (component instanceof JScrollPane) { return getInnerComponent((JComponent) ((JScrollPane) component).getViewport().getView()); } if (component instanceof HasInnerComponent) { return getInnerComponent(((HasInnerComponent) component).getInnerComponent()); } return component; }
Check for JScrollPane. @param component @return the component itself, or the inner component if it was a JScrollPane.
public String getHeader() { if (this.header == null) { if (this.headerKeys == null) { this.headerKeys = new String[2]; this.headerKeys[0] = getPropertyName() + ".header"; this.headerKeys[1] = getPropertyName(); } this.header = ValkyrieRepository.getInstance().getApplicationConfig().messageResolver().getMessage(new DefaultMessageSourceResolvable(this.headerKeys, null, this.headerKeys[this.headerKeys.length - 1])); } // JTableHeader has a reusable defaultHeaderRenderer on which the default height must be correct. // when painting, the columns headers are processed in order and height is being calculated, // if label is null or empty string header height is 4 and thus leaves us with a very small // table-header, fix this by returning a space (-> font-size is incorporated) return "".equals(this.header) ? " " : this.header; }
Returns the header to be used as column title. If no explicit header was set, the headerKeys are used to fetch a message from the available resources.
public String renderQualifiedName(String qualifiedName) { Assert.notNull(qualifiedName, "No qualified name specified"); StringBuffer sb = new StringBuffer(qualifiedName.length() + 5); char[] chars = qualifiedName.toCharArray(); sb.append(Character.toUpperCase(chars[0])); boolean foundDot = false; for (int i = 1; i < chars.length; i++) { char c = chars[i]; if (Character.isLetter(c)) { if (Character.isLowerCase(c)) { if (foundDot) { sb.append(Character.toUpperCase(c)); foundDot = false; } else { sb.append(c); } } else { sb.append(c); } } else if (c == '.') { sb.append(c); foundDot = true; } } return sb.toString(); }
Renders a unqualified bean property string in the format: "parentProperty.myBeanProperty" like "ParentProperty.MyBeanProperty". @param qualifiedName @return the formatted string
public String renderShortName(String shortName) { Assert.notNull(shortName, "No short name specified"); StringBuffer sb = new StringBuffer(shortName.length() + 5); char[] chars = shortName.toCharArray(); sb.append(Character.toUpperCase(chars[0])); for (int i = 1; i < chars.length; i++) { char c = chars[i]; if (Character.isUpperCase(c)) { sb.append(' '); } sb.append(c); } return sb.toString(); }
Renders a unqualified bean property string in the format: "myBeanProperty" like "My Bean Property". @return the formatted string
protected void fill(GroupContainerPopulator container, Object factory, CommandButtonConfigurer configurer, List previousButtons) { container.addSeparator(); }
Asks the given container populator to add a separator to its underlying container.
public static void setup(final Context context, final Goro goro) { if (goro == null) { throw new IllegalArgumentException("Goro instance cannot be null"); } if (!Util.checkMainThread()) { throw new IllegalStateException("GoroService.setup must be called on the main thread"); } GoroService.goro = goro; context.getPackageManager().setComponentEnabledSetting( new ComponentName(context, GoroService.class), COMPONENT_ENABLED_STATE_ENABLED, DONT_KILL_APP ); }
* Initialize GoroService which will allow you to use {@code Goro.bindXXX} methods. @param context context instance used to enable GoroService component @param goro instance of Goro that should be used by the service
public static <T extends Callable<?> & Parcelable> Intent foregroundTaskIntent(final Context context, final String queueName, final T task, final int notificationId, final Notification notification) { // It may produce ClassNotFoundException when using custom Parcelable (for example via an AlarmManager). // As a workaround pack a Parcelable into an additional Bundle, then put that Bundle into Intent. // XXX http://code.google.com/p/android/issues/detail?id=6822 Bundle taskBundle = new Bundle(); taskBundle.putParcelable(EXTRA_TASK, task); Bundle notificationBundle = new Bundle(); notificationBundle.putParcelable(EXTRA_NOTIFICATION, notification); return new Intent(context, GoroService.class) .putExtra(EXTRA_TASK_BUNDLE, taskBundle) .putExtra(EXTRA_NOTIFICATION_BUNDLE, notificationBundle) .putExtra(EXTRA_QUEUE_NAME, queueName) .putExtra(EXTRA_NOTIFICATION_ID, notificationId); }
Create an intent that contains a task that should be scheduled on a defined queue. The Service will run in the foreground and display notification. Intent can be used as an argument for {@link android.content.Context#startService(android.content.Intent)} or {@link android.content.Context#startForegroundService(Intent)} @param context context instance @param task task instance @param queueName queue name @param <T> task type @param notificationId id of notification for foreground Service, must not be 0 @param notification notification for foreground Service, should be not null to start service in the foreground
public static <T extends Callable<?> & Parcelable> Intent foregroundTaskIntent(final Context context, final T task, final int notificationId, final Notification notification) { return foregroundTaskIntent(context, Goro.DEFAULT_QUEUE, task, notificationId, notification); }
Create an intent that contains a task that should be scheduled on a defined queue. The Service will run in the foreground and display notification. Intent can be used as an argument for {@link android.content.Context#startService(android.content.Intent)} or {@link android.content.Context#startForegroundService(Intent)} @param context context instance @param task task instance @param <T> task type @param notificationId id of notification for foreground Service, must not be 0 @param notification notification for foreground Service, should be not null to start service in the foreground
public static <T extends Callable<?> & Parcelable> Intent taskIntent(final Context context, final String queueName, final T task) { // XXX http://code.google.com/p/android/issues/detail?id=6822 Bundle bundle = new Bundle(); bundle.putParcelable(EXTRA_TASK, task); return new Intent(context, GoroService.class) .putExtra(EXTRA_TASK_BUNDLE, bundle) .putExtra(EXTRA_QUEUE_NAME, queueName); }
Create an intent that contains a task that should be scheduled on a defined queue. Intent can be used as an argument for {@link android.content.Context#startService(android.content.Intent)}. @param context context instance @param task task instance @param queueName queue name @param <T> task type
public static <T extends Callable<?> & Parcelable> Intent taskIntent(final Context context, final T task) { return taskIntent(context, Goro.DEFAULT_QUEUE, task); }
Create an intent that contains a task that should be scheduled on a default queue. @param context context instance @param task task instance @param <T> task type @see #taskIntent(android.content.Context, String, java.util.concurrent.Callable)
public static void bind(final Context context, final ServiceConnection connection) { Intent serviceIntent = new Intent(context, GoroService.class); if (context.startService(serviceIntent) == null) { throw new GoroException("Service " + GoroService.class + " does not seem to be included to your manifest file"); } boolean bound = context.bindService(serviceIntent, connection, 0); if (!bound) { throw new GoroException("Cannot bind to GoroService though this component seems to " + "be registered in the app manifest"); } }
Bind to Goro service. This method will start the service and then bind to it. @param context context that is binding to the service @param connection service connection callbacks @throws GoroException when service is not declared in the application manifest
public static Callable<?> getTaskFromExtras(final Intent intent) { if (!intent.hasExtra(EXTRA_TASK) && !intent.hasExtra(EXTRA_TASK_BUNDLE)) { return null; } Parcelable taskArg = intent.getParcelableExtra(EXTRA_TASK); if (taskArg == null) { Bundle bundle = intent.getBundleExtra(EXTRA_TASK_BUNDLE); if (bundle != null) { taskArg = bundle.getParcelable(EXTRA_TASK); } } if (!(taskArg instanceof Callable)) { throw new IllegalArgumentException("Task " + taskArg + " is not a Callable"); } return (Callable<?>)taskArg; }
Get a task instance packed into an {@code Intent} with {@link #taskIntent(android.content.Context, java.util.concurrent.Callable)}.
public void configure(Object object, String objectName) { if (object == null) { logger.debug("object to be configured is null"); return; } Assert.notNull(objectName, "objectName"); if (object instanceof TitleConfigurable) { configureTitle((TitleConfigurable) object, objectName); } if (object instanceof LabelConfigurable) { configureLabel((LabelConfigurable) object, objectName); } if (object instanceof ColorConfigurable) { configureColor((ColorConfigurable)object, objectName); } if (object instanceof CommandLabelConfigurable) { configureCommandLabel((CommandLabelConfigurable) object, objectName); } if (object instanceof DescriptionConfigurable) { configureDescription((DescriptionConfigurable) object, objectName); } if (object instanceof ImageConfigurable) { configureImage((ImageConfigurable) object, objectName); } if (object instanceof IconConfigurable) { configureIcon((IconConfigurable) object, objectName); } if (object instanceof CommandIconConfigurable) { configureCommandIcons((CommandIconConfigurable) object, objectName); } if (object instanceof Secured) { configureSecurityController((Secured) object, objectName); } }
Configures the given object according to the interfaces that it implements. <p> This implementation forwards the object to the following overridable methods in the order listed. Subclasses can use these methods as hooks to modify the default configuration behaviour without having to override this method entirely. <ul> <li>{@link #configureTitle(TitleConfigurable, String)}</li> <li>{@link #configureLabel(LabelConfigurable, String)}</li> <li>{@link #configureCommandLabel(CommandLabelConfigurable, String)}</li> <li>{@link #configureDescription(DescriptionConfigurable, String)}</li> <li>{@link #configureImage(ImageConfigurable, String)}</li> <li>{@link #configureIcon(IconConfigurable, String)}</li> <li>{@link #configureCommandIcons(CommandIconConfigurable, String)}</li> <li>{@link #configureSecurityController(Secured, String)}</li> </ul> </p> @param object The object to be configured. May be null. @param objectName The name for the object, expected to be unique within the application. If {@code object} is not null, then {@code objectName} must also be non-null. @throws IllegalArgumentException if {@code object} is not null, but {@code objectName} is null.
protected void configureTitle(TitleConfigurable configurable, String objectName) { Assert.notNull(configurable, "configurable"); Assert.notNull(objectName, "objectName"); String title = loadMessage(objectName + "." + TITLE_KEY); if (StringUtils.hasText(title)) { configurable.setTitle(title); } }
Sets the title of the given object. The title is loaded from this instance's {@link MessageSource} using a message code in the format <pre> &lt;objectName&gt;.title </pre> @param configurable The object to be configured. Must not be null. @param objectName The name of the configurable object, unique within the application. Must not be null. @throws IllegalArgumentException if either argument is null.
protected void configureLabel(LabelConfigurable configurable, String objectName) { Assert.notNull(configurable, "configurable"); Assert.notNull(objectName, "objectName"); String labelStr = loadMessage(objectName + "." + LABEL_KEY); if (StringUtils.hasText(labelStr)) { LabelInfo labelInfo = LabelInfo.valueOf(labelStr); configurable.setLabelInfo(labelInfo); } }
Sets the {@link LabelInfo} of the given object. The label info is created after loading the encoded label string from this instance's {@link MessageSource} using a message code in the format <pre> &lt;objectName&gt;.label </pre> @param configurable The object to be configured. Must not be null. @param objectName The name of the configurable object, unique within the application. Must not be null. @throws IllegalArgumentException if either argument is null.
protected void configureColor(ColorConfigurable configurable, String objectName) { Assert.notNull(configurable, "configurable"); Assert.notNull(objectName, "objectName"); Color color = loadColor(objectName + ".foreground"); if (color != null) configurable.setForeground(color); color = loadColor(objectName + ".background"); if (color != null) configurable.setBackground(color); }
Sets the foreground and background colours of the given object. Use the following message codes: <pre> &lt;objectName&gt;.foreground &lt;objectName&gt;.background </pre> @param configurable The object to be configured. Must not be null. @param objectName The name of the configurable object, unique within the application. Must not be null. @throws IllegalArgumentException if either argument is null.
protected void configureCommandLabel(CommandLabelConfigurable configurable, String objectName) { Assert.notNull(configurable, "configurable"); Assert.notNull(objectName, "objectName"); String labelStr = loadMessage(objectName + "." + LABEL_KEY); if (StringUtils.hasText(labelStr)) { CommandButtonLabelInfo labelInfo = CommandButtonLabelInfo.valueOf(labelStr); configurable.setLabelInfo(labelInfo); } }
Sets the {@link CommandButtonLabelInfo} of the given object. The label info is created after loading the encoded label string from this instance's {@link MessageSource} using a message code in the format <pre> &lt;objectName&gt;.label </pre> @param configurable The object to be configured. Must not be null. @param objectName The name of the configurable object, unique within the application. Must not be null. @throws IllegalArgumentException if either argument is null.
protected void configureDescription(DescriptionConfigurable configurable, String objectName) { Assert.notNull(configurable, "configurable"); Assert.notNull(objectName, "objectName"); String caption = loadMessage(objectName + "." + CAPTION_KEY); if (StringUtils.hasText(caption)) { configurable.setCaption(caption); } String description = loadMessage(objectName + "." + DESCRIPTION_KEY); if (StringUtils.hasText(description)) { configurable.setDescription(description); } }
Sets the description and caption of the given object. These values are loaded from this instance's {@link MessageSource} using message codes in the format <pre> &lt;objectName&gt;.description </pre> and <pre> &lt;objectName&gt;.caption </pre> respectively. @param configurable The object to be configured. Must not be null. @param objectName The name of the configurable object, unique within the application. Must not be null. @throws IllegalArgumentException if either argument is null.
protected void configureImage(ImageConfigurable configurable, String objectName) { Assert.notNull(configurable, "configurable"); Assert.notNull(objectName, "objectName"); Image image = loadImage(objectName, IMAGE_KEY); if (image != null) { configurable.setImage(image); } }
Sets the image of the given object. The image is loaded from this instance's {@link ImageSource} using a key in the format <pre> &lt;objectName&gt;.image </pre> If the image source cannot find an image under that key, the object's image will be set to null. @param configurable The object to be configured. Must not be null. @param objectName The name of the configurable object, unique within the application. Must not be null. @throws IllegalArgumentException if either argument is null.
protected void configureIcon(IconConfigurable configurable, String objectName) { Assert.notNull(configurable, "configurable"); Assert.notNull(objectName, "objectName"); Icon icon = loadIcon(objectName, ICON_KEY); if (icon != null) { configurable.setIcon(icon); } }
Sets the icon of the given object. The icon is loaded from this instance's {@link IconSource} using a key in the format <pre> &lt;objectName&gt;.icon </pre> If the icon source cannot find an icon under that key, the object's icon will be set to null. @param configurable The object to be configured. Must not be null. @param objectName The name of the configurable object, unique within the application. Must not be null. @throws IllegalArgumentException if either argument is null.
protected void configureCommandIcons(CommandIconConfigurable configurable, String objectName) { Assert.notNull(configurable, "configurable"); Assert.notNull(objectName, "objectName"); setIconInfo(configurable, objectName, false); setIconInfo(configurable, objectName, true); }
Sets the icons of the given object. <p> The icons are loaded from this instance's {@link IconSource}. using a key in the format </p> <pre> &lt;objectName&gt;.someIconType </pre> <p> The keys used to retrieve large icons from the icon source are created by concatenating the given {@code objectName} with a dot (.), the text 'large' and then an icon type like so: </p> <pre> &lt;myObjectName&gt;.large.someIconType </pre> <p> If the icon source cannot find an icon under that key, the object's icon will be set to null. </p> <p> If the {@code loadOptionalIcons} flag is set to true (it is by default) all the following icon types will be used. If the flag is false, only the first will be used: </p> <ul> <li>{@value #ICON_KEY}</li> <li>{@value #SELECTED_ICON_KEY}</li> <li>{@value #ROLLOVER_ICON_KEY}</li> <li>{@value #DISABLED_ICON_KEY}</li> <li>{@value #PRESSED_ICON_KEY}</li> </ul> @param configurable The object to be configured. Must not be null. @param objectName The name of the configurable object, unique within the application. Must not be null. @throws IllegalArgumentException if either argument is null.
protected void configureSecurityController(Secured controllable, String objectName) { Assert.notNull(controllable, "controllable"); Assert.notNull(objectName, "objectName"); String controllerId = controllable.getSecurityControllerId(); if (controllerId != null) { // Find the referenced controller. if (logger.isDebugEnabled()) { logger.debug("Lookup SecurityController with id [" + controllerId + "]"); } SecurityController controller = getSecurityControllerManager().getSecurityController(controllerId); // And add the object to the controlled object set if (controller != null) { if (logger.isDebugEnabled()) { logger.debug("configuring SecurityControllable [" + objectName + "]; security controller id='" + controllerId + "'"); } controller.addControlledObject(controllable); } else { if (logger.isDebugEnabled()) { logger.debug("configuring SecurityControllable [" + objectName + "]; no security controller for id='" + controllerId + "'"); } } } else { if (logger.isDebugEnabled()) { logger.debug("configuring SecurityControllable [" + objectName + "]; no security controller Id specified"); } } }
Associates the given object with a security controller if it implements the {@link Secured} interface. @param controllable The object to be configured. @param objectName The name (id) of the object. @throws org.springframework.beans.BeansException if a referenced security controller is not found or is of the wrong type
private Color loadColor(String colorKey) { String colorCode = loadMessage(colorKey); if (colorCode == null) { return null; } try { return Color.decode(colorCode); } catch (NumberFormatException nfe) { if (logger.isWarnEnabled()) { logger.warn("Could not parse a valid Color from code [" + colorCode + "]. Ignoring and returning null."); } return null; } }
Attempts to load a {@link Color} by decoding the message that is found by looking up the given colorKey. Decoding is done by by {@link Color#decode(String)}. @param colorKey The message code used to retrieve the colour code. @return the decoded {@link Color} or <code>null</code> if no colour could be decoded/found.
private String loadMessage(String messageCode) { Assert.notNull(messageCode, "messageCode"); if (logger.isDebugEnabled()) { logger.debug("Resolving label with code '" + messageCode + "'"); } try { return getMessageSource().getMessage(messageCode, null, getLocale()); } catch (NoSuchMessageException e) { if (logger.isInfoEnabled()) { logger.info("The message source is unable to find message code [" + messageCode + "]. Ignoring and returning null."); } return null; } }
Attempts to load the message corresponding to the given message code using this instance's {@link MessageSource} and locale. @param messageCode The message code that will be used to retrieve the message. Must not be null. @return The message for the given code, or null if the message code could not be found. @throws IllegalArgumentException if {@code messageCode} is null.
@Override public Optional<Counter> getCounter(final String counterName, final boolean skipCache) { Preconditions.checkNotNull(counterName); // This method always load the CounterData from the Datastore (or its Objectify cache), but sometimes returns // the // cached count value. // ////////////// // ShortCircuit: If nothing is present in the datastore. // ////////////// final Optional<CounterData> optCounterData = this.getCounterData(counterName); if (!optCounterData.isPresent()) { logger.log(Level.FINEST, String.format("Counter '%s' was not found in hte Datastore!", counterName)); return Optional.absent(); } final CounterData counterData = optCounterData.get(); // ////////////// // ShortCircuit: If the counter is in an indeterminate state, then return its count as 0. // ////////////// if (this.counterStatusYieldsIndeterminateCount(counterData.getCounterStatus())) { logger.log(Level.FINEST, String.format("Counter '%s' was in an indeterminate state. Returning 0!", counterName)); return Optional.of(new CounterBuilder(counterData).withCount(BigInteger.ZERO).build()); } // ////////////// // ShortCircuit: If the counter was found in memcache. // ////////////// final String memCacheKey = this.assembleCounterKeyforMemcache(counterName); if (!skipCache) { final BigInteger cachedCounterCount = this.memcacheSafeGet(memCacheKey); if (cachedCounterCount != null) { // ///////////////////////////////////// // The count was found in memcache, so return it. // ///////////////////////////////////// logger.log(Level.FINEST, String.format("Cache Hit for Counter Named '%s': value=%s", counterName, cachedCounterCount)); return Optional.of(new CounterBuilder(counterData).withCount(cachedCounterCount).build()); } else { logger.log(Level.FINE, String.format("Cache Miss for CounterData Named '%s': value='%s'. Checking Datastore instead!", counterName, cachedCounterCount)); } } // ///////////////////////////////////// // skipCache was true or the count was NOT found in memcache! // ///////////////////////////////////// // Note: No Need to clear the Objectify session cache here because it will be cleared automatically and // repopulated upon every request. logger.log(Level.FINE, String.format("Aggregating counts from '%s' CounterDataShards for CounterData named '%s'!", counterData.getNumShards(), counterData.getName())); // /////////////////// // Assemble a List of CounterShardData Keys to retrieve in parallel! final List<Key<CounterShardData>> keysToLoad = Lists.newArrayList(); for (int i = 0; i < counterData.getNumShards(); i++) { final Key<CounterShardData> counterShardKey = CounterShardData.key(counterData.getTypedKey(), i); keysToLoad.add(counterShardKey); } long sum = 0; // For added performance, we could spawn multiple threads to wait for each value to be returned from the // DataStore, and then aggregate that way. However, the simple summation below is not very expensive, so // creating multiple threads to get each value would probably be overkill. Just let objectify do this for // us. Even though we have to wait for all entities to return before summation begins, the summation is a quick // in-memory operation with a relatively small number of shards, so parallelizing it would likely not increase // performance. // No TX - get is Strongly consistent by default, and we will exceed the TX limit for high-shard-count // counters if we try to do this in a TX. final Map<Key<CounterShardData>, CounterShardData> counterShardDatasMap = ObjectifyService.ofy() .transactionless().load().keys(keysToLoad); final Collection<CounterShardData> counterShardDatas = counterShardDatasMap.values(); for (CounterShardData counterShardData : counterShardDatas) { if (counterShardData != null) { sum += counterShardData.getCount(); } } logger.log(Level.FINE, String.format("The Datastore is reporting a count of %s for CounterData '%s' count. Resetting memcache " + "count to %s for this counter name.", sum, counterData.getName(), sum)); final BigInteger bdSum = BigInteger.valueOf(sum); try { // This method will only get here if there was nothing in Memcache, or if the caller requested to skip // reading the Counter count from memcache. In these cases, the value in memcache should always be replaced. memcacheService.put(memCacheKey, bdSum, config.getDefaultCounterCountExpiration(), SetPolicy.SET_ALWAYS); } catch (MemcacheServiceException mse) { // Do nothing. The method will still return even though memcache is not available. } return Optional.of(new CounterBuilder(counterData).withCount(bdSum).build()); }
The cache will expire after {@code defaultCounterCountExpiration} seconds, so the counter will be accurate after a minute because it performs a load from the datastore. @param counterName @param skipCache A boolean that allows a caller to skip memcache when retrieving a counter. Set to {@code true} to load the counter and all of its shards directly from the Datastore. Set to {@code false} to attempt to load the count from memcache, with fallback to the datastore. @return
@Override public void updateCounterDetails(final Counter incomingCounter) { Preconditions.checkNotNull(incomingCounter); // First, assert the counter is in a proper state. If done consistently (i.e., in a TX, then this will function // as an effective CounterData lock). // Second, Update the counter details. ObjectifyService.ofy().transact(new Work<Void>() { @Override public Void run() { // First, load the incomingCounter from the datastore via a transactional get to ensure it has the // proper state. final Optional<CounterData> optCounterData = getCounterData(incomingCounter.getName()); // ////////////// // ShortCircuit: Can't update a counter that doesn't exist! // ////////////// if (!optCounterData.isPresent()) { throw new NoCounterExistsException(incomingCounter.getName()); } final CounterData counterDataInDatastore = optCounterData.get(); // Make sure the stored counter is currently in an updatable state! assertCounterDetailsMutatable(incomingCounter.getName(), counterDataInDatastore.getCounterStatus()); // Make sure the incoming counter status is a validly settable status assertValidExternalCounterStatus(incomingCounter.getName(), incomingCounter.getCounterStatus()); // NOTE: READ_ONLY_COUNT status means the count can't be incremented/decremented. However, it's details // can still be mutated. // NOTE: The counterName/counterId may not change! // Update the Description counterDataInDatastore.setDescription(incomingCounter.getDescription()); // Update the numShards. Aside from setting this value, nothing explicitly needs to happen in the // datastore since shards will be created when a counter in incremented (if the shard doesn't already // exist). However, if the number of shards is being reduced, then throw an exception since this // requires counter shard reduction and some extra thinking. We can't allow the shard-count to go down // unless we collapse the entire counter's shards into a single shard or zero, and it's ambiguous if // this is even required. Note that if we allow this numShards value to decrease without capturing // the count from any of the shards that might no longer be used, then we might lose counts from the // shards that would no longer be factored into the #getCount method. if (incomingCounter.getNumShards() < counterDataInDatastore.getNumShards()) { throw new IllegalArgumentException( "Reducing the number of counter shards is not currently allowed! See https://github.com/instacount/appengine-counter/issues/4 for more details."); } counterDataInDatastore.setNumShards(incomingCounter.getNumShards()); // The Exception above disallows any invalid states. counterDataInDatastore.setCounterStatus(incomingCounter.getCounterStatus()); // Update the CounterDataIndexes counterDataInDatastore.setIndexes( incomingCounter.getIndexes() == null ? CounterIndexes.none() : incomingCounter.getIndexes()); // Update the counter in the datastore. ObjectifyService.ofy().save().entity(counterDataInDatastore).now(); // return null to satisfy Java... return null; } }); }
NOTE: We don't allow the counter's "count" to be updated by this method. Instead, {@link #increment} and {@link #decrement} should be used. @param incomingCounter
@Override public int determineRandomShardNumber(final Optional<Integer> optShardNumber, final int numShards) { Preconditions.checkArgument(numShards > 0); Preconditions.checkNotNull(optShardNumber); if (optShardNumber.isPresent()) { final int shardNumber = optShardNumber.get(); if (shardNumber >= 0 && shardNumber < numShards) { return optShardNumber.get(); } } // Otherwise... return generator.nextInt(numShards); }
Helper method to determine the random shard number for the mutation operation. If {@code optShardNumber} is present, then this value will be used so long as it is greater-than or equal to zero. Otherwise, a PRNG will be used to select the next shard number based upon the current number of shards that are allowed for the current counter as specified by {@code numShards}. @param optShardNumber An {@link Optional} instance of {@link Integer} that specifies the shard number to use, if present. @param numShards The number of shards that the mutating counter has available to it for increment/decrement operations. @return
@Override public CounterOperation decrement(final String counterName, final long amount) { Preconditions.checkNotNull(counterName); Preconditions.checkArgument(!StringUtils.isBlank(counterName)); Preconditions.checkArgument(amount > 0, "Decrement amounts must be positive!"); // Perform the Decrement final long decrementAmount = amount * -1L; return this.mutateCounterShard(counterName, decrementAmount, Optional.<Integer> absent(), UUID.randomUUID()); }
/////////////////////////////
@Override public void reset(final String counterName) { Preconditions.checkNotNull(counterName); try { // Update the Counter's Status in a New TX to the RESETTING_STATE and apply the TX. // The "new" TX ensures that no other thread nor parent transaction is performing this operation at the // same time, since if that were the case the updateCounter would fail. This Work returns the number of // counter shards that existed for the counter. Capture the number of shards that exist in the counter // so that the datastore doesn't need to be hit again. final Integer numCounterShards = ObjectifyService.ofy().transactNew(new Work<Integer>() { @Override public Integer run() { // Use the cache here if possible, because the first two short-circuits don't really need accurate // counts to work. final Optional<CounterData> optCounterData = getCounterData(counterName); // ///////////// // ShortCircuit: Do nothing - there's nothing to return. // ///////////// if (!optCounterData.isPresent()) { // The counter was not found, so we can't reset it. throw new NoCounterExistsException(counterName); } else { final CounterData counterData = optCounterData.get(); // Make sure the counter can be put into the RESETTING state! assertCounterDetailsMutatable(counterName, counterData.getCounterStatus()); counterData.setCounterStatus(CounterStatus.RESETTING); ObjectifyService.ofy().save().entity(counterData); return counterData.getNumShards(); } } }); // TODO: Refactor the below code into a transactional enqueing mechansim that either encodes all shards, or // else creates a single task that re-enqueues itself with a decrementing number so that it will run on // every shard and then reset the status of the counter. In this way, "reset" can be async, and work for // shards larger than 25, but since the counter is in the RESETTING state, it won't be allowed to be // mutated. // For now, perform all reset operations in same TX to provide atomic rollback. Since Appengine now support // up to 25 entities in a transaction, this will work for all counters up to 25 shards. ObjectifyService.ofy().transactNew(new VoidWork() { @Override public void vrun() { // For each shard, reset it. Shard Index starts at 0. for (int shardNumber = 0; shardNumber < numCounterShards; shardNumber++) { final ResetCounterShardWork resetWork = new ResetCounterShardWork(counterName, shardNumber); ObjectifyService.ofy().transact(resetWork); } } }); } finally { // Clear the cache to ensure that future callers get the right count. this.memcacheSafeDelete(counterName); // If the reset-shards loop above completes properly, OR if an exception is thrown above, the counter status // needs to be reset to AVAILABLE. In the first case (an exception is thrown) then the reset TX will be // rolled-back, and the counter status needs to become AVAILABLE. In the second case (the counter was // successfully reset) the same counter status update to AVAILABLE needs to occur. ObjectifyService.ofy().transactNew(new VoidWork() { /** * Updates the {@link CounterData} status to be {@link CounterStatus#AVAILABLE}, but only if the current * status is {@link CounterStatus#RESETTING}. */ @Override public void vrun() { final Optional<CounterData> optCounterData = getCounterData(counterName); if (optCounterData.isPresent()) { final CounterData counterData = optCounterData.get(); if (counterData.getCounterStatus() == CounterStatus.RESETTING) { counterData.setCounterStatus(CounterStatus.AVAILABLE); ObjectifyService.ofy().save().entity(counterData).now(); } } } }); } }
}
private CounterOperation mutateCounterShard(final String counterName, final long amount, final Optional<Integer> optShardNumber, final UUID incrementOperationId) { // /////////// // Precondition Checks are performed by calling methods. // This get is transactional and strongly consistent, but we perform it here so that the increment doesn't have // to be part of an XG transaction. Since the CounterData isn't expected to mutate that often, we want // increment/decrement operations to be as speedy as possibly. In this way, the IncrementWork can take place in // a non-XG transaction. final CounterDataGetCreateContainer counterDataGetCreateContainer = this.getOrCreateCounterData(counterName); final CounterData counterData = counterDataGetCreateContainer.getCounterData(); // Create the Work to be done for this increment, which will be done inside of a TX. See // "https://developers.google.com/appengine/docs/java/datastore/transactions#Java_Isolation_and_consistency" final Work<CounterOperation> atomicIncrementShardWork = new IncrementShardWork(counterData, incrementOperationId, optShardNumber, amount, counterDataGetCreateContainer.isNewCounterDataCreated()); // Note that this operation is idempotent from the perspective of a ConcurrentModificationException. In that // case, the increment operation will fail and will not have been applied. An Objectify retry of the // increment/decrement will occur, however and a successful increment/decrement will only ever happen once (if // the Appengine datastore is functioning properly). See the Javadoc in the API about DatastoreTimeoutException // or // DatastoreFailureException in cases where transactions have been committed and eventually will be applied // successfully." // We use the "counterShardOperationInTx" to force this thread to wait until the work inside of // "atomicIncrementShardWork" completes. This is because we don't want to increment memcache (below) until after // that operation's transaction successfully commits. final CounterOperation counterShardOperationInTx = ObjectifyService.ofy().transact(atomicIncrementShardWork); // ///////////////// // Try to increment this counter in memcache atomically, but only if we're not inside of a parent caller's // transaction. If that's the case, then we can't know if the parent TX will fail upon commit, which would // happen after our call to memcache. // ///////////////// if (isParentTransactionActive()) { // If a parent-transaction is active, then don't update memcache. Instead, clear it out since we can't know // if the parent commit will actually stick. this.memcacheSafeDelete(counterName); } else { // Otherwise, try to increment memcache. If the memcache operation fails, it's ok because memcache is merely // a cache of the actual count data, and will eventually become accurate when the cache is reloaded via a // call to #getCount. long amountToMutateCache = counterShardOperationInTx.getAppliedAmount(); if (amount < 0) { amountToMutateCache *= -1L; } this.incrementMemcacheAtomic(counterName, amountToMutateCache); } return counterShardOperationInTx; }
Does the work of incrementing or decrementing the value of a single shard for the counter named {@code counterName}. @param counterName @param amount The amount to mutate a counter shard by. This value will be negative for a decrement, and positive for an increment. @param incrementOperationId @param optShardNumber An optionally specified shard number to increment. If not specified, a random shard number will be chosen. @return An instance of {@link CounterOperation} with information about the increment/decrement.
@Override public void delete(final String counterName) { Preconditions.checkNotNull(counterName); Preconditions.checkArgument(!StringUtils.isBlank(counterName)); // Delete the main counter in a new TX... ObjectifyService.ofy().transactNew(new VoidWork() { @Override public void vrun() { // Load in a TX so that two threads don't mark the counter as deleted at the same time. final Key<CounterData> counterDataKey = CounterData.key(counterName); final CounterData counterData = ObjectifyService.ofy().load().key(counterDataKey).now(); if (counterData == null) { // We throw an exception here so that callers can be aware that the deletion failed. In the // task-queue, however, no exception is thrown since failing to delete something that's not there // can be treated the same as succeeding at deleting something that's there. throw new NoCounterExistsException(counterName); } Queue queue; if (config.getDeleteCounterShardQueueName() == null) { queue = QueueFactory.getDefaultQueue(); } else { queue = QueueFactory.getQueue(config.getDeleteCounterShardQueueName()); } // The TaskQueue will delete the counter once all shards are deleted. counterData.setCounterStatus(CounterData.CounterStatus.DELETING); // Call this Async so that the rest of the thread can // continue. Everything will block till commit is called. ObjectifyService.ofy().save().entity(counterData); // Transactionally enqueue this task to the path specified in the constructor (if this is null, then the // default queue will be used). TaskOptions taskOptions = TaskOptions.Builder.withParam(COUNTER_NAME, counterName); if (config.getRelativeUrlPathForDeleteTaskQueue() != null) { taskOptions = taskOptions.url(config.getRelativeUrlPathForDeleteTaskQueue()); } // Kick off a Task to delete the Shards for this CounterData and the CounterData itself, but only if the // overall TX commit succeeds queue.add(taskOptions); } }); }
/////////////////////////////
@VisibleForTesting void memcacheSafeDelete(final String counterName) { Preconditions.checkNotNull(counterName); try { memcacheService.delete(counterName); } catch (MemcacheServiceException mse) { // Do nothing. This merely indicates that memcache was unreachable, which is fine. If it's // unreachable, there's likely nothing in the cache anyway, but in any case there's nothing we can do here. } }
Attempt to delete a counter from memcache but swallow any exceptions from memcache if it's down. @param counterName
@VisibleForTesting BigInteger memcacheSafeGet(final String memcacheKey) { Preconditions.checkNotNull(memcacheKey); BigInteger cachedCounterCount; try { cachedCounterCount = (BigInteger) memcacheService.get(memcacheKey); } catch (MemcacheServiceException mse) { // Do nothing. This merely indicates that memcache was unreachable, which is fine. If it's // unreachable, there's likely nothing in the cache anyway, but in any case there's nothing we can do here. cachedCounterCount = null; } return cachedCounterCount; }
Attempt to delete a counter from memcache but swallow any exceptions from memcache if it's down. @param memcacheKey
@VisibleForTesting protected Optional<CounterData> getCounterData(final String counterName) { Preconditions.checkNotNull(counterName); final Key<CounterData> counterKey = CounterData.key(counterName); final CounterData counterData = ObjectifyService.ofy().load().key(counterKey).now(); return Optional.fromNullable(counterData); }
Helper method to get the {@link CounterData} associated with the supplied {@code counterName}. @param counterName @return
@VisibleForTesting protected CounterData createCounterData(final String counterName) { this.counterNameValidator.validateCounterName(counterName); final Key<CounterData> counterKey = CounterData.key(counterName); // Perform a transactional GET to see if the counter exists. If it does, throw an exception. Otherwise, create // the counter in the same TX. return ObjectifyService.ofy().transact(new Work<CounterData>() { @Override public CounterData run() { final CounterData loadedCounterData = ObjectifyService.ofy().load().key(counterKey).now(); if (loadedCounterData == null) { final CounterData counterData = new CounterData(counterName, config.getNumInitialShards()); ObjectifyService.ofy().save().entity(counterData).now(); return counterData; } else { throw new CounterExistsException(counterName); } } }); }
Helper method to create the {@link CounterData} associated with the supplied counter information. @param counterName @return @throws IllegalArgumentException If the {@code counterName} is invalid. @throws CounterExistsException If the counter with {@code counterName} already exists in the Datastore.
@VisibleForTesting protected CounterDataGetCreateContainer getOrCreateCounterData(final String counterName) { // Validation failures will throw an exception. See JavaDoc for details. this.counterNameValidator.validateCounterName(counterName); final Key<CounterData> counterKey = CounterData.key(counterName); // This get/create is acceptable to perform outside of a transaction. In certain edge-cases, it's possible // that two threads might call this operation at the same time, and one or both threads might think (errantly) // that no CounterData exists in the Datastore when in reality one of the threads (or some other thread) may // have created the CoutnerData already. However, in this case, the two create operations will be the same using // default data, so even though the "winner" will be random, the result will be the same. In future, this // assumption may need to change. CounterData counterData = ObjectifyService.ofy().load().key(counterKey).now(); if (counterData == null) { counterData = new CounterData(counterName, config.getNumInitialShards()); // counterData.setNegativeCountAllowed(config.isNegativeCountAllowed()); ObjectifyService.ofy().save().entity(counterData).now(); return new CounterDataGetCreateContainer(counterData, NEW_COUNTER_CREATED); } else { return new CounterDataGetCreateContainer(counterData, COUNTER_EXISTED); } }
Helper method to get (or create and then get) a {@link CounterData} from the Datastore with a given name. The result of this function is guaranteed to be non-null if no exception is thrown. @param counterName @return @throws NullPointerException if the {@code counterName} is null. @throws InvalidCounterNameException If the counter name is too long or too short.
@VisibleForTesting protected Optional<Long> incrementMemcacheAtomic(final String counterName, final long amount) { Preconditions.checkNotNull(counterName); // Get the cache counter at a current point in time. String memCacheKey = this.assembleCounterKeyforMemcache(counterName); for (int currentRetry = 0; currentRetry < NUM_RETRIES_LIMIT; currentRetry++) { try { final IdentifiableValue identifiableCounter = memcacheService.getIdentifiable(memCacheKey); // See Javadoc about a null identifiableCounter. If it's null, then the named counter doesn't exist in // memcache. if (identifiableCounter == null || (identifiableCounter != null && identifiableCounter.getValue() == null)) { final String msg = "No identifiableCounter was found in Memcache. Unable to Atomically increment for CounterName '%s'. Memcache will be populated on the next called to getCounter()!"; logger.log(Level.FINEST, String.format(msg, counterName)); // This will return an absent value. Only #getCounter should "put" a value to memcache. break; } // If we get here, the count exists in memcache, so it can be atomically incremented/decremented. final BigInteger cachedCounterAmount = (BigInteger) identifiableCounter.getValue(); final long newMemcacheAmount = cachedCounterAmount.longValue() + amount; logger.log(Level.FINEST, String.format("Just before Atomic Increment of %s, Memcache has value: %s", amount, identifiableCounter.getValue())); if (memcacheService.putIfUntouched(counterName, identifiableCounter, BigInteger.valueOf(newMemcacheAmount), config.getDefaultCounterCountExpiration())) { logger.log(Level.FINEST, String.format("MemcacheService.putIfUntouched SUCCESS! with value: %s", newMemcacheAmount)); // If we get here, the put succeeded... return Optional.of(new Long(newMemcacheAmount)); } else { logger.log(Level.WARNING, String.format("Unable to update memcache counter atomically. Retrying %s more times...", (NUM_RETRIES_LIMIT - currentRetry))); continue; } } catch (MemcacheServiceException mse) { // Check and post-decrement the numRetries counter in one step if ((currentRetry + 1) < NUM_RETRIES_LIMIT) { logger.log(Level.WARNING, String.format("Unable to update memcache counter atomically. Retrying %s more times...", (NUM_RETRIES_LIMIT - currentRetry))); // Keep trying... continue; } else { // Evict the counter here, and let the next call to getCounter populate memcache final String logMessage = "Unable to update memcache counter atomically, with no more allowed retries. Evicting counter named '%s' from the cache!"; logger.log(Level.SEVERE, String.format(logMessage, (NUM_RETRIES_LIMIT - currentRetry)), mse); this.memcacheSafeDelete(memCacheKey); break; } } } // The increment did not work... return Optional.absent(); }
Increment the memcache version of the named-counter by {@code amount} (positive or negative) in an atomic fashion. Use memcache as a Semaphore/Mutex, and retry up to 10 times if other threads are attempting to update memcache at the same time. If nothing is in Memcache when this function is called, then do nothing because only #getCounter should "put" a value to memcache. Additionally, if this operation fails, the cache will be re-populated after a configurable amount of time, so the count will eventually become correct. @param counterName @param amount @return The new count of this counter as reflected by memcache
@VisibleForTesting protected void assertCounterAmountMutatable(final String counterName, final CounterStatus counterStatus) { if (counterStatus != CounterStatus.AVAILABLE) { final String msg = String.format( "Can't mutate the amount of counter '%s' because it's currently in the %s state but must be in in " + "the %s state!", counterName, counterStatus.name(), CounterStatus.AVAILABLE); throw new CounterNotMutableException(counterName, msg); } }
Helper method to determine if a counter's incrementAmount can be mutated (incremented or decremented). In order for that to happen, the counter's status must be {@link CounterStatus#AVAILABLE}. @param counterName @param counterStatus @return
@VisibleForTesting protected void assertCounterDetailsMutatable(final String counterName, final CounterStatus counterStatus) { Preconditions.checkNotNull(counterName); Preconditions.checkNotNull(counterStatus); if (counterStatus != CounterStatus.AVAILABLE && counterStatus != CounterStatus.READ_ONLY_COUNT) { final String msg = String.format("Can't mutate with status %s. Counter must be in in the %s or %s state!", counterStatus, CounterStatus.AVAILABLE, CounterStatus.READ_ONLY_COUNT); throw new CounterNotMutableException(counterName, msg); } }
Helper method to determine if a counter's incrementAmount can be mutated (incremented or decremented). In order for that to happen, the counter's status must be {@link CounterStatus#AVAILABLE}. @param counterName The name of the counter. @param counterStatus The {@link CounterStatus} of a counter that is currently stored in the Datastore. @return
@VisibleForTesting protected void assertValidExternalCounterStatus(final String counterName, final CounterStatus incomingCounterStatus) { Preconditions.checkNotNull(counterName); Preconditions.checkNotNull(incomingCounterStatus); if (incomingCounterStatus != CounterStatus.AVAILABLE && incomingCounterStatus != CounterStatus.READ_ONLY_COUNT) { final String msg = String.format( "This Counter can only be put into the %s or %s status! %s is not allowed.", CounterStatus.AVAILABLE, CounterStatus.READ_ONLY_COUNT, incomingCounterStatus); throw new CounterNotMutableException(counterName, msg); } }
Helper method to determine if a counter can be put into the {@code incomingCounterStatus} by an external caller. Currently, external callers may only put a Counter into the AVAILABLE or READ_ONLY status. @param counterName The name of the counter. @param incomingCounterStatus The status of an incoming counter that is being updated by an external counter. @return
protected boolean counterStatusYieldsIndeterminateCount(final CounterStatus counterStatus) { Preconditions.checkNotNull(counterStatus); return counterStatus == CounterStatus.DELETING || counterStatus == CounterStatus.CONTRACTING_SHARDS || counterStatus == CounterStatus.RESETTING || counterStatus == CounterStatus.EXPANDING_SHARDS; }
When a counter is in certain statuses, its count can not be determined for various reasons. For example, if the number of shards is contracting from 5 to 4, then the total summation of all shards will not be possible to determine since counts from shard 5 may have been applied to shards 5 and 4, whereas the actual "number of shards" value in the CoutnerData may not have been updated to indicate this change. Thus, for certain {@link CounterStatus} values, we cannot provide a valid count, and instead return {@link BigInteger#ZERO}. @param counterStatus @return
public static void installImageUrlHandler(ImageSource urlHandlerImageSource) { Assert.notNull(urlHandlerImageSource); Handler.urlHandlerImageSource = urlHandlerImageSource; try { // System properties should be set at JVM startup // Testcases in IDEA/Eclipse are at JVM startup, but not in Maven's // surefire... // TODO this entire implementation should be changed with a // java.net.URLStreamHandlerFactory instead. String packagePrefixList = System.getProperty("java.protocol.handler.pkgs"); String newPackagePrefixList = null; String orgSpringFrameworkRichclientString = "org.springframework.richclient"; if (packagePrefixList == null || packagePrefixList.equals("")) { newPackagePrefixList = orgSpringFrameworkRichclientString; } else if (("|" + packagePrefixList + "|").indexOf("|" + orgSpringFrameworkRichclientString + "|") < 0) { newPackagePrefixList = packagePrefixList + "|" + orgSpringFrameworkRichclientString; } if (newPackagePrefixList != null) { System.setProperty("java.protocol.handler.pkgs", newPackagePrefixList); } } catch (SecurityException e) { logger.warn("Unable to install image URL handler", e); Handler.urlHandlerImageSource = null; } }
Installs this class as a handler for the "image:" protocol. Images will be resolved from the provided image source.
public Authentication getAuthentication() { String username = getValueModel(LoginDetails.PROPERTY_USERNAME, String.class).getValue(); String password = getValueModel(LoginDetails.PROPERTY_PASSWORD, String.class).getValue(); return new UsernamePasswordAuthenticationToken( username, password ); }
Get an Authentication token that contains the current username and password. @return authentication token
protected JComponent createFormControl() { TableFormBuilder formBuilder = new TableFormBuilder( getBindingFactory() ); usernameField = formBuilder.add( LoginDetails.PROPERTY_USERNAME )[1]; formBuilder.row(); passwordField = formBuilder.addPasswordField( LoginDetails.PROPERTY_PASSWORD )[1]; return formBuilder.getForm(); }
Construct the form with the username and password fields.
public void setMessage( Message message ) { Assert.notNull(message, "The message is required"); Assert.hasText( message.getMessage(), "The message text is required" ); this.message = message; }
Set the message. @param message the message
public void setActivePage(DialogPage page) { if (settingSelection) { return; } try { settingSelection = true; super.setActivePage(page); if (page != null) { Tab tab = (Tab) page2tab.get(page); tabbedPaneView.selectTab(tab); } } finally { settingSelection = false; } }
Sets the active page of this TabbedDialogPage. This method will also select the tab wich displays the new active page.
protected void init() { FormModel model = createFormModel(); if(getId() == null) formId = model.getId(); if (model instanceof ValidatingFormModel) { ValidatingFormModel validatingFormModel = (ValidatingFormModel) model; setFormModel(validatingFormModel); } else { throw new IllegalArgumentException("Unsupported form model implementation " + formModel); } getApplicationConfig().applicationObjectConfigurer().configure(this, getId()); }
Hook called when constructing the Form.
public BindingFactory getBindingFactory() { if (bindingFactory == null) { bindingFactory = getApplicationConfig().bindingFactoryProvider().getBindingFactory(formModel); } return bindingFactory; }
Returns a {@link BindingFactory} bound to the inner {@link FormModel} to provide binding support.
protected void setFormModel(ValidatingFormModel formModel) { Assert.notNull(formModel); if (this.formModel != null && isControlCreated()) { throw new UnsupportedOperationException("Cannot reset form model once form control has been created"); } if (this.formModel != null) { this.formModel.removeCommitListener(this); } this.formModel = formModel; this.formGuard = new FormGuard(formModel); this.formModel.addCommitListener(this); setFormModelDefaultEnabledState(); }
Set the {@link FormModel} for this {@link Form}. Normally a Form won't change it's FormModel as this may lead to an inconsistent state. Only use this when the formModel isn't set yet. TODO check why we do allow setting when no control is created. ValueModels might exist already leading to an inconsistent state. @param formModel
public void addChildForm(Form childForm) { childForms.put(childForm.getId(), childForm); getFormModel().addChild(childForm.getFormModel()); }
Add a child (or sub) form to this form. Child forms will be tied in to the same validation results reporter as this form and they will be configured to control the same guarded object as this form. <p> Validation listeners are unique to a form, so calling {@link #addValidationListener(ValidationListener)} will only add a listener to this form. If you want to listen to the child forms, you will need to add a validation listener on each child form of interest. <p> <em>Note:</em> It is very important that the child form provided be created using a form model that is a child model of this form's form model. If this is not done, then commit and revert operations will not be properly delegated to the child form models. @param childForm to add
protected void setFormModelDefaultEnabledState() { if (getFormObject() == null) { getFormModel().setEnabled(false); } else { if (getFormObject() instanceof Guarded) { setEnabled(((Guarded) getFormObject()).isEnabled()); } } }
Set the form's enabled state based on a default policy--specifically, disable if the form object is null or the form object is guarded and is marked as disabled.
private final ActionCommand createCommitCommand() { String commandId = getCommitCommandFaceDescriptorId(); if (!StringUtils.hasText(commandId)) { return null; } ActionCommand commitCmd = new ActionCommand(commandId) { protected void doExecuteCommand() { commit(); } }; commitCmd.setSecurityControllerId(getCommitSecurityControllerId()); attachFormGuard(commitCmd, FormGuard.LIKE_COMMITCOMMAND); return (ActionCommand) getApplicationConfig().commandConfigurer().configure(commitCmd); }
Returns a command wrapping the commit behavior of the {@link FormModel}. This command has the guarded and security aspects.