Example usage for java.beans PropertyEditor setValue

List of usage examples for java.beans PropertyEditor setValue

Introduction

In this page you can find the example usage for java.beans PropertyEditor setValue.

Prototype

void setValue(Object value);

Source Link

Document

Set (or change) the object that is to be edited.

Usage

From source file:net.solarnetwork.node.support.XmlServiceSupport.java

/**
 * Turn an object into a simple XML Element, supporting custom property
 * editors./*ww  w  .  j a v a  2  s.  c o m*/
 * 
 * <p>
 * The returned XML will be a single element with all JavaBean properties
 * turned into attributes. For example:
 * <p>
 * 
 * <pre>
 * &lt;powerDatum
 *   id="123"
 *   pvVolts="123.123"
 *   ... /&gt;
 * </pre>
 * 
 * <p>
 * {@link PropertyEditor} instances can be registered with the supplied
 * {@link BeanWrapper} for custom handling of properties, e.g. dates.
 * </p>
 * 
 * @param bean
 *        the object to turn into XML
 * @param elementName
 *        the name of the XML element
 * @return the element, as an XML DOM Element
 */
protected Element getElement(BeanWrapper bean, String elementName, Document dom) {
    PropertyDescriptor[] props = bean.getPropertyDescriptors();
    Element root = null;
    root = dom.createElement(elementName);
    for (int i = 0; i < props.length; i++) {
        PropertyDescriptor prop = props[i];
        if (prop.getReadMethod() == null) {
            continue;
        }
        String propName = prop.getName();
        if ("class".equals(propName)) {
            continue;
        }
        Object propValue = null;
        PropertyEditor editor = bean.findCustomEditor(prop.getPropertyType(), prop.getName());
        if (editor != null) {
            editor.setValue(bean.getPropertyValue(propName));
            propValue = editor.getAsText();
        } else {
            propValue = bean.getPropertyValue(propName);
        }
        if (propValue == null) {
            continue;
        }
        if (log.isTraceEnabled()) {
            log.trace("attribute name: " + propName + " attribute value: " + propValue);
        }
        root.setAttribute(propName, propValue.toString());
    }
    return root;
}

From source file:net.solarnetwork.node.support.XmlServiceSupport.java

private void writeURLEncodedBeanProperties(BeanWrapper bean, Map<String, ?> attributes, Writer out)
        throws IOException {
    PropertyDescriptor[] props = bean.getPropertyDescriptors();
    boolean propsWritten = false;
    if (attributes != null && attributes.containsKey(ATTR_NODE_ID)) {
        out.write("nodeId=" + attributes.get(ATTR_NODE_ID));
        propsWritten = true;//w ww .  ja  va2 s.  c  om
    }
    for (int i = 0; i < props.length; i++) {
        PropertyDescriptor prop = props[i];
        if (prop.getReadMethod() == null) {
            continue;
        }
        String propName = prop.getName();
        if ("class".equals(propName)) {
            continue;
        }
        Object propValue = null;
        if (attributes != null && attributes.containsKey(propName)) {
            propValue = attributes.get(propName);
        } else {
            PropertyEditor editor = bean.findCustomEditor(prop.getPropertyType(), prop.getName());
            if (editor != null) {
                editor.setValue(bean.getPropertyValue(propName));
                propValue = editor.getAsText();
            } else {
                propValue = bean.getPropertyValue(propName);
            }
        }
        if (propValue == null) {
            continue;
        }
        if (propsWritten) {
            out.write("&");
        }
        out.write(propName);
        out.write("=");
        out.write(URLEncoder.encode(propValue.toString(), "UTF-8"));
        propsWritten = true;
    }
    out.flush();
    out.close();
}

From source file:net.sf.juffrou.reflect.JuffrouTypeConverterDelegate.java

/**
 * Convert the value to the required type (if necessary from a String), using the given property editor.
 * /*from   ww w.j  av  a  2  s .  c o  m*/
 * @param oldValue
 *            the previous value, if available (may be <code>null</code>)
 * @param newValue
 *            the proposed new value
 * @param requiredType
 *            the type we must convert to (or <code>null</code> 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
 */
private Object doConvertValue(Object oldValue, Object newValue, Class<?> requiredType, PropertyEditor editor) {
    Object convertedValue = newValue;
    boolean sharedEditor = false;

    if (editor != null) {
        sharedEditor = this.propertyEditorRegistry.isSharedEditor(editor);
    }

    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 {
            Object newConvertedValue;
            if (sharedEditor) {
                // Synchronized access to shared editor instance.
                synchronized (editor) {
                    editor.setValue(convertedValue);
                    newConvertedValue = editor.getValue();
                }
            } else {
                // Unsynchronized access to non-shared editor instance.
                editor.setValue(convertedValue);
                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;
            if (sharedEditor) {
                // Synchronized access to shared editor instance.
                synchronized (editor) {
                    return doConvertTextValue(oldValue, newTextValue, editor);
                }
            } else {
                // Unsynchronized access to non-shared editor instance.
                return doConvertTextValue(oldValue, newTextValue, editor);
            }
        } else if (String.class.equals(requiredType)) {
            returnValue = convertedValue;
        }
    }

    return returnValue;
}

From source file:org.apache.camel.impl.converter.PropertyEditorTypeConverter.java

public <T> T convertTo(Class<T> type, Object value) {
    // We can't convert null values since we can't figure out a property
    // editor for it.
    if (value == null) {
        return null;
    }/*w  w  w.  j ava  2 s . c  om*/

    if (value.getClass() == String.class) {
        // No conversion needed.
        if (type == String.class) {
            return ObjectHelper.cast(type, value);
        }

        Class key = type;
        PropertyEditor editor = lookupEditor(key);
        if (editor != null) {
            editor.setAsText(value.toString());
            return ObjectHelper.cast(type, editor.getValue());
        }
    } else if (type == String.class) {
        Class key = value.getClass();
        PropertyEditor editor = lookupEditor(key);
        if (editor != null) {
            editor.setValue(value);
            return ObjectHelper.cast(type, editor.getAsText());
        }
    }

    return null;
}

From source file:org.dspace.app.cris.discovery.CrisItemEnhancerUtility.java

private static <P extends Property<TP>, TP extends PropertiesDefinition, NP extends ANestedProperty<NTP>, NTP extends ANestedPropertiesDefinition, ACNO extends ACrisNestedObject<NP, NTP, P, TP>, ATNO extends ATypeNestedObject<NTP>> List<String[]> getPathAsMetadata(
        ApplicationService as, ACrisObject<P, TP, NP, NTP, ACNO, ATNO> aCrisObject, String path) {
    String[] splitted = path.split("\\.", 2);
    List<String[]> result = new ArrayList<String[]>();
    List<P> props = aCrisObject.getAnagrafica4view().get(splitted[0]);
    if (splitted.length == 2) {
        for (P prop : props) {
            if (prop.getObject() instanceof ACrisObject) {
                result.addAll(getPathAsMetadata(as, (ACrisObject) prop.getObject(), splitted[1]));
            } else {
                log.error(/*from   w w w.  ja va 2 s . c om*/
                        "Wrong configuration, asked for path " + splitted[1] + " on a not CRIS Object value.");
            }
        }

    }
    for (P prop : props) {
        if (prop.getObject() instanceof ACrisObject) {
            ACrisObject val = (ACrisObject) prop.getObject();
            result.add(new String[] { val.getName(), ResearcherPageUtils.getPersistentIdentifier(val) });
        } else {
            PropertyEditor editor = prop.getTypo().getRendering().getPropertyEditor(as);
            editor.setValue(prop.getObject());

            result.add(new String[] { editor.getAsText(), null });
        }
    }

    return result;
}

From source file:org.dspace.app.cris.model.ACrisObject.java

@Override
public DCValue[] getMetadata(String schema, String element, String qualifier, String lang) {
    List values = new ArrayList();
    String authority = null;//  www  . jav  a2s.co m
    if ("crisdo".equals(schema) && "name".equals(element)) {
        values.add(getName());
    } else if (!schema.equalsIgnoreCase("cris" + this.getPublicPath())) {
        return new DCValue[0];
    } else {
        element = getCompatibleJDynAShortName(this, element);

        List<P> proprieties = this.getAnagrafica4view().get(element);

        if (proprieties != null) {
            for (P prop : proprieties) {
                Object val = prop.getObject();
                if (StringUtils.isNotEmpty(qualifier) && val instanceof ACrisObject) {
                    authority = ResearcherPageUtils.getPersistentIdentifier((ACrisObject) val);
                    qualifier = getCompatibleJDynAShortName((ACrisObject) val, qualifier);
                    List pointProps = (List) ((ACrisObject) val).getAnagrafica4view().get(qualifier);
                    if (pointProps != null && pointProps.size() > 0) {
                        for (Object pprop : pointProps) {
                            values.add(((Property) pprop).getObject());
                        }
                    }
                } else if (val instanceof ACrisObject) {
                    authority = ResearcherPageUtils.getPersistentIdentifier((ACrisObject) val);
                    values.add(((ACrisObject) val).getName());
                } else {
                    PropertyEditor propertyEditor = prop.getTypo().getRendering().getPropertyEditor(null);
                    propertyEditor.setValue(val);
                    values.add(propertyEditor.getAsText());
                }
            }
        }
    }
    DCValue[] result = new DCValue[values.size()];
    for (int idx = 0; idx < values.size(); idx++) {
        result[idx] = new DCValue();
        result[idx].schema = schema;
        result[idx].element = element;
        result[idx].qualifier = qualifier;
        result[idx].authority = authority;
        result[idx].confidence = StringUtils.isNotEmpty(authority) ? Choices.CF_ACCEPTED : Choices.CF_UNSET;
        result[idx].value = values.get(idx).toString();
    }
    return result;
}

From source file:org.dspace.app.cris.util.UtilsXLS.java

private static int createSimpleElement(ApplicationService applicationService, int y, int i, String shortName,
        List<RPProperty> proprietaDellaTipologia, WritableSheet sheet)
        throws RowsExceededException, WriteException {
    String field_value = "";
    String field_visibility = "";
    boolean first = true;
    for (RPProperty rr : proprietaDellaTipologia) {

        PropertyEditor pe = rr.getTypo().getRendering().getPropertyEditor(applicationService);
        pe.setValue(rr.getObject());
        if (!first) {
            field_value += STOPFIELDS_EXCEL;
        }/* w  w w . ja v a  2s . co  m*/
        field_value += pe.getAsText();
        if (!first) {
            field_visibility += STOPFIELDS_EXCEL;
        }
        field_visibility += VisibilityConstants.getDescription(rr.getVisibility());
        first = false;

    }
    y = y + 1;
    Label label_v = new Label(y, i, field_value);
    sheet.addCell(label_v);
    Label labelCaption = new Label(y, 0, shortName);
    sheet.addCell(labelCaption);
    y = y + 1;
    Label label_vv = new Label(y, i, field_visibility);
    sheet.addCell(label_vv);
    labelCaption = new Label(y, 0, shortName + ImportExportUtils.LABELCAPTION_VISIBILITY_SUFFIX);
    sheet.addCell(labelCaption);

    return y;
}

From source file:org.easyrec.plugin.configuration.ConfigurationHelper.java

/**
 * Converts the parameter value to a string. If a custom {@link PropertyEditor} is configured for the parameter (via
 * the {@link PluginParameterPropertyEditor} Annotation), it is used for conversion, otherwise the value's
 * <code>toString()</code> method is called. If the value is <code>null</code>, <code>null</code> is returned.
 *
 * @param parameterName/*w  w w.j a  v  a2 s .com*/
 *
 * @throws IllegalArgumentException if no parameter of given name exists.
 */
public String getParameterStringValue(String parameterName) {
    Field field = getParameterField(parameterName);
    PropertyEditor editor = this.configurationWrapper.findCustomEditor(field.getType(), field.getName());
    Object value = getParameterValue(parameterName);
    if (editor != null) {
        editor.setValue(value);
        return editor.getAsText();
    } else {
        if (value == null) {
            return null;
        }
        return value.toString();
    }
}

From source file:org.jsecurity.web.attr.AbstractWebAttribute.java

protected String toStringValue(T value) {
    Class clazz = getEditorClass();
    if (clazz == null) {

        if (log.isDebugEnabled()) {
            log.debug("No 'editorClass' property set - returning value.toString() as the string value for "
                    + "method argument.");
        }//from  ww  w  . jav a2 s. c  o m
        return value.toString();
    } else {
        PropertyEditor editor = (PropertyEditor) ClassUtils.newInstance(getEditorClass());
        editor.setValue(value);
        return editor.getAsText();
    }
}

From source file:org.kuali.rice.krad.uif.util.ObjectPropertyUtils.java

/**
 * Looks up a property value, then convert to text using a registered property editor.
 *
 * @param bean bean instance to look up a property value for
 * @param path property path relative to the bean
 * @return The property value, converted to text using a registered property editor.
 *///from   www  .  j a v  a 2  s . c o m
public static String getPropertyValueAsText(Object bean, String path) {
    Object propertyValue = getPropertyValue(bean, path);
    PropertyEditor editor = getPropertyEditor(bean, path);

    if (editor == null) {
        return propertyValue == null ? null : propertyValue.toString();
    } else {
        editor.setValue(propertyValue);
        return editor.getAsText();
    }
}