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.thiesen.helenaorm.HelenaDAO.java

HelenaDAO(final Class<T> clz, final String hostname, final int port,
        final SerializeUnknownClasses serializationPolicy,
        final ImmutableMap<Class<?>, TypeMapping<?>> typeMappings) {

    if (!clz.isAnnotationPresent(HelenaBean.class)) {
        throw new IllegalArgumentException(
                "Trying to get a HelenaDAO for a class that is not mapped with @HelenaBean");
    }/*  www .  ja  v  a  2  s.com*/

    final HelenaBean annotation = clz.getAnnotation(HelenaBean.class);
    _typeConverter = new TypeConverter(typeMappings, serializationPolicy);
    _clz = clz;
    _propertyDescriptors = PropertyUtils.getPropertyDescriptors(clz);
    _columnFamily = annotation.columnFamily();
    _hostname = hostname;
    _port = port;
    _keyspace = annotation.keyspace();

    if (annotation.consistency() != null) {
        this.setConsistencyLevel(annotation.consistency());
    }

    _fields = new HashMap<String, Field>();
    for (Field field : clz.getDeclaredFields()) {
        _fields.put(field.getName(), field);
        if (field.isAnnotationPresent(KeyProperty.class)) {
            _keyField = field;
        }
    }

    final Builder<byte[]> setBuilder = ImmutableSet.<byte[]>builder();
    for (final PropertyDescriptor descriptor : _propertyDescriptors) {
        setBuilder.add(_typeConverter.stringToBytes(descriptor.getName()));
        if (isKeyProperty(descriptor)) {
            _keyPropertyDescriptor = descriptor;
        }
        if (isSuperColumnProperty(descriptor)) {
            _superColumnPropertyDescriptor = descriptor;
        }
    }
    _columnNames = ImmutableList.copyOf(setBuilder.build());

    if (_keyField == null && _keyPropertyDescriptor == null) {
        throw new HelenaRuntimeException(
                "Could not find key of class " + clz.getName() + ", did you annotate with @KeyProperty");
    }
}

From source file:org.tinygroup.commons.beanutil.BeanUtil.java

public static Object deepCopy(Object orig) throws Exception {
    Object dest = orig.getClass().newInstance();
    PropertyDescriptor[] origDescriptors = PropertyUtils.getPropertyDescriptors(orig);
    for (PropertyDescriptor propertyDescriptor : origDescriptors) {
        String name = propertyDescriptor.getName();
        if (PropertyUtils.isReadable(orig, name) && PropertyUtils.isWriteable(dest, name)) {
            Object value = PropertyUtils.getSimpleProperty(orig, name);
            Object valueDest = null;
            if (value != null && canDeepCopyObject(value)) {
                if (value instanceof Collection) {
                    Collection coll = (Collection) value;
                    Collection newColl = createApproximateCollection(value);
                    Iterator it = coll.iterator();
                    while (it.hasNext()) {
                        newColl.add(deepCopy(it.next()));
                    }/*from w w w  .j a va  2 s  . c  o m*/
                    valueDest = newColl;
                } else if (value.getClass().isArray()) {
                    Object[] values = (Object[]) value;
                    Object[] newValues = new Object[values.length];
                    for (int i = 0; i < newValues.length; i++) {
                        newValues[i] = deepCopy(values[i]);
                    }
                    valueDest = newValues;
                } else if (value instanceof Map) {
                    Map map = (Map) value;
                    Map newMap = createApproximateMap(map);
                    for (Object key : map.keySet()) {
                        newMap.put(key, deepCopy(map.get(key)));
                    }
                    valueDest = newMap;
                } else {
                    valueDest = deepCopy(value);
                }
            } else {
                valueDest = value;
            }
            PropertyUtils.setSimpleProperty(dest, name, valueDest);
        }

    }
    return dest;

}

From source file:org.tinygroup.context2object.impl.ClassNameObjectGenerator.java

private Object buildObject(String varName, Object object, Context context, String preName) {
    if (object == null) {
        return null;
    }/*  ww  w .  ja v a 2 s  .  c  om*/
    Class<?> clazz = object.getClass();

    String objName = varName;
    ObjectAssembly assembly = getObjectAssembly(object.getClass());
    if (assembly != null) {
        assembly.assemble(varName, object, context);
        return object;
    }
    // 20130424
    // ?
    boolean allPropertyNull = true;
    if (isNull(objName)) {
        objName = getObjName(object);
    }
    for (PropertyDescriptor descriptor : PropertyUtils.getPropertyDescriptors(object.getClass())) {
        if (descriptor.getPropertyType().equals(Class.class)) {
            continue;
        }

        // 201402025?propertyName?
        // String propertyName = getPropertyName(clazz,
        // descriptor.getName());
        String propertyName = descriptor.getName();
        Object propertyValue = getPerpertyValue(preName, objName, propertyName, context);// user.name,user_name,name
        if (propertyValue != null) { // ????
            try {
                if (descriptor.getPropertyType().equals( // ?()
                        propertyValue.getClass())
                        || implmentInterface(propertyValue.getClass(), descriptor.getPropertyType())) {
                    BeanUtils.setProperty(object, descriptor.getName(), propertyValue);
                    allPropertyNull = false;
                    continue;
                } else if (isSimpleType(descriptor.getPropertyType())) {// ?
                    if (String.class == propertyValue.getClass()) { // String
                        BeanUtils.setProperty(object, descriptor.getName(), BasicTypeConverter
                                .getValue(propertyValue.toString(), descriptor.getPropertyType().getName()));
                        allPropertyNull = false;
                    } else if (isSimpleType(propertyValue.getClass())) { // ?????
                        BeanUtils.setProperty(object, descriptor.getName(), propertyValue.toString());
                        allPropertyNull = false;
                    } else {
                        LOGGER.logMessage(LogLevel.WARN,
                                "?{0}.{1},{3},{4}", objName,
                                propertyName, descriptor.getPropertyType(), propertyValue.getClass());
                    }
                    continue;
                }
                // else {
                // }
                // ???
            } catch (Exception e) {
                LOGGER.errorMessage("{0}", e, descriptor.getName());
            }
        }

        // ????
        // ???
        TypeConverter typeConverter = getTypeConverter(descriptor.getPropertyType());
        if (typeConverter != null) {
            if (propertyValue != null) {
                try {
                    BeanUtils.setProperty(object, descriptor.getName(), typeConverter.getObject(propertyValue));
                    allPropertyNull = false;
                } catch (Exception e) {
                    LOGGER.errorMessage("{0}", e, descriptor.getName());
                }
            }
            continue;
        }
        // ??
        if (!isSimpleType(descriptor.getPropertyType())) {
            // 
            try {
                String newPreName = getReallyPropertyName(preName, objName, propertyName);
                // ===============begin======================
                // 20151208getDeclaredFieldWithParent?type???
                // Class<?> type = null;
                // try{
                Field field = getDeclaredFieldWithParent(clazz, propertyName);
                // type =
                // clazz.getDeclaredField(descriptor.getName()).getType();
                // type = descriptor.getPropertyType();
                // }catch (NoSuchFieldException e)

                if (field == null) {
                    LOGGER.logMessage(LogLevel.WARN, "{}?{}", clazz.getName(), propertyName);
                    continue;
                }
                Class<?> type = field.getType();
                // ===============end======================
                if (type.isArray()) {// 
                    Object value = getObject(newPreName, null, descriptor.getPropertyType(), context, null);
                    if (value != null) {
                        BeanUtils.setProperty(object, descriptor.getName(), value);
                        allPropertyNull = false;
                    }
                } else if (implmentInterface(descriptor.getPropertyType(), Collection.class)) {// ?
                    // ===============begin======================
                    // 20151208getDeclaredFieldWithParent?type???
                    Field propertyType = getDeclaredFieldWithParent(clazz, propertyName);
                    if (propertyType == null) {
                        LOGGER.logMessage(LogLevel.WARN, "{}?{}", clazz.getName(), propertyName);
                        continue;
                    }
                    // ParameterizedType pt = (ParameterizedType) clazz
                    // .getDeclaredField(descriptor.getName())
                    // .getGenericType();
                    ParameterizedType pt = (ParameterizedType) propertyType.getGenericType();
                    // ===============end======================
                    Type[] actualTypeArguments = pt.getActualTypeArguments();
                    Collection<Object> collection = (Collection<Object>) getObjectInstance(type);
                    buildCollection(newPreName, collection, (Class) actualTypeArguments[0], context, null);
                    if (!collection.isEmpty()) {
                        BeanUtils.setProperty(object, descriptor.getName(), collection);
                        allPropertyNull = false;
                    }
                } else {// 
                    Object value = getObject(newPreName, null, descriptor.getPropertyType(), context, null);
                    if (value != null) {
                        BeanUtils.setProperty(object, descriptor.getName(), value);
                        allPropertyNull = false;
                    }
                }
            } catch (Exception e) {
                LOGGER.errorMessage("{0}", e, descriptor.getName());
            }
        }
    }
    if (allPropertyNull) {
        return null;
    }
    return object;
}

From source file:org.tinygroup.context2object.impl.ClassNameObjectGenerator.java

private void dealComplexObject(String varName, Collection<Object> collection, Class<?> clazz, Context context,
        String preName) {/*from   w  ww.jav a  2 s.  c o  m*/
    Object object = getObjectInstance(clazz);
    String objName = varName;
    if (isNull(objName)) {
        // 20130806??????
        objName = getObjName(object);
    }
    Map<String, Object> valueMap = new HashMap<String, Object>();
    Class<?> reallyType = object.getClass();
    int size = -1;

    // collectionsize
    for (PropertyDescriptor descriptor : PropertyUtils.getPropertyDescriptors(reallyType)) {
        if (descriptor.getPropertyType().equals(Class.class)) {
            continue;
        }
        if (size != -1) {
            break;
        }
        // 201402025?propertyName?
        // String propertyName = getPropertyName(reallyType,
        // descriptor.getName());
        String propertyName = descriptor.getName();

        Object propertyValue = getPerpertyValue(preName, objName, propertyName, context);
        if (propertyValue != null) {
            valueMap.put(propertyName, propertyValue);
            if (propertyValue.getClass().isArray()) {
                // 
                Object[] objArray = (Object[]) propertyValue;
                if (objArray.length > size) {
                    size = objArray.length;
                }
            } else if (size == -1) {
                size = 1;
            }
        }
    }
    // 20130424
    // ?
    // ?
    if (size == -1) {
        return;
    }
    // ?objecList?
    List<Object> objecList = new ArrayList<Object>();
    for (int i = 0; i < size; i++) {
        Object o = getObjectInstance(clazz);
        objecList.add(o);
    }

    for (PropertyDescriptor descriptor : PropertyUtils.getPropertyDescriptors(reallyType)) {
        if (descriptor.getPropertyType().equals(Class.class)) {
            continue;
        }
        // 201402025?propertyName?
        // String propertyName = getPropertyName(reallyType,
        // descriptor.getName());
        String propertyName = descriptor.getName();
        Object propertyValue = getPerpertyValue(preName, objName, propertyName, context);
        if (propertyValue == null) {
            continue;
        }

        try {
            if (size == 1) {
                Object realvalue = propertyValue;
                if (propertyValue.getClass().isArray()) {
                    realvalue = ((Object[]) propertyValue)[0];
                }
                setSimpleValue(objecList, 0, descriptor, realvalue);

            } else {
                Object[] objArray = (Object[]) propertyValue;
                for (int i = 0; i < size; i++) {
                    // BeanUtils.setProperty(objecList.get(i),
                    // descriptor.getName(), objArray[i]);
                    setSimpleValue(objecList, i, descriptor, objArray[i]);
                }
            }
            continue;
        } catch (Exception e) {
            LOGGER.errorMessage("{0}", e, descriptor.getName());
        }
    }
    // objecList?collection
    for (Object o : objecList) {
        collection.add(o);
    }
    // return collection;
}

From source file:org.tinygroup.factory.impl.SimpleFactory.java

private void autoAssembleBean(Bean beanDefine, Object newInstance) {
    for (PropertyDescriptor propertyDescriptor : PropertyUtils.getPropertyDescriptors(newInstance)) {
        try {/*ww w  .ja  v a2s  . c o  m*/
            if (propertyDescriptor.getPropertyType().equals(Class.class)) {
                continue;
            }
            if (beanDefine.getAutowire().equalsIgnoreCase(BY_NAME)) {
                Object bean = getBean(propertyDescriptor.getName());
                if (bean != null && propertyDescriptor.getPropertyType().isInstance(bean)) {
                    BeanUtils.setProperty(newInstance, propertyDescriptor.getName(), bean);
                }
            } else if (beanDefine.getAutowire().equalsIgnoreCase(BY_TYPE)) {
                Object bean = getBean(propertyDescriptor.getPropertyType());
                if (bean != null) {
                    BeanUtils.setProperty(newInstance, propertyDescriptor.getName(), bean);
                }
            }
        } catch (Exception e) {
            LOGGER.errorMessage("{0}", e, propertyDescriptor.getName());
        }
    }
}

From source file:org.tinygroup.jdbctemplatedslsession.SimpleDslSession.java

private <T> Map<String, Object> convertMap(T param) throws Exception {
    Map<String, Object> description = new LinkedHashMap<String, Object>();
    PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(param);
    for (int i = 0; i < descriptors.length; i++) {
        String name = descriptors[i].getName();
        if (PropertyUtils.isReadable(param, name) && PropertyUtils.isWriteable(param, name)) {
            if (descriptors[i].getReadMethod() != null) {
                Object value = PropertyUtils.getProperty(param, name);
                description.put(name, value);
                description.put(nameStrategy.getFieldName(name), value);
            }/*from  w w  w .j a  v  a  2  s . c o m*/
        }
    }
    return description;
}

From source file:org.tylproject.vaadin.addon.fieldbinder.FieldBinder.java

/**
 * Retrieves the type of the property with the given name of the given
 * Class.//from   w  ww .ja  v  a 2 s .  c  o  m
 *
 * Supports nested properties following bean naming convention.
 * e.g., "foo.bar.name"
 *
 * @see PropertyUtils#getPropertyDescriptors(Class)
 * @throws java.lang.IllegalArgumentException if the given propertyId does not exist
 */
public Class<?> getPropertyType(Object propertyId) {
    if (propertyId == null)
        throw new IllegalArgumentException("PropertyName must not be null.");

    final String propertyName = propertyId.toString();

    final String[] path = propertyName.split("\\.");

    Class<?> propClass = beanClass;

    for (int i = 0; i < path.length; i++) {
        String propertyFragment = path[i];
        final PropertyDescriptor[] propDescs = PropertyUtils.getPropertyDescriptors(propClass);

        for (final PropertyDescriptor propDesc : propDescs)
            if (propDesc.getName().equals(propertyFragment)) {
                propClass = propDesc.getPropertyType();
                if (i == path.length - 1)
                    return propClass;
            }
    }

    throw new IllegalArgumentException("No such propertyId: " + propertyId);
}

From source file:org.vulpe.view.tags.Functions.java

/**
 *
 * @param bean/*from   w  w  w  .j a v a2  s  .  c o m*/
 * @return
 */

public static List fieldsInBean(final Object bean) {
    final PropertyDescriptor pDescriptor[] = PropertyUtils.getPropertyDescriptors(bean);
    final List list = new ArrayList();
    for (PropertyDescriptor propertyDescriptor : pDescriptor) {
        if (propertyDescriptor.getReadMethod() == null || propertyDescriptor.getWriteMethod() == null) {
            continue;
        }

        list.add(propertyDescriptor.getName());
    }
    return list;
}

From source file:org.wildfly.swarm.microprofile.openapi.api.util.MergeUtil.java

/**
 * Generic merge of two objects of the same type.
 * @param object1/*from   ww w .j av  a2s.  c  o  m*/
 * @param object2
 */
@SuppressWarnings({ "rawtypes" })
public static <T> T mergeObjects(T object1, T object2) {
    if (object1 == null && object2 != null) {
        return object2;
    }
    if (object1 != null && object2 == null) {
        return object1;
    }
    if (object1 == null && object2 == null) {
        return null;
    }

    // It's uncommon, but in some cases (like Link Parameters or Examples) the values could
    // be different types.  In this case, just take the 2nd one (the override).
    if (!object1.getClass().equals(object2.getClass())) {
        return object2;
    }

    PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(object1);
    for (PropertyDescriptor descriptor : descriptors) {
        if (EXCLUDED_PROPERTIES.contains(descriptor.getName())) {
            continue;
        }
        Class ptype = descriptor.getPropertyType();
        if (Map.class.isAssignableFrom(ptype)) {
            try {
                Map values1 = (Map) descriptor.getReadMethod().invoke(object1);
                Map values2 = (Map) descriptor.getReadMethod().invoke(object2);
                Map newValues = mergeMaps(values1, values2);
                descriptor.getWriteMethod().invoke(object1, newValues);
            } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                throw new RuntimeException(e);
            }
        } else if (List.class.isAssignableFrom(ptype)) {
            try {
                List values1 = (List) descriptor.getReadMethod().invoke(object1);
                List values2 = (List) descriptor.getReadMethod().invoke(object2);
                List newValues = mergeLists(values1, values2);
                descriptor.getWriteMethod().invoke(object1, newValues);
            } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                throw new RuntimeException(e);
            }
        } else if (Constructible.class.isAssignableFrom(ptype)) {
            try {
                Object val1 = descriptor.getReadMethod().invoke(object1);
                Object val2 = descriptor.getReadMethod().invoke(object2);
                Object newValue = mergeObjects(val1, val2);
                if (newValue != null) {
                    descriptor.getWriteMethod().invoke(object1, newValue);
                }
            } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                throw new RuntimeException(e);
            }
        } else {
            try {
                Object newValue = descriptor.getReadMethod().invoke(object2);
                if (newValue != null) {
                    descriptor.getWriteMethod().invoke(object1, newValue);
                }
            } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                throw new RuntimeException(e);
            }
        }
    }
    return object1;
}

From source file:org.wte4j.impl.service.FlatBeanModelService.java

@Override
public Map<String, Class<?>> listModelElements(Class<?> inputClass, Map<String, String> properties) {
    Map<String, Class<?>> elements = new HashMap<String, Class<?>>();

    for (PropertyDescriptor descriptor : PropertyUtils.getPropertyDescriptors(inputClass)) {
        elements.put(descriptor.getName(), descriptor.getPropertyType());
    }/*  w  w w .j a  va  2 s.  co m*/

    return elements;
}