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.web.support.SimpleCsvView.java

private void writeCSV(ICsvMapWriter writer, String[] fields, Object row) throws IOException {
    if (row instanceof Map) {
        @SuppressWarnings("unchecked")
        Map<String, ?> map = (Map<String, ?>) row;
        writer.write(map, fields);/*from   w  w  w. ja  v  a 2s  .  co  m*/
    } else if (row != null) {
        Map<String, Object> map = new HashMap<String, Object>(fields.length);

        // use bean properties
        if (getPropertySerializerRegistrar() != null) {
            // try whole-bean serialization first
            row = getPropertySerializerRegistrar().serializeProperty("row", row.getClass(), row, row);
            if (row == null) {
                return;
            }
        }

        BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(row);
        for (String name : fields) {
            Object val = wrapper.getPropertyValue(name);
            if (val != null) {
                if (getPropertySerializerRegistrar() != null) {
                    val = getPropertySerializerRegistrar().serializeProperty(name, val.getClass(), row, val);
                } else {
                    // Spring does not apply PropertyEditors on read methods, so manually handle
                    PropertyEditor editor = wrapper.findCustomEditor(null, name);
                    if (editor != null) {
                        editor.setValue(val);
                        val = editor.getAsText();
                    }
                }
                if (val instanceof Enum<?> || getJavaBeanTreatAsStringValues() != null
                        && getJavaBeanTreatAsStringValues().contains(val.getClass())) {
                    val = val.toString();
                }
                if (val != null) {
                    map.put(name, val);
                }
            }
        }

        writer.write(map, fields);
    }
}

From source file:net.solarnetwork.web.support.JSONView.java

private void generateJavaBeanObject(JsonGenerator json, String key, Object bean,
        PropertyEditorRegistrar registrar) throws JsonGenerationException, IOException {
    if (key != null) {
        json.writeFieldName(key);/*from  ww  w  . j a v a 2 s  .  co m*/
    }
    if (bean == null) {
        json.writeNull();
        return;
    }
    BeanWrapper wrapper = getPropertyAccessor(bean, registrar);
    PropertyDescriptor[] props = wrapper.getPropertyDescriptors();
    json.writeStartObject();
    for (PropertyDescriptor prop : props) {
        String name = prop.getName();
        if (this.getJavaBeanIgnoreProperties() != null && this.getJavaBeanIgnoreProperties().contains(name)) {
            continue;
        }
        if (wrapper.isReadableProperty(name)) {
            Object propVal = wrapper.getPropertyValue(name);
            if (propVal != null) {

                // test for SerializeIgnore
                Method getter = prop.getReadMethod();
                if (getter != null && getter.isAnnotationPresent(SerializeIgnore.class)) {
                    continue;
                }

                if (getPropertySerializerRegistrar() != null) {
                    propVal = getPropertySerializerRegistrar().serializeProperty(name, propVal.getClass(), bean,
                            propVal);
                } else {
                    // Spring does not apply PropertyEditors on read methods, so manually handle
                    PropertyEditor editor = wrapper.findCustomEditor(null, name);
                    if (editor != null) {
                        editor.setValue(propVal);
                        propVal = editor.getAsText();
                    }
                }
                if (propVal instanceof Enum<?> || getJavaBeanTreatAsStringValues() != null
                        && getJavaBeanTreatAsStringValues().contains(propVal.getClass())) {
                    propVal = propVal.toString();
                }
                writeJsonValue(json, name, propVal, registrar);
            }
        }
    }
    json.writeEndObject();
}

From source file:net.sourceforge.vulcan.spring.SpringBeanXmlEncoder.java

void encodeAsValue(final Element propertyNode, final Object object) {
    if (object == null) {
        propertyNode.addContent(new Element("null"));
        return;/* ww w .  jav  a2  s  .c  om*/
    } else if (object instanceof Enum<?>) {
        encodeEnum(propertyNode, (Enum<?>) object);
        return;
    }

    final Element valueNode = new Element("value");

    PropertyEditor editor = PropertyEditorManager.findEditor(object.getClass());

    if (editor == null && object instanceof Date) {
        editor = new DateEditor();
    }

    if (editor != null) {
        editor.setValue(object);
        valueNode.setText(editor.getAsText());
    } else {
        valueNode.setText(object.toString());
    }
    propertyNode.addContent(valueNode);
}

From source file:it.cilea.osd.jdyna.util.AnagraficaUtils.java

private <P extends Property<TP>, TP extends PropertiesDefinition> void toXML(PrintWriter writer,
        List<P> proprietaList, Class<P> proprietaClass) {
    for (P proprieta : proprietaList) {
        writer.print("                 <bean id=\"" + proprietaClass.getSimpleName() + proprieta.getId()
                + "\" class=\"" + proprietaClass.getCanonicalName() + "\">\n");
        writer.print("                     <property name=\"tipologia\" value=\""
                + proprieta.getTypo().getShortName() + "\" />\n");
        writer.print("                     <property name=\"posizione\" value=\"" + proprieta.getPositionDef()
                + "\" />\n");

        Class valoreClass = proprieta.getTypo().getRendering().getValoreClass();
        writer.print("                     <property name=\"valore\">\n");
        writer.print("                     <bean class=\"" + valoreClass.getCanonicalName() + "\">\n");
        writer.print("                        <property name=\"real\">\n");

        PropertyEditor propertyEditor = valorePropertyEditors
                .get(proprieta.getTypo().getRendering().getValoreClass());

        propertyEditor.setValue(proprieta.getValue());
        writer.print(/*from ww w.  j av a 2 s  .c om*/
                "                           <value><![CDATA[" + propertyEditor.getAsText() + "]]></value>\n");

        writer.print("                         </property>\n");
        writer.print("                     </bean>\n");
        writer.print("                     </property>\n");

        writer.print("                 </bean>\n");
    }
}

From source file:net.solarnetwork.support.XmlSupport.java

/**
 * Turn an object into a simple XML Element, supporting custom property
 * editors./*w  ww  .  jav  a  2 s  . co  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
 */
public 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:org.hdiv.web.servlet.tags.form.OptionTagTests.java

public void testWithCustomObjectAndEditorSelected() throws Exception {
    final PropertyEditor floatEditor = new SimpleFloatEditor();
    floatEditor.setValue(new Float("12.34"));
    BindStatus bindStatus = new BindStatus(getRequestContext(), "testBean.someNumber", false) {
        public PropertyEditor getEditor() {
            return floatEditor;
        }//from w  w  w .j  a v a 2  s .  c  om
    };
    getPageContext().setAttribute(SelectTagHDIV.LIST_VALUE_PAGE_ATTRIBUTE, bindStatus);

    this.tag.setValue("${myNumber}");
    this.tag.setLabel("${myNumber}");

    int result = this.tag.doStartTag();
    assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
    result = this.tag.doEndTag();
    assertEquals(Tag.EVAL_PAGE, result);

    String output = getOutput();
    assertOptionTagOpened(output);
    assertOptionTagClosed(output);
    assertContainsAttribute(output, "selected", "selected");
    assertBlockTagContains(output, "12.34f");
}

From source file:org.hdiv.web.servlet.tags.form.OptionTagTests.java

public void testWithPropertyEditorStringComparison() throws Exception {
    final PropertyEditor testBeanEditor = new TestBeanPropertyEditor();
    testBeanEditor.setValue(new TestBean("Sally"));
    BindStatus bindStatus = new BindStatus(getRequestContext(), "testBean.spouse", false) {
        public PropertyEditor getEditor() {
            return testBeanEditor;
        }/*  w ww  . j  a v a2  s  . c  om*/
    };
    getPageContext().setAttribute(SelectTagHDIV.LIST_VALUE_PAGE_ATTRIBUTE, bindStatus);

    this.tag.setValue("Sally");

    int result = this.tag.doStartTag();
    assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
    result = this.tag.doEndTag();
    assertEquals(Tag.EVAL_PAGE, result);

    String output = getOutput();
    assertOptionTagOpened(output);
    assertOptionTagClosed(output);

    String hdivValue = this.confidentiality ? "0" : "Sally";
    assertContainsAttribute(output, "value", hdivValue);
    assertContainsAttribute(output, "selected", "selected");
    assertBlockTagContains(output, "Sally");
}

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

/**
 * Convert the given text value using the given property editor.
 * /*from ww  w .j  a v a2s .c om*/
 * @param oldValue
 *            the previous value, if available (may be <code>null</code>)
 * @param newTextValue
 *            the proposed text value
 * @param editor
 *            the PropertyEditor to use
 * @return the converted value
 */
private Object doConvertTextValue(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:com.springframework.beans.TypeConverterDelegate.java

/**
 * Convert the value to the required type (if necessary from a String),
 * using the given property editor.// w  ww . j  a  v a2 s  . 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
 */
private Object doConvertValue(Object oldValue, Object newValue, Class<?> requiredType, 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.equals(requiredType)) {
            returnValue = convertedValue;
        }
    }

    return returnValue;
}

From source file:com.alibaba.citrus.service.form.impl.GroupImpl.java

/**
 * fields//from w  w  w .  j a  v a  2s  . c om
 * <p>
 * <code>isValidated()</code><code>true</code>group
 * </p>
 */
public void mapTo(Object object) {
    if (isValidated() || object == null) {
        return;
    }

    if (log.isDebugEnabled()) {
        log.debug("Mapping properties to fields: group=\"{}\", object={}", getName(),
                ObjectUtil.identityToString(object));
    }

    BeanWrapper bean = new BeanWrapperImpl(object);
    getForm().getFormConfig().getPropertyEditorRegistrar().registerCustomEditors(bean);

    for (Field field : getFields()) {
        String propertyName = field.getFieldConfig().getPropertyName();

        if (bean.isReadableProperty(propertyName)) {
            Object propertyValue = bean.getPropertyValue(propertyName);
            Class<?> propertyType = bean.getPropertyType(propertyName);
            PropertyEditor editor = bean.findCustomEditor(propertyType, propertyName);

            if (editor == null) {
                editor = BeanUtils.findEditorByConvention(propertyType);
            }

            if (editor == null) {
                if (propertyType.isArray() || CollectionFactory.isApproximableCollectionType(propertyType)) {
                    field.setValues((String[]) bean.convertIfNecessary(propertyValue, String[].class));
                } else {
                    field.setValue(bean.convertIfNecessary(propertyValue, String.class));
                }
            } else {
                editor.setValue(propertyValue);
                field.setValue(editor.getAsText());
            }
        } else {
            log.debug("No readable property \"{}\" found in type {}", propertyName,
                    object.getClass().getName());
        }
    }
}