Example usage for java.beans Introspector getBeanInfo

List of usage examples for java.beans Introspector getBeanInfo

Introduction

In this page you can find the example usage for java.beans Introspector getBeanInfo.

Prototype

public static BeanInfo getBeanInfo(Class<?> beanClass) throws IntrospectionException 

Source Link

Document

Introspect on a Java Bean and learn about all its properties, exposed methods, and events.

Usage

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. j  a  v a  2 s  .  co  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:org.apache.ojb.broker.metadata.fieldaccess.PersistentFieldIntrospectorImpl.java

/**
 * Get the PropertyDescriptor for aClass and aPropertyName
 *//*from w  ww  .j  a va2  s.c  om*/
protected static PropertyDescriptor findPropertyDescriptor(Class aClass, String aPropertyName) {
    BeanInfo info;
    PropertyDescriptor[] pd;
    PropertyDescriptor descriptor = null;

    try {
        info = Introspector.getBeanInfo(aClass);
        pd = info.getPropertyDescriptors();
        for (int i = 0; i < pd.length; i++) {
            if (pd[i].getName().equals(aPropertyName)) {
                descriptor = pd[i];
                break;
            }
        }
        if (descriptor == null) {
            /*
            * Daren Drummond:    Throw here so we are consistent
            *                with PersistentFieldDefaultImpl.
            */
            throw new MetadataException("Can't find property " + aPropertyName + " in " + aClass.getName());
        }
        return descriptor;
    } catch (IntrospectionException ex) {
        /*
        * Daren Drummond:    Throw here so we are consistent
        *                with PersistentFieldDefaultImpl.
        */
        throw new MetadataException("Can't find property " + aPropertyName + " in " + aClass.getName(), ex);
    }
}

From source file:org.apache.tiles.evaluator.el.TilesContextELResolver.java

/**
 * Collects bean infos from a class and filling a list.
 *
 * @param clazz The class to be inspected.
 * @param list The list to fill.// www. j  a v a 2s. c  om
 * @param properties The properties set to be filled.
 * @since 2.1.0
 */
protected void collectBeanInfo(Class<?> clazz, List<FeatureDescriptor> list, Set<String> properties) {
    BeanInfo info = null;
    try {
        info = Introspector.getBeanInfo(clazz);
    } catch (Exception ex) {
        if (log.isDebugEnabled()) {
            log.debug("Cannot inspect class " + clazz, ex);
        }
    }
    if (info == null) {
        return;
    }
    for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
        pd.setValue("type", pd.getPropertyType());
        pd.setValue("resolvableAtDesignTime", Boolean.TRUE);
        list.add(pd);
        properties.add(pd.getName());
    }
}

From source file:org.apache.axis2.jaxws.utility.XMLRootElementUtil.java

/**
 * The JAXBClass has a set of bean properties each represented by a PropertyDescriptor Each of
 * the fields of the class has an associated xml name. The method returns a map where the key is
 * the xml name and value is the PropertyDescriptor
 *
 * @param jaxbClass/*  ww w  . j  ava  2s  . c o m*/
 * @return map
 */
public static Map<String, PropertyDescriptorPlus> createPropertyDescriptorMap(Class jaxbClass)
        throws NoSuchFieldException, IntrospectionException {

    if (log.isDebugEnabled()) {
        log.debug("Get the PropertyDescriptor[] for " + jaxbClass);
    }

    PropertyDescriptor[] pds = Introspector.getBeanInfo(jaxbClass).getPropertyDescriptors();
    Map<String, PropertyDescriptorPlus> map = new HashMap<String, PropertyDescriptorPlus>();

    // Unfortunately the element names are stored on the fields.
    // Get all of the fields in the class and super classes

    List<Field> fields = getFields(jaxbClass);

    // Now match up the fields with the property descriptors...Sigh why didn't JAXB put the @XMLElement annotations on the 
    // property methods!
    for (PropertyDescriptor pd : pds) {

        // Skip over the class property..it is never represented as an xml element
        if (pd.getName().equals("class")) {
            continue;
        }

        // For the current property, find a matching field...so that we can get the xml name
        boolean found = false;
        if (log.isDebugEnabled()) {
            log.debug("  Start: Find xmlname for property:" + pd.getName());
        }
        for (Field field : fields) {
            String fieldName = field.getName();

            // Use the name of the field and property to find the match
            if (fieldName.equalsIgnoreCase(pd.getDisplayName()) || fieldName.equalsIgnoreCase(pd.getName())) {
                // Get the xmlElement name for this field
                QName xmlName = getXmlElementRefOrElementQName(field.getDeclaringClass(), field);
                found = true;
                if (log.isDebugEnabled()) {
                    log.debug("    Found field " + field.getName() + " which has xmlname=" + xmlName);
                }
                if (map.get(xmlName) != null) {
                    if (log.isDebugEnabled()) {
                        log.debug("    ALERT: property " + map.get(xmlName).getPropertyName()
                                + " already has this same xmlName..this may cause problems.");
                    }
                }
                map.put(xmlName.getLocalPart(), new PropertyDescriptorPlus(pd, xmlName));
                break;
            }

            // Unfortunately, sometimes the field name is preceeded by an underscore
            if (fieldName.startsWith("_")) {
                fieldName = fieldName.substring(1);
                if (fieldName.equalsIgnoreCase(pd.getDisplayName())
                        || fieldName.equalsIgnoreCase(pd.getName())) {
                    // Get the xmlElement name for this field
                    QName xmlName = getXmlElementRefOrElementQName(field.getDeclaringClass(), field);
                    found = true;
                    if (log.isDebugEnabled()) {
                        log.debug("    Found field " + field.getName() + " which has xmlname=" + xmlName);
                    }
                    if (map.get(xmlName) != null) {
                        if (log.isDebugEnabled()) {
                            log.debug("    ALERT: property " + map.get(xmlName).getPropertyName()
                                    + " already has this same xmlName..this may cause problems.");
                        }
                    }
                    map.put(xmlName.getLocalPart(), new PropertyDescriptorPlus(pd, xmlName));
                    break;
                }
            }
        }

        // We didn't find a field.  Default the xmlname to the property name
        if (!found) {
            String xmlName = pd.getName();
            if (log.isDebugEnabled()) {
                log.debug("    A matching field was not found.  Defaulting xmlname to " + xmlName);
            }
            if (map.get(xmlName) != null) {
                if (log.isDebugEnabled()) {
                    log.debug("    ALERT: property " + map.get(xmlName).getPropertyName()
                            + " already has this same xmlName..this may cause problems.");
                }
            }
            map.put(xmlName, new PropertyDescriptorPlus(pd, xmlName));
        }
        if (log.isDebugEnabled()) {
            log.debug("  End: Find xmlname for property:" + pd.getName());
        }
    }
    return map;
}

From source file:com.sunsprinter.diffunit.core.translators.AbstractPropertyDrivenTranslator.java

protected Collection<PropertyDescriptor> retrieveAllProperties(final T object) throws TranslationException {
    try {//  w  w w  .j  a va  2  s. c  o  m
        final Collection<PropertyDescriptor> properties = new TreeSet<PropertyDescriptor>(
                createPropertyDescriptorComparator());
        properties.addAll(Arrays.asList(Introspector.getBeanInfo(object.getClass()).getPropertyDescriptors()));
        return properties;
    } catch (final IntrospectionException e) {
        throw new TranslationException(object, String.format("Unable to retrieve properties for object '%s'.",
                getInstanceTracker().getObjectId(object)));
    }
}

From source file:org.jaffa.soa.dataaccess.TransformerUtils.java

/**
 * Same as printGraph(Object source), except the objectStack lists all the parent
 * objects its printed, and if this is one of them, it stops. This allows detection
 * of possible infinite recusion.//from  w  ww.j  a  v  a2s. c  o  m
 *
 * @param source      Javabean who's contents should be printed
 * @param objectStack List of objects already traversed
 * @return multi-line string of this beans properties and their values
 */
public static String printGraph(Object source, List objectStack) {
    if (source == null)
        return null;

    // Prevent infinite object recursion
    if (objectStack != null)
        if (objectStack.contains(source))
            return "Object Already Used. " + source.getClass().getName() + '@' + source.hashCode();
        else
            objectStack.add(source);
    else {
        objectStack = new ArrayList();
        objectStack.add(source);
    }

    StringBuffer out = new StringBuffer();
    out.append(source.getClass().getName());
    out.append("\n");

    try {
        BeanInfo sInfo = Introspector.getBeanInfo(source.getClass());
        PropertyDescriptor[] sDescriptors = sInfo.getPropertyDescriptors();
        if (sDescriptors != null && sDescriptors.length != 0)
            for (int i = 0; i < sDescriptors.length; i++) {
                PropertyDescriptor sDesc = sDescriptors[i];
                Method sm = sDesc.getReadMethod();
                if (sm != null && sDesc.getWriteMethod() != null) {
                    if (!sm.isAccessible())
                        sm.setAccessible(true);
                    Object sValue = sm.invoke(source, (Object[]) null);

                    out.append("  ");
                    out.append(sDesc.getName());
                    if (source instanceof GraphDataObject) {
                        if (((GraphDataObject) source).hasChanged(sDesc.getName()))
                            out.append('*');
                    }
                    out.append('=');
                    if (sValue == null)
                        out.append("<--NULL-->\n");
                    else if (sm.getReturnType().isArray()
                            && !sm.getReturnType().getComponentType().isPrimitive()) {
                        StringBuffer out2 = new StringBuffer();
                        out2.append("Array of ");
                        out2.append(sm.getReturnType().getComponentType().getName());
                        out2.append("\n");
                        // Loop through array
                        Object[] a = (Object[]) sValue;
                        for (int j = 0; j < a.length; j++) {
                            out2.append('[');
                            out2.append(j);
                            out2.append("] ");
                            if (a[j] == null)
                                out2.append("<--NULL-->");
                            else if (GraphDataObject.class.isAssignableFrom(a[j].getClass()))
                                out2.append(((GraphDataObject) a[j]).toString(objectStack));
                            else
                                //out2.append(StringHelper.linePad(a[j].toString(), 4, " ",true));
                                out2.append(a[j].toString());
                        }
                        out.append(StringHelper.linePad(out2.toString(), 4, " ", true));
                    } else {
                        if (GraphDataObject.class.isAssignableFrom(sValue.getClass()))
                            out.append(StringHelper.linePad(((GraphDataObject) sValue).toString(objectStack), 4,
                                    " ", true));
                        else {
                            out.append(StringHelper.linePad(sValue.toString(), 4, " ", true));
                            out.append("\n");
                        }

                    }
                }
            }
    } catch (IllegalAccessException e) {
        TransformException me = new TransformException(TransformException.ACCESS_ERROR, "???", e.getMessage());
        log.error(me.getLocalizedMessage(), e);
        //throw me;
    } catch (InvocationTargetException e) {
        TransformException me = new TransformException(TransformException.INVOCATION_ERROR, "???", e);
        log.error(me.getLocalizedMessage(), me.getCause());
        //throw me;
    } catch (IntrospectionException e) {
        TransformException me = new TransformException(TransformException.INTROSPECT_ERROR, "???",
                e.getMessage());
        log.error(me.getLocalizedMessage(), e);
        //throw me;
    }
    return out.toString();
}

From source file:org.tros.utils.PropertiesInitializer.java

/**
 * Initialize from JSON if possible./*from w w  w .  j  a  v a 2s  . co  m*/
 *
 * @param dir
 */
private void initializeFromJson(String dir) {
    if (dir == null) {
        return;
    }
    String propFile = dir + '/' + this.getClass().getSimpleName() + ".properties";
    File f = new File(propFile);
    if (f.exists()) {

        try (FileInputStream fis = new FileInputStream(f)) {
            PropertyDescriptor[] props = Introspector.getBeanInfo(this.getClass()).getPropertyDescriptors();
            PropertiesInitializer obj = (PropertiesInitializer) readValue(fis, this.getClass());

            for (PropertyDescriptor p : props) {
                if (p.getWriteMethod() != null && p.getReadMethod() != null
                        && p.getReadMethod().getDeclaringClass() != Object.class) {
                    Object val = p.getReadMethod().invoke(obj);
                    if (val != null) {
                        p.getWriteMethod().invoke(this, val);
                    }
                }
            }
        } catch (NullPointerException | IOException | IllegalArgumentException | InvocationTargetException
                | IllegalAccessException ex) {
            LOGGER.debug(null, ex);
        } catch (IntrospectionException ex) {
            LOGGER.warn(null, ex);
        }
    }
}

From source file:org.apache.myfaces.util.DebugUtils.java

private static void printComponent(UIComponent comp, PrintStream stream, int indent,
        boolean withChildrenAndFacets, String facetName) {
    printIndent(stream, indent);/*from  ww  w.  ja v a2s. c  o  m*/
    stream.print('<');

    String compType = comp.getClass().getName();
    if (compType.startsWith(JSF_COMPONENT_PACKAGE)) {
        compType = compType.substring(JSF_COMPONENT_PACKAGE.length());
    } else if (compType.startsWith(MYFACES_COMPONENT_PACKAGE)) {
        compType = compType.substring(MYFACES_COMPONENT_PACKAGE.length());
    }
    stream.print(compType);

    printAttribute(stream, "id", comp.getId());

    if (facetName != null) {
        printAttribute(stream, "facetName", facetName);
    }

    for (Iterator it = comp.getAttributes().entrySet().iterator(); it.hasNext();) {
        Map.Entry entry = (Map.Entry) it.next();
        if (!"id".equals(entry.getKey())) {
            printAttribute(stream, (String) entry.getKey(), entry.getValue());
        }
    }

    //HACK: comp.getAttributes() only returns attributes, that are NOT backed
    //by a corresponding component property. So, we must explicitly get the
    //available properties by Introspection:
    BeanInfo beanInfo;
    try {
        beanInfo = Introspector.getBeanInfo(comp.getClass());
    } catch (IntrospectionException e) {
        throw new RuntimeException(e);
    }

    PropertyDescriptor propDescriptors[] = beanInfo.getPropertyDescriptors();
    for (int i = 0; i < propDescriptors.length; i++) {
        if (propDescriptors[i].getReadMethod() != null) {
            String name = propDescriptors[i].getName();
            if (!"id".equals(name)) {
                ValueBinding vb = comp.getValueBinding(name);
                if (vb != null) {
                    printAttribute(stream, name, vb.getExpressionString());
                } else {
                    if (name.equals("value") && comp instanceof ValueHolder) {
                        //-> localValue
                    } else if (!IGNORE_ATTRIBUTES.contains(name)) {
                        try {
                            Object value = comp.getAttributes().get(name);
                            printAttribute(stream, name, value);
                        } catch (Exception e) {
                            log.error(e);
                            printAttribute(stream, name, null);
                        }
                    }
                }
            }
        }
    }

    boolean mustClose = true;
    boolean nestedObjects = false;

    if (comp instanceof UICommand) {
        FacesListener[] listeners = ((UICommand) comp).getActionListeners();
        if (listeners != null && listeners.length > 0) {
            nestedObjects = true;
            stream.println('>');
            mustClose = false;
            for (int i = 0; i < listeners.length; i++) {
                FacesListener listener = listeners[i];
                printIndent(stream, indent + 1);
                stream.print('<');
                stream.print(listener.getClass().getName());
                stream.println("/>");
            }
        }
    }

    if (comp instanceof UIInput) {
        FacesListener[] listeners = ((UIInput) comp).getValueChangeListeners();
        if (listeners != null && listeners.length > 0) {
            nestedObjects = true;
            stream.println('>');
            mustClose = false;
            for (int i = 0; i < listeners.length; i++) {
                FacesListener listener = listeners[i];
                printIndent(stream, indent + 1);
                stream.print('<');
                stream.print(listener.getClass().getName());
                stream.println("/>");
            }
        }

        Validator[] validators = ((UIInput) comp).getValidators();
        if (validators != null && validators.length > 0) {
            nestedObjects = true;
            stream.println('>');
            mustClose = false;
            for (int i = 0; i < validators.length; i++) {
                Validator validator = validators[i];
                printIndent(stream, indent + 1);
                stream.print('<');
                stream.print(validator.getClass().getName());
                stream.println("/>");
            }
        }
    }

    if (withChildrenAndFacets) {
        int childCount = comp.getChildCount();
        Map facetsMap = comp.getFacets();
        if (childCount > 0 || !facetsMap.isEmpty()) {
            nestedObjects = true;
            if (mustClose) {
                stream.println('>');
                mustClose = false;
            }

            if (childCount > 0) {
                for (Iterator it = comp.getChildren().iterator(); it.hasNext();) {
                    UIComponent child = (UIComponent) it.next();
                    printComponent(child, stream, indent + 1, true, null);
                }
            }

            for (Iterator it = facetsMap.entrySet().iterator(); it.hasNext();) {
                Map.Entry entry = (Map.Entry) it.next();
                printComponent((UIComponent) entry.getValue(), stream, indent + 1, true,
                        (String) entry.getKey());
            }
        }
    }

    if (nestedObjects) {
        if (mustClose) {
            stream.println("/>");
        } else {
            printIndent(stream, indent);
            stream.print("</");
            stream.print(compType);
            stream.println('>');
        }
    } else {
        stream.println("/>");
    }
}

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
 *///from w  w  w. j a  va 2 s .c  om
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:no.sesat.search.datamodel.DataModelFactoryImplTest.java

private <T> T testInstantiate(final Class<T> cls) throws IntrospectionException {

    LOG.info("    instantiating " + cls.getSimpleName());

    final PropertyDescriptor[] properties = Introspector.getBeanInfo(cls).getPropertyDescriptors();
    final Property[] props = new Property[properties.length];
    for (int i = 0; i < props.length; ++i) {
        props[i] = new Property(properties[i].getName(), null);
    }/*from   w ww.j a  va2 s. co m*/

    final T data = factory.instantiate(cls, datamodel, props);

    assert null != data : "instantiate(" + cls.getSimpleName() + ", properties) returned null";
    LOG.info("      instantiated .." + data.toString().replaceFirst("no.sesat.search.datamodel", ""));

    return data;
}