List of usage examples for java.beans PropertyEditor setValue
void setValue(Object value);
From source file:org.lnicholls.galleon.gui.HMEConfigurationPanel.java
public HMEConfigurationPanel(Object bean) { setLayout(new GridLayout(0, 1)); target = bean;/* ww w .j ava2 s . co m*/ try { BeanInfo bi = Introspector.getBeanInfo(target.getClass()); properties = bi.getPropertyDescriptors(); } catch (IntrospectionException ex) { Tools.logException(HMEConfigurationPanel.class, ex, "PropertySheet: Couldn't introspect"); return; } editors = new PropertyEditor[properties.length]; values = new Object[properties.length]; views = new Component[properties.length]; labels = new JLabel[properties.length]; for (int i = 0; i < properties.length; i++) { // Don't display hidden or expert properties. if (properties[i].isHidden() || properties[i].isExpert()) { continue; } String name = properties[i].getDisplayName(); Class type = properties[i].getPropertyType(); Method getter = properties[i].getReadMethod(); Method setter = properties[i].getWriteMethod(); // Only display read/write properties. if (getter == null || setter == null) { continue; } Component view = null; try { Object args[] = {}; Object value = getter.invoke(target, args); values[i] = value; PropertyEditor editor = null; Class pec = properties[i].getPropertyEditorClass(); if (pec != null) { try { editor = (PropertyEditor) pec.newInstance(); } catch (Exception ex) { // Drop through. } } if (editor == null) { editor = PropertyEditorManager.findEditor(type); } editors[i] = editor; // If we can't edit this component, skip it. if (editor == null) { // If it's a user-defined property we give a warning. String getterClass = properties[i].getReadMethod().getDeclaringClass().getName(); if (getterClass.indexOf("java.") != 0) { log.error("Warning: Can't find public property editor for property \"" + name + "\". Skipping."); } continue; } // Don't try to set null values: if (value == null) { // If it's a user-defined property we give a warning. String getterClass = properties[i].getReadMethod().getDeclaringClass().getName(); if (getterClass.indexOf("java.") != 0) { log.error("Warning: Property \"" + name + "\" has null initial value. Skipping."); } continue; } editor.setValue(value); // editor.addPropertyChangeListener(adaptor); // Now figure out how to display it... if (editor.isPaintable() && editor.supportsCustomEditor()) { view = new PropertyCanvas(frame, editor); } else if (editor.getTags() != null) { view = new PropertySelector(editor); } else if (editor.getAsText() != null) { String init = editor.getAsText(); view = new PropertyText(editor); } else { log.error("Warning: Property \"" + name + "\" has non-displayabale editor. Skipping."); continue; } } catch (InvocationTargetException ex) { Tools.logException(HMEConfigurationPanel.class, ex.getTargetException(), "Skipping property " + name); continue; } catch (Exception ex) { Tools.logException(HMEConfigurationPanel.class, ex, "Skipping property " + name); continue; } labels[i] = new JLabel(WordUtils.capitalize(name), JLabel.RIGHT); // add(labels[i]); views[i] = view; // add(views[i]); } int validCounter = 0; for (int i = 0; i < labels.length; i++) { if (labels[i] != null) validCounter++; } String rowStrings = ""; // general if (validCounter > 0) rowStrings = "pref, "; else rowStrings = "pref"; int counter = 0; for (int i = 0; i < labels.length; i++) { if (labels[i] != null) { if (++counter == (validCounter)) rowStrings = rowStrings + "9dlu, " + "pref"; else rowStrings = rowStrings + "9dlu, " + "pref, "; } } FormLayout layout = new FormLayout("right:pref, 3dlu, 50dlu:g, right:pref:grow", rowStrings); PanelBuilder builder = new PanelBuilder(layout); //DefaultFormBuilder builder = new DefaultFormBuilder(new FormDebugPanel(), layout); builder.setDefaultDialogBorder(); CellConstraints cc = new CellConstraints(); builder.addSeparator("General", cc.xyw(1, 1, 4)); counter = 0; for (int i = 0; i < labels.length; i++) { if (labels[i] != null) { counter++; builder.add(labels[i], cc.xy(1, counter * 2 + 1)); builder.add(views[i], cc.xy(3, counter * 2 + 1)); } } JPanel panel = builder.getPanel(); //FormDebugUtils.dumpAll(panel); add(panel); }
From source file:org.nextframework.controller.ExtendedBeanWrapper.java
/** * Convert the value to the required type (if necessary from a String), * for the specified property.//from www . j a v a 2 s .c o m * @param propertyName name of the property * @param oldValue previous value, if available (may be <code>null</code>) * @param newValue proposed change value * @param requiredType the type we must convert to * (or <code>null</code> if not known, for example in case of a collection element) * @return the new value, possibly the result of type conversion * @throws TypeMismatchException if type conversion failed */ protected Object doTypeConversionIfNecessary(String propertyName, String fullPropertyName, Object oldValue, Object newValue, Class requiredType) throws TypeMismatchException { Object convertedValue = newValue; if (convertedValue != null) { // Custom editor for this type? PropertyEditor pe = findCustomEditor(requiredType, fullPropertyName); // Value not of required type? if (pe != null || (requiredType != null && (requiredType.isArray() || !requiredType.isAssignableFrom(convertedValue.getClass())))) { if (requiredType != null) { if (pe == null) { // No custom editor -> check BeanWrapperImpl's default editors. pe = (PropertyEditor) this.defaultEditors.get(requiredType); if (pe == null) { // No BeanWrapper default editor -> check standard JavaBean editors. pe = PropertyEditorManager.findEditor(requiredType); } } } if (pe != null && !(convertedValue instanceof String)) { // Not a String -> use PropertyEditor's setValue. // With standard PropertyEditors, this will return the very same object; // we just want to allow special PropertyEditors to override setValue // for type conversion from non-String values to the required type. try { pe.setValue(convertedValue); Object newConvertedValue = pe.getValue(); if (newConvertedValue != convertedValue) { convertedValue = newConvertedValue; // Reset PropertyEditor: It already did a proper conversion. // Don't use it again for a setAsText call. pe = null; } } catch (IllegalArgumentException ex) { throw new TypeMismatchException( createPropertyChangeEvent(fullPropertyName, oldValue, newValue), requiredType, ex); } } if (requiredType != null && !requiredType.isArray() && convertedValue instanceof String[]) { // Convert String array to a comma-separated String. // Only applies if no PropertyEditor converted the String array before. // The CSV String will be passed into a PropertyEditor's setAsText method, if any. if (logger.isDebugEnabled()) { logger.debug("Converting String array to comma-delimited String [" + convertedValue + "]"); } convertedValue = StringUtils.arrayToCommaDelimitedString((String[]) convertedValue); } if (pe != null && convertedValue instanceof String) { // Use PropertyEditor's setAsText in case of a String value. if (logger.isDebugEnabled()) { logger.debug( "Converting String to [" + requiredType + "] using property editor [" + pe + "]"); } try { pe.setValue(oldValue); pe.setAsText((String) convertedValue); convertedValue = pe.getValue(); } catch (IllegalArgumentException ex) { throw new TypeMismatchException( createPropertyChangeEvent(fullPropertyName, oldValue, newValue), requiredType, ex); } } if (requiredType != null) { // Array required -> apply appropriate conversion of elements. if (requiredType.isArray()) { Class componentType = requiredType.getComponentType(); if (convertedValue instanceof Collection) { // Convert Collection elements to array elements. Collection coll = (Collection) convertedValue; Object result = Array.newInstance(componentType, coll.size()); int i = 0; for (Iterator it = coll.iterator(); it.hasNext(); i++) { Object value = doTypeConversionIfNecessary(propertyName, propertyName + PROPERTY_KEY_PREFIX + i + PROPERTY_KEY_SUFFIX, null, it.next(), componentType); Array.set(result, i, value); } return result; } else if (convertedValue != null && convertedValue.getClass().isArray()) { // Convert Collection elements to array elements. int arrayLength = Array.getLength(convertedValue); Object result = Array.newInstance(componentType, arrayLength); for (int i = 0; i < arrayLength; i++) { Object value = doTypeConversionIfNecessary(propertyName, propertyName + PROPERTY_KEY_PREFIX + i + PROPERTY_KEY_SUFFIX, null, Array.get(convertedValue, i), componentType); Array.set(result, i, value); } return result; } else { // A plain value: convert it to an array with a single component. Object result = Array.newInstance(componentType, 1); Object value = doTypeConversionIfNecessary(propertyName, propertyName + PROPERTY_KEY_PREFIX + 0 + PROPERTY_KEY_SUFFIX, null, convertedValue, componentType); Array.set(result, 0, value); return result; } } // If the resulting value definitely doesn't match the required type, // try field lookup as fallback. If no matching field found, // throw explicit TypeMismatchException with full context information. if (convertedValue != null && !requiredType.isPrimitive() && !requiredType.isAssignableFrom(convertedValue.getClass())) { // In case of String value, try to find matching field (for JDK 1.5 // enum or custom enum with values defined as static fields). if (convertedValue instanceof String) { try { Field enumField = requiredType.getField((String) convertedValue); return enumField.get(null); } catch (Exception ex) { logger.debug("Field [" + convertedValue + "] isn't an enum value", ex); } } // Definitely doesn't match: throw TypeMismatchException. throw new TypeMismatchException( createPropertyChangeEvent(fullPropertyName, oldValue, newValue), requiredType); } } } } if (requiredType != null && List.class.isAssignableFrom(requiredType)) { //treat conventions of enum lists Type genericReturnType = getPropertyDescriptorInternal(fullPropertyName).getReadMethod() .getGenericReturnType(); if (genericReturnType instanceof ParameterizedType) { Type actualType = ((ParameterizedType) genericReturnType).getActualTypeArguments()[0]; if (actualType instanceof Class && convertedValue != null) { List list = (List) convertedValue; for (int i = 0; i < list.size(); i++) { Object o = list.remove(i); o = doTypeConversionIfNecessary(o, (Class) actualType); list.add(i, o); } } } } return convertedValue; }
From source file:org.pentaho.reporting.engine.classic.core.modules.output.pageable.xml.internal.XmlDocumentWriter.java
private void writeElementAttributes(final RenderNode element) throws IOException { final ReportAttributeMap attributes = element.getAttributes(); final ElementType type = element.getElementType(); final Set<AttributeMap.DualKey> collection = attributes.keySet(); final AttributeMap.DualKey[] attributeNames = collection .toArray(new AttributeMap.DualKey[collection.size()]); Arrays.sort(attributeNames, new DualKeySorter()); for (int j = 0; j < attributeNames.length; j++) { final String namespace = attributeNames[j].namespace; if (AttributeNames.Designtime.NAMESPACE.equals(namespace)) { continue; }// w ww.ja v a2 s . c o m final String name = attributeNames[j].name; final Object value = attributes.getAttribute(namespace, name); if (value == null) { continue; } if (metaData.isFeatureSupported(XmlPageOutputProcessorMetaData.WRITE_RESOURCEKEYS) == false && value instanceof ResourceKey) { continue; } final AttributeMetaData attrMeta = type.getMetaData().getAttributeDescription(namespace, name); if (attrMeta == null) { // if you want to use attributes in this output target, declare the attribute's metadata first. continue; } final AttributeList attList = new AttributeList(); if (value instanceof String) { final String s = (String) value; if (StringUtils.isEmpty(s)) { continue; } if (xmlWriter.isNamespaceDefined(namespace) == false && attList.isNamespaceUriDefined(namespace) == false) { attList.addNamespaceDeclaration("autoGenNs", namespace); } // preserve strings, but discard anything else. Until a attribute has a definition, we cannot // hope to understand the attribute's value. String-attributes can be expressed in XML easily, // and string is also how all unknown attributes are stored by the parser. attList.setAttribute(namespace, name, String.valueOf(value)); this.xmlWriter.writeTag(XmlDocumentWriter.LAYOUT_OUTPUT_NAMESPACE, "attribute", attList, XmlWriter.CLOSE); continue; } if (xmlWriter.isNamespaceDefined(namespace) == false && attList.isNamespaceUriDefined(namespace) == false) { attList.addNamespaceDeclaration("autoGenNs", namespace); } try { final PropertyEditor propertyEditor = attrMeta.getEditor(); final String textValue; if (propertyEditor != null) { propertyEditor.setValue(value); textValue = propertyEditor.getAsText(); } else { textValue = ConverterRegistry.toAttributeValue(value); } if (textValue != null) { if ("".equals(textValue) == false) { attList.setAttribute(namespace, name, textValue); this.xmlWriter.writeTag(XmlDocumentWriter.LAYOUT_OUTPUT_NAMESPACE, "attribute", attList, XmlWriter.CLOSE); } } else { if (value instanceof ResourceKey) { final ResourceKey reskey = (ResourceKey) value; final String identifierAsString = reskey.getIdentifierAsString(); attList.setAttribute(namespace, name, "resource-key:" + reskey.getSchema() + ":" + identifierAsString); this.xmlWriter.writeTag(XmlDocumentWriter.LAYOUT_OUTPUT_NAMESPACE, "attribute", attList, XmlWriter.CLOSE); } else { XmlDocumentWriter.logger.debug("Attribute '" + namespace + '|' + name + "' is not convertible to a text - returned null: " + value); } } } catch (BeanException e) { if (attrMeta.isTransient() == false) { XmlDocumentWriter.logger.warn( "Attribute '" + namespace + '|' + name + "' is not convertible with the bean-methods"); } else { XmlDocumentWriter.logger.debug( "Attribute '" + namespace + '|' + name + "' is not convertible with the bean-methods"); } } } }
From source file:org.pentaho.reporting.engine.classic.core.modules.output.table.xml.internal.XmlDocumentWriter.java
private void writeAttributes(final ReportAttributeMap attributes, ElementType type) throws IOException { if (type == null) { type = AutoLayoutBoxType.INSTANCE; }//from ww w . ja va2 s. c o m final Set<AttributeMap.DualKey> collection = attributes.keySet(); final AttributeMap.DualKey[] attributeNames = collection .toArray(new AttributeMap.DualKey[collection.size()]); Arrays.sort(attributeNames, new DualKeySorter()); for (int j = 0; j < attributeNames.length; j++) { final String namespace = attributeNames[j].namespace; if (AttributeNames.Designtime.NAMESPACE.equals(namespace)) { continue; } final String name = attributeNames[j].name; final Object value = attributes.getAttribute(namespace, name); if (value == null) { continue; } if (metaData.isFeatureSupported(XmlTableOutputProcessorMetaData.WRITE_RESOURCEKEYS) == false && value instanceof ResourceKey) { continue; } final AttributeMetaData attrMeta = type.getMetaData().getAttributeDescription(namespace, name); if (attrMeta == null) { // if you want to use attributes in this output target, declare the attribute's metadata first. continue; } final AttributeList attList = new AttributeList(); if (value instanceof String) { final String s = (String) value; if (StringUtils.isEmpty(s)) { continue; } if (xmlWriter.isNamespaceDefined(namespace) == false && attList.isNamespaceUriDefined(namespace) == false) { attList.addNamespaceDeclaration("autoGenNs", namespace); } // preserve strings, but discard anything else. Until a attribute has a definition, we cannot // hope to understand the attribute's value. String-attributes can be expressed in XML easily, // and string is also how all unknown attributes are stored by the parser. attList.setAttribute(namespace, name, s); this.xmlWriter.writeTag(XmlDocumentWriter.LAYOUT_OUTPUT_NAMESPACE, "attribute", attList, XmlWriter.CLOSE); continue; } if (xmlWriter.isNamespaceDefined(namespace) == false && attList.isNamespaceUriDefined(namespace) == false) { attList.addNamespaceDeclaration("autoGenNs", namespace); } try { final PropertyEditor propertyEditor = attrMeta.getEditor(); final String textValue; if (propertyEditor != null) { propertyEditor.setValue(value); textValue = propertyEditor.getAsText(); } else { textValue = ConverterRegistry.toAttributeValue(value); } if (textValue != null) { if ("".equals(textValue) == false) { attList.setAttribute(namespace, name, textValue); this.xmlWriter.writeTag(XmlDocumentWriter.LAYOUT_OUTPUT_NAMESPACE, "attribute", attList, XmlWriter.CLOSE); } } else { if (value instanceof ResourceKey) { final ResourceKey reskey = (ResourceKey) value; final String identifierAsString = reskey.getIdentifierAsString(); attList.setAttribute(namespace, name, "resource-key:" + reskey.getSchema() + ":" + identifierAsString); this.xmlWriter.writeTag(XmlDocumentWriter.LAYOUT_OUTPUT_NAMESPACE, "attribute", attList, XmlWriter.CLOSE); } else { XmlDocumentWriter.logger.debug("Attribute '" + namespace + '|' + name + "' is not convertible to a text - returned null: " + value); } } } catch (BeanException e) { if (attrMeta.isTransient() == false) { XmlDocumentWriter.logger.warn( "Attribute '" + namespace + '|' + name + "' is not convertible with the bean-methods"); } else { XmlDocumentWriter.logger.debug( "Attribute '" + namespace + '|' + name + "' is not convertible with the bean-methods"); } } } }
From source file:org.pentaho.reporting.engine.classic.core.modules.parser.bundle.writer.elements.AbstractElementWriteHandler.java
protected AttributeList createMainAttributes(final Element element, final XmlWriter writer, final AttributeList attList) { if (element == null) { throw new NullPointerException(); }/*from www . j ava 2s .co m*/ if (writer == null) { throw new NullPointerException(); } if (attList == null) { throw new NullPointerException(); } final ElementMetaData metaData = element.getElementType().getMetaData(); final String[] attributeNamespaces = element.getAttributeNamespaces(); for (int i = 0; i < attributeNamespaces.length; i++) { final String namespace = attributeNamespaces[i]; final String[] attributeNames = element.getAttributeNames(namespace); for (int j = 0; j < attributeNames.length; j++) { final String name = attributeNames[j]; final Object value = element.getAttribute(namespace, name); if (value == null) { continue; } final AttributeMetaData attrMeta = metaData.getAttributeDescription(namespace, name); if (attrMeta == null) { if (value instanceof String) { ensureNamespaceDefined(writer, attList, namespace); // preserve strings, but discard anything else. Until a attribute has a definition, we cannot // hope to understand the attribute's value. String-attributes can be expressed in XML easily, // and string is also how all unknown attributes are stored by the parser. attList.setAttribute(namespace, name, String.valueOf(value)); } continue; } if (attrMeta.isTransient()) { continue; } if (isFiltered(attrMeta)) { continue; } if (attrMeta.isBulk()) { continue; } ensureNamespaceDefined(writer, attList, namespace); try { final PropertyEditor propertyEditor = attrMeta.getEditor(); if (propertyEditor != null) { propertyEditor.setValue(value); attList.setAttribute(namespace, name, propertyEditor.getAsText()); } else { final String attrValue = ConverterRegistry.toAttributeValue(value); attList.setAttribute(namespace, name, attrValue); } } catch (BeanException e) { AbstractElementWriteHandler.logger.warn( "Attribute '" + namespace + '|' + name + "' is not convertible with the bean-methods"); } } } return attList; }
From source file:org.pentaho.reporting.engine.classic.core.modules.parser.bundle.writer.elements.AbstractElementWriteHandler.java
private void writeBulkAttributes(final WriteableDocumentBundle bundle, final BundleWriterState state, final Element element, final XmlWriter writer) throws IOException, BundleWriterException { final ElementMetaData metaData = element.getElementType().getMetaData(); final String[] attributeNamespaces = element.getAttributeNamespaces(); for (int i = 0; i < attributeNamespaces.length; i++) { final String namespace = attributeNamespaces[i]; final String[] attributeNames = element.getAttributeNames(namespace); for (int j = 0; j < attributeNames.length; j++) { final String name = attributeNames[j]; final Object value = element.getAttribute(namespace, name); if (value == null) { continue; }/*w ww . ja va2s.c om*/ final AttributeMetaData attrMeta = metaData.getAttributeDescription(namespace, name); if (attrMeta == null) { continue; } if (attrMeta.isTransient()) { continue; } if (isFiltered(attrMeta)) { continue; } if (attrMeta.isBulk() == false) { continue; } if ("Resource".equals(attrMeta.getValueRole())) { final AttributeList attList = new AttributeList(); if (attList.isNamespaceUriDefined(namespace) == false && writer.isNamespaceDefined(namespace) == false) { attList.addNamespaceDeclaration("autoGenNS", namespace); } if (value instanceof URL) { attList.setAttribute(AttributeNames.Core.NAMESPACE, "resource-type", "url"); writer.writeTag(namespace, attrMeta.getName(), attList, XmlWriter.OPEN); writer.writeTextNormalized(String.valueOf(value), true); writer.writeCloseTag(); } else if (value instanceof ResourceKey) { try { final ResourceKey key = (ResourceKey) value; final ResourceManager resourceManager = bundle.getResourceManager(); final ResourceKey bundleKey = bundle.getBundleKey().getParent(); final String serializedKey = resourceManager.serialize(bundleKey, key); attList.setAttribute(AttributeNames.Core.NAMESPACE, "resource-type", "resource-key"); writer.writeTag(namespace, attrMeta.getName(), attList, XmlWriter.OPEN); writer.writeTextNormalized(serializedKey, true); writer.writeCloseTag(); } catch (ResourceException re) { logger.error("Could not serialize the ResourceKey: " + re.getMessage(), re); throw new IOException("Could not serialize the ResourceKey: ", re); } } else if (value instanceof File) { attList.setAttribute(AttributeNames.Core.NAMESPACE, "resource-type", "file"); writer.writeTag(namespace, attrMeta.getName(), attList, XmlWriter.OPEN); writer.writeTextNormalized(String.valueOf(value), true); writer.writeCloseTag(); } else if (value instanceof String) { attList.setAttribute(AttributeNames.Core.NAMESPACE, "resource-type", "local-ref"); writer.writeTag(namespace, attrMeta.getName(), attList, XmlWriter.OPEN); writer.writeTextNormalized(String.valueOf(value), true); writer.writeCloseTag(); } else { logger.warn("Unknown value-type in resource-attribute " + namespace + ":" + name); } continue; } if ("Expression".equals(attrMeta.getValueRole()) && value instanceof Expression) { // write attribute-expressions. final AttributeList attList = new AttributeList(); attList.setAttribute(BundleNamespaces.LAYOUT, "attribute-namespace", namespace); attList.setAttribute(BundleNamespaces.LAYOUT, "attribute-name", name); ExpressionWriterUtility.writeExpressionCore(bundle, state, (Expression) value, writer, BundleNamespaces.LAYOUT, "expression", attList); continue; } try { final PropertyEditor propertyEditor = attrMeta.getEditor(); if (propertyEditor != null) { propertyEditor.setValue(value); final String text = propertyEditor.getAsText(); final AttributeList attList = new AttributeList(); if (attList.isNamespaceUriDefined(namespace) == false && writer.isNamespaceDefined(namespace) == false) { attList.addNamespaceDeclaration("autoGenNS", namespace); } writer.writeTag(namespace, attrMeta.getName(), attList, XmlWriter.OPEN); writer.writeTextNormalized(text, true); writer.writeCloseTag(); } else { final String attrValue = ConverterRegistry.toAttributeValue(value); final AttributeList attList = new AttributeList(); if (attList.isNamespaceUriDefined(namespace) == false && writer.isNamespaceDefined(namespace) == false) { attList.addNamespaceDeclaration("autoGenNS", namespace); } writer.writeTag(namespace, attrMeta.getName(), attList, XmlWriter.OPEN); writer.writeTextNormalized(attrValue, true); writer.writeCloseTag(); } } catch (BeanException e) { AbstractElementWriteHandler.logger.warn( "Attribute '" + namespace + '|' + name + "' is not convertible with the bean-methods"); } } } }
From source file:org.ppwcode.vernacular.value_III.jsf.AbstractPropertyEditorConverter.java
/** * @pre context != null;//from w w w .j a v a2s . c o m * @pre component != null; * @return ; the result of the conversion of <code>value</code> * to a String by {@link #getPropertyEditor(FacesContext, UIComponent)} * @throws ConverterException * getPropertyEditor(context, component); */ public final String getAsString(final FacesContext context, final UIComponent component, final Object value) throws ConverterException { assert context != null; assert component != null; if (LOG.isDebugEnabled()) { LOG.debug("request to convert object \"" + value + "\" to String for " + component + "(id = " + component.getClientId(context) + ")"); } PropertyEditor editor = getPropertyEditor(context, component); // ConverterException LOG.debug("retrieved PropertyEditor: " + editor); editor.setValue(value); String result = editor.getAsText(); LOG.debug("convertion result: " + result); return result; }
From source file:org.springframework.beans.TypeConverterDelegate.java
/** * Convert the value to the required type (if necessary from a String), * using the given property editor.//from w ww. j ava2s . co m * @param oldValue the previous value, if available (may be {@code null}) * @param newValue the proposed new value * @param requiredType the type we must convert to * (or {@code null} if not known, for example in case of a collection element) * @param editor the PropertyEditor to use * @return the new value, possibly the result of type conversion * @throws IllegalArgumentException if type conversion failed */ @Nullable private Object doConvertValue(@Nullable Object oldValue, @Nullable Object newValue, @Nullable Class<?> requiredType, @Nullable PropertyEditor editor) { Object convertedValue = newValue; if (editor != null && !(convertedValue instanceof String)) { // Not a String -> use PropertyEditor's setValue. // With standard PropertyEditors, this will return the very same object; // we just want to allow special PropertyEditors to override setValue // for type conversion from non-String values to the required type. try { editor.setValue(convertedValue); Object newConvertedValue = editor.getValue(); if (newConvertedValue != convertedValue) { convertedValue = newConvertedValue; // Reset PropertyEditor: It already did a proper conversion. // Don't use it again for a setAsText call. editor = null; } } catch (Exception ex) { if (logger.isDebugEnabled()) { logger.debug( "PropertyEditor [" + editor.getClass().getName() + "] does not support setValue call", ex); } // Swallow and proceed. } } Object returnValue = convertedValue; if (requiredType != null && !requiredType.isArray() && convertedValue instanceof String[]) { // Convert String array to a comma-separated String. // Only applies if no PropertyEditor converted the String array before. // The CSV String will be passed into a PropertyEditor's setAsText method, if any. if (logger.isTraceEnabled()) { logger.trace("Converting String array to comma-delimited String [" + convertedValue + "]"); } convertedValue = StringUtils.arrayToCommaDelimitedString((String[]) convertedValue); } if (convertedValue instanceof String) { if (editor != null) { // Use PropertyEditor's setAsText in case of a String value. if (logger.isTraceEnabled()) { logger.trace( "Converting String to [" + requiredType + "] using property editor [" + editor + "]"); } String newTextValue = (String) convertedValue; return doConvertTextValue(oldValue, newTextValue, editor); } else if (String.class == requiredType) { returnValue = convertedValue; } } return returnValue; }
From source file:org.springframework.beans.TypeConverterDelegate.java
/** * Convert the given text value using the given property editor. * @param oldValue the previous value, if available (may be {@code null}) * @param newTextValue the proposed text value * @param editor the PropertyEditor to use * @return the converted value/*from ww w. j av a2 s . c o m*/ */ private Object doConvertTextValue(@Nullable Object oldValue, String newTextValue, PropertyEditor editor) { try { editor.setValue(oldValue); } catch (Exception ex) { if (logger.isDebugEnabled()) { logger.debug("PropertyEditor [" + editor.getClass().getName() + "] does not support setValue call", ex); } // Swallow and proceed. } editor.setAsText(newTextValue); return editor.getValue(); }
From source file:org.springframework.faces.mvc.bind.ReverseDataBinder.java
/** * Utility method to convert a given value into a string using a property editor. * @param value The value to convert (can be <tt>null</tt>) * @param propertyEditor The property editor or <tt>null</tt> if no suitable property editor exists * @return The converted value/* w ww . j a va 2 s . c om*/ */ private String convertToStringUsingPropertyEditor(Object value, PropertyEditor propertyEditor) { if (propertyEditor != null) { propertyEditor.setValue(value); return propertyEditor.getAsText(); } if (value instanceof String) { return value == null ? null : value.toString(); } return null; }