Example usage for java.beans BeanInfo getPropertyDescriptors

List of usage examples for java.beans BeanInfo getPropertyDescriptors

Introduction

In this page you can find the example usage for java.beans BeanInfo getPropertyDescriptors.

Prototype

PropertyDescriptor[] getPropertyDescriptors();

Source Link

Document

Returns descriptors for all properties of the bean.

Usage

From source file:de.xwic.appkit.core.transport.xml.EtoSerializer.java

/**
 * @param o/* www  .  j  ava  2s .  c om*/
 * @return
 * @throws IntrospectionException
 */
private static Map<String, PropertyDescriptor> getMap(final Object o) throws IntrospectionException {
    final BeanInfo beanInfo = Introspector.getBeanInfo(o.getClass(), Introspector.USE_ALL_BEANINFO);
    final List<PropertyDescriptor> asList = Arrays.asList(beanInfo.getPropertyDescriptors());
    final Map<String, PropertyDescriptor> map = MapUtil.generateMap(asList,
            new Function<PropertyDescriptor, String>() {

                @Override
                public String evaluate(final PropertyDescriptor obj) {
                    return obj.getName();
                }
            });
    return map;
}

From source file:org.apache.niolex.commons.bean.BeanUtil.java

/**
 * Merge the non null properties from the source bean to the target bean.
 *
 * @param to the target bean//from  ww w  .  j a v  a  2s .c  o  m
 * @param from the source bean
 * @param mergeDefault whether do we merge default numeric primitives
 * @return the target bean
 */
public static final <To, From> To merge(To to, From from, boolean mergeDefault) {
    try {
        Map<String, Method> writeMap = prepareWriteMethodMap(to.getClass());
        BeanInfo fromInfo = Introspector.getBeanInfo(from.getClass());
        // Iterate over all the attributes of from, do copy here.
        for (PropertyDescriptor descriptor : fromInfo.getPropertyDescriptors()) {
            Method readMethod = descriptor.getReadMethod();
            if (readMethod == null) {
                continue;
            }
            Method writeMethod = writeMap.get(descriptor.getName());
            if (writeMethod == null) {
                continue;
            }
            Object value = readMethod.invoke(from);
            if (value == null) {
                continue;
            }
            if (!mergeDefault && isNumericPrimitiveDefaultValue(readMethod.getReturnType(), value)) {
                continue;
            }
            // Only copy value if it's assignable, auto boxing is OK.
            if (ClassUtils.isAssignable(value.getClass(), writeMethod.getParameterTypes()[0], true)) {
                writeMethod.invoke(to, value);
            }
        }
    } catch (Exception e) {
        throw new IllegalArgumentException("Failed to merge propeties.", e);
    }
    return to;
}

From source file:org.archive.crawler.restlet.XmlMarshaller.java

/**
 * generate nested XML structure for a bean {@code obj}. enclosing element
 * will not be generated if {@code key} is empty. each readable JavaBeans property
 * is mapped to an nested element named after its name. Those properties
 * annotated with {@link XmlTransient} are ignored.
 * @param xmlWriter XmlWriter//from   ww w.ja v  a 2  s. c  om
 * @param key name of enclosing element
 * @param obj bean
 * @throws SAXException
 */
protected static void marshalBean(XmlWriter xmlWriter, String key, Object obj) throws SAXException {
    if (!StringUtils.isEmpty(key))
        xmlWriter.startElement(key);
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass(), Object.class);
        PropertyDescriptor[] props = beanInfo.getPropertyDescriptors();
        XmlType xmlType = obj.getClass().getAnnotation(XmlType.class);
        if (xmlType != null) {
            String[] propOrder = xmlType.propOrder();
            if (propOrder != null) {
                // TODO: should cache this sorted version?
                orderProperties(props, propOrder);
            }
        }
        for (PropertyDescriptor prop : props) {
            Method m = prop.getReadMethod();
            if (m == null || m.getAnnotation(XmlTransient.class) != null)
                continue;
            try {
                Object propValue = m.invoke(obj);
                if (propValue != null && !"".equals(propValue)) {
                    marshal(xmlWriter, prop.getName(), propValue);
                }
            } catch (Exception ex) {
                // generate empty element, for now. generate comment?
                xmlWriter.emptyElement(prop.getName());
            }
        }
    } catch (IntrospectionException ex) {
        // ignored, for now.
    }
    if (!StringUtils.isEmpty(key))
        xmlWriter.endElement(key);
}

From source file:org.zht.framework.util.ZBeanUtil.java

@SuppressWarnings("rawtypes")
public static Object convertMapToBean(Map map, Class<?> type) {
    Object obj = null;//  w  w  w .  ja va2s .  c  o  m
    try {
        BeanInfo beanInfo = null;

        beanInfo = Introspector.getBeanInfo(type);
        obj = type.newInstance();
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor property : propertyDescriptors) {
            String properName = property.getName();
            if (map.containsKey(property.getName())) {
                try {// ??

                    Object value = map.get(properName);
                    Method setter = property.getWriteMethod();
                    setter.invoke(obj, value);
                    //Unable to find non-private method
                    //               access.invoke(obj,"set" + ZStrUtil.toUpCaseFirst(properName),value);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        return obj;
    }
    return obj;
}

From source file:com.glaf.core.jdbc.connection.ConnectionProviderFactory.java

@SuppressWarnings("rawtypes")
private static ConnectionProvider createProvider(Properties properties, Map connectionProviderInjectionData) {
    if (properties == null || properties.isEmpty()) {
        return null;
    }/*from w w  w.ja v a 2 s . c o m*/
    log.debug("---------------------------ConnectionProvider create----------------");
    ConnectionProvider provider = null;
    String providerClass = properties.getProperty(DBConfiguration.JDBC_PROVIDER);
    if (providerClass != null) {
        provider = initializeConnectionProviderFromConfig(providerClass);
    } else if (c3p0ConfigDefined(properties) && c3p0ProviderPresent()) {
        provider = initializeConnectionProviderFromConfig(
                "com.glaf.core.jdbc.connection.C3P0ConnectionProvider");
    } else if (druidConfigDefined(properties) && druidProviderPresent()) {
        provider = initializeConnectionProviderFromConfig(
                "com.glaf.core.jdbc.connection.DruidConnectionProvider");
    }

    if (provider == null) {
        provider = initializeConnectionProviderFromConfig(
                "com.glaf.core.jdbc.connection.DruidConnectionProvider");
        if (StringUtils.equals(properties.getProperty(DBConfiguration.JDBC_DRIVER), "org.sqlite.JDBC")) {
            provider = initializeConnectionProviderFromConfig(
                    "com.glaf.core.jdbc.connection.C3P0ConnectionProvider");
        }
    }

    if (connectionProviderInjectionData != null && connectionProviderInjectionData.size() != 0) {
        try {
            BeanInfo info = Introspector.getBeanInfo(provider.getClass());
            PropertyDescriptor[] descritors = info.getPropertyDescriptors();
            int size = descritors.length;
            for (int index = 0; index < size; index++) {
                String propertyName = descritors[index].getName();
                if (connectionProviderInjectionData.containsKey(propertyName)) {
                    Method method = descritors[index].getWriteMethod();
                    method.invoke(provider, new Object[] { connectionProviderInjectionData.get(propertyName) });
                }
            }
        } catch (IntrospectionException e) {
            throw new RuntimeException("Unable to inject objects into the connection provider", e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException("Unable to inject objects into the connection provider", e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException("Unable to inject objects into the connection provider", e);
        }
    }
    provider.configure(properties);
    log.debug("---------------------------ConnectionProvider end----------------");
    return provider;
}

From source file:BeanUtil.java

/**
 * Retreives a property descriptor object for a given property.
 * <p>/*from  w  ww.j  ava2  s  .c o m*/
 * Uses the classes in <code>java.beans</code> to get back
 * a descriptor for a property.  Read-only and write-only
 * properties will have a slower return time.
 * </p>
 *
 * @param propertyName The programmatic name of the property
 * @param beanClass The Class object for the target bean.
 *                  For example sun.beans.OurButton.class.
 * @return a PropertyDescriptor for a property that follows the
 *         standard Java naming conventions.
 * @throws PropertyNotFoundException indicates that the property
 *         could not be found on the bean class.
 */
private static final PropertyDescriptor getPropertyDescriptor(String propertyName, Class beanClass) {

    PropertyDescriptor resultPropertyDescriptor = null;

    char[] pNameArray = propertyName.toCharArray();
    pNameArray[0] = Character.toLowerCase(pNameArray[0]);
    propertyName = new String(pNameArray);

    try {
        resultPropertyDescriptor = new PropertyDescriptor(propertyName, beanClass);
    } catch (IntrospectionException e1) {
        // Read-only and write-only properties will throw this
        // exception.  The properties must be looked up using
        // brute force.

        // This will get the list of all properties and iterate
        // through looking for one that matches the property
        // name passed into the method.
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);

            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

            for (int i = 0; i < propertyDescriptors.length; i++) {
                if (propertyDescriptors[i].getName().equals(propertyName)) {

                    // If the names match, this this describes the
                    // property being searched for.  Break out of
                    // the iteration.
                    resultPropertyDescriptor = propertyDescriptors[i];
                    break;
                }
            }
        } catch (IntrospectionException e2) {
            e2.printStackTrace();
        }
    }

    // If no property descriptor was found, then this bean does not
    // have a property matching the name passed in.
    if (resultPropertyDescriptor == null) {
        System.out.println("resultPropertyDescriptor == null");
    }

    return resultPropertyDescriptor;
}

From source file:ShowComponent.java

/**
 * This method loops through the command line arguments looking for class
 * names of components to create and property settings for those components
 * in the form name=value. This method demonstrates reflection and JavaBeans
 * introspection as they can be applied to dynamically created GUIs
 */// w  ww  .ja  v  a 2s  . com
public static Vector getComponentsFromArgs(String[] args) {
    Vector components = new Vector(); // List of components to return
    Component component = null; // The current component
    PropertyDescriptor[] properties = null; // Properties of the component
    Object[] methodArgs = new Object[1]; // We'll use this below

    nextarg: // This is a labeled loop
    for (int i = 0; i < args.length; i++) { // Loop through all arguments
        // If the argument does not contain an equal sign, then it is
        // a component class name. Otherwise it is a property setting
        int equalsPos = args[i].indexOf('=');
        if (equalsPos == -1) { // Its the name of a component
            try {
                // Load the named component class
                Class componentClass = Class.forName(args[i]);
                // Instantiate it to create the component instance
                component = (Component) componentClass.newInstance();
                // Use JavaBeans to introspect the component
                // And get the list of properties it supports
                BeanInfo componentBeanInfo = Introspector.getBeanInfo(componentClass);
                properties = componentBeanInfo.getPropertyDescriptors();
            } catch (Exception e) {
                // If any step failed, print an error and exit
                System.out.println("Can't load, instantiate, " + "or introspect: " + args[i]);
                System.exit(1);
            }

            // If we succeeded, store the component in the vector
            components.addElement(component);
        } else { // The arg is a name=value property specification
            String name = args[i].substring(0, equalsPos); // property name
            String value = args[i].substring(equalsPos + 1); // property
            // value

            // If we don't have a component to set this property on, skip!
            if (component == null)
                continue nextarg;

            // Now look through the properties descriptors for this
            // component to find one with the same name.
            for (int p = 0; p < properties.length; p++) {
                if (properties[p].getName().equals(name)) {
                    // Okay, we found a property of the right name.
                    // Now get its type, and the setter method
                    Class type = properties[p].getPropertyType();
                    Method setter = properties[p].getWriteMethod();

                    // Check if property is read-only!
                    if (setter == null) {
                        System.err.println("Property " + name + " is read-only");
                        continue nextarg; // continue with next argument
                    }

                    // Try to convert the property value to the right type
                    // We support a small set of common property types here
                    // Store the converted value in an Object[] so it can
                    // be easily passed when we invoke the property setter
                    try {
                        if (type == String.class) { // no conversion needed
                            methodArgs[0] = value;
                        } else if (type == int.class) { // String to int
                            methodArgs[0] = Integer.valueOf(value);
                        } else if (type == boolean.class) { // to boolean
                            methodArgs[0] = Boolean.valueOf(value);
                        } else if (type == Color.class) { // to Color
                            methodArgs[0] = Color.decode(value);
                        } else if (type == Font.class) { // String to Font
                            methodArgs[0] = Font.decode(value);
                        } else {
                            // If we can't convert, ignore the property
                            System.err
                                    .println("Property " + name + " is of unsupported type " + type.getName());
                            continue nextarg;
                        }
                    } catch (Exception e) {
                        // If conversion failed, continue with the next arg
                        System.err.println("Can't convert  '" + value + "' to type " + type.getName()
                                + " for property " + name);
                        continue nextarg;
                    }

                    // Finally, use reflection to invoke the property
                    // setter method of the component we created, and pass
                    // in the converted property value.
                    try {
                        setter.invoke(component, methodArgs);
                    } catch (Exception e) {
                        System.err.println("Can't set property: " + name);
                    }

                    // Now go on to next command-line arg
                    continue nextarg;
                }
            }

            // If we get here, we didn't find the named property
            System.err.println("Warning: No such property: " + name);
        }
    }

    return components;
}

From source file:com.ebay.pulsar.analytics.dao.service.BaseDBService.java

public static Map<String, Object> describe(Object obj) {
    if (obj == null) {
        return null;
    }/* ww w .j  a v  a 2  s .  c o m*/
    Map<String, Object> map = new HashMap<String, Object>();
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor property : propertyDescriptors) {
            String key = property.getName();
            if (!key.equals("class")) {
                try {
                    Method getter = property.getReadMethod();
                    Object value = getter.invoke(obj);
                    if (value != null) {

                        if ("properties".equalsIgnoreCase(key) || "config".equalsIgnoreCase(key)) {
                            value = new SerialBlob(((String) value).getBytes());
                        }
                        map.put(key, value);
                    }
                } catch (Exception e) {
                    logger.error("transBean1Map Error " + e);
                }
            }

        }
    } catch (Exception e) {
        logger.error("transBean2Map Error " + e);
    }
    return map;

}

From source file:com.sparkplatform.api.core.PropertyAsserter.java

/**
 * See {@link #assertBasicGetterSetterBehavior(Object,String)} method. Big difference here is that we try to
 * automatically introspect the target object, finding read/write properties, and automatically testing the getter
 * and setter. Note specifically that read-only properties are ignored, as there is no way for us to know how to set
 * the value (since there isn't a public setter).
 * <p/>/* w w w.  j  a  va2  s. com*/
 * Any property names contained in the blacklist will be skipped.
 * <p/>
 *
 * @param target        the object on which to invoke the getter and setter
 * @param propertyNames the list of property names that should not be tested
 */
public static void assertBasicGetterSetterBehaviorWithBlacklist(Object target, String... propertyNames) {
    List<String> blacklist = Arrays.asList(propertyNames);
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(target.getClass());
        PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor descriptor : descriptors) {
            if (descriptor.getWriteMethod() == null) {
                continue;
            }
            if (!blacklist.contains(descriptor.getDisplayName())) {
                assertBasicGetterSetterBehavior(target, descriptor.getDisplayName());
            }
        }
    } catch (IntrospectionException e) {
        fail("Failed while introspecting target " + target.getClass());
    }
}

From source file:org.apache.niolex.commons.bean.BeanUtil.java

/**
 * Parse all the write methods and prepare them to the hash map.
 *
 * @param toClass the class to be introspected
 * @return the hash map/*from  w ww  . j av a2 s .com*/
 * @throws IntrospectionException
 */
public static Map<String, Method> prepareWriteMethodMap(Class<?> toClass) throws IntrospectionException {
    BeanInfo toInfo = Introspector.getBeanInfo(toClass);
    HashMap<String, Method> writeMap = Maps.newHashMap();
    // Iterate over all the attributes of to, prepare write methods.
    for (PropertyDescriptor descriptor : toInfo.getPropertyDescriptors()) {
        Method writeMethod = descriptor.getWriteMethod();
        if (writeMethod == null) {
            continue;
        }
        writeMap.put(descriptor.getName(), writeMethod);
    }
    return writeMap;
}