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:org.force66.beantester.tests.AccessorMutatorTest.java

@Override
public boolean testBeanClass(Class<?> klass, Object[] constructorArgs) {
    this.setFailureReason(null);
    Object bean = InstantiationUtils.safeNewInstance(klass, constructorArgs);
    Object localBean = null;//  www  .  ja  v a2 s.  co  m

    for (PropertyDescriptor descriptor : PropertyUtils.getPropertyDescriptors(bean)) {
        if (!fieldExclusionSet.contains(descriptor.getName())) {
            // Use a fresh instance for each property test
            localBean = InstantiationUtils.safeNewInstance(klass, constructorArgs);
            try {
                testProperty(localBean, descriptor);
            } catch (TestFailureException e) {
                this.setFailureReason(e.getMessage());
                return false;
            }
        }
    }

    return true;
}

From source file:org.force66.beantester.utils.InjectionUtils.java

public static void injectValues(Object bean, ValueGeneratorFactory valueGeneratorFactory,
        boolean reportExceptions) {

    ValueGenerator<?> generator;/*from  www .  j  av a 2 s .  c  o m*/
    Object[] generatedValues = null;
    for (PropertyDescriptor descriptor : PropertyUtils.getPropertyDescriptors(bean)) {
        try {
            generator = valueGeneratorFactory.forClass(descriptor.getPropertyType());
            if (generator != null && descriptor.getWriteMethod() != null) {
                generatedValues = generator.makeValues();

                descriptor.getWriteMethod().invoke(bean, generatedValues[0]);

            }
        } catch (Exception e) {
            if (reportExceptions) {
                throw new BeanTesterException("Error setting property value", e)
                        .addContextValue("class", bean.getClass().getName())
                        .addContextValue("field", descriptor.getName()).addContextValue("value",
                                generatedValues != null && generatedValues.length > 0 ? generatedValues[0]
                                        : null);
            }
        }
    }
}

From source file:org.fudgemsg.mapping.JavaBeanBuilder.java

/**
 * Creates a new {@link JavaBeanBuilder} for a class.
 * /* w  ww .j  ava2 s .co  m*/
 * @param <T> class the builder should process
 * @param clazz class the builder should process
 * @return the {@code JavaBeanBuilder}
 */
/* package */ static <T> JavaBeanBuilder<T> create(final Class<T> clazz) {
    // customise the properties
    final ArrayList<JBProperty> propList = new ArrayList<JBProperty>();
    for (PropertyDescriptor prop : PropertyUtils.getPropertyDescriptors(clazz)) {
        // ignore the class
        if (prop.getName().equals("class"))
            continue;
        // check for FudgeFieldName annotations on either accessor or mutator
        FudgeFieldName annoName;
        FudgeFieldOrdinal annoOrdinal;
        String name = prop.getName();
        Integer ordinal = null;
        if (prop.getWriteMethod() != null) {
            // give up if it's a transient property
            if (TransientUtil.hasTransientAnnotation(prop.getWriteMethod()))
                continue;
            if ((annoName = prop.getWriteMethod().getAnnotation(FudgeFieldName.class)) != null)
                name = annoName.value();
            if ((annoOrdinal = prop.getWriteMethod().getAnnotation(FudgeFieldOrdinal.class)) != null) {
                ordinal = (int) annoOrdinal.value();
                if (annoOrdinal.noFieldName())
                    name = null;
            }
        }
        if (prop.getReadMethod() != null) {
            // give up if it's a transient property
            if (TransientUtil.hasTransientAnnotation(prop.getReadMethod()))
                continue;
            if ((annoName = prop.getReadMethod().getAnnotation(FudgeFieldName.class)) != null)
                name = annoName.value();
            if ((annoOrdinal = prop.getReadMethod().getAnnotation(FudgeFieldOrdinal.class)) != null) {
                ordinal = (int) annoOrdinal.value();
                if (annoOrdinal.noFieldName())
                    name = null;
            }
        }
        propList.add(new JBProperty(name, ordinal, prop.getReadMethod(), prop.getWriteMethod(),
                prop.getPropertyType()));
    }
    // try and find a constructor
    try {
        return new JavaBeanBuilder<T>(propList.toArray(new JBProperty[propList.size()]),
                clazz.getConstructor());
    } catch (SecurityException e) {
        // ignore
    } catch (NoSuchMethodException e) {
        // ignore
    }
    // otherwise bean behaviour (about 5 times slower!)
    return new JavaBeanBuilder<T>(propList.toArray(new JBProperty[propList.size()]), clazz.getName());
}

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

/**
 * ??MapMapKey??//  w  w  w  .  j  av a 2s.  c o m
 * 
 * @param bean
 * @return
 * @throws Exception
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
@Deprecated
public static Map getProperties(Object bean) {
    if (bean == null) {
        return null;
    }

    Map dataMap = new HashMap();
    try {
        PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(bean);

        for (int i = 0; i < origDescriptors.length; i++) {
            String name = origDescriptors[i].getName();
            if (name.equals("class")) {
                continue;
            }

            if (PropertyUtils.isReadable(bean, name)) {
                Object obj = PropertyUtils.getProperty(bean, name);
                if (obj == null) {
                    continue;
                }
                obj = convertValue(origDescriptors[i], obj);
                dataMap.put(name, obj);
            }
        } // for end
    } catch (Exception e) {
        e.printStackTrace();
        throw new AppException(e.getMessage());
    }
    return dataMap;
}

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

/**
 * bean??bean???//from  ww w .j a  va  2  s.co m
 * zhf 2012-5-14 [] BeanUtils.copyPropertiescopy
 * @param fromBean
 * @param toBean
 */
public static void copyProperties(Object fromBean, Object toBean) {
    if (fromBean == null || toBean == null) {
        return;
    }
    try {
        //         BeanUtils.copyProperties(toBean, fromBean);
        PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(toBean);

        for (int i = 0; i < origDescriptors.length; i++) {
            String name = origDescriptors[i].getName();
            if (name.equals("class")) {
                continue;
            }

            //if (PropertyUtils.isReadable(fromBean, name)||PropertyUtils.isWriteable(toBean, name)) {
            if (PropertyUtils.isReadable(fromBean, name) && PropertyUtils.isWriteable(toBean, name)) {
                Object obj = PropertyUtils.getProperty(fromBean, name);
                if (obj == null) {
                    continue;
                }
                obj = convertValue(origDescriptors[i], obj);
                BeanUtils.copyProperty(toBean, name, obj);
            }
        } // for end
    } catch (Exception e) {
        e.printStackTrace();
        throw new AppException(e.getMessage());
    }
}

From source file:org.intermine.task.DynamicAttributeTask.java

/**
 * Look at set methods on a target object and lookup values in project
 * properties.  If no value found property will not be set but no error
 * will be thrown./*from   w w w.  ja va 2  s.  c  o  m*/
 * @param bean an object to search for setter methods
 */
protected void configureDynamicAttributes(Object bean) {
    Project antProject = getProject();
    Hashtable<?, ?> projectProps = antProject.getProperties();
    PropertyDescriptor[] props = PropertyUtils.getPropertyDescriptors(bean);
    for (int i = 0; i < props.length; i++) {
        PropertyDescriptor desc = props[i];
        Method setter = desc.getWriteMethod();
        if (setter != null) {
            Class<?> propType = desc.getPropertyType();
            String propName = setter.getName().substring(3).toLowerCase();
            Object propValue = projectProps.get(propName);

            if (propValue == null) {
                // there is not all-lowercase property in projectProps, so try the camelCase
                // version
                String setterName = setter.getName();
                String camelCasePropName = setterName.substring(3, 4).toLowerCase() + setterName.substring(4);
                propName = camelCasePropName;
                propValue = projectProps.get(camelCasePropName);
            }

            if (propValue == null) {
                // still not found, try replacing each capital (after first) in camelCase
                // to be a dot - i.e. setSrcDataDir -> src.data.dir
                String setterName = setter.getName();
                String camelCasePropName = setterName.substring(3, 4).toLowerCase() + setterName.substring(4);
                String dotName = "";
                for (int j = 0; j < camelCasePropName.length(); j++) {
                    if (Character.isUpperCase(camelCasePropName.charAt(j))) {
                        dotName += "." + camelCasePropName.substring(j, j + 1).toLowerCase();
                    } else {
                        dotName += camelCasePropName.substring(j, j + 1);
                    }
                }
                propValue = projectProps.get(dotName);
            }

            if (propValue != null) {
                try {
                    if (propType.equals(File.class)) {

                        String filePropValue = (String) propValue;
                        //First check to see if we were given a complete file path, if so then
                        // we can use it directly instead of trying to search for it.
                        File maybeFile = new File(filePropValue);
                        if (maybeFile.exists()) {
                            propValue = maybeFile;
                            LOG.info("Configuring task to use file:" + filePropValue);
                        } else {
                            propValue = getProject().resolveFile(filePropValue);
                        }
                    }
                    PropertyUtils.setProperty(bean, propName, propValue);
                } catch (Exception e) {
                    throw new BuildException(
                            "failed to set value for " + propName + " to " + propValue + " in " + bean, e);
                }
            }
        }
    }
}

From source file:org.jaxygen.typeconverter.util.BeanUtil.java

/**
 * Copies bean content from one bean to another. The bean is copied using the
 * set and get methods. Method invokes all getXX methods on the from object,
 * and result pass to the corresponding setXX methods in the to object. Note
 * that it is not obvious that both object are of the same type.
 * If get and set methods do not match then it tries to use appropriate
 * converter registered in default type converter factory.
 *
 * @param from data provider object./*from   w w w  . j av  a2  s  . co m*/
 * @param to data acceptor object.
 */
public static void translateBean(Object from, Object to) {
    PropertyDescriptor[] fromGetters = null;
    fromGetters = PropertyUtils.getPropertyDescriptors(from.getClass());
    for (PropertyDescriptor pd : fromGetters) {
        if (pd.getReadMethod().isAnnotationPresent(BeanTransient.class) == false) {
            if (PropertyUtils.isWriteable(to, pd.getName())) {
                try {
                    PropertyDescriptor wd = PropertyUtils.getPropertyDescriptor(to, pd.getName());
                    if (!wd.getWriteMethod().isAnnotationPresent(BeanTransient.class)) {
                        Object copyVal = PropertyUtils.getProperty(from, pd.getName());
                        if (wd.getPropertyType().isAssignableFrom(pd.getPropertyType())) {
                            PropertyUtils.setProperty(to, wd.getName(), copyVal);
                        } else {
                            try {
                                Object convertedCopyVal = TypeConverterFactory.instance().convert(copyVal,
                                        wd.getPropertyType());
                                PropertyUtils.setProperty(to, wd.getName(), convertedCopyVal);
                            } catch (ConversionError ex) {
                                Logger.getAnonymousLogger().log(Level.WARNING,
                                        "Method {0}.{1} of type {2} is not compatible to {3}.{4} of type{5}",
                                        new Object[] { from.getClass().getName(), pd.getName(),
                                                pd.getPropertyType(), to.getClass().getName(), wd.getName(),
                                                wd.getPropertyType() });
                            }
                        }
                    }
                } catch (IllegalAccessException ex) {
                    throw new java.lang.IllegalArgumentException("Could not translate bean", ex);
                } catch (InvocationTargetException ex) {
                    throw new java.lang.IllegalArgumentException("Could not translate bean", ex);
                } catch (NoSuchMethodException ex) {
                    throw new java.lang.IllegalArgumentException("Could not translate bean", ex);
                }
            }
        }
    }
}

From source file:org.jspresso.framework.util.bean.PropertyHelper.java

private static PropertyDescriptor getPropertyDescriptorNoException(Class<?> beanClass, String property) {
    PropertyDescriptor descriptorToReturn = null;
    int nestedDotIndex = property.indexOf(IAccessor.NESTED_DELIM);
    if (nestedDotIndex > 0) {
        PropertyDescriptor rootDescriptor = getPropertyDescriptorNoException(beanClass,
                property.substring(0, nestedDotIndex));
        if (rootDescriptor != null) {
            descriptorToReturn = getPropertyDescriptorNoException(rootDescriptor.getPropertyType(),
                    property.substring(nestedDotIndex + 1));
        }//from   w  w  w .  jav  a 2 s. co m
    } else {
        PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(beanClass);
        for (PropertyDescriptor descriptor : descriptors) {
            if (property.substring(0, 1).equalsIgnoreCase(descriptor.getName().substring(0, 1))
                    && property.substring(1).equals(descriptor.getName().substring(1))) {
                // 1st letter might be uppercase in descriptor and lowercase in
                // property when property name is like 'tEst'.
                descriptorToReturn = descriptor;
            }
        }
    }
    if (descriptorToReturn == null || descriptorToReturn.getWriteMethod() == null) {
        // If we reach this point, no property with the given name has been found.
        // or the found descriptor is read-only.
        // If beanClass is indeed an interface, we must also deal with all its
        // super-interfaces.
        List<Class<?>> superTypes = new ArrayList<>();
        if (beanClass.getSuperclass() != null && beanClass.getSuperclass() != Object.class) {
            superTypes.add(beanClass.getSuperclass());
        }
        Collections.addAll(superTypes, beanClass.getInterfaces());
        for (Class<?> superType : superTypes) {
            PropertyDescriptor descriptor;
            descriptor = getPropertyDescriptorNoException(superType, property);
            if (descriptor != null) {
                if (descriptorToReturn != null) {
                    try {
                        descriptorToReturn.setWriteMethod(descriptor.getWriteMethod());
                    } catch (IntrospectionException ex) {
                        throw new NestedRuntimeException(ex);
                    }
                } else {
                    descriptorToReturn = descriptor;
                }
            }
        }
    }
    return descriptorToReturn;
}

From source file:org.jspresso.framework.util.bean.PropertyHelper.java

/**
 * Retrieves all property names declared by a bean class.
 *
 * @param beanClass/*from   ww  w.  java 2 s . c  o  m*/
 *          the class to introspect.
 * @return the collection of property names.
 */
public static Collection<String> getPropertyNames(Class<?> beanClass) {
    Collection<String> propertyNames = new HashSet<>();
    PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(beanClass);
    for (PropertyDescriptor descriptor : descriptors) {
        propertyNames.add(descriptor.getName());
    }
    if (beanClass.isInterface()) {
        for (Class<?> superInterface : beanClass.getInterfaces()) {
            propertyNames.addAll(getPropertyNames(superInterface));
        }
    }
    return propertyNames;
}

From source file:org.jtrfp.trcl.dbg.PropertyDumpSupport.java

public void dumpProperties(Map<String, PropertyDumpElement> dest) {
    PropertyDescriptor[] props = PropertyUtils.getPropertyDescriptors(delegator.getClass());
    // Try to get a stacktrace.
    final HashMap<String, StackTraceElement[]> stackTraces = new HashMap<String, StackTraceElement[]>();
    try {/*from   www .j  a v a2 s .c  o  m*/
        final Method sm = delegator.getClass().getDeclaredMethod("getStackTracingPropertyChangeSupport");
        ((StackTracingPropertyChangeSupport) sm.invoke(delegator)).getStackTraces(stackTraces);
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
    for (PropertyDescriptor pd : props) {
        final Method rm = pd.getReadMethod();
        if (rm != null) {
            final String name = pd.getName();
            final boolean irrelevantProperty = rm.getDeclaringClass() == Object.class
                    || name.contentEquals("class") || name.contentEquals("propertyChangeListeners");
            if (!irrelevantProperty) {
                try {
                    Object val = rm.invoke(delegator);
                    try {
                        final Method sm = rm.getReturnType().getMethod("dumpProperties", Map.class);
                        final HashMap<String, Object> subDest = new HashMap<String, Object>();
                        sm.invoke(val, subDest);
                        val = subDest;
                    } catch (NoSuchMethodException e) {
                    }
                    StackTraceElement[] stackTrace = stackTraces.get(pd.getName());
                    PropertyDumpElement gsp = new PropertyDumpElement(val, stackTrace);
                    dest.put(pd.getName(), gsp);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } //end if(!irrelevant)
        } //end if(readMethod)
    } //end for(props)
}