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.apache.ignite.cache.store.cassandra.common.PropertyMappingHelper.java

/**
 * Extracts all property descriptors from a class.
 *
 * @param clazz class which property descriptors should be extracted.
 * @param primitive boolean flag indicating that only property descriptors for primitive properties
 *      should be extracted.//w w  w.jav a2  s .c o m
 *
 * @return list of class property descriptors
 */
public static List<PropertyDescriptor> getPojoPropertyDescriptors(Class clazz, boolean primitive) {
    PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(clazz);

    List<PropertyDescriptor> list = new ArrayList<>(descriptors == null ? 1 : descriptors.length);

    if (descriptors == null || descriptors.length == 0)
        return list;

    for (PropertyDescriptor descriptor : descriptors) {
        if (descriptor.getReadMethod() == null || (primitive && !isPrimitivePropertyDescriptor(descriptor)))
            continue;

        list.add(descriptor);
    }

    return list;
}

From source file:org.apache.ignite.cache.store.cassandra.persistence.PersistenceSettings.java

/**
 * Extracts POJO fields from a list of corresponding XML field nodes.
 *
 * @param fieldNodes Field nodes to process.
 * @return POJO fields list.//from w  w w .  j  a  va2 s  . c  o m
 */
protected List<PojoField> detectPojoFields(NodeList fieldNodes) {
    List<PojoField> detectedFields = new LinkedList<>();

    if (fieldNodes != null && fieldNodes.getLength() != 0) {
        int cnt = fieldNodes.getLength();

        for (int i = 0; i < cnt; i++) {
            PojoField field = createPojoField((Element) fieldNodes.item(i), getJavaClass());

            // Just checking that such field exists in the class
            PropertyMappingHelper.getPojoFieldAccessor(getJavaClass(), field.getName());

            detectedFields.add(field);
        }

        return detectedFields;
    }

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

    // Collecting Java Beans property descriptors
    if (descriptors != null) {
        for (PropertyDescriptor desc : descriptors) {
            // Skip POJO field if it's read-only
            if (desc.getWriteMethod() != null) {
                Field field = null;

                try {
                    field = getJavaClass().getDeclaredField(desc.getName());
                } catch (Throwable ignore) {
                }

                detectedFields.add(createPojoField(new PojoFieldAccessor(desc, field)));
            }
        }
    }

    Field[] fields = getJavaClass().getDeclaredFields();

    // Collecting all fields annotated with @QuerySqlField
    if (fields != null) {
        for (Field field : fields) {
            if (field.getAnnotation(QuerySqlField.class) != null
                    && !PojoField.containsField(detectedFields, field.getName()))
                detectedFields.add(createPojoField(new PojoFieldAccessor(field)));
        }
    }

    return detectedFields;
}

From source file:org.apache.nifi.processors.hl7.ExtractHL7Attributes.java

private static Map<String, Type> getAllComponents(final String fieldKey, final Type field,
        final boolean useNames) throws HL7Exception {
    final Map<String, Type> components = new TreeMap<>();
    if (!isEmpty(field) && (field instanceof Composite)) {
        if (useNames) {
            final Pattern p = Pattern.compile("^(cm_msg|[a-z][a-z][a-z]?)([0-9]+)_(\\w+)$");
            try {
                final java.beans.PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(field);
                for (final java.beans.PropertyDescriptor property : properties) {
                    final String propertyName = property.getName();
                    final Matcher matcher = p.matcher(propertyName);
                    if (matcher.find()) {
                        final Type type = (Type) PropertyUtils.getProperty(field, propertyName);
                        if (!isEmpty(type)) {
                            final String componentName = matcher.group(3);
                            final String typeKey = new StringBuilder().append(fieldKey).append(".")
                                    .append(componentName).toString();
                            components.put(typeKey, type);
                        }//from  w  w  w  . ja  va 2  s  . c o  m
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        } else {
            final Type[] types = ((Composite) field).getComponents();
            for (int i = 0; i < types.length; i++) {
                final Type type = types[i];
                if (!isEmpty(type)) {
                    String fieldName = field.getName();
                    if (fieldName.equals("CM_MSG")) {
                        fieldName = "CM";
                    }
                    final String typeKey = new StringBuilder().append(fieldKey).append(".").append(fieldName)
                            .append(".").append(i + 1).toString();
                    components.put(typeKey, type);
                }
            }
        }
    }
    return components;
}

From source file:org.apache.qpid.disttest.message.ParticipantAttributeExtractor.java

public static Map<ParticipantAttribute, Object> getAttributes(Object targetObject) {
    Map<ParticipantAttribute, Object> attributes = new HashMap<ParticipantAttribute, Object>();

    PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(targetObject);
    for (PropertyDescriptor propertyDescriptor : descriptors) {
        final Method readMethod = getPropertyReadMethod(targetObject, propertyDescriptor);

        for (Annotation annotation : readMethod.getDeclaredAnnotations()) {
            if (annotation instanceof OutputAttribute) {
                OutputAttribute outputAttribute = (OutputAttribute) annotation;

                Object value = getPropertyValue(targetObject, propertyDescriptor.getName());
                attributes.put(outputAttribute.attribute(), value);
            }//from   ww  w .  j a  va  2 s  .c o m
        }
    }

    return attributes;
}

From source file:org.apache.shiro.guice.BeanTypeListener.java

public <I> void hear(TypeLiteral<I> type, final TypeEncounter<I> encounter) {
    PropertyDescriptor propertyDescriptors[] = PropertyUtils.getPropertyDescriptors(type.getRawType());
    final Map<PropertyDescriptor, Key<?>> propertyDependencies = new HashMap<PropertyDescriptor, Key<?>>(
            propertyDescriptors.length);
    final Provider<Injector> injectorProvider = encounter.getProvider(Injector.class);
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        if (propertyDescriptor.getWriteMethod() != null
                && Modifier.isPublic(propertyDescriptor.getWriteMethod().getModifiers())) {
            Type propertyType = propertyDescriptor.getWriteMethod().getGenericParameterTypes()[0];
            propertyDependencies.put(propertyDescriptor, createDependencyKey(propertyDescriptor, propertyType));
        }//from  w w  w. j a  v a  2 s .  com
    }
    encounter.register(new MembersInjector<I>() {
        public void injectMembers(I instance) {
            for (Map.Entry<PropertyDescriptor, Key<?>> dependency : propertyDependencies.entrySet()) {
                try {
                    final Injector injector = injectorProvider.get();

                    Object value = injector.getInstance(getMappedKey(injector, dependency.getValue()));
                    dependency.getKey().getWriteMethod().invoke(instance, value);

                } catch (ConfigurationException e) {
                    // This is ok, it simply means that we can't fulfill this dependency.
                    // Is there a better way to do this?
                } catch (InvocationTargetException e) {
                    throw new RuntimeException("Couldn't set property " + dependency.getKey().getDisplayName(),
                            e);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(
                            "We shouldn't have ever reached this point, we don't try to inject to non-accessible methods.",
                            e);
                }
            }

        }
    });
}

From source file:org.apache.usergrid.persistence.Schema.java

public synchronized void registerEntity(Class<? extends Entity> entityClass) {
    logger.info("Registering {}", entityClass);
    EntityInfo e = registeredEntityClasses.get(entityClass);
    if (e != null) {
        return;//from  w  w  w  . j  a va2  s  .  c om
    }

    Map<String, PropertyDescriptor> propertyDescriptors = entityClassPropertyToDescriptor.get(entityClass);
    if (propertyDescriptors == null) {
        EntityInfo entity = new EntityInfo();

        String type = getEntityType(entityClass);

        propertyDescriptors = new LinkedHashMap<String, PropertyDescriptor>();
        Map<String, PropertyInfo> properties = new TreeMap<String, PropertyInfo>(String.CASE_INSENSITIVE_ORDER);
        Map<String, CollectionInfo> collections = new TreeMap<String, CollectionInfo>(
                String.CASE_INSENSITIVE_ORDER);
        Map<String, DictionaryInfo> sets = new TreeMap<String, DictionaryInfo>(String.CASE_INSENSITIVE_ORDER);

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

        for (PropertyDescriptor descriptor : descriptors) {
            String name = descriptor.getName();

            EntityProperty propertyAnnotation = getAnnotation(entityClass, descriptor, EntityProperty.class);
            if (propertyAnnotation != null) {
                if (isNotBlank(propertyAnnotation.name())) {
                    name = propertyAnnotation.name();
                }
                propertyDescriptors.put(name, descriptor);

                PropertyInfo propertyInfo = new PropertyInfo(propertyAnnotation);
                propertyInfo.setName(name);
                propertyInfo.setType(descriptor.getPropertyType());

                properties.put(name, propertyInfo);
                // logger.info(propertyInfo);
            }

            EntityCollection collectionAnnotation = getAnnotation(entityClass, descriptor,
                    EntityCollection.class);
            if (collectionAnnotation != null) {
                CollectionInfo collectionInfo = new CollectionInfo(collectionAnnotation);
                collectionInfo.setName(name);
                collectionInfo.setContainer(entity);

                collections.put(name, collectionInfo);
                // logger.info(collectionInfo);
            }

            EntityDictionary setAnnotation = getAnnotation(entityClass, descriptor, EntityDictionary.class);
            if (setAnnotation != null) {
                DictionaryInfo setInfo = new DictionaryInfo(setAnnotation);
                setInfo.setName(name);
                // setInfo.setType(descriptor.getPropertyType());
                sets.put(name, setInfo);
                // logger.info(setInfo);
            }
        }

        if (!DynamicEntity.class.isAssignableFrom(entityClass)) {
            entity.setProperties(properties);
            entity.setCollections(collections);
            entity.setDictionaries(sets);
            entity.mapCollectors(this, type);

            entityMap.put(type, entity);

            allProperties.putAll(entity.getProperties());

            Set<String> propertyNames = entity.getIndexedProperties();
            for (String propertyName : propertyNames) {
                PropertyInfo property = entity.getProperty(propertyName);
                if ((property != null) && !allIndexedProperties.containsKey(propertyName)) {
                    allIndexedProperties.put(propertyName, property);
                }
            }
        }

        entityClassPropertyToDescriptor.put(entityClass, propertyDescriptors);

        registeredEntityClasses.put(entityClass, entity);
    }
}

From source file:org.beangle.spring.bind.AutoConfigProcessor.java

protected Map<String, PropertyDescriptor> unsatisfiedNonSimpleProperties(BeanDefinition mbd) {
    Map<String, PropertyDescriptor> properties = CollectUtils.newHashMap();
    PropertyValues pvs = mbd.getPropertyValues();
    Class<?> clazz = null;//from   w w w . java 2 s  .  c  o  m
    try {
        clazz = Class.forName(mbd.getBeanClassName());
    } catch (ClassNotFoundException e) {
        logger.error("Class " + mbd.getBeanClassName() + "not found", e);
        return properties;
    }
    PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(clazz);
    for (PropertyDescriptor pd : pds) {
        if (pd.getWriteMethod() != null && !isExcludedFromDependencyCheck(pd) && !pvs.contains(pd.getName())
                && !BeanUtils.isSimpleProperty(pd.getPropertyType())) {
            properties.put(pd.getName(), pd);
        }
    }
    return properties;
}

From source file:org.beangle.struts2.view.component.ComponentHelper.java

public static final void registe(Class<?> clazz) {
    PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(clazz);
    Map<String, Method> keys = CollectUtils.newHashMap();
    for (PropertyDescriptor a : descriptors) {
        if (null != a.getWriteMethod()) {
            keys.put(a.getName(), a.getWriteMethod());
        }/*from w w  w .  j a va2s  .  c o m*/
    }
    writables.put(clazz, keys);
}

From source file:org.bitsofinfo.util.address.usps.ais.USPSFullAddressService.java

public USPSFullAddressService() {
    // ensure prop descriptors are cached
    PropertyDescriptor[] zip4detailsProps = PropertyUtils.getPropertyDescriptors(ZipPlus4Detail.class);
    PropertyDescriptor[] fullAddressProps = PropertyUtils.getPropertyDescriptors(USPSFullAddress.class);
}

From source file:org.carewebframework.ui.xml.ZK2XML.java

/**
 * Adds the root component to the XML document at the current level along with all bean
 * properties that return String or primitive types. Then, recurses over all of the root
 * component's children.//from  www .  j  ava2  s. c  o m
 * 
 * @param root The root component.
 * @param parent The parent XML node.
 */
private void toXML(Component root, Node parent) {
    TreeMap<String, String> properties = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
    Class<?> clazz = root.getClass();
    ComponentDefinition def = root.getDefinition();
    String cmpname = def.getName();

    if (def.getImplementationClass() != clazz) {
        properties.put("use", clazz.getName());
    }

    if (def.getApply() != null) {
        properties.put("apply", def.getApply());
    }

    Node child = doc.createElement(cmpname);
    parent.appendChild(child);

    for (PropertyDescriptor propDx : PropertyUtils.getPropertyDescriptors(root)) {
        Method getter = propDx.getReadMethod();
        Method setter = propDx.getWriteMethod();
        String name = propDx.getName();

        if (getter != null && setter != null && !isExcluded(name, cmpname, null)
                && !setter.isAnnotationPresent(Deprecated.class)
                && (getter.getReturnType() == String.class || getter.getReturnType().isPrimitive())) {
            try {
                Object raw = getter.invoke(root);
                String value = raw == null ? null : raw.toString();

                if (StringUtils.isEmpty(value) || ("id".equals(name) && value.startsWith("z_"))
                        || isExcluded(name, cmpname, value)) {
                    continue;
                }

                properties.put(name, value.toString());
            } catch (Exception e) {
            }
        }
    }

    for (Entry<String, String> entry : properties.entrySet()) {
        Attr attr = doc.createAttribute(entry.getKey());
        child.getAttributes().setNamedItem(attr);
        attr.setValue(entry.getValue());
    }

    properties = null;

    for (Component cmp : root.getChildren()) {
        toXML(cmp, child);
    }
}