Example usage for java.beans PropertyEditor setAsText

List of usage examples for java.beans PropertyEditor setAsText

Introduction

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

Prototype

void setAsText(String text) throws java.lang.IllegalArgumentException;

Source Link

Document

Set the property value by parsing a given String.

Usage

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;
    }/*from  w w  w.jav a 2s.  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.synyx.hades.extensions.beans.DomainClassPropertyEditor.java

/**
 * Returns the actual typed id. Looks up an available customly registered
 * {@link PropertyEditor} from the {@link PropertyEditorRegistry} before
 * falling back on a {@link SimpleTypeConverter} to translate the
 * {@link String} id into the type one./* w  ww  .  j  ava2 s.  c o m*/
 * 
 * @param idAsString
 * @return
 */
@SuppressWarnings("unchecked")
private T getId(String idAsString) {

    Class<T> idClass = (Class<T>) ClassUtils.getIdClass(dao.getClass());

    PropertyEditor idEditor = registry.findCustomEditor(idClass, null);

    if (idEditor != null) {
        idEditor.setAsText(idAsString);
        return (T) idEditor.getValue();
    }

    return new SimpleTypeConverter().convertIfNecessary(idAsString, idClass);
}

From source file:org.springmodules.cache.provider.ReflectionCacheModelEditor.java

/**
 * @throws IllegalStateException//  w ww .  j  a va2s. c om
 *           if the class of the cache model to create has not been set.
 * @see SemicolonSeparatedPropertiesParser#parseProperties(String)
 * @see PropertyEditor#setAsText(String)
 * @see org.springframework.beans.PropertyAccessor#setPropertyValue(String,
 *      Object)
 */
public final void setAsText(String text) {
    if (cacheModelClass == null) {
        throw new IllegalStateException("cacheModelClass should not be null");
    }

    Properties properties = SemicolonSeparatedPropertiesParser.parseProperties(text);

    BeanWrapper beanWrapper = new BeanWrapperImpl(cacheModelClass);

    if (properties != null) {
        for (Iterator i = properties.keySet().iterator(); i.hasNext();) {
            String propertyName = (String) i.next();
            String textProperty = properties.getProperty(propertyName);

            Object propertyValue = null;

            PropertyEditor propertyEditor = getPropertyEditor(propertyName);
            if (propertyEditor != null) {
                propertyEditor.setAsText(textProperty);
                propertyValue = propertyEditor.getValue();
            } else {
                propertyValue = textProperty;
            }
            beanWrapper.setPropertyValue(propertyName, propertyValue);
        }
    }

    setValue(beanWrapper.getWrappedInstance());
}

From source file:com.easyget.commons.csv.bean.CsvToBean.java

/**
 * Convert a string value to its Object value.
 *
 * @param value - String value//from   ww w  . j  av a2  s . c o m
 * @param prop  - PropertyDescriptor
 * @return The object set to value (i.e. Integer).  Will return String if no PropertyEditor is found.
 * @throws InstantiationException - Thrown on error getting the property editor from the property descriptor.
 * @throws IllegalAccessException - Thrown on error getting the property editor from the property descriptor.
 */
protected Object convertValue(String value, PropertyDescriptor prop)
        throws InstantiationException, IllegalAccessException {
    PropertyEditor editor = getPropertyEditor(prop);
    Object obj = value;
    if (null != editor) {
        editor.setAsText(value);
        obj = editor.getValue();
    }
    return obj;
}

From source file:org.ppwcode.vernacular.value_III.jsf.AbstractPropertyEditorConverter.java

/**
 * @pre context != null;/*  w w w  .  jav a2  s  . c om*/
 * @pre component != null;
 * @return ; the result of the conversion of <code>value</code>
 *           to an Object by {@link #getPropertyEditor(FacesContext, UIComponent)}
 * @throws ConverterException
 *         getPropertyEditor(context, component);
 * @throws ConverterException
 *         getPropertyEditor(context, component).getValue()#IllegalArgumentException;
 * @throws ConverterException
 *         isLabelRepresenation();
 */
public final Object getAsObject(final FacesContext context, final UIComponent component, final String value)
        throws ConverterException {
    assert context != null;
    assert component != null;
    LOG.debug("request to convert \"" + value + "\" to object for " + component + "(id = "
            + component.getClientId(context) + ")");
    if (isLabelRepresentation()) {
        LOG.debug("Cannot convert from String to Object in label-representation-mode");
        throw new ConverterException("Cannot convert from String to Object in " + "label-representation-mode");
    }
    try {
        PropertyEditor editor = getPropertyEditor(context, component); // ConverterException
        LOG.debug("retrieved PropertyEditor: " + editor);
        editor.setAsText(value);
        Object result = editor.getValue();
        if (LOG.isDebugEnabled()) {
            LOG.debug("convertion result: " + result);
        }
        return result;
    } catch (IllegalArgumentException iae) {
        // MUDO (jand) good FacesMessage, i18n; find out what happens if this fails
        throw new ConverterException(iae);
    }
}

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

@SuppressWarnings({ "unchecked" })
protected T fromStringValue(String stringValue) {
    Class clazz = getEditorClass();
    if (clazz == null) {
        try {//from  ww w.  j a  v  a  2 s .  c o m
            return (T) stringValue;
        } catch (Exception e) {
            String msg = "If the type is not String, you must specify the 'editorClass' property.";
            throw new JSecurityException(msg, e);
        }
    } else {
        PropertyEditor editor = (PropertyEditor) ClassUtils.newInstance(getEditorClass());
        editor.setAsText(stringValue);
        Object value = editor.getValue();
        try {
            return (T) value;
        } catch (ClassCastException e) {
            String msg = "Returned value from PropertyEditor does not match the specified type.";
            throw new JSecurityException(msg, e);
        }
    }
}

From source file:org.pentaho.reporting.engine.classic.core.function.sys.AttributeExpressionsEvaluator.java

/**
 * Evaluates all defined style-expressions of the given element.
 *
 * @param e/*from   w  w  w  .  j  a  va 2 s. co  m*/
 *          the element that should be updated.
 * @return true, if the element had attribute-expressions, false otherwise.
 */
protected boolean evaluateElement(final ReportElement e) {
    if (e == null) {
        throw new NullPointerException();
    }
    final String[] namespaces = e.getAttributeExpressionNamespaces();
    if (namespaces.length == 0) {
        return false;
    }

    final ConverterRegistry instance = ConverterRegistry.getInstance();
    final ElementMetaData metaData = e.getMetaData();
    boolean retval = false;

    for (int namespaceIdx = 0; namespaceIdx < namespaces.length; namespaceIdx++) {
        final String namespace = namespaces[namespaceIdx];
        final String[] names = e.getAttributeExpressionNames(namespace);
        for (int nameIdx = 0; nameIdx < names.length; nameIdx++) {
            final String name = names[nameIdx];
            final Expression ex = e.getAttributeExpression(namespace, name);
            if (ex == null) {
                continue;
            }

            final AttributeMetaData attribute = metaData.getAttributeDescription(namespace, name);
            if (attribute != null && attribute.isDesignTimeValue()) {
                continue;
            }

            retval = true;
            ex.setRuntime(getRuntime());
            try {
                final Object value = evaluate(ex);
                if (attribute == null) {
                    // Not a declared attribute, but maybe one of the output-handlers can work on this one.
                    e.setAttribute(namespace, name, value);
                } else {
                    final Class<?> type = attribute.getTargetType();
                    if (value == null || type.isAssignableFrom(value.getClass())) {
                        e.setAttribute(namespace, name, value);
                    } else if (value instanceof ErrorValue) {
                        if (failOnErrors) {
                            throw new InvalidReportStateException(String.format(
                                    "Failed to evaluate attribute-expression for attribute %s:%s on element [%s]", // NON-NLS
                                    namespace, name, FunctionUtilities.computeElementLocation(e)));
                        }
                        e.setAttribute(namespace, name, null);
                    } else {

                        final PropertyEditor propertyEditor = attribute.getEditor();
                        if (propertyEditor != null) {
                            propertyEditor.setAsText(String.valueOf(value));
                            e.setAttribute(namespace, name, propertyEditor.getValue());
                        } else {
                            final ValueConverter valueConverter = instance.getValueConverter(type);
                            if (type.isAssignableFrom(String.class)) {
                                // the attribute would allow raw-string values, so copy the element ..
                                e.setAttribute(namespace, name, value);
                            } else if (valueConverter != null) {
                                final Object o = ConverterRegistry.toPropertyValue(String.valueOf(value), type);
                                e.setAttribute(namespace, name, o);
                            } else {
                                // undo any previous computation
                                e.setAttribute(namespace, name, null);
                            }
                        }
                    }
                }
            } catch (InvalidReportStateException exception) {
                throw exception;
            } catch (Exception exception) {
                if (logger.isDebugEnabled()) {
                    logger.debug(String.format(
                            "Failed to evaluate attribute-expression for attribute %s:%s on element [%s]", // NON-NLS
                            namespace, name, FunctionUtilities.computeElementLocation(e)), exception);
                }
                if (failOnErrors) {
                    throw new InvalidReportStateException(String.format(
                            "Failed to evaluate attribute-expression for attribute %s:%s on element [%s]", // NON-NLS
                            namespace, name, FunctionUtilities.computeElementLocation(e)), exception);
                }
                e.setAttribute(namespace, name, null);
            } finally {
                ex.setRuntime(null);
            }
        }
    }
    return retval;
}

From source file:fr.cedrik.util.ExtendedProperties.java

/**
 * convert via a {@link java.beans.PropertyEditor}
 *///from w w  w. j  av  a 2 s . c  o m
// see also org.springframework.beans.propertyeditors
// http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/validation.html
// see also org.apache.commons.configuration.PropertyConverter
protected <T> T convert(String valueStr, Class<T> targetType) {
    PropertyEditor propertyEditor = PropertyEditorManager.findEditor(targetType);
    if (propertyEditor == null) {
        throw new IllegalArgumentException("Can not find a PropertyEditor for class " + targetType);
    }
    propertyEditor.setAsText(valueStr);
    T value = (T) propertyEditor.getValue();
    return value;
}

From source file:org.springmodules.cache.interceptor.caching.AbstractCachingInterceptor.java

private Map propertiesToModels() {
    PropertyEditor editor = cache.getCachingModelEditor();
    Properties properties = (Properties) modelMap;

    Map m = new HashMap();
    for (Iterator i = properties.keySet().iterator(); i.hasNext();) {
        String id = (String) i.next();
        editor.setAsText(properties.getProperty(id));
        m.put(id, editor.getValue());/*from   ww w.  j a va 2  s.c om*/
    }
    return m;
}

From source file:io.fabric8.apmagent.ApmConfiguration.java

private Object convert(Object value, Class type) throws Exception {
    PropertyEditor editor = PropertyEditorManager.findEditor(type);
    if (editor != null) {
        editor.setAsText(value.toString());
        return editor.getValue();
    }/* w ww. j  a  v a2  s . co  m*/
    if (type == URI.class) {
        return new URI(value.toString());
    }
    return null;
}