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.codehaus.mojo.pomtools.wrapper.reflection.BeanFields.java

public BeanFields(String fieldFullName, Object objectToInspect) {
    this.fieldFullName = fieldFullName;

    PomToolsPluginContext context = PomToolsPluginContext.getInstance();

    Log log = context.getLog();//  w w w. ja  va2 s . co  m

    PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(objectToInspect);

    for (int i = 0; i < descriptors.length; i++) {
        PropertyDescriptor pd = descriptors[i];

        FieldConfiguration config = context
                .getFieldConfiguration(ModelHelper.buildFullName(fieldFullName, pd.getName()));
        if (pd.getWriteMethod() != null && (config == null || !config.isIgnore())) {
            if (log.isDebugEnabled()) {
                log.debug("Property: " + ModelHelper.buildFullName(fieldFullName, pd.getName()) + " => "
                        + pd.getPropertyType().getName());
            }

            if (pd.getPropertyType().equals(String.class)) {
                add(new StringField(fieldFullName, pd.getName()));
            } else if (pd.getPropertyType().equals(boolean.class)) {
                add(new BooleanField(fieldFullName, pd.getName()));
            } else if (pd.getPropertyType().equals(List.class)) {
                addListField(pd, objectToInspect);
            } else if (pd.getPropertyType().equals(Properties.class)) {
                add(new PropertiesBeanField(fieldFullName, pd.getName()));
            } else {
                add(new CompositeField(fieldFullName, pd.getName(), pd.getPropertyType()));
            }
        }
    }

}

From source file:org.constretto.internal.store.ObjectConfigurationStore.java

private TaggedPropertySet createPropertySetForObject(Object configurationObject) {
    String tag = ConfigurationValue.DEFAULT_TAG;
    String basePath = "";
    Map<String, String> properties = new HashMap<String, String>();
    if (configurationObject.getClass().isAnnotationPresent(ConfigurationSource.class)) {
        ConfigurationSource configurationAnnotation = configurationObject.getClass()
                .getAnnotation(ConfigurationSource.class);
        tag = configurationAnnotation.tag();
        if (tag.equals("")) {
            tag = ConfigurationValue.DEFAULT_TAG;
        }//from w ww.  j a  v a 2  s . c om
        basePath = configurationAnnotation.basePath();
    }

    for (PropertyDescriptor propertyDescriptor : PropertyUtils.getPropertyDescriptors(configurationObject)) {
        boolean canRead = propertyDescriptor.getReadMethod() != null;
        boolean isString = propertyDescriptor.getPropertyType().isAssignableFrom(String.class);
        if (canRead && isString) {
            String path = propertyDescriptor.getName();
            try {
                String value = (String) PropertyUtils.getProperty(configurationObject, path);
                if (!ConstrettoUtils.isEmpty(basePath)) {
                    path = basePath + "." + path;
                }
                properties.put(path, value);
            } catch (Exception e) {
                throw new ConstrettoException("Could not access data in field", e);
            }
        }

    }

    return new TaggedPropertySet(tag, properties, getClass());
}

From source file:org.craftercms.commons.jackson.mvc.CrafterJackson2MessageConverter.java

private void runAnnotations(final Object object) {
    try {//from ww w.jav  a2  s  . c om

        if (Iterable.class.isInstance(object) && !Iterator.class.isInstance(object)) {
            for (Object element : (Iterable) object) {
                runAnnotations(element);
            }
        }
        PropertyDescriptor[] propertiesDescriptor = PropertyUtils.getPropertyDescriptors(object);
        for (PropertyDescriptor propertyDescriptor : propertiesDescriptor) {
            // Avoid the "getClass" as a property
            if (propertyDescriptor.getPropertyType().equals(Class.class)
                    || (propertyDescriptor.getReadMethod() == null
                            && propertyDescriptor.getWriteMethod() == null)) {
                continue;
            }
            Field field = findField(object.getClass(), propertyDescriptor.getName());

            if (field != null && field.isAnnotationPresent(SecureProperty.class)
                    && securePropertyHandler != null) {
                secureProperty(object, field);
            }

            if (field != null && field.isAnnotationPresent(InjectValue.class) && injectValueFactory != null) {
                injectValue(object, field);
                continue;
            }

            Object fieldValue = PropertyUtils.getProperty(object, propertyDescriptor.getName());
            if (Iterable.class.isInstance(fieldValue) && !Iterator.class.isInstance(object)) {
                for (Object element : (Iterable) fieldValue) {
                    runAnnotations(element);
                }
            }
        }
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
        log.error("Unable to secure value for " + object.getClass(), e);
    }
}

From source file:org.dozer.util.ReflectionUtils.java

static PropertyDescriptor[] getInterfacePropertyDescriptors(Class<?> interfaceClass) {
    List<PropertyDescriptor> propDescriptors = new ArrayList<PropertyDescriptor>();
    // Add prop descriptors for interface passed in
    propDescriptors.addAll(Arrays.asList(PropertyUtils.getPropertyDescriptors(interfaceClass)));

    // Look for interface inheritance. If super interfaces are found, recurse up the hierarchy tree and add prop
    // descriptors for each interface found.
    // PropertyUtils.getPropertyDescriptors() does not correctly walk the inheritance hierarchy for interfaces.
    Class<?>[] interfaces = interfaceClass.getInterfaces();
    if (interfaces != null) {
        for (Class<?> superInterfaceClass : interfaces) {
            List<PropertyDescriptor> superInterfacePropertyDescriptors = Arrays
                    .asList(getInterfacePropertyDescriptors(superInterfaceClass));
            /*/* ww w .jav  a 2 s  .  c om*/
             * #1814758
             * Check for existing descriptor with the same name to prevent 2 property descriptors with the same name being added
             * to the result list.  This caused issues when getter and setter of an attribute on different interfaces in
             * an inheritance hierarchy
             */
            for (PropertyDescriptor superPropDescriptor : superInterfacePropertyDescriptors) {
                PropertyDescriptor existingPropDescriptor = findPropDescriptorByName(propDescriptors,
                        superPropDescriptor.getName());
                if (existingPropDescriptor == null) {
                    propDescriptors.add(superPropDescriptor);
                } else {
                    try {
                        if (existingPropDescriptor.getReadMethod() == null) {
                            existingPropDescriptor.setReadMethod(superPropDescriptor.getReadMethod());
                        }
                        if (existingPropDescriptor.getWriteMethod() == null) {
                            existingPropDescriptor.setWriteMethod(superPropDescriptor.getWriteMethod());
                        }
                    } catch (IntrospectionException e) {
                        throw new MappingException(e);
                    }

                }
            }
        }
    }
    return propDescriptors.toArray(new PropertyDescriptor[propDescriptors.size()]);
}

From source file:org.eclipse.jubula.client.core.preferences.database.DatabaseConnectionConverter.java

/**
 * // w  ww .j a  v  a2s  .  c o m
 * @param connection The connection to represent as a string. Must not be 
 *                   <code>null</code>.
 * @return a persistable String representation of the given object.
 */
private static String serialize(DatabaseConnection connection) {
    Validate.notNull(connection);

    StringBuilder sb = new StringBuilder();
    sb.append(connection.getName()).append(PROPERTY_SEPARATOR);
    for (PropertyDescriptor propDesc : PropertyUtils.getPropertyDescriptors(connection.getConnectionInfo())) {
        String propName = propDesc.getName();
        try {
            // only save writable properties, as we will not be able to 
            // set read-only properties when reading connection info back 
            // in from the preference store 
            if (PropertyUtils.isWriteable(connection.getConnectionInfo(), propName)) {
                sb.append(propName).append(PROPERTY_SEPARATOR)
                        .append(BeanUtils.getProperty(connection.getConnectionInfo(), propName))
                        .append(PROPERTY_SEPARATOR);
            }
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }

    sb.deleteCharAt(sb.length() - 1);
    return sb.toString();
}

From source file:org.eclipse.jubula.rc.common.util.PropertyUtil.java

/**
 * Returns a sorted map consisting of the bean properties of a component
 * /*from  w  w w.  j av a2s . c  o  m*/
 * @param currComp 
 *              the component
 * @return the sorted map of properties
 */
public static Map getMapOfComponentProperties(final Object currComp) {
    PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(currComp);
    Map componentProperties = new TreeMap();
    for (int i = 0; i < propertyDescriptors.length; i++) {
        PropertyDescriptor pd = propertyDescriptors[i];
        try {
            Method readMethod = pd.getReadMethod();
            if (readMethod != null) {
                Object obj = readMethod.invoke(currComp, new Object[] {});
                String value = String.valueOf(obj);
                if (value.length() > 200) {
                    value = StringUtils.substring(value, 0, 200);
                }
                if (obj instanceof Character) {
                    Character c = (Character) obj;
                    if (c.charValue() == 0) {
                        value = ""; //$NON-NLS-1$
                    }
                }
                componentProperties.put(pd.getName(), value);
            } else {
                componentProperties.put(pd.getName(), "This property is not readable"); //$NON-NLS-1$
            }
        } catch (IllegalArgumentException e) {
            componentProperties.put(pd.getName(), "Error"); //$NON-NLS-1$
        } catch (IllegalAccessException e) {
            componentProperties.put(pd.getName(), "Error accessing this property"); //$NON-NLS-1$
        } catch (InvocationTargetException e) {
            componentProperties.put(pd.getName(), "Error reading this property"); //$NON-NLS-1$
        }
    }
    return componentProperties;
}

From source file:org.efs.openreports.services.servlet.ReportServiceServlet.java

public void init(ServletConfig servletConfig) throws ServletException {
    ApplicationContext appContext = WebApplicationContextUtils
            .getRequiredWebApplicationContext(servletConfig.getServletContext());

    reportService = (ReportService) appContext.getBean("reportService", ReportService.class);

    //cache ServletReportServiceInput PropertyDescriptors
    descriptors = PropertyUtils.getPropertyDescriptors(ServletReportServiceInput.class);

    super.init(servletConfig);

    log.info("Started...");
}

From source file:org.extremecomponents.tree.TreeNode.java

public TreeNode(Object bean, Object identifier, int depth)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    if (bean instanceof Map) {
        this.putAll((Map) bean);
    } else {//from www  .j a  v a2 s  .  c  o m
        PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(bean.getClass());
        for (int i = 0; i < descriptors.length; i++) {
            this.put(descriptors[i].getName(), BeanUtils.getProperty(bean, descriptors[i].getName()));
        }
    }
    setBean(bean);
    this.identifier = identifier;
    this.depth = depth;
}

From source file:org.extremecomponents.tree.TreeNode.java

/**
 * @param bean/*www  .  j a v a2 s  .  c  om*/
 *            The bean to set.
 */
public void setBean(Object bean) {
    this.bean = bean;

    PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(bean);

    for (int i = 0; i < descriptors.length; i++) {
        try {
            String propertyName = descriptors[i].getDisplayName();
            Object val = BeanUtils.getProperty(bean, propertyName);
            this.put(propertyName, val);
        } catch (Exception e) {
            logger.error("TreeNode.setBean() Problem", e);
        }
    }
}

From source file:org.fhcrc.cpl.toolbox.filehandler.TabLoader.java

private void initColumnInfos(Class clazz) {
    PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(clazz);
    HashMap<String, PropertyDescriptor> mappedPropNames = new HashMap<String, PropertyDescriptor>();
    for (PropertyDescriptor origDescriptor : origDescriptors) {
        if (origDescriptor.getName().equals("class"))
            continue;

        mappedPropNames.put(origDescriptor.getName().toLowerCase(), origDescriptor);
    }//from w ww  .  j  a  va 2s.  c om

    boolean isMapClass = java.util.Map.class.isAssignableFrom(clazz);
    for (ColumnDescriptor column : _columns) {
        PropertyDescriptor prop = mappedPropNames.get(column.name.toLowerCase());
        if (null != prop) {
            column.name = prop.getName();
            column.clazz = prop.getPropertyType();
            column.isProperty = true;
            column.setter = prop.getWriteMethod();
            if (column.clazz.isPrimitive()) {
                if (Float.TYPE.equals(column.clazz))
                    column.missingValues = 0.0F;
                else if (Double.TYPE.equals(column.clazz))
                    column.missingValues = 0.0;
                else if (Boolean.TYPE.equals(column.clazz))
                    column.missingValues = Boolean.FALSE;
                else
                    column.missingValues = 0; //Will get converted.
            }
        } else if (isMapClass) {
            column.isProperty = false;
        } else {
            column.load = false;
        }
    }
}