Example usage for java.beans PropertyDescriptor getPropertyEditorClass

List of usage examples for java.beans PropertyDescriptor getPropertyEditorClass

Introduction

In this page you can find the example usage for java.beans PropertyDescriptor getPropertyEditorClass.

Prototype

public Class<?> getPropertyEditorClass() 

Source Link

Document

Gets any explicit PropertyEditor Class that has been registered for this property.

Usage

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

/**
 * Attempt to find custom property editor on descriptor first, else try the propery editor manager.
 *
 * @param desc - PropertyDescriptor.// w  w w.  j a v  a 2s .c om
 * @return - the PropertyEditor for the given PropertyDescriptor.
 * @throws InstantiationException - thrown when getting the PropertyEditor for the class.
 * @throws IllegalAccessException - thrown when getting the PropertyEditor for the class.
 */
protected PropertyEditor getPropertyEditor(PropertyDescriptor desc)
        throws InstantiationException, IllegalAccessException {
    Class<?> cls = desc.getPropertyEditorClass();
    if (null != cls) {
        return (PropertyEditor) cls.newInstance();
    }
    return getPropertyEditorValue(desc.getPropertyType());
}

From source file:com.springframework.beans.CachedIntrospectionResults.java

private PropertyDescriptor buildGenericTypeAwarePropertyDescriptor(Class<?> beanClass, PropertyDescriptor pd) {
    try {//from  w  w  w  .  j  av  a 2  s .  co m
        return new GenericTypeAwarePropertyDescriptor(beanClass, pd.getName(), pd.getReadMethod(),
                pd.getWriteMethod(), pd.getPropertyEditorClass());
    } catch (IntrospectionException ex) {
        throw new FatalBeanException("Failed to re-introspect class [" + beanClass.getName() + "]", ex);
    }
}

From source file:com.twinsoft.convertigo.beans.core.MySimpleBeanInfo.java

protected PropertyDescriptor getPropertyDescriptor(String name) throws IntrospectionException {
    checkAdditionalProperties();/*from  ww w .jav  a  2  s .  co m*/
    for (int i = 0; i < properties.length; i++) {
        PropertyDescriptor property = properties[i];
        if (name.equals(property.getName())) {
            PropertyDescriptor clone = new PropertyDescriptor(name, property.getReadMethod(),
                    property.getWriteMethod());
            clone.setDisplayName(property.getDisplayName());
            clone.setShortDescription(property.getShortDescription());
            clone.setPropertyEditorClass(property.getPropertyEditorClass());
            clone.setBound(property.isBound());
            clone.setConstrained(property.isConstrained());
            clone.setExpert(property.isExpert());
            clone.setHidden(property.isHidden());
            clone.setPreferred(property.isPreferred());
            for (String attributeName : Collections.list(property.attributeNames())) {
                clone.setValue(attributeName, property.getValue(attributeName));
            }
            return properties[i] = clone;
        }
    }
    return null;
}

From source file:com.springframework.beans.CachedIntrospectionResults.java

/**
 * Create a new CachedIntrospectionResults instance for the given class.
 * @param beanClass the bean class to analyze
 * @throws BeansException in case of introspection failure
 *///from  ww w  .ja v  a2 s .  c  om
private CachedIntrospectionResults(Class<?> beanClass) throws BeansException {
    try {
        if (logger.isTraceEnabled()) {
            logger.trace("Getting BeanInfo for class [" + beanClass.getName() + "]");
        }

        BeanInfo beanInfo = null;
        for (BeanInfoFactory beanInfoFactory : beanInfoFactories) {
            beanInfo = beanInfoFactory.getBeanInfo(beanClass);
            if (beanInfo != null) {
                break;
            }
        }
        if (beanInfo == null) {
            // If none of the factories supported the class, fall back to the default
            beanInfo = (shouldIntrospectorIgnoreBeaninfoClasses
                    ? Introspector.getBeanInfo(beanClass, Introspector.IGNORE_ALL_BEANINFO)
                    : Introspector.getBeanInfo(beanClass));
        }
        this.beanInfo = beanInfo;

        if (logger.isTraceEnabled()) {
            logger.trace("Caching PropertyDescriptors for class [" + beanClass.getName() + "]");
        }
        this.propertyDescriptorCache = new LinkedHashMap<String, PropertyDescriptor>();

        // This call is slow so we do it once.
        PropertyDescriptor[] pds = this.beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor pd : pds) {
            if (Class.class.equals(beanClass)
                    && ("classLoader".equals(pd.getName()) || "protectionDomain".equals(pd.getName()))) {
                // Ignore Class.getClassLoader() and getProtectionDomain() methods - nobody needs to bind to those
                continue;
            }
            if (logger.isTraceEnabled()) {
                logger.trace("Found bean property '" + pd.getName() + "'"
                        + (pd.getPropertyType() != null ? " of type [" + pd.getPropertyType().getName() + "]"
                                : "")
                        + (pd.getPropertyEditorClass() != null
                                ? "; editor [" + pd.getPropertyEditorClass().getName() + "]"
                                : ""));
            }
            pd = buildGenericTypeAwarePropertyDescriptor(beanClass, pd);
            this.propertyDescriptorCache.put(pd.getName(), pd);
        }

        this.typeDescriptorCache = new ConcurrentReferenceHashMap<PropertyDescriptor, TypeDescriptor>();
    } catch (IntrospectionException ex) {
        throw new FatalBeanException("Failed to obtain BeanInfo for class [" + beanClass.getName() + "]", ex);
    } finally {

    }
}

From source file:eu.qualityontime.commons.QPropertyUtilsBean.java

/**
 * <p>/*  w  w  w  .  j a v  a  2s  .  co  m*/
 * Return the Java Class repesenting the property editor class that has been
 * registered for this property (if any). This method follows the same name
 * resolution rules used by <code>getPropertyDescriptor()</code>, so if the
 * last element of a name reference is indexed, the property editor for the
 * underlying property's class is returned.
 * </p>
 *
 * <p>
 * Note that <code>null</code> will be returned if there is no property, or
 * if there is no registered property editor class. Because this return
 * value is ambiguous, you should determine the existence of the property
 * itself by other means.
 * </p>
 *
 * <p>
 * <strong>FIXME</strong> - Does not work with DynaBeans.
 * </p>
 *
 * @param bean
 *            Bean for which a property descriptor is requested
 * @param name
 *            Possibly indexed and/or nested name of the property for which
 *            a property descriptor is requested
 * @return the property editor class
 *
 * @throws IllegalAccessException
 *             if the caller does not have access to the property accessor
 *             method
 * @throws IllegalArgumentException
 *             if <code>bean</code> or <code>name</code> is null
 * @throws IllegalArgumentException
 *             if a nested reference to a property returns null
 * @throws InvocationTargetException
 *             if the property accessor method throws an exception
 * @throws NoSuchMethodException
 *             if an accessor method for this propety cannot be found
 */
public Class<?> getPropertyEditorClass(final Object bean, final String name)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {

    if (bean == null) {
        throw new IllegalArgumentException("No bean specified");
    }
    if (name == null) {
        throw new IllegalArgumentException("No name specified for bean class '" + bean.getClass() + "'");
    }

    final PropertyDescriptor descriptor = getPropertyDescriptor(bean, name);
    if (descriptor != null) {
        return descriptor.getPropertyEditorClass();
    } else {
        return null;
    }

}

From source file:com.twinsoft.convertigo.beans.core.DatabaseObject.java

public Element toXml(Document document) throws EngineException {
    Element element = document.createElement(getDatabaseType().toLowerCase());

    element.setAttribute("classname", getClass().getName());
    if (exportOptions.contains(ExportOption.bIncludeVersion)) {
        element.setAttribute("version", com.twinsoft.convertigo.beans.Version.version);
    }//from w w w  .  j a va  2s  .  co m

    // Storing the database object priority
    element.setAttribute("priority", new Long(priority).toString());

    int len;
    PropertyDescriptor[] propertyDescriptors;
    PropertyDescriptor propertyDescriptor;
    Element propertyElement;

    try {
        BeanInfo bi = CachedIntrospector.getBeanInfo(getClass());
        propertyDescriptors = bi.getPropertyDescriptors();
        len = propertyDescriptors.length;
        if (exportOptions.contains(ExportOption.bIncludeDisplayName)) {
            element.setAttribute("displayName", bi.getBeanDescriptor().getDisplayName());
        }
    } catch (IntrospectionException e) {
        throw new EngineException("Couldn't introspect the bean \"" + getName() + "\"", e);
    }

    for (int i = 0; i < len; i++) {
        propertyDescriptor = propertyDescriptors[i];
        String name = propertyDescriptor.getName();
        String displayName = propertyDescriptor.getDisplayName();
        String shortDescription = propertyDescriptor.getShortDescription();

        Method getter = propertyDescriptor.getReadMethod();

        // Only analyze read propertyDescriptors.
        if (getter == null) {
            continue;
        }

        if (checkBlackListParentClass(propertyDescriptor)) {
            continue;
        }

        try {
            // Storing the database object bean properties
            Object uncompiledValue = getCompilablePropertySourceValue(name);
            Object compiledValue = null;
            Object cypheredValue = null;
            Object value = getter.invoke(this);

            if (uncompiledValue != null) {
                compiledValue = value;
                value = uncompiledValue;
            }

            // Only write non-null values
            if (value == null) {
                Engine.logBeans.warn("Attempting to store null property (\"" + name + "\"); skipping...");
                continue;
            }

            propertyElement = document.createElement("property");
            propertyElement.setAttribute("name", name);

            // Encrypts value if needed
            //if (isCipheredProperty(name) && !this.exportOptions.contains(ExportOption.bIncludeDisplayName)) {
            if (isCipheredProperty(name) && (this.exportOptions.contains(ExportOption.bHidePassword)
                    || !this.exportOptions.contains(ExportOption.bIncludeDisplayName))) {
                cypheredValue = encryptPropertyValue(value);
                if (!value.equals(cypheredValue)) {
                    value = cypheredValue;
                    propertyElement.setAttribute("ciphered", "true");
                }
            }

            // Stores the value
            Node node = null;
            if (exportOptions.contains(ExportOption.bIncludeCompiledValue)) {
                node = XMLUtils.writeObjectToXml(document, value, compiledValue);
            } else {
                node = XMLUtils.writeObjectToXml(document, value);
            }
            propertyElement.appendChild(node);

            // Add visibility for logs
            if (!isTraceableProperty(name)) {
                propertyElement.setAttribute("traceable", "false");
            }

            if (exportOptions.contains(ExportOption.bIncludeBlackListedElements)) {
                Object propertyDescriptorBlackListValue = propertyDescriptor
                        .getValue(MySimpleBeanInfo.BLACK_LIST_NAME);
                if (propertyDescriptorBlackListValue != null && (Boolean) propertyDescriptorBlackListValue) {
                    propertyElement.setAttribute("blackListed", "blackListed");
                }
            }
            if (exportOptions.contains(ExportOption.bIncludeDisplayName)) {
                propertyElement.setAttribute("displayName", displayName);
                propertyElement.setAttribute("isHidden", Boolean.toString(propertyDescriptor.isHidden()));
                propertyElement.setAttribute("isMasked",
                        isMaskedProperty(Visibility.Platform, name) ? "true" : "false");
                propertyElement.setAttribute("isExpert", Boolean.toString(propertyDescriptor.isExpert()));
            }
            if (exportOptions.contains(ExportOption.bIncludeShortDescription)) {
                propertyElement.setAttribute("shortDescription", shortDescription);
            }

            if (exportOptions.contains(ExportOption.bIncludeEditorClass)) {
                Class<?> pec = propertyDescriptor.getPropertyEditorClass();
                String message = "";
                if (pec != null) {
                    message = propertyDescriptor.getPropertyEditorClass().toString().replaceFirst("(.)*\\.",
                            "");
                } else {
                    message = "null";
                }
                if (this instanceof ITagsProperty || (pec != null && Enum.class.isAssignableFrom(pec))) {
                    String[] sResults = null;
                    try {
                        if (this instanceof ITagsProperty) {
                            sResults = ((ITagsProperty) this).getTagsForProperty(name);
                        } else {
                            sResults = EnumUtils.toNames(pec);
                        }
                    } catch (Exception ex) {
                        sResults = new String[0];
                    }

                    if (sResults != null) {
                        if (sResults.length > 0) {
                            Element possibleValues = document.createElement("possibleValues");
                            Element possibleValue = null;
                            for (int j = 0; j < sResults.length; j++) {
                                possibleValue = document.createElement("value");
                                possibleValue.setTextContent(sResults[j]);
                                possibleValues.appendChild(possibleValue);
                            }
                            propertyElement.appendChild(possibleValues);
                        }
                    }
                }
                propertyElement.setAttribute("editorClass", message);
            }

            element.appendChild(propertyElement);

            if (Boolean.TRUE.equals(propertyDescriptor.getValue("nillable"))) {
                try {
                    Method method = this.getClass().getMethod("isNullProperty", new Class[] { String.class });
                    Object isNull = method.invoke(this, new Object[] { name });
                    propertyElement.setAttribute("isNull", isNull.toString());
                } catch (Exception ex) {
                    Engine.logBeans.error(
                            "[Serialization] Skipping 'isNull' attribute for property \"" + name + "\".", ex);
                }
            }
        } catch (Exception e) {
            Engine.logBeans.error("[Serialization] Skipping property \"" + name + "\".", e);
        }
    }

    return element;
}

From source file:net.yasion.common.core.bean.wrapper.CachedIntrospectionResults.java

/**
 * Create a new CachedIntrospectionResults instance for the given class.
 * /*from   w  w  w .  j av a2 s  . c  om*/
 * @param beanClass
 *            the bean class to analyze
 * @throws BeansException
 *             in case of introspection failure
 */
private CachedIntrospectionResults(Class<?> beanClass) throws BeansException {
    try {
        if (logger.isTraceEnabled()) {
            logger.trace("Getting BeanInfo for class [" + beanClass.getName() + "]");
        }

        BeanInfo beanInfo = null;
        for (BeanInfoFactory beanInfoFactory : beanInfoFactories) {
            beanInfo = beanInfoFactory.getBeanInfo(beanClass);
            if (beanInfo != null) {
                break;
            }
        }
        if (beanInfo == null) {
            // If none of the factories supported the class, fall back to the default
            beanInfo = (shouldIntrospectorIgnoreBeaninfoClasses
                    ? Introspector.getBeanInfo(beanClass, Introspector.IGNORE_ALL_BEANINFO)
                    : Introspector.getBeanInfo(beanClass));
        }
        this.beanInfo = beanInfo;

        if (logger.isTraceEnabled()) {
            logger.trace("Caching PropertyDescriptors for class [" + beanClass.getName() + "]");
        }
        this.propertyDescriptorCache = new LinkedHashMap<String, PropertyDescriptor>();

        // This call is slow so we do it once.
        PropertyDescriptor[] pds = this.beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor pd : pds) {
            if (Class.class.equals(beanClass)
                    && ("classLoader".equals(pd.getName()) || "protectionDomain".equals(pd.getName()))) {
                // Ignore Class.getClassLoader() and getProtectionDomain() methods - nobody needs to bind to those
                continue;
            }
            if (logger.isTraceEnabled()) {
                logger.trace("Found bean property '" + pd.getName() + "'"
                        + (pd.getPropertyType() != null ? " of type [" + pd.getPropertyType().getName() + "]"
                                : "")
                        + (pd.getPropertyEditorClass() != null
                                ? "; editor [" + pd.getPropertyEditorClass().getName() + "]"
                                : ""));
            }
            pd = buildGenericTypeAwarePropertyDescriptor(beanClass, pd);
            this.propertyDescriptorCache.put(pd.getName(), pd);
        }

        this.typeDescriptorCache = new ConcurrentReferenceHashMap<PropertyDescriptor, TypeDescriptor>();
    } catch (IntrospectionException ex) {
        throw new FatalBeanException("Failed to obtain BeanInfo for class [" + beanClass.getName() + "]", ex);
    }
}

From source file:org.apache.jmeter.testbeans.gui.GenericTestBeanCustomizer.java

/**
 * Create a customizer for a given test bean type.
 *
 * @param testBeanClass/*w w w.j ava  2s . c  o m*/
 *            a subclass of TestBean
 * @see org.apache.jmeter.testbeans.TestBean
 */
GenericTestBeanCustomizer(BeanInfo beanInfo) {
    super();

    this.beanInfo = beanInfo;

    // Get and sort the property descriptors:
    descriptors = beanInfo.getPropertyDescriptors();
    Arrays.sort(descriptors, new PropertyComparator(beanInfo));

    // Obtain the propertyEditors:
    editors = new PropertyEditor[descriptors.length];
    int scriptLanguageIndex = 0;
    int textAreaEditorIndex = 0;
    for (int i = 0; i < descriptors.length; i++) { // Index is also used for accessing editors array
        PropertyDescriptor descriptor = descriptors[i];
        String name = descriptor.getName();

        // Don't get editors for hidden or non-read-write properties:
        if (TestBeanHelper.isDescriptorIgnored(descriptor)) {
            log.debug("Skipping editor for property " + name);
            editors[i] = null;
            continue;
        }

        PropertyEditor propertyEditor;
        Object guiType = descriptor.getValue(GUITYPE);
        if (guiType instanceof TypeEditor) {
            propertyEditor = ((TypeEditor) guiType).getInstance(descriptor);
        } else if (guiType instanceof Class && Enum.class.isAssignableFrom((Class<?>) guiType)) {
            @SuppressWarnings("unchecked") // we check the class type above
            final Class<? extends Enum<?>> enumClass = (Class<? extends Enum<?>>) guiType;
            propertyEditor = new EnumEditor(descriptor, enumClass,
                    (ResourceBundle) descriptor.getValue(GenericTestBeanCustomizer.RESOURCE_BUNDLE));
        } else {
            Class<?> editorClass = descriptor.getPropertyEditorClass();
            if (log.isDebugEnabled()) {
                log.debug("Property " + name + " has editor class " + editorClass);
            }

            if (editorClass != null) {
                try {
                    propertyEditor = (PropertyEditor) editorClass.newInstance();
                } catch (InstantiationException | IllegalAccessException e) {
                    log.error("Can't create property editor.", e);
                    throw new Error(e.toString());
                }
            } else {
                Class<?> c = descriptor.getPropertyType();
                propertyEditor = PropertyEditorManager.findEditor(c);
            }
        }

        if (propertyEditor == null) {
            log.warn("No editor for property: " + name + " type: " + descriptor.getPropertyType() + " in bean: "
                    + beanInfo.getBeanDescriptor().getDisplayName());
            editors[i] = null;
            continue;
        }

        if (log.isDebugEnabled()) {
            log.debug("Property " + name + " has property editor " + propertyEditor);
        }

        validateAttributes(descriptor, propertyEditor);

        if (!propertyEditor.supportsCustomEditor()) {
            propertyEditor = createWrapperEditor(propertyEditor, descriptor);

            if (log.isDebugEnabled()) {
                log.debug("Editor for property " + name + " is wrapped in " + propertyEditor);
            }
        }
        if (propertyEditor instanceof TestBeanPropertyEditor) {
            ((TestBeanPropertyEditor) propertyEditor).setDescriptor(descriptor);
        }

        if (propertyEditor instanceof TextAreaEditor) {
            textAreaEditorIndex = i;
        }
        if (propertyEditor.getCustomEditor() instanceof JScrollPane) {
            scrollerCount++;
        }

        editors[i] = propertyEditor;

        // Initialize the editor with the provided default value or null:
        setEditorValue(i, descriptor.getValue(DEFAULT));

        if (name.equals("scriptLanguage")) {
            scriptLanguageIndex = i;
        }

    }
    // In case of BSF and JSR elements i want to add textAreaEditor as a listener to scriptLanguage ComboBox.
    String beanName = this.beanInfo.getBeanDescriptor().getName();
    if (beanName.startsWith("BSF") || beanName.startsWith("JSR223")) { // $NON-NLS-1$ $NON-NLS-2$
        WrapperEditor we = (WrapperEditor) editors[scriptLanguageIndex];
        TextAreaEditor tae = (TextAreaEditor) editors[textAreaEditorIndex];
        we.addChangeListener(tae);
    }

    // Obtain message formats:
    propertyFieldLabelMessage = new MessageFormat(JMeterUtils.getResString("property_as_field_label")); //$NON-NLS-1$
    propertyToolTipMessage = new MessageFormat(JMeterUtils.getResString("property_tool_tip")); //$NON-NLS-1$

    // Initialize the GUI:
    init();
}

From source file:org.eclipse.wb.internal.core.model.description.rules.StandardBeanPropertiesRule.java

private static void tryToSetPropertyEditorAWT(PropertyDescriptor propertyDescriptor,
        GenericPropertyDescription propertyDescription) throws Exception {
    // check for editor based on attributes of PropertyDescriptor
    {/*  ww  w.  j  ava 2s  .  co m*/
        PropertyEditor editor = DescriptionPropertiesHelper.getEditorForPropertyDescriptor(propertyDescriptor);
        if (editor != null) {
            propertyDescription.setEditor(editor);
            return;
        }
    }
    // check for java.beans.PropertyEditor
    Class<?> propertyEditorType = propertyDescriptor.getPropertyEditorClass();
    if (propertyEditorType != null) {
        PropertyEditor editor = DescriptionPropertiesHelper.getEditorForEditorType(propertyEditorType);
        propertyDescription.setEditor(editor);
    }
}

From source file:org.enerj.apache.commons.beanutils.PropertyUtilsBean.java

/**
 * <p>Return the Java Class repesenting the property editor class that has
 * been registered for this property (if any).  This method follows the
 * same name resolution rules used by <code>getPropertyDescriptor()</code>,
 * so if the last element of a name reference is indexed, the property
 * editor for the underlying property's class is returned.</p>
 *
 * <p>Note that <code>null</code> will be returned if there is no property,
 * or if there is no registered property editor class.  Because this
 * return value is ambiguous, you should determine the existence of the
 * property itself by other means.</p>
 *
 * <p><strong>FIXME</strong> - Does not work with DynaBeans.</p>
 *
 * @param bean Bean for which a property descriptor is requested
 * @param name Possibly indexed and/or nested name of the property for
 *  which a property descriptor is requested
 *
 * @exception IllegalAccessException if the caller does not have
 *  access to the property accessor method
 * @exception IllegalArgumentException if <code>bean</code> or
 *  <code>name</code> is null
 * @exception IllegalArgumentException if a nested reference to a
 *  property returns null//from   w w w. j  a v  a 2s  .co m
 * @exception InvocationTargetException if the property accessor method
 *  throws an exception
 * @exception NoSuchMethodException if an accessor method for this
 *  propety cannot be found
 */
public Class getPropertyEditorClass(Object bean, String name)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {

    if (bean == null) {
        throw new IllegalArgumentException("No bean specified");
    }
    if (name == null) {
        throw new IllegalArgumentException("No name specified");
    }

    PropertyDescriptor descriptor = getPropertyDescriptor(bean, name);
    if (descriptor != null) {
        return (descriptor.getPropertyEditorClass());
    } else {
        return (null);
    }

}