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.apache.myfaces.tomahawk.util.ErrorPageWriter.java

private static void writeAttributes(Writer writer, UIComponent c) {
    try {/*from  w ww .  j  av a 2s . co m*/
        BeanInfo info = Introspector.getBeanInfo(c.getClass());
        PropertyDescriptor[] pd = info.getPropertyDescriptors();
        Method m = null;
        Object v = null;
        String str = null;
        for (int i = 0; i < pd.length; i++) {
            if (pd[i].getWriteMethod() != null && Arrays.binarySearch(IGNORE, pd[i].getName()) < 0) {
                m = pd[i].getReadMethod();
                try {
                    v = m.invoke(c, null);
                    if (v != null) {
                        if (v instanceof Collection || v instanceof Map || v instanceof Iterator) {
                            continue;
                        }
                        writer.write(" ");
                        writer.write(pd[i].getName());
                        writer.write("=\"");
                        if (v instanceof Expression) {
                            str = ((Expression) v).getExpressionString();
                        }
                        writer.write(str.replaceAll("<", TS));
                        writer.write("\"");
                    }
                } catch (Exception e) {
                    // do nothing
                }
            }
        }

        ValueExpression binding = c.getValueExpression("binding");
        if (binding != null) {
            writer.write(" binding=\"");
            writer.write(binding.getExpressionString().replaceAll("<", TS));
            writer.write("\"");
        }
    } catch (Exception e) {
        // do nothing
    }
}

From source file:net.sf.ij_plugins.util.DialogUtil.java

/**
 * Utility to automatically create ImageJ's GenericDialog for editing bean properties. It uses BeanInfo to extract
 * display names for each field. If a fields type is not supported irs name will be displayed with a tag
 * "[Unsupported type: class_name]".//www .ja v  a  2s .c o  m
 *
 * @param bean
 * @return <code>true</code> if user closed bean dialog using OK button, <code>false</code> otherwise.
 */
static public boolean showGenericDialog(final Object bean, final String title) {
    final BeanInfo beanInfo;
    try {
        beanInfo = Introspector.getBeanInfo(bean.getClass());
    } catch (IntrospectionException e) {
        throw new IJPluginsRuntimeException("Error extracting bean info.", e);
    }

    final GenericDialog genericDialog = new GenericDialog(title);

    // Create generic dialog fields for each bean's property
    final PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    try {
        for (int i = 0; i < propertyDescriptors.length; i++) {
            final PropertyDescriptor pd = propertyDescriptors[i];
            final Class type = pd.getPropertyType();
            if (type.equals(Class.class) && "class".equals(pd.getName())) {
                continue;
            }

            final Object o = PropertyUtils.getSimpleProperty(bean, pd.getName());
            if (type.equals(Boolean.TYPE)) {
                boolean value = ((Boolean) o).booleanValue();
                genericDialog.addCheckbox(pd.getDisplayName(), value);
            } else if (type.equals(Integer.TYPE)) {
                int value = ((Integer) o).intValue();
                genericDialog.addNumericField(pd.getDisplayName(), value, 0);
            } else if (type.equals(Float.TYPE)) {
                double value = ((Float) o).doubleValue();
                genericDialog.addNumericField(pd.getDisplayName(), value, 6, 10, "");
            } else if (type.equals(Double.TYPE)) {
                double value = ((Double) o).doubleValue();
                genericDialog.addNumericField(pd.getDisplayName(), value, 6, 10, "");
            } else {
                genericDialog.addMessage(pd.getDisplayName() + "[Unsupported type: " + type + "]");
            }

        }
    } catch (IllegalAccessException e) {
        throw new IJPluginsRuntimeException(e);
    } catch (InvocationTargetException e) {
        throw new IJPluginsRuntimeException(e);
    } catch (NoSuchMethodException e) {
        throw new IJPluginsRuntimeException(e);
    }

    //        final Panel helpPanel = new Panel();
    //        helpPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 0));
    //        final Button helpButton = new Button("Help");
    ////                helpButton.addActionListener(this);
    //        helpPanel.add(helpButton);
    //        genericDialog.addPanel(helpPanel, GridBagConstraints.EAST, new Insets(15,0,0,0));

    // Show modal dialog
    genericDialog.showDialog();
    if (genericDialog.wasCanceled()) {
        return false;
    }

    // Read fields from generic dialog into bean's properties.
    try {
        for (int i = 0; i < propertyDescriptors.length; i++) {
            final PropertyDescriptor pd = propertyDescriptors[i];
            final Class type = pd.getPropertyType();
            final Object propertyValue;
            if (type.equals(Boolean.TYPE)) {
                boolean value = genericDialog.getNextBoolean();
                propertyValue = Boolean.valueOf(value);
            } else if (type.equals(Integer.TYPE)) {
                int value = (int) Math.round(genericDialog.getNextNumber());
                propertyValue = new Integer(value);
            } else if (type.equals(Float.TYPE)) {
                double value = genericDialog.getNextNumber();
                propertyValue = new Float(value);
            } else if (type.equals(Double.TYPE)) {
                double value = genericDialog.getNextNumber();
                propertyValue = new Double(value);
            } else {
                continue;
            }
            PropertyUtils.setProperty(bean, pd.getName(), propertyValue);
        }
    } catch (IllegalAccessException e) {
        throw new IJPluginsRuntimeException(e);
    } catch (InvocationTargetException e) {
        throw new IJPluginsRuntimeException(e);
    } catch (NoSuchMethodException e) {
        throw new IJPluginsRuntimeException(e);
    }

    return true;
}

From source file:org.jaffa.util.BeanHelper.java

/** This method will introspect the bean & get the setter method for the input propertyName.
 * It will then try & convert the propertyValue to the appropriate datatype.
 * Finally it will invoke the setter./*from  ww  w  . j  a va 2s . c o  m*/
 * @return A true indicates, the property was succesfully set to the passed value. A false indicates the property doesn't exist or the propertyValue passed is not compatible with the setter.
 * @param bean The bean class to be introspected.
 * @param propertyName The Property being searched for.
 * @param propertyValue The value to be set.
 * @throws IntrospectionException if an exception occurs during introspection.
 * @throws IllegalAccessException if the underlying method is inaccessible.
 * @throws InvocationTargetException if the underlying method throws an exception.
 */
public static boolean setField(Object bean, String propertyName, Object propertyValue)
        throws IntrospectionException, IllegalAccessException, InvocationTargetException {
    boolean result = false;
    if (bean instanceof DynaBean) {
        try {
            PropertyUtils.setProperty(bean, propertyName, propertyValue);
            result = true;
        } catch (NoSuchMethodException ignore) {
            // If the bean is a FlexBean instance, then the field could exist on the associated persistentObject
            if (bean instanceof FlexBean && ((FlexBean) bean).getPersistentObject() != null) {
                try {
                    PropertyUtils.setProperty(((FlexBean) bean).getPersistentObject(), propertyName,
                            propertyValue);
                    result = true;
                } catch (NoSuchMethodException ignore2) {
                }
            }
        }
    } else {
        BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
        if (beanInfo != null) {
            PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
            if (pds != null) {
                for (PropertyDescriptor pd : pds) {
                    if (StringHelper.equalsIgnoreCaseFirstChar(pd.getName(), propertyName)) {
                        Method m = pd.getWriteMethod();
                        Object convertedPropertyValue = null;
                        if (propertyValue != null) {
                            if (pd.getPropertyType().isEnum()) {
                                convertedPropertyValue = findEnum(pd.getPropertyType(),
                                        propertyValue.toString());
                            } else {
                                try {
                                    convertedPropertyValue = DataTypeMapper.instance().map(propertyValue,
                                            pd.getPropertyType());
                                } catch (Exception e) {
                                    // do nothing
                                    break;
                                }
                            }
                        }
                        m.invoke(bean, new Object[] { convertedPropertyValue });
                        result = true;
                        break;
                    }
                }
            }
        }

        try {
            // Finally, check the FlexBean
            if (!result && bean instanceof IFlexFields && ((IFlexFields) bean).getFlexBean() != null
                    && ((IFlexFields) bean).getFlexBean().getDynaClass()
                            .getDynaProperty(propertyName) != null) {
                ((IFlexFields) bean).getFlexBean().set(propertyName, propertyValue);
                result = true;
            }
        } catch (Exception ignore) {
        }
    }
    return result;
}

From source file:disko.DU.java

@SuppressWarnings("unchecked")
public static <T> T cloneObject(T p, Mapping<Pair<Object, String>, Boolean> propertyFilter) throws Exception {
    if (p == null)
        return null;

    if (p instanceof Cloneable) {
        Method cloneMethod = p.getClass().getMethod("clone", (Class[]) null);
        if (cloneMethod != null)
            return (T) cloneMethod.invoke(p, (Object[]) null);

    } else if (p.getClass().isArray()) {
        Object[] A = (Object[]) p;
        Class<?> type = p.getClass();
        Object[] ac = (Object[]) Array.newInstance(type.getComponentType(), A.length);
        for (int i = 0; i < A.length; i++)
            ac[i] = cloneObject(A[i], propertyFilter);
        return (T) ac;
    } else if (identityCloneClasses.contains(p.getClass()))
        return p;

    ////  w  w w  .ja v  a 2s  . com
    // Need to implement cloning ourselves. We do this by copying bean properties.
    //
    Constructor<?> cons = null;

    try {
        cons = p.getClass().getConstructor((Class[]) null);
    } catch (Throwable t) {
        return p;
    }

    Object copy = cons.newInstance((Object[]) null);

    if (p instanceof Collection) {
        Collection<Object> cc = (Collection<Object>) copy;
        for (Object el : (Collection<?>) p)
            cc.add(cloneObject(el, propertyFilter));
    } else if (p instanceof Map) {
        Map<Object, Object> cm = (Map<Object, Object>) copy;
        for (Object key : ((Map<Object, Object>) p).keySet())
            cm.put(key, cloneObject(((Map<Object, Object>) p).get(key), propertyFilter));
    } else {
        BeanInfo bean_info = Introspector.getBeanInfo(p.getClass());
        PropertyDescriptor beanprops[] = bean_info.getPropertyDescriptors();
        if (beanprops == null || beanprops.length == 0)
            copy = p;
        else
            for (PropertyDescriptor desc : beanprops) {
                Method rm = desc.getReadMethod();
                Method wm = desc.getWriteMethod();
                if (rm == null || wm == null)
                    continue;
                Object value = rm.invoke(p, (Object[]) null);
                if (propertyFilter == null || propertyFilter.eval(new Pair<Object, String>(p, desc.getName())))
                    value = cloneObject(value, propertyFilter);
                wm.invoke(copy, new Object[] { value });
            }
    }
    return (T) copy;
}

From source file:org.jaffa.util.BeanHelper.java

/** Clones the input bean, performing a deep copy of its properties.
 * @param bean the bean to be cloned./*from   w ww .  java  2 s  .  c om*/
 * @param deepCloneForeignField if false, then the foreign-fields of a GraphDataObject will not be deep cloned.
 * @return a clone of the input bean.
 * @throws IllegalAccessException if the underlying method is inaccessible.
 * @throws InvocationTargetException if the underlying method throws an exception.
 * @throws InstantiationException if the bean cannot be instantiated.
 * @throws IntrospectionException if an exception occurs during introspection.
 */
public static Object cloneBean(Object bean, boolean deepCloneForeignField) throws IllegalAccessException,
        InvocationTargetException, InstantiationException, IntrospectionException {
    if (bean == null)
        return bean;

    Class beanClass = bean.getClass();

    // Return the input as-is, if immutable
    if (beanClass == String.class || beanClass == Boolean.class || Number.class.isAssignableFrom(beanClass)
            || IDateBase.class.isAssignableFrom(beanClass) || Currency.class.isAssignableFrom(beanClass)
            || beanClass.isPrimitive()) {
        return bean;
    }

    // Handle an array
    if (beanClass.isArray()) {
        Class componentType = beanClass.getComponentType();
        int length = Array.getLength(bean);
        Object clone = Array.newInstance(componentType, length);
        for (int i = 0; i < length; i++) {
            Object arrayElementClone = cloneBean(Array.get(bean, i), deepCloneForeignField);
            Array.set(clone, i, arrayElementClone);
        }
        return clone;
    }

    // Handle a Collection
    if (bean instanceof Collection) {
        Collection clone = (Collection) bean.getClass().newInstance();
        for (Object collectionElement : (Collection) bean) {
            Object collectionElementClone = cloneBean(collectionElement, deepCloneForeignField);
            clone.add(collectionElementClone);
        }
        return clone;
    }

    // Handle a Map
    if (bean instanceof Map) {
        Map clone = (Map) bean.getClass().newInstance();
        for (Iterator i = ((Map) bean).entrySet().iterator(); i.hasNext();) {
            Map.Entry me = (Map.Entry) i.next();
            Object keyClone = cloneBean(me.getKey(), deepCloneForeignField);
            Object valueClone = cloneBean(me.getValue(), deepCloneForeignField);
            clone.put(keyClone, valueClone);
        }
        return clone;
    }

    // Invoke the 'public Object clone()' method, if available
    if (bean instanceof Cloneable) {
        try {
            Method cloneMethod = beanClass.getMethod("clone");
            return cloneMethod.invoke(bean);
        } catch (NoSuchMethodException e) {
            // do nothing
        }
    }

    // Create a clone using bean introspection
    Object clone = beanClass.newInstance();
    BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
    if (beanInfo != null) {
        PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
        if (pds != null) {
            // Obtain a GraphMapping; only if foreign-fields are not to be cloned
            //Use reflection to achieve the following:
            //GraphMapping graphMapping = !deepCloneForeignField && bean instanceof GraphDataObject ? MappingFactory.getInstance(bean) : null;
            Object graphMapping = null;
            Method isForeignFieldMethod = null;
            try {
                if (!deepCloneForeignField
                        && Class.forName("org.jaffa.soa.graph.GraphDataObject").isInstance(bean)) {
                    graphMapping = Class.forName("org.jaffa.soa.dataaccess.MappingFactory")
                            .getMethod("getInstance", Object.class).invoke(null, bean);
                    isForeignFieldMethod = graphMapping.getClass().getMethod("isForeignField", String.class);
                }
            } catch (Exception e) {
                // do nothing since JaffaSOA may not be deployed
                if (log.isDebugEnabled())
                    log.debug("Exception in obtaining the GraphMapping", e);
            }

            for (PropertyDescriptor pd : pds) {
                if (pd.getReadMethod() != null && pd.getWriteMethod() != null) {
                    // Do not clone a foreign-field
                    Object property = pd.getReadMethod().invoke(bean);

                    //Use reflection to achieve the following:
                    //Object propertyClone = graphMapping != null && graphMapping.isForeignField(pd.getName()) ? property : cloneBean(property, deepCloneForeignField);
                    Object propertyClone = null;
                    boolean propertyCloned = false;
                    if (graphMapping != null && isForeignFieldMethod != null) {
                        try {
                            if ((Boolean) isForeignFieldMethod.invoke(graphMapping, pd.getName())) {
                                propertyClone = property;
                                propertyCloned = true;
                            }
                        } catch (Exception e) {
                            // do nothing since JaffaSOA may not be deployed
                            if (log.isDebugEnabled())
                                log.debug("Exception in invoking GraphMapping.isForeignField()", e);
                        }
                    }
                    if (!propertyCloned)
                        propertyClone = cloneBean(property, deepCloneForeignField);

                    pd.getWriteMethod().invoke(clone, propertyClone);
                }
            }
        }
    }
    return clone;
}

From source file:org.hx.rainbow.common.util.JavaBeanUtil.java

@SuppressWarnings("rawtypes")
private static Map<String, Class> getFileds(Class clazz) {
    BeanInfo beanInfo = null;
    try {/*from w  w  w . j  av a  2  s.c om*/
        beanInfo = Introspector.getBeanInfo(clazz);
    } catch (IntrospectionException e) {
        e.printStackTrace();
    }
    Map<String, Class> map = new HashMap<String, Class>();
    PropertyDescriptor[] pr = beanInfo.getPropertyDescriptors();
    for (int i = 1; i < pr.length; i++) {
        map.put(pr[i].getName(), pr[i].getPropertyType());
    }
    Field[] field = clazz.getDeclaredFields();
    for (int i = 1; i < field.length; i++) {
        map.put(field[i].getName(), field[i].getType());
    }
    return map;
}

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  w  w  w . j  ava2  s .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:io.coala.enterprise.Fact.java

/**
 * override and deserialize bean properties as declared in factType
 * <p>//w w  w  .  j a v  a  2  s.  c  om
 * TODO detect properties from builder methods: {@code withKey(T value)}
 * 
 * @param om
 * @param json
 * @param factType
 * @param properties
 * @return the properties again, to allow chaining
 * @throws IntrospectionException
 */
static <T extends Fact> Map<String, Object> fromJSON(final ObjectMapper om, final TreeNode json,
        final Class<T> factType, final Map<String, Object> properties) {
    try {
        final ObjectNode tree = (ObjectNode) json;
        final BeanInfo beanInfo = Introspector.getBeanInfo(factType);
        for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors())
            if (tree.has(pd.getName()))
                properties.computeIfPresent(pd.getName(),
                        (property, current) -> JsonUtil.valueOf(om, tree.get(property), pd.getPropertyType()));
        return properties;
    } catch (final Throwable e) {
        return Thrower.rethrowUnchecked(e);
    }
}

From source file:com.unboundid.scim2.common.utils.SchemaUtils.java

/**
 * Gets property descriptors for the given class.
 *
 * @param cls The class to get the property descriptors for.
 * @return a collection of property values.
 * @throws java.beans.IntrospectionException throw if there are any
 * introspection errors./*from w  w  w  .  jav  a  2  s  .c o  m*/
 */
public static Collection<PropertyDescriptor> getPropertyDescriptors(final Class cls)
        throws IntrospectionException {
    BeanInfo beanInfo = Introspector.getBeanInfo(cls, Object.class);
    PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    return Arrays.asList(propertyDescriptors);
}

From source file:net.authorize.api.controller.test.ApiCoreTestBase.java

public static void showProperties(Object bean) {
    if (null == bean) {
        return;/*from w  w  w .  j av a  2 s  .co  m*/
    }
    try {
        BeanInfo info = Introspector.getBeanInfo(bean.getClass(), Object.class);
        PropertyDescriptor[] props = info.getPropertyDescriptors();
        for (PropertyDescriptor pd : props) {
            String name = pd.getName();
            Method getter = pd.getReadMethod();
            Class<?> type = pd.getPropertyType();

            if (null != getter && !"class".equals(name)) {
                Object value = getter.invoke(bean);
                logger.info(String.format("Type: '%s', Name:'%s', Value:'%s'", type, name, value));
                processCollections(type, name, value);
                //process compositions of custom classes
                if (null != value && 0 <= type.toString().indexOf("net.authorize.")) {
                    showProperties(value);
                }
            }
        }
    } catch (Exception e) {
        logger.error(String.format("Exception during navigating properties: Message: %s, StackTrace: %s",
                e.getMessage(), e.getStackTrace()));
    }
}