Example usage for java.beans PropertyEditorManager findEditor

List of usage examples for java.beans PropertyEditorManager findEditor

Introduction

In this page you can find the example usage for java.beans PropertyEditorManager findEditor.

Prototype

public static PropertyEditor findEditor(Class<?> targetType) 

Source Link

Document

Locate a value editor for a given target type.

Usage

From source file:org.tinygroup.beanwrapper.TypeConverterDelegate.java

/**
 * Find a default editor for the given type.
 * @param requiredType the type to find an editor for
 * @param descriptor the JavaBeans descriptor for the property
 * @return the corresponding editor, or <code>null</code> if none
 *///from   www.java2s  . co m
protected PropertyEditor findDefaultEditor(Class requiredType, PropertyDescriptor descriptor) {
    PropertyEditor editor = null;
    if (descriptor != null) {
        if (JdkVersion.isAtLeastJava15()) {
            editor = descriptor.createPropertyEditor(this.targetObject);
        } else {
            Class editorClass = descriptor.getPropertyEditorClass();
            if (editorClass != null) {
                editor = (PropertyEditor) BeanUtils.instantiateClass(editorClass);
            }
        }
    }
    if (editor == null && requiredType != null) {
        // No custom editor -> check BeanWrapperImpl's default editors.
        editor = (PropertyEditor) this.propertyEditorRegistry.getDefaultEditor(requiredType);
        if (editor == null && !String.class.equals(requiredType)) {
            // No BeanWrapper default editor -> check standard JavaBean editor.
            editor = BeanUtils.findEditorByConvention(requiredType);
            if (editor == null && !unknownEditorTypes.containsKey(requiredType)) {
                // Deprecated global PropertyEditorManager fallback...
                editor = PropertyEditorManager.findEditor(requiredType);
                if (editor == null) {
                    // Regular case as of Spring 2.5
                    unknownEditorTypes.put(requiredType, Boolean.TRUE);
                } else {
                    logger.warn("PropertyEditor [" + editor.getClass().getName()
                            + "] found through deprecated global PropertyEditorManager fallback - "
                            + "consider using a more isolated form of registration, e.g. on the BeanWrapper/BeanFactory!");
                }
            }
        }
    }
    return editor;
}

From source file:de.xwic.appkit.webbase.table.DefaultColumnLabelProvider.java

/**
 * @throws IntrospectionException //ww  w .j  a va 2  s  .  c  o  m
 * 
 */
private void buildReadPath(Object element) throws IntrospectionException {
    StringTokenizer stk = new StringTokenizer(column.getPropertyId(), ".");
    readMethods = new Method[stk.countTokens()];

    int idx = 0;
    Class<?> clazz = element.getClass();
    while (stk.hasMoreTokens()) {
        String propertyName = stk.nextToken();

        PropertyDescriptor desc = new PropertyDescriptor(propertyName, clazz, makeGetterName(propertyName),
                null);
        clazz = desc.getPropertyType();
        readMethods[idx++] = desc.getReadMethod();
    }
    propertyEditor = PropertyEditorManager.findEditor(clazz);
    baseClass = element.getClass();
}

From source file:org.apache.camel.util.IntrospectionSupport.java

@SuppressWarnings("unchecked")
private static Object convert(TypeConverter typeConverter, Class type, Object value)
        throws URISyntaxException, NoTypeConversionAvailableException {
    if (typeConverter != null) {
        return typeConverter.mandatoryConvertTo(type, value);
    }//from   w ww.  j a va2 s. com
    PropertyEditor editor = PropertyEditorManager.findEditor(type);
    if (editor != null) {
        editor.setAsText(value.toString());
        return editor.getValue();
    }
    if (type == URI.class) {
        return new URI(value.toString());
    }
    return null;
}

From source file:com.interface21.beans.BeanWrapperImpl.java

/**
 * Convert the value to the required type (if necessary from a String).
 * Conversions from String to any type use the setAsText() method of
 * the PropertyEditor class. Note that a PropertyEditor must be registered
 * for this class for this to work. This is a standard Java Beans API.
 * A number of property editors are automatically registered by this class.
 * @param target target bean/*from  ww w. j a  v  a 2  s.com*/
 * @param propertyName name of the property
 * @param oldValue previous value, if available. May be null.
 * @param newValue proposed change value.
 * @param requiredType type we must convert to
 * @throws BeansException if there is an internal error
 * @return new value, possibly the result of type convertion.
 */
public Object doTypeConversionIfNecessary(Object target, String propertyName, Object oldValue, Object newValue,
        Class requiredType) throws BeansException {
    // Only need to cast if value isn't null
    if (newValue != null) {
        // We may need to change the value of newValue
        // custom editor for this type?
        PropertyEditor pe = findCustomEditor(requiredType, propertyName);
        if ((pe != null || !requiredType.isAssignableFrom(newValue.getClass()))
                && (newValue instanceof String)) {
            if (logger.isDebugEnabled())
                logger.debug("Convert: String to " + requiredType);
            if (pe == null) {
                // no custom editor -> check BeanWrapper's default editors
                pe = (PropertyEditor) defaultEditors.get(requiredType);
                if (pe == null) {
                    // no BeanWrapper default editor -> check standard editors
                    pe = PropertyEditorManager.findEditor(requiredType);
                }
            }
            if (logger.isDebugEnabled())
                logger.debug("Using property editor [" + pe + "]");
            if (pe != null) {
                try {
                    pe.setAsText((String) newValue);
                    newValue = pe.getValue();
                } catch (IllegalArgumentException ex) {
                    throw new TypeMismatchException(
                            new PropertyChangeEvent(target, propertyName, oldValue, newValue), requiredType,
                            ex);
                }
            }
        }
    }
    return newValue;
}

From source file:org.helios.redis.ts.controller.conn.RedisConnectionManager.java

/**
 * Initializes the pool config from the pool properties
 * @param configProps the pool properties
 *//*  w  w w .j a va  2  s .c om*/
protected void initPoolConfig(Properties configProps) {
    String fName = null;
    try {
        for (String s : configProps.stringPropertyNames()) {
            if (s.startsWith("redis.pool.")) {
                fName = s.replace("redis.pool.", "");
                Field f = poolConfigFieldNames.get(fName);
                if (f != null) {
                    String value = configProps.getProperty(s);
                    if (value == null || value.trim().isEmpty())
                        continue;
                    value = value.trim();
                    PropertyEditor pe = PropertyEditorManager.findEditor(f.getType());
                    pe.setAsText(value);
                    f.set(poolConfig, pe.getValue());
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException("Failed to configure Jedis Pool Item [" + fName + "]", e);
    }
}

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

/**
 * Get a property editor given a property type.
 *
 * @param propertyType The property type to look up an editor for.
 * @param path The property path, if applicable.
 * @return property editor// w w  w. j  a  va 2 s  . c o m
 */
public static PropertyEditor getPropertyEditor(Class<?> propertyType) {
    PropertyEditorRegistry registry = getPropertyEditorRegistry();
    PropertyEditor editor = null;

    if (registry != null) {
        editor = registry.findCustomEditor(propertyType, null);
    } else {

        DataDictionaryService dataDictionaryService = KRADServiceLocatorWeb.getDataDictionaryService();
        Map<Class<?>, String> editorMap = dataDictionaryService.getPropertyEditorMap();
        String editorPrototypeName = editorMap == null ? null : editorMap.get(propertyType);

        if (editorPrototypeName != null) {
            editor = (PropertyEditor) dataDictionaryService.getDataDictionary()
                    .getDictionaryPrototype(editorPrototypeName);
        }
    }

    if (editor == null && propertyType != null) {
        // Fall back to default beans lookup
        editor = PropertyEditorManager.findEditor(propertyType);
    }

    return editor;
}

From source file:com.sun.faces.el.impl.Coercions.java

/**
 * Coerces a value to the specified Class that is not covered by any
 * of the above cases//from   w  w w.j  av  a2  s .  com
 */
public static Object coerceToObject(Object pValue, Class pClass) throws ElException {
    if (pValue == null) {
        return null;
    } else if (pClass.isAssignableFrom(pValue.getClass())) {
        return pValue;
    } else if (pValue instanceof String) {
        String str = (String) pValue;
        PropertyEditor pe = PropertyEditorManager.findEditor(pClass);
        if (pe == null) {
            if ("".equals(str)) {
                return null;
            } else {
                if (log.isErrorEnabled()) {
                    String message = MessageUtil.getMessageWithArgs(Constants.NO_PROPERTY_EDITOR, str,
                            pClass.getName());
                    log.error(message);
                    throw new ElException(message);
                }
                return null;
            }
        }
        try {
            pe.setAsText(str);
            return pe.getValue();
        } catch (IllegalArgumentException exc) {
            if ("".equals(str)) {
                return null;
            } else {
                if (log.isErrorEnabled()) {
                    String message = MessageUtil.getMessageWithArgs(Constants.PROPERTY_EDITOR_ERROR, pValue,
                            pClass.getName());
                    log.error(message, exc);
                    throw new ElException(message, exc);
                }
                return null;
            }
        }
    } else {
        if (log.isErrorEnabled()) {
            String message = MessageUtil.getMessageWithArgs(Constants.COERCE_TO_OBJECT,
                    pValue.getClass().getName(), pClass.getName());
            log.error(message);
            throw new ElException(message);
        }
        return null;
    }
}

From source file:org.nextframework.controller.ExtendedBeanWrapper.java

/**
 * Convert the value to the required type (if necessary from a String),
 * for the specified property./*  ww  w  . j a v  a 2  s  . c  om*/
 * @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;
}