code
stringlengths 67
466k
| docstring
stringlengths 1
13.2k
|
---|---|
public boolean containsCommand(String commandId) {
Assert.notNull(commandId, "commandId");
if (this.commandMap.containsKey(commandId)) {
return true;
}
if (this.parent != null) {
return this.parent.containsCommand(commandId);
}
return false;
} | {@inheritDoc} |
public Object getCommand(String commandId, Class requiredType) throws CommandNotOfRequiredTypeException {
Assert.notNull(commandId, "commandId");
Object command = this.commandMap.get(commandId);
if (command == null && this.parent != null) {
command = this.parent.getCommand(commandId);
}
if (command == null) {
return null;
}
if (requiredType != null && !ClassUtils.isAssignableValue(requiredType, command)) {
throw new CommandNotOfRequiredTypeException(commandId, requiredType, command.getClass());
}
return command;
} | {@inheritDoc} |
public Class getType(String commandId) {
Assert.notNull(commandId, "commandId");
Object command = getCommand(commandId);
if (command == null) {
return null;
}
else {
return command.getClass();
}
} | {@inheritDoc} |
public boolean isTypeMatch(String commandId, Class targetType) {
Assert.notNull(commandId, "commandId");
Assert.notNull(targetType, "targetType");
Class commandType = getType(commandId);
if (commandType == null) {
return false;
}
else {
return ClassUtils.isAssignable(targetType, commandType);
}
} | {@inheritDoc} |
public void setImage(Resource resource)
{
ImageIcon image = null;
if (resource != null && resource.exists())
{
try
{
image = new ImageIcon(resource.getURL());
}
catch (IOException e)
{
logger.warn("Error reading resource: " + resource);
throw new RuntimeException("Error reading resource " + resource, e);
}
}
setImage(image);
} | Sets the image content of the widget based on a resource
@param resource
points to a image resource |
public org.valkyriercp.binding.validation.ValidationResults validate(Object object) {
return validate(object, null);
} | {@inheritDoc} |
public org.valkyriercp.binding.validation.ValidationResults validate(Object object, String propertyName) {
// Forms can have different types of objects, so when type of object
// changes, messages that are already listed on the previous type must
// be removed. If evaluating the whole object (propertyName == null)
// also clear results.
if ((propertyName == null) || ((objectClass != null) && objectClass != object.getClass())) {
clearMessages();
}
objectClass = object.getClass();
Rules rules = null;
if (object instanceof PropertyConstraintProvider) {
PropertyConstraintProvider propertyConstraintProvider = (PropertyConstraintProvider) object;
if (propertyName != null) {
PropertyConstraint validationRule = propertyConstraintProvider.getPropertyConstraint(propertyName);
checkRule(validationRule);
}
else {
for (Iterator fieldNamesIter = formModel.getFieldNames().iterator(); fieldNamesIter.hasNext();) {
PropertyConstraint validationRule = propertyConstraintProvider
.getPropertyConstraint((String) fieldNamesIter.next());
checkRule(validationRule);
}
}
}
else {
if (getRulesSource() != null) {
rules = getRulesSource().getRules(objectClass, getRulesContextId());
if (rules != null) {
for (Iterator i = rules.iterator(); i.hasNext();) {
PropertyConstraint validationRule = (PropertyConstraint) i.next();
if (propertyName == null) {
if (formModel.hasValueModel(validationRule.getPropertyName())) {
checkRule(validationRule);
}
}
else if (validationRule.isDependentOn(propertyName)) {
checkRule(validationRule);
}
}
}
}
else {
logger.debug("No rules source has been configured; "
+ "please set a valid reference to enable rules-based validation.");
}
}
return results;
} | {@inheritDoc} |
protected final void fireValueChange(boolean oldValue, boolean newValue) {
fireValueChange(Boolean.valueOf(oldValue), Boolean.valueOf(newValue));
} | Notifies all listeners that have registered interest for
notification on this event type. The event instance
is lazily created using the parameters passed into
the fire method.
@param oldValue the boolean value before the change
@param newValue the boolean value after the change |
protected void fireValueChange(Object oldValue, Object newValue) {
if (hasValueChanged(oldValue, newValue)) {
fireValueChangeEvent(oldValue, newValue);
}
} | Notifies all listeners that have registered interest for
notification on this event type. The event instance
is lazily created using the parameters passed into
the fire method.
@param oldValue the float value before the change
@param newValue the float value after the change |
protected void fireValueChangeEvent(Object oldValue, Object newValue) {
if (logger.isDebugEnabled()) {
logger.debug("Firing value changed event. Old value='" + oldValue + "' new value='" + newValue + "'");
}
final PropertyChangeListener[] propertyChangeListeners = getPropertyChangeListeners(VALUE_PROPERTY);
if (propertyChangeListeners.length > 0) {
final Object listenerToSkip = listenerToSkipHolder.get();
final PropertyChangeEvent propertyChangeEvent = new PropertyChangeEvent(this, VALUE_PROPERTY, oldValue,
newValue);
for (PropertyChangeListener listener : propertyChangeListeners) {
if (listener != listenerToSkip) {
listener.propertyChange(propertyChangeEvent);
}
}
}
} | Notifies all listeners that have registered interest for
notification on this event type. This method does not check if there is any change
between the old and new value unlike the various fireValueChanged() methods. |
public void setAntiAlias(boolean antiAlias) {
if (this.antiAlias == antiAlias) {
return;
}
this.antiAlias = antiAlias;
firePropertyChange("antiAlias", !antiAlias, antiAlias);
repaint();
} | Set whether the pane should render the HTML using anti-aliasing. |
public void setAllowSelection(boolean allowSelection) {
if (this.allowSelection == allowSelection) {
return;
}
this.allowSelection = allowSelection;
setCaretInternal();
firePropertyChange("allowSelection", !allowSelection, allowSelection);
} | Set whether or not selection should be allowed in this pane. |
protected void installLaFStyleSheet() {
Font defaultFont = UIManager.getFont("Button.font");
String stylesheet = "body { font-family: " + defaultFont.getName() + "; font-size: " + defaultFont.getSize()
+ "pt; }" + "a, p, li { font-family: " + defaultFont.getName() + "; font-size: "
+ defaultFont.getSize() + "pt; }";
try {
((HTMLDocument)getDocument()).getStyleSheet().loadRules(new StringReader(stylesheet), null);
}
catch (IOException e) {
}
} | Applies the current LaF font setting to the document. |
public void add(ApplicationWindow window) {
if (activeWindow == null) // first window will be set as activeWindow
setActiveWindow(window);
if (!windows.contains(window)) {
windows.add(window);
window.setWindowManager(this);
setChanged();
notifyObservers();
}
} | Adds the given window to the set of windows managed by this window
manager. Does nothing is this window is already managed by this window
manager.
@param window
the window |
private void addWindowManager(WindowManager wm) {
if (subManagers == null) {
subManagers = new ArrayList();
}
if (!subManagers.contains(wm)) {
subManagers.add(wm);
wm.parentManager = this;
}
} | Adds the given window manager to the list of window managers that have
this one as a parent.
@param wm
the child window manager |
public boolean close() {
List t = (List)((ArrayList)windows).clone();
Iterator e = t.iterator();
while (e.hasNext()) {
ApplicationWindow window = (ApplicationWindow)e.next();
if (!window.close()) { return false; }
}
if (subManagers != null) {
e = subManagers.iterator();
while (e.hasNext()) {
WindowManager wm = (WindowManager)e.next();
if (!wm.close()) { return false; }
}
}
return true;
} | Attempts to close all windows managed by this window manager, as well as
windows managed by any descendent window managers.
@return <code>true</code> if all windows were sucessfully closed, and
<code>false</code> if any window refused to close |
public ApplicationWindow[] getWindows() {
ApplicationWindow managed[] = new ApplicationWindow[windows.size()];
windows.toArray(managed);
return managed;
} | Returns this window manager's set of windows.
@return a possibly empty list of window |
public final void remove(ApplicationWindow window) {
if (windows.contains(window)) {
windows.remove(window);
window.setWindowManager(null);
setChanged();
notifyObservers();
}
} | Removes the given window from the set of windows managed by this window
manager. Does nothing is this window is not managed by this window
manager.
@param window
the window |
public final void setActiveWindow(ApplicationWindow window)
{
final ApplicationWindow old = this.activeWindow;
this.activeWindow = window;
if (getParent() != null) // let things ripple up
getParent().setActiveWindow(window);
getChangeSupport().firePropertyChange("activeWindow", old, window);
} | Set the currently active window. When a window gets focus, it will set itself
as the current window of it's manager.
@param window |
public final FormComponentInterceptor getInterceptor( FormModel formModel ) {
// if excludedFormModelIds have been specified, use this to check if the
// form is excluded
if( excludedFormModelIds != null && Arrays.asList(excludedFormModelIds).contains( formModel.getId() ) ) {
return null;
}
// if includedFormModelIds have been specified, use this to check if the
// form is included
if( includedFormModelIds != null && !Arrays.asList( includedFormModelIds ).contains( formModel.getId() ) ) {
return null;
}
// if we fall through, create an interceptor
return createInterceptor( formModel );
} | Returns a <code>FormComponentInterceptor</code> for the given
<code>FormModel</code>. Checks against the included and excluded
<code>FormModel</code> ids.
<p>
If the excluded ids are specified and contain the given form model, returns
<code>null</code>. <br>
If the included ids are specified and don't contain the given form model, returns
<code>null</code>. <br>
@param formModel the <code>FormModel</code>
@return a <code>FormComponentInterceptor</code> for the given
<code>FormModel</code> |
@Override
public void onPreWindowOpen(ApplicationWindowConfigurer configurer) {
configurer.setTitle(application.getName());
configurer.setImage(application.getImage());
} | Hook called right before the application opens a window.
@param configurer |
public final void run(Closure templateCallback) {
reset();
setRunning();
doSetup();
while (processing()) {
templateCallback.call(doWork());
}
setCompleted();
doCleanup();
} | {@inheritDoc}
Defines the workflow sequence. |
public Object findFirst(Collection collection, Constraint constraint) {
return findFirst(collection.iterator(), constraint);
} | Find the first element in the collection matching the specified
constraint.
@param collection the collection
@param constraint the predicate
@return The first object match, or null if no match |
public Object findFirst(Iterator it, Constraint constraint) {
return new IteratorTemplate(it).findFirst(constraint);
} | Find the first element in the collection matching the specified
constraint.
@param it the iterator
@param constraint the predicate
@return The first object match, or null if no match |
public Collection findAll(Collection collection, Constraint constraint) {
return findAll(collection.iterator(), constraint);
} | Find all the elements in the collection that match the specified
constraint.
@param collection
@param constraint
@return The objects that match, or a empty collection if none match |
public Collection findAll(Iterator it, Constraint constraint) {
ElementGenerator finder = new IteratorTemplate(it).findAll(constraint);
final Collection results = new ArrayList();
finder.run(new Block() {
protected void handle(Object element) {
results.add(element);
}
});
return results;
} | Find all the elements in the collection that match the specified
constraint.
@param it the iterator
@param constraint the constraint
@return The objects that match, or a empty collection if none match |
private static Class getGenericParameterType(MethodParameter methodParam, int typeIndex) {
return toClass(extractType(methodParam, getTargetType(methodParam), typeIndex, methodParam.getNestingLevel()));
} | Extract the generic parameter type from the given method or constructor.
@param methodParam the method parameter specification
@param typeIndex the index of the type (e.g. 0 for Collections,
0 for Map keys, 1 for Map values)
@return the generic type, or <code>null</code> if none |
private static Class getSourceClass(Type type) {
Class sourceClass = toClass(type);
if (Collection.class.isAssignableFrom(sourceClass)) {
return Collection.class;
}
else if (Map.class.isAssignableFrom(sourceClass)) {
return Map.class;
}
else {
return sourceClass;
}
} | Returns the source class for the specified type.
This is either <code>Collection.class</code> or <code>Map.class</code>.
If none of both matches the baseclass of the specified type is returned.
@param type the type to determine the source class for
@return the source class |
private static Class getGenericFieldType(Field field, int typeIndex, int nestingLevel) {
return toClass(extractType(null, field.getGenericType(), typeIndex, nestingLevel));
} | Extract the generic type from the given field.
@param field the field to check the type for
@param typeIndex the index of the type (e.g. 0 for Collections,
0 for Map keys, 1 for Map values)
@param nestingLevel the nesting level of the target type
@return the generic type, or <code>null</code> if none |
public Object set(int index, Object element) {
Object oldObject = items.set(index, element);
if (hasChanged(oldObject, element)) {
fireContentsChanged(index);
}
return oldObject;
} | Set the value of a list element at the specified index.
@param index of element to set
@param element New element value
@return old element value |
public boolean replaceWith(Collection collection) {
boolean changed = false;
if (items.size() > 0) {
items.clear();
changed = true;
}
if (items.addAll(0, collection) && !changed) {
changed = true;
}
if (changed) {
fireContentsChanged(-1, -1);
}
return changed;
} | Replace this list model's items with the contents of the provided
collection.
@param collection
The collection to replace with |
public static TableFormat makeTableFormat(final TableDescription desc)
{
return new AdvancedWritableTableFormat()
{
public Class getColumnClass(int i)
{
return desc.getType(i);
}
public Comparator getColumnComparator(int i)
{
Comparator comp = desc.getColumnComparator(i);
if (comp != null)
return comp;
Class type = getColumnClass(i);
if (Boolean.class.isAssignableFrom(type) || Boolean.TYPE.isAssignableFrom(type))
return GlazedLists.booleanComparator();
else if (String.class.isAssignableFrom(type))
return getLowerCaseStringComparator();
else if(Comparable.class.isAssignableFrom(type))
return GlazedLists.comparableComparator();
else
return null;
}
public int getColumnCount()
{
return desc.getColumnCount();
}
public String getColumnName(int i)
{
return desc.getHeader(i);
}
public Object getColumnValue(Object obj, int i)
{
return desc.getValue(obj, i);
}
public boolean isEditable(Object baseObject, int column)
{
return desc.getColumnEditor(column) != null;
}
public Object setColumnValue(Object baseObject, Object editedValue, int column)
{
desc.setValue(baseObject, column, editedValue);
return baseObject;
}
};
} | Conversion of RCP TableDescription to GlazedLists TableFormat
@param desc
@return AdvancedWritableTableFormat |
public ValidationResults validate(T object, String propertyName) {
if (propertyName == null) {
results.clearMessages();
}
else {
results.clearMessages(propertyName);
}
addInvalidValues(doValidate(object, propertyName));
return results;
} | {@inheritDoc} |
protected void addInvalidValues(Set<ConstraintViolation<T>> invalidValues) {
if (invalidValues != null) {
for (ConstraintViolation invalidValue : invalidValues) {
results.addMessage(translateMessage(invalidValue));
}
}
} | Add all {@link ConstraintViolation}s to the {@link ValidationResults}. |
protected ValidationMessage translateMessage(ConstraintViolation invalidValue) {
return new DefaultValidationMessage(invalidValue.getPropertyPath().toString(), Severity.ERROR,
resolveObjectName(invalidValue.getPropertyPath().toString()) + " " + invalidValue.getMessage());
} | Translate a single {@link ConstraintViolation} to a {@link ValidationMessage}. |
protected Set<ConstraintViolation<T>> doValidate(final T object, final String property) {
if (property == null) {
final Set<ConstraintViolation<T>> ret = Sets.newHashSet();
PropertyDescriptor[] propertyDescriptors;
try {
propertyDescriptors = Introspector.getBeanInfo(object.getClass()).getPropertyDescriptors();
}
catch (IntrospectionException e) {
throw new IllegalStateException("Could not retrieve property information");
}
for (final PropertyDescriptor prop : propertyDescriptors) {
String propertyName = prop.getName();
if (formModel.hasValueModel(propertyName) && !ignoredProperties.contains(propertyName)) {
final Set<ConstraintViolation<T>> result = validator.validateValue(beanClass, propertyName, formModel
.getValueModel(propertyName).getValue()); //validator.validateProperty(object, propertyName);
if (result != null) {
ret.addAll(result);
}
}
}
return ret;
}
else if (!ignoredProperties.contains(property) && formModel.hasValueModel(property)) {
return validator.validateValue(beanClass, property, formModel
.getValueModel(property).getValue());
}
else {
return null;
}
} | Validates the object through Hibernate Validator
@param object The object that needs to be validated
@param property The properties that needs to be validated
@return An array of {@link ConstraintViolation}, containing all validation
errors |
public static <Q> Object getPropertyValue(Q bean, String propertyName) {
return ObjectUtils.getPropertyValue(bean, propertyName, Object.class);
} | Gets the value of a given property into a given bean.
@param <Q>
the bean type.
@param bean
the bean itself.
@param propertyName
the property name.
@return the property value.
@see #getPropertyValue(Object, String, Class) |
@SuppressWarnings("unchecked")
public static <T, Q> T getPropertyValue(Q bean, String propertyName, Class<T> propertyType) {
Assert.notNull(bean, "bean");
Assert.notNull(propertyName, "propertyName");
final PropertyAccessor propertyAccessor = PropertyAccessorFactory.forDirectFieldAccess(bean);
try {
Assert.isAssignable(propertyType, propertyAccessor.getPropertyType(propertyName));
} catch (InvalidPropertyException e) {
throw new IllegalStateException("Invalid property \"" + propertyName + "\"", e);
}
return (T) propertyAccessor.getPropertyValue(propertyName);
} | Gets the value of a given property into a given bean.
@param <T>
the property type.
@param <Q>
the bean type.
@param bean
the bean itself.
@param propertyName
the property name.
@param propertyType
the property type.
@return the property value.
@see PropertyAccessorFactory |
public static void shallowCopy(Object source, Object target) {
ObjectUtils.doShallowCopy(source, target, Boolean.TRUE);
} | Makes a shallow copy of the source object into the target one.
<p>
This method differs from {@link ReflectionUtils#shallowCopyFieldState(Object, Object)} this doesn't require
source and target objects to share the same class hierarchy.
@param source
the source object.
@param target
the target object. |
public static void shallowCopy(Object source, Object target, final String... propertyNames) {
ObjectUtils.doShallowCopy(source, target, Boolean.FALSE, propertyNames);
} | Makes a shallow copy of the source object into the target one excluding properties not in
<code>propertyNames</code>.
<p>
This method differs from {@link ReflectionUtils#shallowCopyFieldState(Object, Object)} this doesn't require
source and target objects to share the same class hierarchy.
@param source
the source object.
@param target
the target object.
@param propertyNames
the property names to be processed. Never mind if property names are invalid, in such a case are
ignored. |
public static Field[] getAllDeclaredFields(Class<?> leafClass) {
Assert.notNull(leafClass, "leafClass");
final List<Field> fields = new ArrayList<Field>(32);
ReflectionUtils.doWithFields(leafClass, new ReflectionUtils.FieldCallback() {
@Override
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
fields.add(field);
}
});
return fields.toArray(new Field[fields.size()]);
} | Get all declared fields on the leaf class and all superclasses. Leaf class methods are included first.
@param leafClass
the leaf class.
@return all declared fields.
@see ReflectionUtils#getAllDeclaredMethods(Class) since is the same approach as this one. |
public static <T> Boolean isEqualList(List<T> list1, List<T> list2) {
if (list1 == list2) {
return Boolean.TRUE;
} else if ((list1 == null) || (list2 == null) || (list1.size() != list2.size())) {
return Boolean.FALSE;
}
final Iterator<T> itr1 = list1.iterator();
final Iterator<T> itr2 = list2.iterator();
Object obj1 = null;
Object obj2 = null;
while (itr1.hasNext() && itr2.hasNext()) {
obj1 = itr1.next();
obj2 = itr2.next();
if (!(obj1 == null ? obj2 == null : Objects.equal(obj1, obj2))) {
return Boolean.FALSE;
}
}
return !(itr1.hasNext() || itr2.hasNext());
} | Method based on
{@link org.apache.commons.collections.ListUtils#isEqualList(java.util.Collection, java.util.Collection)} rewrote
for performance reasons.
<p>
Basically employs {@link ObjectUtils#equals(Object)} instead of {@link #equals(Object)} since the first
one checks identity before calling <code>equals</code>.
@param <T>
the type of the elements in the list.
@param list1
the first list, may be null
@param list2
the second list, may be null
@return whether the lists are equal by value comparison |
public static Object unwrapProxy(Object bean, Boolean recursive) {
Assert.notNull(recursive, "recursive");
Object unwrapped = bean;
// If the given object is a proxy, set the return value as the object being proxied, otherwise return the given
// object
if ((bean != null) && (bean instanceof Advised) && (AopUtils.isAopProxy(bean))) {
final Advised advised = (Advised) bean;
try {
final Object target = advised.getTargetSource().getTarget();
unwrapped = recursive ? ObjectUtils.unwrapProxy(target, recursive) : target;
} catch (Exception e) {
unwrapped = bean;
ObjectUtils.LOGGER.warn("Failure unwrapping \"" + bean + "\".", e);
}
}
return unwrapped;
} | This is a utility method for getting raw objects that may have been proxied. It is intended to be used in cases
where raw implementations are needed rather than working with interfaces which they implement.
@param bean
the potential proxy.
@param recursive
whether to procceeed recursively through nested proxies.
@return the unwrapped bean or <code>null</code> if target bean is <code>null</code>. If <code>recursive</code>
parameter is <code>true</code> then returns the most inner unwrapped bean, otherwise the nearest target
bean is returned.
Based on this <a href="http://forum.springsource.org/showthread.php?t=60216">Spring forum topic</a>.
@see Advised
@since 20101223 thanks to <a href="http://jirabluebell.b2b2000.com/browse/BLUE-34">BLUE-34</a> |
private static void doShallowCopy(Object source, Object target, final Boolean allProperties,
final String... propertyNames) {
Assert.notNull(source, "source");
Assert.notNull(target, "target");
Assert.notNull(allProperties, "allProperties");
Assert.notNull(propertyNames, "propertyNames");
final PropertyAccessor sourceAccessor = PropertyAccessorFactory.forDirectFieldAccess(source);
final PropertyAccessor targetAccessor = PropertyAccessorFactory.forDirectFieldAccess(target);
// Try to copy every property
ReflectionUtils.doWithFields(source.getClass(), new ReflectionUtils.FieldCallback() {
/**
* {@inheritDoc}
*/
@Override
public void doWith(Field field) { // throws IllegalArgumentException, IllegalAccessException {
final String fieldName = field.getName();
Boolean proceed = !Modifier.isFinal(field.getModifiers());
proceed &= (targetAccessor.isWritableProperty(fieldName));
proceed &= (allProperties | Arrays.asList(propertyNames).contains(fieldName));
if (proceed) {
final Object value = sourceAccessor.getPropertyValue(fieldName);
targetAccessor.setPropertyValue(fieldName, value);
}
}
});
} | Makes a shallow copy of the source object into the target one excluding properties not in
<code>propertyNames</code> unless <code>allProperties</code> is true.
<p>
This method differs from {@link ReflectionUtils#shallowCopyFieldState(Object, Object)} this doesn't require
source and target objects to share the same class hierarchy.
@param source
the source object.
@param target
the target object.
@param allProperties
if <code>true</code> then <code>propertyNames</code> will be ignored and all properties processed.
@param propertyNames
the property names to be processed. Never mind if property names are invalid, in such a case are
ignored. |
public static void mapObjectOnFormModel(FormModel formModel, Object objectToMap)
{
BeanWrapper beanWrapper = new BeanWrapperImpl(objectToMap);
for (String fieldName : (Set<String>) formModel.getFieldNames())
{
try
{
formModel.getValueModel(fieldName).setValue(beanWrapper.getPropertyValue(fieldName));
}
catch (BeansException be)
{
// silently ignoring, just mapping values, so if there's one missing, don't bother
}
}
} | This method tries to map the values of the given object on the valueModels of the formModel. Instead of
setting the object as a backing object, all valueModels are processed one by one and the corresponding
property value is fetched from the objectToMap and set on that valueModel. This triggers the usual
buffering etc. just as if the user entered the values.
@param formModel
@param objectToMap |
public final boolean hasAppropriateHandler(Throwable throwable) {
if (exceptionPurger != null && purgeOnAppropriateCheck) {
throwable = exceptionPurger.purge(throwable);
}
return hasAppropriateHandlerPurged(throwable);
} | {@inheritDoc} |
public final void uncaughtException(Thread thread, Throwable throwable) {
if (exceptionPurger != null && purgeOnHandling) {
throwable = exceptionPurger.purge(throwable);
}
uncaughtExceptionPurged(thread, throwable);
} | {@inheritDoc} |
@Override
protected final JLabel createMessageLabel() {
// Remember message label
final JLabel jLabel = super.createMessageLabel();
jLabel.setBorder(BorderFactory.createEmptyBorder());
this.setMessageLabel(jLabel);
return jLabel;
} | {@inheritDoc} |
protected JComponent createControl() {
super.createControl();
final JXStatusBar jxStatusBar = new JXStatusBar();
jxStatusBar.putClientProperty(BasicStatusBarUI.AUTO_ADD_SEPARATOR, false);
jxStatusBar.add(this.getMessageLabel(), JXStatusBar.Constraint.ResizeBehavior.FILL);
// jxStatusBar.add(new JSeparator(JSeparator.VERTICAL));
// jxStatusBar.add(new SubstanceSkinChooserComboBox().getControl());
// jxStatusBar.add(test.check.statusbar.FontSizePanel.getPanel());
jxStatusBar.add(((StatusBarProgressMonitor) this.getProgressMonitor()).getControl());
return jxStatusBar;
} | {@inheritDoc} |
public ApplicationPage createApplicationPage(ApplicationWindow window, PageDescriptor descriptor) {
if (reusePages) {
VLDockingApplicationPage page = findPage(window, descriptor);
if (page != null) {
return page;
}
}
VLDockingApplicationPage page = new VLDockingApplicationPage(window, descriptor);
if (reusePages) {
cachePage(page);
}
window.addPageListener(new PageListener() {
public void pageOpened(ApplicationPage page) {
// nothing to do here
}
public void pageClosed(ApplicationPage page) {
VLDockingApplicationPage vlDockingApplicationPage = (VLDockingApplicationPage) page;
saveDockingContext(vlDockingApplicationPage);
}
});
return page;
} | /*
(non-Javadoc)
@see org.springframework.richclient.application.ApplicationPageFactory#createApplicationPage(org.springframework.richclient.application.ApplicationWindow,
org.springframework.richclient.application.PageDescriptor) |
private void saveDockingContext(VLDockingApplicationPage dockingPage) {
DockingContext dockingContext = dockingPage.getDockingContext();
// Page descriptor needed for config path
VLDockingPageDescriptor vlDockingPageDescriptor = ValkyrieRepository.getInstance().getBean(dockingPage.getId(), VLDockingPageDescriptor.class);
// Write docking context to file
BufferedOutputStream buffOs = null;
try {
File desktopLayoutFile = vlDockingPageDescriptor.getInitialLayout().getFile();
checkForConfigPath(desktopLayoutFile);
buffOs = new BufferedOutputStream(new FileOutputStream(desktopLayoutFile));
dockingContext.writeXML(buffOs);
buffOs.close();
logger.debug("Wrote docking context to config file " + desktopLayoutFile);
}
catch (IOException e) {
logger.warn("Error writing VLDocking config", e);
}
finally {
try {
if(buffOs != null)
buffOs.close();
}
catch (Exception e) {
logger.debug("Error closing layoutfile", e);
}
}
} | Saves the docking layout of a docking page fo the application
@param dockingPage
The application window (needed to hook in for the docking context) |
private void checkForConfigPath(File configFile) {
String desktopLayoutFilePath = configFile.getAbsolutePath();
String configDirPath = desktopLayoutFilePath.substring(0, desktopLayoutFilePath.lastIndexOf(System
.getProperty("file.separator")));
File configDir = new File(configDirPath);
// create config dir if it does not exist
if (!configDir.exists()) {
boolean success = configDir.mkdirs();
if(success)
logger.debug("Newly created config directory");
else
logger.warn("Could not create config directory");
}
} | Creates the config directory, if it doesn't exist already
@param configFile
The file for which to create the path |
public void setCellRenderer(ListCellRenderer cellRenderer) {
// Apply this to both lists
sourceList.setCellRenderer(cellRenderer);
chosenList.setCellRenderer(cellRenderer);
helperList.setCellRenderer(cellRenderer);
} | Sets the delegate that's used to paint each cell in the list.
<p>
The default value of this property is provided by the ListUI delegate,
i.e. by the look and feel implementation.
<p>
@param cellRenderer the <code>ListCellRenderer</code> that paints list
cells
@see #getCellRenderer |
public void setModel(ListModel model) {
helperList.setModel(model);
dataModel = model;
clearSelection();
// Once we have a model, we can properly size the two display lists
// They should be wide enough to hold the widest string in the model.
// So take the width of the source list since it currently has all the
// data.
Dimension d = helperScroller.getPreferredSize();
chosenPanel.setPreferredSize(d);
sourcePanel.setPreferredSize(d);
} | Sets the model that represents the contents or "value" of the list and
clears the list selection.
@param model the <code>ListModel</code> that provides the list of items
for display
@exception IllegalArgumentException if <code>model</code> is
<code>null</code> |
public void setVisibleRowCount(int visibleRowCount) {
sourceList.setVisibleRowCount(visibleRowCount);
chosenList.setVisibleRowCount(visibleRowCount);
helperList.setVisibleRowCount(visibleRowCount);
// Ok, since we've haven't set a preferred size on the helper scroller,
// we can use it's current preferred size for our two control lists.
Dimension d = helperScroller.getPreferredSize();
chosenPanel.setPreferredSize(d);
sourcePanel.setPreferredSize(d);
} | Sets the preferred number of rows in the list that can be displayed
without a scrollbar.
@param visibleRowCount an integer specifying the preferred number of
visible rows |
public void setEditIcon(Icon editIcon, String text) {
if (editIcon != null) {
editButton.setIcon(editIcon);
if (text != null) {
editButton.setToolTipText(text);
}
editButton.setText("");
} else {
editButton.setIcon(null);
if (text != null) {
editButton.setText(text);
}
}
} | Set the icon to use on the edit button. If no icon is specified, then
just the label will be used otherwise the text will be a tooltip.
@param editIcon Icon to use on edit button |
public void setListLabels(String chosenLabel, String sourceLabel) {
if (chosenLabel != null) {
this.chosenLabel.setText(chosenLabel);
this.chosenLabel.setVisible(true);
} else {
this.chosenLabel.setVisible(false);
}
if (sourceLabel != null) {
this.sourceLabel.setText(sourceLabel);
this.sourceLabel.setVisible(true);
} else {
this.sourceLabel.setVisible(false);
}
Dimension d = chosenList.getPreferredSize();
Dimension d1 = this.chosenLabel.getPreferredSize();
Dimension dChosenPanel = chosenPanel.getPreferredSize();
dChosenPanel.width = Math.max(d.width, Math.max(dChosenPanel.width, d1.width));
chosenPanel.setPreferredSize(dChosenPanel);
Dimension dSourceList = sourceList.getPreferredSize();
Dimension dSource = this.sourceLabel.getPreferredSize();
Dimension dSourcePanel = sourcePanel.getPreferredSize();
dSourcePanel.width = Math.max(dSource.width, Math.max(dSourceList.width, dSourcePanel.width));
sourcePanel.setPreferredSize(dSourcePanel);
Dimension fullPanelSize = getPreferredSize();
fullPanelSize.width =
dSourcePanel.width + dChosenPanel.width + (editButton != null ? editButton.getPreferredSize().width : 0)
+ (buttonPanel != null ? buttonPanel.getPreferredSize().width : 0) + 20;
setPreferredSize(fullPanelSize);
} | Add labels on top of the 2 lists. If not present, do not show the labels.
@param chosenLabel
@param sourceLabel |
protected JComponent buildComponent() {
helperList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(gbl);
editButton = new JButton("Edit...");
editButton.setIconTextGap(0);
editButton.setMargin(new Insets(2, 4, 2, 4));
editButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
togglePanels();
}
});
gbc.fill = GridBagConstraints.NONE;
gbc.weightx = 0.0;
gbc.weighty = 0.0;
gbc.insets = new Insets(0, 0, 0, 3);
gbc.anchor = GridBagConstraints.NORTHWEST;
gbl.setConstraints(editButton, gbc);
add(editButton);
sourceList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
sourceList.addKeyListener(new KeyAdapter() {
public void keyPressed(final KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER || e.getKeyCode() == KeyEvent.VK_RIGHT) {
moveLeftToRight();
}
}
});
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
sourcePanel.add(BorderLayout.NORTH, sourceLabel);
JScrollPane sourceScroller = new JScrollPane(sourceList);
sourcePanel.add(BorderLayout.CENTER, sourceScroller);
gbl.setConstraints(sourcePanel, gbc);
add(sourcePanel);
// JPanel buttonPanel = new ControlButtonPanel();
JPanel buttonPanel = buildButtonPanel();
gbc.fill = GridBagConstraints.VERTICAL;
gbc.weightx = 0;
gbc.weighty = 1.0;
gbl.setConstraints(buttonPanel, gbc);
add(buttonPanel);
chosenList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
chosenList.addKeyListener(new KeyAdapter() {
public void keyPressed(final KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER || e.getKeyCode() == KeyEvent.VK_LEFT) {
moveRightToLeft();
}
}
});
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
chosenPanel.add(BorderLayout.NORTH, chosenLabel);
JScrollPane chosenScroller = new JScrollPane(chosenList);
chosenPanel.add(BorderLayout.CENTER, chosenScroller);
gbl.setConstraints(chosenPanel, gbc);
add(chosenPanel);
editButton.setVisible(showEditButton);
this.buttonPanel.setVisible(panelsShowing);
sourcePanel.setVisible(panelsShowing);
return this;
} | Build our component panel.
@return component |
protected JPanel buildButtonPanel() {
buttonPanel = new JPanel();
leftToRight = new JButton(">");
allLeftToRight = new JButton(">>");
rightToLeft = new JButton("<");
allRightToLeft = new JButton("<<");
Font smallerFont = leftToRight.getFont().deriveFont(9.0F);
leftToRight.setFont(smallerFont);
allLeftToRight.setFont(smallerFont);
rightToLeft.setFont(smallerFont);
allRightToLeft.setFont(smallerFont);
Insets margin = new Insets(2, 4, 2, 4);
leftToRight.setMargin(margin);
allLeftToRight.setMargin(margin);
rightToLeft.setMargin(margin);
allRightToLeft.setMargin(margin);
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
buttonPanel.setLayout(gbl);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbl.setConstraints(leftToRight, gbc);
gbl.setConstraints(allLeftToRight, gbc);
gbl.setConstraints(rightToLeft, gbc);
gbl.setConstraints(allRightToLeft, gbc);
buttonPanel.add(leftToRight);
buttonPanel.add(allLeftToRight);
buttonPanel.add(rightToLeft);
buttonPanel.add(allRightToLeft);
leftToRight.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
moveLeftToRight();
}
});
allLeftToRight.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
moveAllLeftToRight();
}
});
rightToLeft.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
moveRightToLeft();
}
});
allRightToLeft.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
moveAllRightToLeft();
}
});
buttonPanel.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
// buttonPanel.setBackground( Color.lightGray );
return buttonPanel;
} | Construct the control button panel.
@return JPanel |
protected void moveLeftToRight() {
// Loop over the selected items and locate them in the data model, Add
// these to the selection.
Object[] sourceSelected = sourceList.getSelectedValues();
int nSourceSelected = sourceSelected.length;
int[] currentSelection = helperList.getSelectedIndices();
int[] newSelection = new int[currentSelection.length + nSourceSelected];
System.arraycopy(currentSelection, 0, newSelection, 0, currentSelection.length);
int destPos = currentSelection.length;
for (int i = 0; i < sourceSelected.length; i++) {
newSelection[destPos++] = indexOf(sourceSelected[i]);
}
helperList.setSelectedIndices(newSelection);
update();
} | Move the selected items in the source list to the chosen list. I.e., add
the items to our selection model. |
protected void moveAllLeftToRight() {
int sz = dataModel.getSize();
int[] selected = new int[sz];
for (int i = 0; i < sz; i++) {
selected[i] = i;
}
helperList.setSelectedIndices(selected);
update();
} | Move all the source items to the chosen side. I.e., select all the items. |
protected void moveRightToLeft() {
Object[] chosenSelectedValues = chosenList.getSelectedValues();
int nChosenSelected = chosenSelectedValues.length;
int[] chosenSelected = new int[nChosenSelected];
if (nChosenSelected == 0) {
return; // Nothing to move
}
// Get our current selection
int[] currentSelected = helperList.getSelectedIndices();
int nCurrentSelected = currentSelected.length;
// Fill the chosenSelected array with the indices of the selected chosen
// items
for (int i = 0; i < nChosenSelected; i++) {
chosenSelected[i] = indexOf(chosenSelectedValues[i]);
}
// Construct the new selected indices. Loop through the current list
// and compare to the head of the chosen list. If not equal, then add
// to the new list. If equal, skip it and bump the head pointer on the
// chosen list.
int newSelection[] = new int[nCurrentSelected - nChosenSelected];
int newSelPos = 0;
int chosenPos = 0;
for (int i = 0; i < nCurrentSelected; i++) {
int currentIdx = currentSelected[i];
if (chosenPos < nChosenSelected && currentIdx == chosenSelected[chosenPos]) {
chosenPos += 1;
} else {
newSelection[newSelPos++] = currentIdx;
}
}
// Install the new selection
helperList.setSelectedIndices(newSelection);
update();
} | Move the selected items in the chosen list to the source list. I.e.,
remove them from our selection model. |
protected int indexOf(final Object o) {
final int size = dataModel.getSize();
for (int i = 0; i < size; i++) {
if (comparator == null) {
if (o.equals(dataModel.getElementAt(i))) {
return i;
}
} else if (comparator.compare(o, dataModel.getElementAt(i)) == 0) {
return i;
}
}
return -1;
} | Get the index of a given object in the underlying data model.
@param o Object to locate
@return index of object in model, -1 if not found |
protected void update() {
int sz = dataModel.getSize();
int[] selected = helperList.getSelectedIndices();
ArrayList sourceItems = new ArrayList(sz);
ArrayList chosenItems = new ArrayList(selected.length);
// Start with the source items filled from our data model
for (int i = 0; i < sz; i++) {
sourceItems.add(dataModel.getElementAt(i));
}
// Now move the selected items to the chosen list
for (int i = selected.length - 1; i >= 0; i--) {
chosenItems.add(sourceItems.remove(selected[i]));
}
Collections.reverse(chosenItems); // We built it backwards
// Now install the two new lists
sourceList.setListData(sourceItems.toArray());
chosenList.setListData(chosenItems.toArray());
} | Update the two lists based on the current selection indices. |
public E to(String to) {
if (isNotBlank(to)) {
to(to.split(";"));
} else {
addParameter("to", null);
}
return getThis();
} | 收件人地址. 发送多个地址支持调用该方法多次或使用';'分隔, 如 [email protected];[email protected]
@param to 收件人地址
@return E |
public E attachments(File[] attachments) {
for (File file : attachments) {
addBinaryAttachment(file);
}
return getThis();
} | 添加附件。附件名默认使用文件名
@param attachments 附件列表
@return |
public E attachment(File attachment, String name) {
addBinaryAttachment(attachment, name);
return getThis();
} | 添加附件
@param attachment 附件文件
@param name 附件名
@return E |
public E attachment(byte[] attachment, String name) {
attachments.put(name, attachment);
return getThis();
} | 添加附件
@param attachment 附件内容
@param name 附件名
@return E |
protected Object convertValue(Object value, Class targetClass) throws ConversionException {
Assert.notNull(value);
Assert.notNull(targetClass);
return getConversionService().getConversionExecutor(value.getClass(), targetClass).execute(value);
} | Converts the given object value into the given targetClass
@param value
the value to convert
@param targetClass
the target class to convert the value to
@return the converted value
@throws org.springframework.binding.convert.ConversionException
if the value can not be converted |
public final void setCommitTrigger(CommitTrigger commitTrigger) {
if (this.commitTrigger == commitTrigger) {
return;
}
if (this.commitTrigger != null) {
this.commitTrigger.removeCommitTriggerListener(commitTriggerHandler);
this.commitTrigger = null;
}
if (commitTrigger != null) {
if (this.commitTriggerHandler == null) {
this.commitTriggerHandler = new CommitTriggerHandler();
}
this.commitTrigger = commitTrigger;
this.commitTrigger.addCommitTriggerListener(commitTriggerHandler);
}
} | Sets the <code>CommitTrigger</code> that triggers the commit and flush events.
@param commitTrigger the commit trigger; or null to deregister the
existing trigger. |
public void setValue(Object value) {
if (logger.isDebugEnabled()) {
logger.debug("Setting buffered value to '" + value + "'");
}
final Object oldValue = getValue();
this.bufferedValue = value;
updateBuffering();
fireValueChange(oldValue, bufferedValue);
} | Sets a new buffered value and turns this BufferedValueModel into
the buffering state. The buffered value is not provided to the
underlying model until the trigger channel indicates a commit.
@param value the value to be buffered |
protected void onWrappedValueChanged() {
if (logger.isDebugEnabled()) {
logger.debug("Wrapped model value has changed; new value is '" + wrappedModel.getValue() + "'");
}
setValue(wrappedModel.getValue());
} | Called when the value held by the wrapped value model changes. |
public void commit() {
if (isBuffering()) {
if (logger.isDebugEnabled()) {
logger.debug("Committing buffered value '" + getValue() + "' to wrapped value model '" + wrappedModel
+ "'");
}
wrappedModel.setValueSilently(getValueToCommit(), wrappedModelChangeHandler);
setValue(wrappedModel.getValue()); // check if the wrapped model changed the committed value
}
else {
if (logger.isDebugEnabled()) {
logger.debug("No buffered edit to commit; nothing to do...");
}
}
} | Commits the value buffered by this value model back to the
wrapped value model. |
private void updateBuffering() {
boolean wasBuffering = isBuffering();
buffering = hasValueChanged(wrappedModel.getValue(), bufferedValue);
firePropertyChange(BUFFERING_PROPERTY, wasBuffering, buffering);
} | Updates the value of the buffering property. Fires a property change event
if there's been a change. |
public final void revert() {
if (isBuffering()) {
if (logger.isDebugEnabled()) {
logger.debug("Reverting buffered value '" + getValue() + "' to value '" + wrappedModel.getValue() + "'");
}
setValue(wrappedModel.getValue());
}
else {
if (logger.isDebugEnabled()) {
logger.debug("No buffered edit to commit; nothing to do...");
}
}
} | Reverts the value held by the value model back to the value held by the
wrapped value model. |
public static CommandButtonLabelInfo valueOf(String labelDescriptor) {
if (!StringUtils.hasText(labelDescriptor)) {
return BLANK_BUTTON_LABEL;
}
StringBuffer labelInfoBuffer = new StringBuffer();
char currentChar;
KeyStroke keyStroke = null;
for (int i = 0, textCharsIndex = 0; i < labelDescriptor.length(); i++, textCharsIndex++) {
currentChar = labelDescriptor.charAt(i);
if (currentChar == '\\') {
int nextCharIndex = i + 1;
//if this backslash is escaping an @ symbol, we remove the backslash and
//continue with the next char
if (nextCharIndex < labelDescriptor.length()) {
char nextChar = labelDescriptor.charAt(nextCharIndex);
if (nextChar == '@') {
labelInfoBuffer.append(nextChar);
i++;
} else {
labelInfoBuffer.append(currentChar);
labelInfoBuffer.append(nextChar);
i++;
}
}
}
else if (currentChar == '@') {
//we've found the accelerator indicator
if (i + 1 == labelDescriptor.length()) {
throw new IllegalArgumentException(
"The label descriptor ["
+ labelDescriptor
+ "] does not specify a valid accelerator after the last "
+ "non-espaced @ symbol.");
}
String acceleratorStr = labelDescriptor.substring(i + 1);
keyStroke = KeyStroke.getKeyStroke(acceleratorStr);
if (keyStroke == null) {
throw new IllegalArgumentException(
"The keystroke accelerator string ["
+ acceleratorStr
+ "] from the label descriptor ["
+ labelDescriptor
+ "] is not a valid keystroke format.");
}
break;
}
else {
labelInfoBuffer.append(currentChar);
}
}
LabelInfo info = LabelInfo.valueOf(labelInfoBuffer.toString());
return new CommandButtonLabelInfo(info, keyStroke);
} | Return an instance of this class, created by parsing the information in the given label
descriptor string. The expected format of this descriptor is the same as that used by
the {@link LabelInfo} class, with the following additions:
<ul>
<li>The @ symbol is an escapable character.</li>
<li>Everything after the first unescaped @ symbol will be treated as the textual representation
of the keystroke accelerator.</li>
</ul>
The expected format of the keystroke accelerator string is as described in the javadocs for the
{@link KeyStroke#getKeyStroke(String)} method.
@param labelDescriptor The label descriptor. May be null or empty, in which case, a default
blank label info will be returned.
@return A CommandButtonLabelInfo instance, never null.
@throws IllegalArgumentException if {@code labelDescriptor} contains invalid syntax.
@see LabelInfo
@see KeyStroke |
public AbstractButton configure(AbstractButton button) {
Assert.notNull(button);
button.setText(this.labelInfo.getText());
button.setMnemonic(this.labelInfo.getMnemonic());
button.setDisplayedMnemonicIndex(this.labelInfo.getMnemonicIndex());
configureAccelerator(button, getAccelerator());
return button;
} | Configures an existing button appropriately based on this label info's
properties.
@param button |
protected void configureAccelerator(AbstractButton button, KeyStroke keystrokeAccelerator) {
if ((button instanceof JMenuItem) && !(button instanceof JMenu)) {
((JMenuItem)button).setAccelerator(keystrokeAccelerator);
}
} | Sets the given keystroke accelerator on the given button.
@param button The button. May be null.
@param keystrokeAccelerator The accelerator. May be null. |
public JLabel createLabel(String labelKey) {
JLabel label = createNewLabel();
getLabelInfo(getRequiredMessage(labelKey)).configureLabel(label);
return label;
} | {@inheritDoc} |
protected String getRequiredMessage(final String[] messageKeys) {
MessageSourceResolvable resolvable = new MessageSourceResolvable() {
public String[] getCodes() {
return messageKeys;
}
public Object[] getArguments() {
return null;
}
public String getDefaultMessage() {
if (messageKeys.length > 0) {
return messageKeys[0];
}
return "";
}
};
return getMessages().getMessage(resolvable);
} | Get the message for the given key. Don't throw an exception if it's not
found but return a default value.
@param messageKeys The keys to use when looking for the message.
@return the message found in the resources or a default message. |
public JLabel createLabel(String labelKey, ValueModel[] argumentValueHolders) {
return new LabelTextRefresher(labelKey, argumentValueHolders).getLabel();
} | {@inheritDoc} |
public JRadioButton createRadioButton(String labelKey) {
return (JRadioButton) getButtonLabelInfo(getRequiredMessage(labelKey)).configure(createNewRadioButton());
} | /*
(non-Javadoc)
@see org.springframework.richclient.factory.ComponentFactory#createRadioButton(java.lang.String) |
public JTable createTable(TableModel model) {
return (getTableFactory() != null) ? getTableFactory().createTable(model) : new JTable(model);
} | Construct a JTable with the specified table model. It will delegate the
creation to a TableFactory if it exists.
@param model the table model
@return The new table. |
public JComponent createToolBar() {
JToolBar toolBar = new JToolBar();
toolBar.setFloatable(false);
toolBar.setRollover(true);
return toolBar;
} | {@inheritDoc} |
private String[] createLabels(final String id, final Object[] keys)
{
String[] messages = new String[keys.length];
for (int i = 0; i < messages.length; ++i)
{
messages[i] = getApplicationConfig().messageResolver().getMessage(id, keys[i] == null ? "null" : keys[i].toString(),
"label");
}
return messages;
} | Will resolve keys to messages using 'id'.'key'.label as a message
resource key.
@param id
id to use with message key resolving.
@param keys
keys to extract messages from.
@return array containing labels/messages for each key. |
public static Collection getLabelsFromMap(Collection sortedKeys, Map keysAndLabels)
{
Collection<Object> labels = new ArrayList<Object>();
Iterator keyIt = sortedKeys.iterator();
while (keyIt.hasNext())
{
labels.add(keysAndLabels.get(keyIt.next()));
}
return labels;
} | Will extract labels from a map in sorted order.
@param sortedKeys
collection with keys in the appropriate order. Each key
corresponds to one in the map.
@param keysAndLabels
map containing both, keys and labels, from which the labels
have to be extracted.
@return a collection containing the labels corresponding to the
collection of sortedKeys. |
protected void selectItem(Object item)
{
if (this.selectionListLabelMessages != null && this.selectionListLabelMessages.length > 0)
{
int itemIndex = search(this.selectionListKeys, item);
if (itemIndex > -1) // item found in list (may/can be null)
{
settingValueModel = true;
this.combobox.setSelectedItem(this.selectionListLabelMessages[itemIndex]);
settingValueModel = false;
}
else
// newValue not in list, select defaultIndex or nothing
{
this.combobox.setSelectedIndex(getDefaultKeyIndex());
}
}
} | Selects the given item in the current selectionList of the comboBoxModel.
When the item doesn't map to an entry in the comboBoxModel, select a
default one. See {@link #getDefaultKeyIndex()} and
{@link #setDefaultKeyIndex(int)} for default.
@param item
object that needs to be selected in the comboBox. |
private int search(Object[] keys, Object toFind)
{
for (int i = 0; i < keys.length; ++i)
{
if (toFind == null)
{
if (keys[i] == null)
return i;
}
else if (toFind.equals(keys[i]))
return i;
}
return -1; // niets gevonden
} | Arrays.binarySearch(..) does exist in java, but assumes that array is
sorted, we don't have this restriction so dumb search from first to
last...
@param keys
@param toFind
@return |
public final void setSelectionList(Object[] keys, Object[] labels)
{
selectionListKeys = keys;
selectionListLabelMessages = createLabels(getId(), labels);
combobox.setModel(new DefaultComboBoxModel(selectionListLabelMessages));
selectItem(getValue());
} | Replace the comboBoxModel in order to use the new keys/labels.
@param keys
array of objects to use as keys.
@param labels
array of objects to use as labels in the comboBox. |
@VisibleForTesting
static String constructCounterShardIdentifier(final String counterName, final int shardNumber)
{
Preconditions.checkNotNull(counterName);
Preconditions.checkArgument(!StringUtils.isBlank(counterName),
"CounterData Names may not be null, blank, or empty!");
Preconditions.checkArgument(shardNumber >= 0, "shardNumber must be greater than or equal to 0!");
return counterName + COUNTER_SHARD_KEY_SEPARATOR + shardNumber;
} | Helper method to set the internal identifier for this entity.
@param counterName
@param shardNumber A unique identifier to distinguish shards for the same {@code counterName} from each other. |
public static Key<CounterShardData> key(final Key<CounterData> counterDataKey, final int shardNumber)
{
// Preconditions checked by #constructCounterShardIdentifier
return Key.create(CounterShardData.class,
constructCounterShardIdentifier(counterDataKey.getName(), shardNumber));
} | Create a {@link Key Key<CounterShardData>}. Keys for this entity are not "parented" so that they can be added
under high volume load in a given application. Note that CounterData will be in a namespace specific.
@param counterDataKey
@param shardNumber
@return |
public static Integer computeShardIndex(final Key<CounterShardData> counterShardDataKey) {
Preconditions.checkNotNull(counterShardDataKey);
final String key = counterShardDataKey.getName();
int lastDashIndex = key.lastIndexOf("-");
final String shardIndexAsString = key.substring((lastDashIndex + 1), key.length());
return Integer.valueOf(shardIndexAsString);
} | Helper method to compute the shard number index from an instance of {@link Key} of type {@link CounterShardData}.
This method assumes that the "name" field of a counter shard key will end in a dash, followed by the shard
index.
@param counterShardDataKey
@return |
public Object call(Object value) {
if (value == null) { return new Integer(0); }
return new Integer(String.valueOf(value).length());
} | Evaluate the string form of the object returning an Integer representing
the string length.
@return The string length Integer.
@see Closure#call(java.lang.Object) |
public void addRules(Rules rules) {
if (logger.isDebugEnabled()) {
logger.debug("Adding rules -> " + rules);
}
addRules(DEFAULT_CONTEXT_ID, rules);
} | Add or update the rules for a single bean class.
@param rules
The rules. |
public void setRules(List rules) {
Assert.notNull(rules);
if (logger.isDebugEnabled()) {
logger.debug("Configuring rules in source...");
}
getRuleContext(DEFAULT_CONTEXT_ID).clear();
for (Iterator i = rules.iterator(); i.hasNext();) {
addRules((Rules) i.next());
}
} | Set the list of rules retrievable by this source, where each item in the list is a <code>Rules</code> object
which maintains validation rules for a bean class.
@param rules
The list of rules. |
public static String getParentPropertyPath(String propertyPath) {
int propertySeparatorIndex = getLastNestedPropertySeparatorIndex(propertyPath);
return propertySeparatorIndex == -1? "": propertyPath.substring(0, propertySeparatorIndex);
} | Returns the path to the parent component of the provided property path. |
public static String getPropertyName(String propertyPath) {
int propertySeparatorIndex = PropertyAccessorUtils.getLastNestedPropertySeparatorIndex(propertyPath);
return propertySeparatorIndex == -1? propertyPath: propertyPath.substring(propertySeparatorIndex + 1);
} | Returns the last component of the specified property path |
public static boolean isIndexedProperty(String propertyName) {
return propertyName.indexOf(PropertyAccessor.PROPERTY_KEY_PREFIX_CHAR) != -1
&& propertyName.charAt(propertyName.length() - 1) == PropertyAccessor.PROPERTY_KEY_SUFFIX_CHAR;
} | Tests whether the specified property path denotes an indexed property. |
public void refresh() {
if (logger.isDebugEnabled()) {
logger.debug("Refreshing held value '"
+ StylerUtils.style(super.getValue()) + "'");
}
setValue(refreshFunction.call(null));
} | Refresh te value by executing the refresh <code>Closure</code>. |
public PropertyConstraint ifTrue(PropertyConstraint ifConstraint, PropertyConstraint thenConstraint, String type) {
return new ConditionalPropertyConstraint(ifConstraint, thenConstraint, type);
} | Returns a ConditionalPropertyConstraint: one property will trigger the
validation of another.
@see ConditionalPropertyConstraint |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.