Example usage for org.apache.commons.beanutils PropertyUtils getPropertyDescriptors

List of usage examples for org.apache.commons.beanutils PropertyUtils getPropertyDescriptors

Introduction

In this page you can find the example usage for org.apache.commons.beanutils PropertyUtils getPropertyDescriptors.

Prototype

public static PropertyDescriptor[] getPropertyDescriptors(Object bean) 

Source Link

Document

Retrieve the property descriptors for the specified bean, introspecting and caching them the first time a particular bean class is encountered.

For more details see PropertyUtilsBean.

Usage

From source file:edu.duke.cabig.c3pr.utils.BeanUtils.java

/**
 * This methods performs deep comparison of two objects of the same class.
 * Comparison is performed only on properties exposed via the standard
 * JavaBean mechanism. Properties of primitive types, wrappers,
 * {@link String}, {@link CharSequence}, {@link Date}, {@link Enum} are
 * compared directly using {@link Object#equals(Object)}; other complex
 * properties are compared recursively. Elements of {@link Collection}
 * properties are iterated and compared.
 * //ww w  .  j  a v a 2 s. com
 * @param <T>
 * @param obj1
 * @param obj2
 * @return
 * @throws NullPointerException
 *             if any of the parameters is null.
 */
public static <T> boolean deepCompare(T obj1, T obj2) {
    if (obj1 == obj2) {
        return true;
    }
    // if it's a "simple" object, do direct comparison.
    for (Class<?> cls : DIRECTLY_COMPARABLE_TYPES) {
        if (cls.isAssignableFrom(obj1.getClass())) {
            if (!obj1.equals(obj2)) {
                log.info("Values don't match: " + obj1 + " and " + obj2);
                System.out.println();
                System.out.println("Values don't match: " + obj1 + " and " + obj2);
                return false;
            } else {
                return true;
            }
        }
    }
    try {
        PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(obj1.getClass());
        for (PropertyDescriptor pd : descriptors) {
            // ignore properties which cannot be read.
            if (pd.getReadMethod() != null) {
                Class<?> type = pd.getPropertyType();
                // this check will skip Object.getClass().
                if (SKIP_TYPES.contains(type)) {
                    continue;
                }
                String name = pd.getName();
                Object v1 = PropertyUtils.getSimpleProperty(obj1, name);
                Object v2 = PropertyUtils.getSimpleProperty(obj2, name);
                if (v1 == v2 || (v1 == null && v2 == null)) {
                    continue;
                }
                if ((v1 == null && v2 != null) || (v1 != null && v2 == null)) {
                    log.info("Values don't match: " + v1 + " and " + v2);
                    System.out.println();
                    System.out.println("Values don't match: " + v1 + " and " + v2);
                    return false;
                }
                // Collections need special handling.
                if (Collection.class.isAssignableFrom(type)) {
                    List l1 = new ArrayList((Collection) v1);
                    List l2 = new ArrayList((Collection) v2);
                    if (l1.size() != l2.size()) {
                        log.info("Collection sizes don't match:" + l1 + l2);
                        System.out.println();
                        System.out.println("Collection sizes don't match:" + l1 + ", " + l2);
                        return false;
                    }
                    for (int i = 0; i < l1.size(); i++) {
                        Object el1 = l1.get(i);
                        Object el2 = l2.get(i);
                        if (!deepCompare(el1, el2)) {
                            return false;
                        }
                    }

                } else if (!deepCompare(v1, v2)) {
                    return false;
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(ExceptionUtils.getFullStackTrace(e));
    }
    return true;
}

From source file:jeeves.server.overrides.AddPropertyUpdater.java

@SuppressWarnings("unchecked")
@Override//from   ww  w.  ja v a2  s . c  o m
protected void doUpdate(ConfigurableListableBeanFactory beanFactory, BeanDefinition bean, Object value) {
    Log.debug(Log.JEEVES, "Adding new value " + value + " to property: " + propertyName + " on " + beanName);
    PropertyValue propertyValue = bean.getPropertyValues().getPropertyValue(propertyName);
    if (propertyValue == null) {
        final String beanClassName = bean.getBeanClassName();
        try {
            final Class<?> aClass = Class.forName(beanClassName);
            final PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(aClass);
            for (PropertyDescriptor descriptor : propertyDescriptors) {
                if (propertyName.equals(descriptor.getName())) {
                    final Class<?> collectionType = descriptor.getWriteMethod().getParameterTypes()[0];
                    if (List.class.isAssignableFrom(collectionType)) {
                        propertyValue = new PropertyValue(propertyName, new ManagedList<Object>());
                    } else if (Set.class.isAssignableFrom(collectionType)) {
                        propertyValue = new PropertyValue(propertyName, new ManagedSet<Object>());
                    } else if (Map.class.isAssignableFrom(collectionType)) {
                        propertyValue = new PropertyValue(propertyName, new ManagedMap<Object, Object>());
                    } else if (Properties.class.isAssignableFrom(collectionType)) {
                        propertyValue = new PropertyValue(propertyName, new ManagedProperties());
                    } else if (Array.class.isAssignableFrom(collectionType)) {
                        throw new IllegalArgumentException("Array collections not currently supported");
                    } else if (Collection.class.isAssignableFrom(collectionType)) {
                        propertyValue = new PropertyValue(propertyName, new ManagedList<Object>());
                    } else {
                        throw new IllegalArgumentException(
                                collectionType + " is not a supported type for adding new values");
                    }
                    break;
                }
            }
            if (propertyValue == null) {
                throw new IllegalArgumentException("Unable to find the collection type for property: "
                        + propertyName + " on bean " + beanName);
            }
            bean.getPropertyValues().addPropertyValue(propertyValue);
        } catch (ClassNotFoundException e) {
            throw new AssertionError(e);
        }
    }

    Object originalValue = propertyValue.getValue();
    if (originalValue instanceof Collection) {
        Collection<Object> coll = (Collection<Object>) originalValue;
        coll.add(value);
    } else {
        throw new IllegalArgumentException(originalValue + " is not a collection as expected");
    }
}

From source file:ca.sqlpower.testutil.TestUtils.java

/**
 * Sets all the settable properties on the given target object which are not
 * in the given ignore set.//  www . j  a  v a 2s  .c o  m
 * <p>
 * TODO merge this with what is in Architect's TestUtils class. This was
 * originally refactored out of there.
 * 
 * @param target
 *            The object to change the properties of
 * @param propertiesToIgnore
 *            The properties of target not to modify or read
 * @return A Map describing the new values of all the non-ignored, readable
 *         properties in target.
 */
public static Map<String, Object> setAllInterestingProperties(Object target, Set<String> propertiesToIgnore,
        NewValueMaker valueMaker) throws Exception {

    PropertyDescriptor props[] = PropertyUtils.getPropertyDescriptors(target);
    for (int i = 0; i < props.length; i++) {
        Object oldVal = null;
        if (PropertyUtils.isReadable(target, props[i].getName()) && props[i].getReadMethod() != null
                && !propertiesToIgnore.contains(props[i].getName())) {
            oldVal = PropertyUtils.getProperty(target, props[i].getName());
        }
        if (PropertyUtils.isWriteable(target, props[i].getName()) && props[i].getWriteMethod() != null
                && !propertiesToIgnore.contains(props[i].getName())) {

            Object newVal = valueMaker.makeNewValue(props[i].getPropertyType(), oldVal, props[i].getName());

            System.out.println("Changing property \"" + props[i].getName() + "\" to \"" + newVal + "\"");
            PropertyUtils.setProperty(target, props[i].getName(), newVal);

        }
    }

    // read them all back at the end in case there were dependencies between properties
    return TestUtils.getAllInterestingProperties(target, propertiesToIgnore);
}

From source file:ca.sqlpower.object.undo.PropertyChangeEdit.java

/**
 * Sets the value of the property to be the old value
 *///ww  w  .j  ava2  s  .  c om
@Override
public void undo() throws CannotUndoException {
    logger.debug("Undoing Property change: Setting " + sourceEvent.getPropertyName() + " from "
            + sourceEvent.getNewValue() + " to " + sourceEvent.getOldValue());
    super.undo();
    try {
        final PropertyDescriptor propertyDescriptor = PropertyUtils
                .getPropertyDescriptor(sourceEvent.getSource(), sourceEvent.getPropertyName());
        logger.debug("Found property descriptor " + propertyDescriptor);
        if (logger.isDebugEnabled()) {
            PropertyDescriptor[] propertyDescriptors = PropertyUtils
                    .getPropertyDescriptors(sourceEvent.getSource());
            logger.debug("Descriptor has write method " + propertyDescriptor.getWriteMethod());
        }
        Method setter = PropertyUtils.getWriteMethod(propertyDescriptor);
        logger.info("Found setter: " + setter.getName());
        setter.invoke(sourceEvent.getSource(), sourceEvent.getOldValue());

    } catch (Exception ex) {
        CannotUndoException wrapper = new CannotUndoException();
        wrapper.initCause(ex);
        throw wrapper;
    }
}

From source file:com.hengyi.japp.sap.convert.impl.SapConverts.java

private ISapConvert newInstance() throws Exception {
    ImmutableSet.Builder<IFieldCopy> fieldCoyps = ImmutableSet.builder();
    PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(beanClass);
    if (descriptors == null) {
        return null;
    }//w  ww  .j a va 2s .  co  m
    for (PropertyDescriptor descriptor : descriptors) {
        String sapFieldName = getSapFieldName(descriptor);
        if (sapFieldName == null) {
            continue;
        }

        IFieldCopy fieldCopy = FieldCopys.begin().addBeanClass(beanClass).addBeanPropertyDescriptor(descriptor)
                .addRecordMetaData(metaData).addSapFieldName(sapFieldName).build();
        if (fieldCopy != null) {
            fieldCoyps.add(fieldCopy);
        }
    }
    return new SapConvert(fieldCoyps.build());
}

From source file:net.mojodna.searchable.SearchableBeanUtils.java

/**
 * Gets the name of the property containing the bean's id.
 * /*from  w  w  w  . j a  v  a  2  s  .c  o  m*/
 * @param clazz Class to reflect on.
 * @return Name of the id property.
 */
public static String getIdPropertyName(final Class<? extends Searchable> clazz) {
    // look for Searchable.ID annotation
    final PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(clazz);
    for (final PropertyDescriptor descriptor : pds) {
        if (null != descriptor && null != descriptor.getReadMethod()
                && descriptor.getReadMethod().isAnnotationPresent(Searchable.ID.class)) {
            return descriptor.getName();
        }
    }

    return SearchableBeanUtils.ID_PROPERTY_NAME;
}

From source file:com.bstek.dorado.data.entity.BeanEntityEnhancer.java

protected synchronized void buildReflectionCahce() throws Exception {
    synchronized (cachedTypes) {
        if (!cachedTypes.contains(beanType)) {
            cachedTypes.add(beanType);/*from  w  w w .  ja  va  2 s. co m*/

            Map<String, Boolean> properties = new Hashtable<String, Boolean>();
            Map<Method, String> readMethods = new Hashtable<Method, String>();
            Map<Method, String> writeMethods = new Hashtable<Method, String>();
            PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(beanType);
            for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                String property = propertyDescriptor.getName();
                if (propertyDescriptor.getReadMethod() == null) {
                    continue;
                }

                properties.put(property, Boolean.valueOf(propertyDescriptor.getWriteMethod() != null));

                Method readMethod = propertyDescriptor.getReadMethod();
                Method writeMethod = propertyDescriptor.getWriteMethod();
                if (readMethod != null) {
                    if (readMethod.getDeclaringClass() != beanType) {
                        readMethod = beanType.getMethod(readMethod.getName(), readMethod.getParameterTypes());
                    }
                    readMethods.put(readMethod, property);
                }
                if (writeMethod != null) {
                    if (writeMethod.getDeclaringClass() != beanType) {
                        writeMethod = beanType.getMethod(writeMethod.getName(),
                                writeMethod.getParameterTypes());
                    }
                    writeMethods.put(writeMethod, property);
                }
            }
            propertiesCache.put(beanType, properties);
            readMethodsCache.put(beanType, readMethods);
            writeMethodsCache.put(beanType, writeMethods);
            this.properties = properties;
            this.readMethods = readMethods;
            this.writeMethods = writeMethods;
        } else {
            this.properties = propertiesCache.get(beanType);
            this.readMethods = readMethodsCache.get(beanType);
            this.writeMethods = writeMethodsCache.get(beanType);
        }
    }
}

From source file:edu.duke.cabig.c3pr.webservice.integration.BeanUtils.java

/**
 * This methods performs deep comparison of two objects of the same class.
 * Comparison is performed only on properties exposed via the standard
 * JavaBean mechanism. Properties of primitive types, wrappers,
 * {@link String}, {@link CharSequence}, {@link Date}, {@link Enum} are
 * compared directly using {@link Object#equals(Object)}; other complex
 * properties are compared recursively. Elements of {@link Collection}
 * properties are iterated and compared.
 * //from   w  w w  .  j  av  a 2 s .co  m
 * @param <T>
 * @param obj1
 * @param obj2
 * @return
 * @throws NullPointerException
 *             if any of the parameters is null.
 */
public static <T> boolean deepCompare(T obj1, T obj2) {
    if (obj1 == obj2) {
        return true;
    }
    // if it's a "simple" object, do direct comparison.
    for (Class<?> cls : DIRECTLY_COMPARABLE_TYPES) {
        if (cls.isAssignableFrom(obj1.getClass())) {
            if (!obj1.equals(obj2)) {
                log.info("Values don't match: " + obj1 + " and " + obj2);
                System.out.println();
                System.out.println("Values don't match: " + obj1 + " and " + obj2);
                return false;
            } else {
                return true;
            }
        }
    }
    try {
        PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(obj1.getClass());
        for (PropertyDescriptor pd : descriptors) {
            // ignore properties which cannot be read.
            if (pd.getReadMethod() != null) {
                Class<?> type = pd.getPropertyType();
                // this check will skip Object.getClass().
                if (SKIP_TYPES.contains(type)) {
                    continue;
                }
                String name = pd.getName();
                Object v1 = PropertyUtils.getSimpleProperty(obj1, name);
                Object v2 = PropertyUtils.getSimpleProperty(obj2, name);
                if (v1 == v2 || (v1 == null && v2 == null)) {
                    continue;
                }
                if ((v1 == null && v2 != null) || (v1 != null && v2 == null)) {
                    log.info("Values don't match: " + v1 + " and " + v2);
                    System.out.println();
                    System.out.println("Values don't match: " + v1 + " and " + v2);
                    return false;
                }
                // Collections need special handling.
                if (Collection.class.isAssignableFrom(type)) {
                    List l1 = new ArrayList((Collection) v1);
                    List l2 = new ArrayList((Collection) v2);
                    if (l1.size() != l2.size()) {
                        log.info("Collection sizes don't match:" + l1 + l2);
                        System.out.println();
                        System.out.println("Collection sizes don't match:" + l1 + ", " + l2);
                        return false;
                    }
                    for (int i = 0; i < l1.size(); i++) {
                        Object el1 = l1.get(i);
                        boolean equals = false;
                        for (int j = 0; j < l2.size(); j++) {
                            Object el2 = l2.get(j);
                            if (deepCompare(el1, el2)) {
                                if (i == j) {
                                    System.out.println("Values matched at the same index in collections");
                                } else {
                                    System.out.println("Values matched at the different index in collections");
                                }
                                equals = true;
                                break;
                            }
                        }
                        if (!equals) {
                            return false;
                        }
                    }

                } else if (!deepCompare(v1, v2)) {
                    return false;
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(ExceptionUtils.getFullStackTrace(e));
    }
    return true;
}

From source file:ar.com.fdvs.dj.domain.builders.ReflectiveReportBuilder.java

/**
 * Takes the first item in the collection and adds a column for every property in that item.
 * @param _data the data collection. A not null and nor empty collection should be passed.
 *//* w  w  w .  java  2  s.  c  om*/
public ReflectiveReportBuilder(final Collection _data) {
    if (_data == null || _data.isEmpty()) {
        throw new IllegalArgumentException("Parameter _data is null or empty");
    }
    final Object item = _data.iterator().next();
    try {
        addProperties(PropertyUtils.getPropertyDescriptors(item));
    } catch (Exception ex) {
        LOGGER.error("", ex);
        throw new ExceptionInInitializerError(ex);
    }
}

From source file:fr.mael.microrss.util.Tools.java

public static HashMap<String, Object> toMap(UserConfig conf)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    HashMap<String, Object> options = new HashMap<String, Object>();
    PropertyDescriptor[] descs = PropertyUtils.getPropertyDescriptors(UserConfig.class);
    for (PropertyDescriptor desc : descs) {
        if (!desc.getName().equals("class") && !desc.getName().equals("user")) {
            options.put(desc.getName(), PropertyUtils.getProperty(conf, desc.getName()));
        }/*  w w w .  j a  v a 2 s.  c om*/
    }
    return options;

}