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.eclipse.wb.internal.swing.model.property.editor.beans.JavaBeanEditorProvider.java

@Override
public PropertyEditor getEditorForType(Class<?> propertyType) throws Exception {
    String propertyTypeName = propertyType.getName();
    if (Object.class.isAssignableFrom(propertyType) && propertyType != char[].class
            && propertyType != byte[].class && propertyType != int[].class && propertyType != int[][].class
            && propertyTypeName.indexOf("java.lang.") == -1 && propertyTypeName.indexOf("java.util.") == -1
            && propertyTypeName.indexOf("java.awt.") == -1 && propertyTypeName.indexOf("javax.swing.") == -1
            && propertyTypeName.indexOf("org.eclipse.") == -1) {
        String[] standard_editorSearchPath = PropertyEditorManager.getEditorSearchPath();
        try {//from  www.  ja  va  2  s.co m
            PropertyEditorManager.setEditorSearchPath(
                    (String[]) ArrayUtils.removeElement(standard_editorSearchPath, "sun.beans.editors"));
            java.beans.PropertyEditor propertyEditor = PropertyEditorManager.findEditor(propertyType);
            if (propertyEditor != null) {
                return createEditor(propertyEditor);
            }
        } finally {
            PropertyEditorManager.setEditorSearchPath(standard_editorSearchPath);
        }
    }
    return null;
}

From source file:therian.operator.ELCoercionConverter.java

public boolean supports(Convert<?, ?> operation) {
    final Class<?> rawTargetType = getRawTargetType(operation);
    final Class<?> useTargetType = ObjectUtils.defaultIfNull(ClassUtils.primitiveToWrapper(rawTargetType),
            rawTargetType);/*from   ww w  .j  av  a  2s  . c  om*/

    // per UEL spec v2.2 section 1.18:
    if (String.class.equals(useTargetType)) {
        return true;
    }
    final Object source = operation.getSourcePosition().getValue();

    if (BigDecimal.class.equals(useTargetType) || BigInteger.class.equals(useTargetType)
            || Number.class.isAssignableFrom(useTargetType)
                    && ClassUtils.wrapperToPrimitive(useTargetType) != null) {
        return source == null || source instanceof String || source instanceof Character
                || source instanceof Number;
    }
    if (Character.class.equals(useTargetType)) {
        return source == null || source instanceof String || source instanceof Number;
    }
    if (Boolean.class.equals(useTargetType)) {
        return source == null || source instanceof String;
    }
    if (Enum.class.isAssignableFrom(useTargetType)) {
        return source == null || source instanceof String;
    }
    return source == null || "".equals(source)
            || source instanceof String && PropertyEditorManager.findEditor(useTargetType) != null;
}

From source file:io.tilt.minka.utils.Defaulter.java

private static PropertyEditor edit(final Properties props, final Object configurable, final Field staticField,
        final Field instanceField) throws IllegalAccessException {

    staticField.setAccessible(true);/*from  www  .j a va  2s  .co m*/
    final String name = instanceField.getName();
    final String staticValue = staticField.get(configurable).toString();
    final Object propertyOrDefault = props.getProperty(name, System.getProperty(name, staticValue));
    final String objName = configurable.getClass().getSimpleName();
    final PropertyEditor editor = PropertyEditorManager.findEditor(instanceField.getType());
    final String setLog = "Defaulter: set <{}> field [{}] = '{}' from {} ";
    try {
        editor.setAsText(propertyOrDefault.toString());
        logger.info(setLog, objName, name, editor.getValue(),
                propertyOrDefault != staticValue ? " property " : staticField.getName());
    } catch (Exception e) {
        logger.error(
                "Defaulter: object <{}> field: {} does not accept property or static "
                        + "default value: {} (reason: {})",
                objName, name, propertyOrDefault, e.getClass().getSimpleName());
        try { // at this moment only prop. might've been failed
            editor.setAsText(staticValue);
            logger.info(setLog, objName, name, editor.getValue(), staticField.getName());
        } catch (Exception e2) {
            final StringBuilder sb = new StringBuilder().append("Defaulter: object <").append(objName)
                    .append("> field: ").append(name).append(" does not accept static default value: ")
                    .append(propertyOrDefault).append(" (reason: ").append(e.getClass().getSimpleName())
                    .append(")");
            throw new RuntimeException(sb.toString());
        }

    }

    return editor;
}

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

private PropertyEditor lookupEditor(Class type) {
    // check misses first
    if (misses.containsKey(type)) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("No previously found property editor for type: " + type);
        }//from   www .ja va  2 s.c  o m
        return null;
    }

    synchronized (cache) {
        // not a miss then try to lookup the editor
        PropertyEditor editor = cache.get(type);
        if (editor == null) {
            // findEditor is synchronized and very slow so we want to only lookup once for a given key
            // and then we use our own local cache for faster lookup
            editor = PropertyEditorManager.findEditor(type);

            // either we found an editor, or if not then register it as a miss
            if (editor != null) {
                if (LOG.isTraceEnabled()) {
                    LOG.trace("Found property editor for type: " + type + " -> " + editor);
                }
                cache.put(type, editor);
            } else {
                if (LOG.isTraceEnabled()) {
                    LOG.trace("Cannot find property editor for type: " + type);
                }
                misses.put(type, type);
            }
        }
        return editor;
    }
}

From source file:com.sworddance.beans.PropertyAdaptor.java

/** @since 1.1 */
private Object convertValueForAssignment(Object target, String value) {
    if (value == null || getReturnType().isInstance(value)) {
        return value;
    }//from   w  ww . j  ava  2s. c  o  m

    PropertyEditor e = PropertyEditorManager.findEditor(getReturnType());

    if (e == null) {
        Object convertedValue = instantiateViaStringConstructor(value);

        if (convertedValue != null) {
            return convertedValue;
        }

        throw new ApplicationGeneralException("noPropertyEditor(" + propertyName + "+)" + target.getClass());
    }

    try {
        e.setAsText(value);

        return e.getValue();
    } catch (Exception ex) {
        throw new ApplicationGeneralException(
                "unableToConvert(" + value + ", " + getReturnType() + ", " + propertyName + ", " + target, ex);
    }
}

From source file:therian.operator.convert.ELCoercionConverter.java

@Override
public boolean supports(TherianContext context, Convert<?, ?> convert) {
    if (!super.supports(context, convert)) {
        return false;
    }/*from w  ww. j a v  a2s . c o m*/
    final Class<?> rawTargetType = getRawTargetType(convert);
    final Class<?> useTargetType = ObjectUtils.defaultIfNull(ClassUtils.primitiveToWrapper(rawTargetType),
            rawTargetType);

    // per UEL spec v2.2 section 1.18:
    if (String.class.equals(useTargetType)) {
        return true;
    }
    final Object source = convert.getSourcePosition().getValue();

    if (BigDecimal.class.equals(useTargetType) || BigInteger.class.equals(useTargetType)
            || Number.class.isAssignableFrom(useTargetType)
                    && ClassUtils.wrapperToPrimitive(useTargetType) != null) {
        return source == null || source instanceof String || source instanceof Character
                || source instanceof Number;
    }
    if (Character.class.equals(useTargetType)) {
        return source == null || source instanceof String || source instanceof Number;
    }
    if (Boolean.class.equals(useTargetType)) {
        return source == null || source instanceof String;
    }
    if (Enum.class.isAssignableFrom(useTargetType)) {
        return source == null || source instanceof String;
    }
    return source == null || "".equals(source)
            || source instanceof String && PropertyEditorManager.findEditor(useTargetType) != null;
}

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

/**
 * convert via a {@link java.beans.PropertyEditor}
 *///from   w  w  w . ja v  a2 s  .c  om
// 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.lnicholls.galleon.gui.HMEConfigurationPanel.java

public HMEConfigurationPanel(Object bean) {

    setLayout(new GridLayout(0, 1));

    target = bean;//from   w ww  . ja v a 2  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.ppwcode.vernacular.value_III.jsf.AutomaticPropertyEditorConverter.java

/**
 * A {@link PropertyEditor} for the//from  w w w .  j av a  2s  .co m
 * {@link ValueBinding#getType(FacesContext) type of the value binding}
 * is requested from the {@link PropertyEditorManager}. If no such
 * editor is found, a {@link ConverterException} is thrown.
 * If the retrieved {@link PropertyEditor} is of type,
 * {@link DisplayLocaleBasedEnumerationValueEditor},
 * the {@link DisplayLocaleBasedEnumerationValueEditor#setDisplayLocale(Locale) display locale}
 * of the editor is set to the locale of the current {@link UIViewRoot}.
 *
 * @basic
 * @throws ConverterException
 *         PropertyEditorManager.findEditor(
 *           component.getValueBinding("value").getType(context)
 *         ) == null;
 *         No {@link PropertyEditor} found for the type of the value binding
 *         of <code>component</code>
 */
@Override
protected PropertyEditor getPropertyEditor(final FacesContext context, final UIComponent component)
        throws ConverterException {
    assert component != null;
    assert context != null;
    if ($propertyEditor == null) {
        LOG.debug("no PropertyEditor in cache; retrieving fresh one");
        try {
            // try to find target type
            Class<?> targetType = component.getValueBinding("value").getType(context);
            /* throws EvaluationException < PropertyNotFoundException
               throws NullPointerException, not  for component == null, context == null
               or "value" == null, but because their might not be a value binding */
            if (targetType.isArray()) {
                LOG.debug("target type " + targetType + " is an array. Converting "
                        + "arrays makes no sense, we probably want to convert elements "
                        + "of the array (and the component is a compound handling "
                        + "component, like selectMany). We'll look for a converter for the "
                        + "component type.");
                targetType = targetType.getComponentType();
            }
            // try to find a property editor for target type
            LOG.debug("target type of component value binding \"value\": " + targetType);
            $propertyEditor = PropertyEditorManager.findEditor(targetType);
            if ($propertyEditor == null) { // still
                LOG.debug("no PropertyEditor found for type \"" + targetType + "\"");
                throw new ConverterException("Could not locate a PropertyEditor for type " + targetType);
            } else {
                LOG.debug("PropertyEditor found: " + $propertyEditor);
                if ($propertyEditor instanceof DisplayLocaleBasedEnumerationValueEditor) {
                    assert $propertyEditor != null;
                    Locale displayLocale = context.getViewRoot().getLocale();
                    LOG.debug("PropertyEditor is of type DisplayLocaleBasedEnumerationValueEditor; "
                            + "setting display locale to " + displayLocale);
                    ((DisplayLocaleBasedEnumerationValueEditor<?>) $propertyEditor)
                            .setDisplayLocale(displayLocale);
                }
            }
        } catch (NullPointerException npExc) {
            new ConverterException(
                    "Could not retrieve target type from component, " + "because there is no value binding");
        } catch (EvaluationException eExc) { // and PropertyNotFoundException
            new ConverterException("Could not retrieve target type from component", eExc);
        }
    }
    LOG.debug("returning PropertyEditor: " + $propertyEditor);
    return $propertyEditor;
}

From source file:org.fusesource.meshkeeper.util.internal.IntrospectionSupport.java

private static Object convert(Object value, Class<?> type) {
    PropertyEditor editor = PropertyEditorManager.findEditor(type);
    if (editor != null) {
        editor.setAsText(value.toString());
        return editor.getValue();
    }/*  w w w . j a v a  2s  .c  om*/
    return null;
}