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:org.androidtransfuse.processor.Merger.java

private <T extends Mergeable> T mergeMergeable(Class<? extends T> targetClass, T target, T source)
        throws MergerException {

    try {/*ww  w  . ja va 2  s.  co m*/

        BeanInfo beanInfo = Introspector.getBeanInfo(targetClass);

        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            Method getter = propertyDescriptor.getReadMethod();
            Method setter = propertyDescriptor.getWriteMethod();

            String propertyName = propertyDescriptor.getDisplayName();

            if (PropertyUtils.isWriteable(target, propertyName)) {

                //check for mergeCollection
                MergeCollection mergeCollection = findAnnotation(MergeCollection.class, getter, setter);
                if (Collection.class.isAssignableFrom(propertyDescriptor.getPropertyType())) {
                    PropertyUtils.setProperty(target, propertyName,
                            mergeList(mergeCollection, propertyName, target, source));
                }

                //check for merge
                Merge mergeAnnotation = findAnnotation(Merge.class, getter, setter);
                PropertyUtils.setProperty(target, propertyName,
                        mergeProperties(mergeAnnotation, propertyName, target, source));
            }
        }
    } catch (NoSuchMethodException e) {
        throw new MergerException("NoSuchMethodException while trying to merge", e);
    } catch (IntrospectionException e) {
        throw new MergerException("IntrospectionException while trying to merge", e);
    } catch (IllegalAccessException e) {
        throw new MergerException("IllegalAccessException while trying to merge", e);
    } catch (InvocationTargetException e) {
        throw new MergerException("InvocationTargetException while trying to merge", e);
    }

    return target;
}

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

public static DatabaseObject read(Node node) throws EngineException {
    String objectClassName = "n/a";
    String childNodeName = "n/a";
    String propertyName = "n/a";
    String propertyValue = "n/a";
    DatabaseObject databaseObject = null;
    Element element = (Element) node;

    objectClassName = element.getAttribute("classname");

    // Migration to 4.x+ projects
    if (objectClassName.equals("com.twinsoft.convertigo.beans.core.ScreenClass")) {
        objectClassName = "com.twinsoft.convertigo.beans.screenclasses.JavelinScreenClass";
    }/*from  w  ww  .  j  a v  a 2s  .  c  o  m*/

    String version = element.getAttribute("version");
    if ("".equals(version)) {
        version = node.getOwnerDocument().getDocumentElement().getAttribute("beans");
        if (!"".equals(version)) {
            element.setAttribute("version", version);
        }
    }
    // Verifying product version
    if (VersionUtils.compareProductVersion(Version.productVersion, version) < 0) {
        String message = "Unable to create an object of product version superior to the current beans product version ("
                + com.twinsoft.convertigo.beans.Version.version + ").\n" + "Object class: " + objectClassName
                + "\n" + "Object version: " + version;
        EngineException ee = new EngineException(message);
        throw ee;
    }

    try {
        Engine.logBeans.trace("Creating object of class \"" + objectClassName + "\"");
        databaseObject = (DatabaseObject) Class.forName(objectClassName).newInstance();
    } catch (Exception e) {
        String s = node.getNodeName();// XMLUtils.prettyPrintDOM(node);
        String message = "Unable to create a new instance of the object from the serialized XML data.\n"
                + "Object class: '" + objectClassName + "'\n" + "Object version: " + version + "\n"
                + "XML data:\n" + s;
        EngineException ee = new EngineException(message, e);
        throw ee;
    }

    try {
        // Performs custom configuration before object de-serialization
        databaseObject.preconfigure(element);
    } catch (Exception e) {
        String s = XMLUtils.prettyPrintDOM(node);
        String message = "Unable to configure the object from serialized XML data before its creation.\n"
                + "Object class: '" + objectClassName + "'\n" + "XML data:\n" + s;
        EngineException ee = new EngineException(message, e);
        throw ee;
    }

    try {
        long priority = new Long(element.getAttribute("priority")).longValue();
        databaseObject.priority = priority;

        Class<? extends DatabaseObject> databaseObjectClass = databaseObject.getClass();
        BeanInfo bi = CachedIntrospector.getBeanInfo(databaseObjectClass);
        PropertyDescriptor[] pds = bi.getPropertyDescriptors();

        NodeList childNodes = element.getChildNodes();
        int len = childNodes.getLength();

        PropertyDescriptor pd;
        Object propertyObjectValue;
        Class<?> propertyType;
        NamedNodeMap childAttributes;
        boolean maskValue = false;

        for (int i = 0; i < len; i++) {
            Node childNode = childNodes.item(i);
            if (childNode.getNodeType() != Node.ELEMENT_NODE) {
                continue;
            }

            Element childElement = (Element) childNode;

            childNodeName = childNode.getNodeName();

            Engine.logBeans.trace("Analyzing node '" + childNodeName + "'");

            if (childNodeName.equalsIgnoreCase("property")) {
                childAttributes = childNode.getAttributes();
                propertyName = childAttributes.getNamedItem("name").getNodeValue();
                Engine.logBeans.trace("  name = '" + propertyName + "'");
                pd = findPropertyDescriptor(pds, propertyName);
                if (pd == null) {
                    Engine.logBeans.warn(
                            "Unable to find the definition of property \"" + propertyName + "\"; skipping.");
                    continue;
                }
                propertyType = pd.getPropertyType();
                propertyObjectValue = XMLUtils
                        .readObjectFromXml((Element) XMLUtils.findChildNode(childNode, Node.ELEMENT_NODE));

                // Hides value in log trace if needed
                if ("false".equals(childElement.getAttribute("traceable"))) {
                    maskValue = true;
                }
                Engine.logBeans.trace("  value='"
                        + (maskValue ? Visibility.maskValue(propertyObjectValue) : propertyObjectValue) + "'");

                // Decrypts value if needed
                try {
                    if ("true".equals(childElement.getAttribute("ciphered"))) {
                        propertyObjectValue = decryptPropertyValue(propertyObjectValue);
                    }
                } catch (Exception e) {
                }

                propertyObjectValue = databaseObject.compileProperty(propertyType, propertyName,
                        propertyObjectValue);

                if (Enum.class.isAssignableFrom(propertyType)) {
                    propertyObjectValue = EnumUtils.valueOf(propertyType, propertyObjectValue);
                }

                propertyValue = propertyObjectValue.toString();

                Method setter = pd.getWriteMethod();
                Engine.logBeans.trace("  setter='" + setter.getName() + "'");
                Engine.logBeans.trace("  param type='" + propertyObjectValue.getClass().getName() + "'");
                Engine.logBeans.trace("  expected type='" + propertyType.getName() + "'");
                try {
                    setter.invoke(databaseObject, new Object[] { propertyObjectValue });
                } catch (InvocationTargetException e) {
                    Throwable targetException = e.getTargetException();
                    Engine.logBeans.warn("Unable to set the property '" + propertyName + "' for the object '"
                            + databaseObject.getName() + "' (" + objectClassName + "): ["
                            + targetException.getClass().getName() + "] " + targetException.getMessage());
                }

                if (Boolean.TRUE.equals(pd.getValue("nillable"))) {
                    Node nodeNull = childAttributes.getNamedItem("isNull");
                    String valNull = (nodeNull == null) ? "false" : nodeNull.getNodeValue();
                    Engine.logBeans.trace("  treats as null='" + valNull + "'");
                    try {
                        Method method = databaseObject.getClass().getMethod("setNullProperty",
                                new Class[] { String.class, Boolean.class });
                        method.invoke(databaseObject, new Object[] { propertyName, Boolean.valueOf(valNull) });
                    } catch (Exception ex) {
                        Engine.logBeans.warn("Unable to set the 'isNull' attribute for property '"
                                + propertyName + "' of '" + databaseObject.getName() + "' object");
                    }
                }
            }
        }
    } catch (Exception e) {
        String message = "Unable to set the object properties from the serialized XML data.\n"
                + "Object class: '" + objectClassName + "'\n" + "XML analyzed node: " + childNodeName + "\n"
                + "Property name: " + propertyName + "\n" + "Property value: " + propertyValue;
        EngineException ee = new EngineException(message, e);
        throw ee;
    }

    try {
        // Performs custom configuration
        databaseObject.configure(element);
    } catch (Exception e) {
        String s = XMLUtils.prettyPrintDOM(node);
        String message = "Unable to configure the object from serialized XML data after its creation.\n"
                + "Object class: '" + objectClassName + "'\n" + "XML data:\n" + s;
        EngineException ee = new EngineException(message, e);
        throw ee;
    }

    return databaseObject;
}

From source file:org.theospi.portfolio.shared.model.impl.GenericXmlRenderer.java

protected void addObjectNodeInfo(Element parentNode, Object object, Element structure, String container,
        String site, String context) throws IntrospectionException {
    if (object == null)
        return;//  w  w w  . j  a  v a  2  s  .  c  o m
    // go through each property... put each one in...
    logger.debug("adding object of class " + object.getClass());

    BeanInfo info = Introspector.getBeanInfo(object.getClass());

    PropertyDescriptor[] props = info.getPropertyDescriptors();

    for (int i = 0; i < props.length; i++) {
        PropertyDescriptor property = props[i];
        logger.debug("examining property: " + property.getName());
        if (isTraversableType(property, structure)) {
            if (isCollection(property, structure)) {
                addCollectionItems(parentNode, property, object, structure, container, site, context);
            } else if (isArtifact(property, structure)) {
                addArtifactItem(parentNode, property, object, container, site, context);
            } else {
                addItem(parentNode, property, object, structure, container, site, context);
            }
        } else {
            addItemToXml(parentNode, property, object);
        }

    }
}

From source file:com.link_intersystems.beans.BeanClass.java

/**
 * @param stopClass/*from   w  w  w .j a v  a2  s .c o m*/
 *            the class to stop {@link PropertyDescriptor} resolution. Must
 *            be a superclass of this class. If the stop class is not null
 *            then all {@link PropertyDescriptor}s are contained in the
 *            result map that this class and every class along the hierarchy
 *            until the stop class has. The {@link PropertyDescriptor} of
 *            the stop class are not included.
 * @return a map whose keys are the property names of the properties that
 *         this class defines according to the java bean specification. The
 *         values are the corresponding {@link PropertyDescriptor}s. The
 *         returned {@link Map} can be modified by clients without
 *         interfering this object's state.
 * @throws IllegalArgumentException
 *             if the stop class is not a super class of this class or
 *             another Exception occurs while resolving the
 *             {@link PropertyDescriptor}s. The cause might be an
 *             {@link IntrospectionException}.
 * @since 1.2.0.0
 */
public Map<String, PropertyDescriptor> getPropertyDescriptors(Class<?> stopClass) throws IllegalStateException {
    Class<T> beanType = getType();
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(beanType, stopClass);
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        Map<String, PropertyDescriptor> propertyDescriptorsMap = UtilFacade.keyMap(
                Arrays.asList(propertyDescriptors),
                new MethodInvokingParameterizedObjectFactory<PropertyDescriptor, String>(
                        PropertyDescriptor.class, "getName"));
        return propertyDescriptorsMap;
    } catch (IntrospectionException e) {
        throw new IllegalArgumentException(
                "Unable to build property map for " + beanType + " with stopClass " + stopClass, e);
    }
}

From source file:com.datatorrent.stram.appdata.AppDataPushAgent.java

private JSONObject extractFields(Object o) {
    List<Field> fields;
    Map<String, Method> methods;

    if (cacheFields.containsKey(o.getClass())) {
        fields = cacheFields.get(o.getClass());
    } else {/*from  w  ww . ja va  2 s  .c  o m*/
        fields = new ArrayList<Field>();

        for (Class<?> c = o.getClass(); c != Object.class; c = c.getSuperclass()) {
            Field[] declaredFields = c.getDeclaredFields();
            for (Field field : declaredFields) {
                field.setAccessible(true);
                AutoMetric rfa = field.getAnnotation(AutoMetric.class);
                if (rfa != null) {
                    field.setAccessible(true);
                    try {
                        fields.add(field);
                    } catch (Exception ex) {
                        LOG.debug("Error extracting fields for app data: {}. Ignoring.", ex.getMessage());
                    }
                }
            }
        }
        cacheFields.put(o.getClass(), fields);
    }
    JSONObject result = new JSONObject();
    for (Field field : fields) {
        try {
            result.put(field.getName(), field.get(o));
        } catch (Exception ex) {
            // ignore
        }
    }
    if (cacheGetMethods.containsKey(o.getClass())) {
        methods = cacheGetMethods.get(o.getClass());
    } else {
        methods = new HashMap<String, Method>();
        try {
            BeanInfo info = Introspector.getBeanInfo(o.getClass());
            for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
                Method method = pd.getReadMethod();
                if (pd.getReadMethod() != null) {
                    AutoMetric rfa = method.getAnnotation(AutoMetric.class);
                    if (rfa != null) {
                        methods.put(pd.getName(), method);
                    }
                }
            }
        } catch (IntrospectionException ex) {
            // ignore
        }
        cacheGetMethods.put(o.getClass(), methods);
    }
    for (Map.Entry<String, Method> entry : methods.entrySet()) {
        try {
            result.put(entry.getKey(), entry.getValue().invoke(o));
        } catch (Exception ex) {
            // ignore
        }
    }
    return result;
}

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 w w  .  ja v a2  s. 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.jsecurity.web.tags.PrincipalTag.java

private String getPrincipalProperty(Object principal, String property) throws JspTagException {
    String strValue = null;//w w  w .  java 2  s.  c  o m

    try {
        BeanInfo bi = Introspector.getBeanInfo(principal.getClass());

        // Loop through the properties to get the string value of the specified property
        boolean foundProperty = false;
        for (PropertyDescriptor pd : bi.getPropertyDescriptors()) {
            if (pd.getName().equals(property)) {
                Object value = pd.getReadMethod().invoke(principal, (Object[]) null);
                strValue = String.valueOf(value);
                foundProperty = true;
                break;
            }
        }

        if (!foundProperty) {
            final String message = "Property [" + property + "] not found in principal of type ["
                    + principal.getClass().getName() + "]";
            if (log.isErrorEnabled()) {
                log.error(message);
            }
            throw new JspTagException(message);
        }

    } catch (Exception e) {
        final String message = "Error reading property [" + property + "] from principal of type ["
                + principal.getClass().getName() + "]";
        if (log.isErrorEnabled()) {
            log.error(message, e);
        }
        throw new JspTagException(message, e);
    }

    return strValue;
}

From source file:org.eclipse.scada.configuration.recipe.lib.internal.DefaultExecutableFactory.java

protected void captureOutput(final Object o, final RunnerContext ctx, final EList<CaptureOutput> outputs)
        throws Exception {
    here: for (final CaptureOutput output : outputs) {
        final String name = output.getLocalName();
        final String storeName = output.getContextName() == null ? name : output.getContextName();

        logger.debug("Capture output: {} -> {}", name, storeName);

        final BeanInfo bi = Introspector.getBeanInfo(o.getClass());
        for (final PropertyDescriptor pd : bi.getPropertyDescriptors()) {
            if (pd.getName().equals(name)) {
                final Object value = pd.getReadMethod().invoke(o);
                ctx.getMap().put(storeName, value);
                logger.debug("By BeanInfo - value: {}", value);
                continue here;
            }/*from w  w  w.  ja  v a 2 s.co  m*/
        }

        final Field field = Reflections.findField(o.getClass(), name);
        if (field != null && field.getAnnotation(Output.class) != null) {
            final Object value = InjectHelper.getField(o, field);
            ctx.getMap().put(storeName, value);
            logger.debug("By field - value: {}", value);
            continue;
        }
        if (field != null) {
            throw new IllegalStateException(String.format(
                    "Unable to capture output. Field '%s' of class '%s' is not marked with @Output and is not accessible using a getter."));
        }

        throw new IllegalStateException(
                String.format("Unable to capture output '%s' of class '%s'", name, o.getClass()));
    }
}

From source file:org.jcurl.core.helpers.PropertyChangeSupport.java

/**
 * Creates a new instance of SafePropertyChangeSupport.
 * /*w w w.j  ava2s. c o  m*/
 * @param producer
 *            This is the object that is producing the property change
 *            events.
 * @throws RuntimeException
 *             If there is an introspection problem.
 */
public PropertyChangeSupport(final Object producer) {
    try {
        final BeanInfo info = Introspector.getBeanInfo(producer.getClass());
        for (final PropertyDescriptor element : info.getPropertyDescriptors())
            listenerMap.put(element.getName(), new WeakHashSet());
        listenerMap.put(ALL_PROPERTIES, new WeakHashSet());
        this.producer = producer;
    } catch (final IntrospectionException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.google.feedserver.util.BeanUtil.java

/**
 * Converts a JavaBean to a collection of properties
 * //from   ww w . j a  v a2s  . co m
 * @param bean The JavaBean to convert
 * @return A map of properties
 */
public Map<String, Object> convertBeanToProperties(Object bean) throws IntrospectionException,
        IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    Map<String, Object> properties = new HashMap<String, Object>();
    BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass(), Object.class);
    for (PropertyDescriptor p : beanInfo.getPropertyDescriptors()) {
        String name = p.getName();
        Method reader = p.getReadMethod();
        if (reader != null) {
            Object value = reader.invoke(bean);
            if (null != value) {
                if (value instanceof Timestamp) {
                    properties.put(name, value.toString());
                } else if (isBean(value.getClass())) {
                    if (value.getClass().isArray()) {
                        Object[] valueArray = (Object[]) value;
                        if (valueArray.length == 0) {
                            properties.put(name, null);
                        } else {
                            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                            for (Object object : (Object[]) value) {
                                list.add(convertBeanToProperties(object));
                            }
                            properties.put(name, list.toArray(new Map[0]));
                        }
                    } else {
                        properties.put(name, convertBeanToProperties(value));
                    }
                } else {
                    properties.put(name, value);
                }
            }
        }
    }
    return properties;
}