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

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

Introduction

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

Prototype

public static PropertyDescriptor getPropertyDescriptor(Object bean, String name)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException 

Source Link

Document

Retrieve the property descriptor for the specified property of the specified bean, or return null if there is no such descriptor.

For more details see PropertyUtilsBean.

Usage

From source file:com.mb.framework.util.property.PropertyUtilExt.java

public static boolean equalsSimpleProperties(Object mainObject, Object otherObject)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(mainObject);
    for (int i = 0; i < origDescriptors.length; i++) {
        String name = origDescriptors[i].getName();

        if (PropertyUtils.getPropertyDescriptor(otherObject, name) != null) {
            Object origValue = PropertyUtils.getSimpleProperty(mainObject, name);
            Object otherValue = PropertyUtils.getSimpleProperty(otherObject, name);

            if (origValue != null && otherValue == null) {
                return false;
            }// w w  w. j a va 2s.co  m

            if (origValue == null && otherValue != null) {
                return false;
            }

            if (origValue != null && otherValue != null) {
                /*
                 * to walk around timestamp and date equals behavior Date d
                 * = new Date(); Timestamp t = new Timestamp(d.getTime());
                 * d.equals(t) > == true; t.equals(d) > == false;
                 */
                if (origValue instanceof java.sql.Timestamp
                        && (otherValue instanceof java.sql.Date || otherValue instanceof java.util.Date)) {
                    if (!otherValue.equals(origValue)) {
                        return false;
                    }
                } else {
                    if (!origValue.equals(otherValue)) {
                        return false;
                    }
                }
            }
        }
    }
    return true;
}

From source file:edu.harvard.med.screensaver.model.AbstractEntity.java

@SuppressWarnings("unchecked")
public <P> P getPropertyValue(String propertyName, Class<P> propertyType) {
    try {//from  w  ww.  j  av a 2 s . c  om
        PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(this, propertyName);
        return (P) propertyDescriptor.getReadMethod().invoke(this);
    } catch (Exception e) {
        log.error(e);
        return null;
    }
}

From source file:eagle.log.entity.meta.IndexDefinition.java

private byte[][] generateIndexValues(TaggedLogAPIEntity entity)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {

    final byte[][] result = new byte[columns.length][];
    for (int i = 0; i < columns.length; ++i) {
        final IndexColumn column = columns[i];
        final String columnName = column.getColumnName();
        if (column.isTag) {
            final Map<String, String> tags = entity.getTags();
            if (tags == null || tags.get(columnName) == null) {
                result[i] = EMPTY_VALUE;
            } else {
                result[i] = tags.get(columnName).getBytes(UTF_8_CHARSET);
            }/*ww  w .  j  a  va2  s  . c o  m*/
        } else {
            PropertyDescriptor pd = column.getPropertyDescriptor();
            if (pd == null) {
                pd = PropertyUtils.getPropertyDescriptor(entity, columnName);
                column.setPropertyDescriptor(pd);
            }
            final Object value = pd.getReadMethod().invoke(entity);
            if (value == null) {
                result[i] = EMPTY_VALUE;
            } else {
                final Qualifier q = column.getQualifier();
                result[i] = q.getSerDeser().serialize(value);
            }
        }
        if (result[i].length > MAX_INDEX_VALUE_BYTE_LENGTH) {
            throw new IllegalArgumentException("Index field value exceeded the max length: "
                    + MAX_INDEX_VALUE_BYTE_LENGTH + ", actual length: " + result[i].length);
        }
    }
    return result;
}

From source file:jenkins.plugins.shiningpanda.ShiningPandaTestCase.java

/**
 * Same as assertEqualBeans, but works on protected and private fields.
 * /*from   ww w .  j  av  a 2 s  .co  m*/
 * @param lhs
 *            The initial object.
 * @param rhs
 *            The final object.
 * @param properties
 *            The properties to check.
 * @throws Exception
 */
public void assertEqualBeans2(Object lhs, Object rhs, String properties) throws Exception {
    assertNotNull("lhs is null", lhs);
    assertNotNull("rhs is null", rhs);
    for (String p : properties.split(",")) {
        PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(lhs, p);
        Object lp, rp;
        if (pd == null) {
            Field f = getField(lhs.getClass(), p);
            assertNotNull("No such property " + p + " on " + lhs.getClass(), f);
            boolean accessible = f.isAccessible();
            if (!accessible)
                f.setAccessible(true);
            lp = f.get(lhs);
            rp = f.get(rhs);
            f.setAccessible(accessible);
        } else {
            lp = PropertyUtils.getProperty(lhs, p);
            rp = PropertyUtils.getProperty(rhs, p);
        }

        if (lp != null && rp != null && lp.getClass().isArray() && rp.getClass().isArray()) {
            // deep array equality comparison
            int m = Array.getLength(lp);
            int n = Array.getLength(rp);
            assertEquals("Array length is different for property " + p, m, n);
            for (int i = 0; i < m; i++)
                assertEquals(p + "[" + i + "] is different", Array.get(lp, i), Array.get(rp, i));
            return;
        }

        assertEquals("Property " + p + " is different", lp, rp);
    }
}

From source file:com.xwtec.xwserver.util.json.JSONObject.java

/**
 * Creates a bean from a JSONObject, with the specific configuration.
 *//*from   w w w .  j  av a 2  s.  c  o  m*/
public static Object toBean(JSONObject jsonObject, JsonConfig jsonConfig) {
    if (jsonObject == null || jsonObject.isNullObject()) {
        return null;
    }

    Class beanClass = jsonConfig.getRootClass();
    Map classMap = jsonConfig.getClassMap();

    if (beanClass == null) {
        return toBean(jsonObject);
    }
    if (classMap == null) {
        classMap = Collections.EMPTY_MAP;
    }

    Object bean = null;
    try {
        if (beanClass.isInterface()) {
            if (!Map.class.isAssignableFrom(beanClass)) {
                throw new JSONException("beanClass is an interface. " + beanClass);
            } else {
                bean = new HashMap();
            }
        } else {
            bean = jsonConfig.getNewBeanInstanceStrategy().newInstance(beanClass, jsonObject);
        }
    } catch (JSONException jsone) {
        throw jsone;
    } catch (Exception e) {
        throw new JSONException(e);
    }

    Map props = JSONUtils.getProperties(jsonObject);
    PropertyFilter javaPropertyFilter = jsonConfig.getJavaPropertyFilter();
    for (Iterator entries = jsonObject.names(jsonConfig).iterator(); entries.hasNext();) {
        String name = (String) entries.next();
        Class type = (Class) props.get(name);
        Object value = jsonObject.get(name);
        if (javaPropertyFilter != null && javaPropertyFilter.apply(bean, name, value)) {
            continue;
        }
        String key = Map.class.isAssignableFrom(beanClass)
                && jsonConfig.isSkipJavaIdentifierTransformationInMapKeys() ? name
                        : JSONUtils.convertToJavaIdentifier(name, jsonConfig);
        PropertyNameProcessor propertyNameProcessor = jsonConfig.findJavaPropertyNameProcessor(beanClass);
        if (propertyNameProcessor != null) {
            key = propertyNameProcessor.processPropertyName(beanClass, key);
        }
        try {
            if (Map.class.isAssignableFrom(beanClass)) {
                // no type info available for conversion
                if (JSONUtils.isNull(value)) {
                    setProperty(bean, key, value, jsonConfig);
                } else if (value instanceof JSONArray) {
                    setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig, name,
                            classMap, List.class), jsonConfig);
                } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type)
                        || JSONUtils.isNumber(type) || JSONUtils.isString(type)
                        || JSONFunction.class.isAssignableFrom(type)) {
                    if (jsonConfig.isHandleJettisonEmptyElement() && "".equals(value)) {
                        setProperty(bean, key, null, jsonConfig);
                    } else {
                        setProperty(bean, key, value, jsonConfig);
                    }
                } else {
                    Class targetClass = findTargetClass(key, classMap);
                    targetClass = targetClass == null ? findTargetClass(name, classMap) : targetClass;
                    JsonConfig jsc = jsonConfig.copy();
                    jsc.setRootClass(targetClass);
                    jsc.setClassMap(classMap);
                    if (targetClass != null) {
                        setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig);
                    } else {
                        setProperty(bean, key, toBean((JSONObject) value), jsonConfig);
                    }
                }
            } else {
                PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(bean, key);
                if (pd != null && pd.getWriteMethod() == null) {
                    log.info("Property '" + key + "' of " + bean.getClass() + " has no write method. SKIPPED.");
                    continue;
                }

                if (pd != null) {
                    Class targetType = pd.getPropertyType();
                    if (!JSONUtils.isNull(value)) {
                        if (value instanceof JSONArray) {
                            if (List.class.isAssignableFrom(pd.getPropertyType())) {
                                setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig,
                                        name, classMap, pd.getPropertyType()), jsonConfig);
                            } else if (Set.class.isAssignableFrom(pd.getPropertyType())) {
                                setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig,
                                        name, classMap, pd.getPropertyType()), jsonConfig);
                            } else {
                                setProperty(bean, key, convertPropertyValueToArray(key, value, targetType,
                                        jsonConfig, classMap), jsonConfig);
                            }
                        } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type)
                                || JSONUtils.isNumber(type) || JSONUtils.isString(type)
                                || JSONFunction.class.isAssignableFrom(type)) {
                            if (pd != null) {
                                if (jsonConfig.isHandleJettisonEmptyElement() && "".equals(value)) {
                                    setProperty(bean, key, null, jsonConfig);
                                } else if (!targetType.isInstance(value)) {
                                    setProperty(bean, key, morphPropertyValue(key, value, type, targetType),
                                            jsonConfig);
                                } else {
                                    setProperty(bean, key, value, jsonConfig);
                                }
                            } else if (beanClass == null || bean instanceof Map) {
                                setProperty(bean, key, value, jsonConfig);
                            } else {
                                log.warn("Tried to assign property " + key + ":" + type.getName()
                                        + " to bean of class " + bean.getClass().getName());
                            }
                        } else {
                            if (jsonConfig.isHandleJettisonSingleElementArray()) {
                                JSONArray array = new JSONArray().element(value, jsonConfig);
                                Class newTargetClass = findTargetClass(key, classMap);
                                newTargetClass = newTargetClass == null ? findTargetClass(name, classMap)
                                        : newTargetClass;
                                JsonConfig jsc = jsonConfig.copy();
                                jsc.setRootClass(newTargetClass);
                                jsc.setClassMap(classMap);
                                if (targetType.isArray()) {
                                    setProperty(bean, key, JSONArray.toArray(array, jsc), jsonConfig);
                                } else if (JSONArray.class.isAssignableFrom(targetType)) {
                                    setProperty(bean, key, array, jsonConfig);
                                } else if (List.class.isAssignableFrom(targetType)
                                        || Set.class.isAssignableFrom(targetType)) {
                                    jsc.setCollectionType(targetType);
                                    setProperty(bean, key, JSONArray.toCollection(array, jsc), jsonConfig);
                                } else {
                                    setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig);
                                }
                            } else {
                                if (targetType == Object.class || targetType.isInterface()) {
                                    Class targetTypeCopy = targetType;
                                    targetType = findTargetClass(key, classMap);
                                    targetType = targetType == null ? findTargetClass(name, classMap)
                                            : targetType;
                                    targetType = targetType == null && targetTypeCopy.isInterface()
                                            ? targetTypeCopy
                                            : targetType;
                                }
                                JsonConfig jsc = jsonConfig.copy();
                                jsc.setRootClass(targetType);
                                jsc.setClassMap(classMap);
                                setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig);
                            }
                        }
                    } else {
                        if (type.isPrimitive()) {
                            // assume assigned default value
                            log.warn("Tried to assign null value to " + key + ":" + type.getName());
                            setProperty(bean, key, JSONUtils.getMorpherRegistry().morph(type, null),
                                    jsonConfig);
                        } else {
                            setProperty(bean, key, null, jsonConfig);
                        }
                    }
                } else {
                    // pd is null
                    if (!JSONUtils.isNull(value)) {
                        if (value instanceof JSONArray) {
                            setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig,
                                    name, classMap, List.class), jsonConfig);
                        } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type)
                                || JSONUtils.isNumber(type) || JSONUtils.isString(type)
                                || JSONFunction.class.isAssignableFrom(type)) {
                            if (beanClass == null || bean instanceof Map
                                    || jsonConfig.getPropertySetStrategy() != null
                                    || !jsonConfig.isIgnorePublicFields()) {
                                setProperty(bean, key, value, jsonConfig);
                            } else {
                                log.warn("Tried to assign property " + key + ":" + type.getName()
                                        + " to bean of class " + bean.getClass().getName());
                            }
                        } else {
                            if (jsonConfig.isHandleJettisonSingleElementArray()) {
                                Class newTargetClass = findTargetClass(key, classMap);
                                newTargetClass = newTargetClass == null ? findTargetClass(name, classMap)
                                        : newTargetClass;
                                JsonConfig jsc = jsonConfig.copy();
                                jsc.setRootClass(newTargetClass);
                                jsc.setClassMap(classMap);
                                setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig);
                            } else {
                                setProperty(bean, key, value, jsonConfig);
                            }
                        }
                    } else {
                        if (type.isPrimitive()) {
                            // assume assigned default value
                            log.warn("Tried to assign null value to " + key + ":" + type.getName());
                            setProperty(bean, key, JSONUtils.getMorpherRegistry().morph(type, null),
                                    jsonConfig);
                        } else {
                            setProperty(bean, key, null, jsonConfig);
                        }
                    }
                }
            }
        } catch (JSONException jsone) {
            throw jsone;
        } catch (Exception e) {
            throw new JSONException("Error while setting property=" + name + " type " + type, e);
        }
    }

    return bean;
}

From source file:net.sf.json.JSONObject.java

/**
 * Creates a bean from a JSONObject, with the specific configuration.
 *//*from   www.  ja v  a 2s  .  co m*/
public static Object toBean(JSONObject jsonObject, JsonConfig jsonConfig) {
    if (jsonObject == null || jsonObject.isNullObject()) {
        return null;
    }

    Class beanClass = jsonConfig.getRootClass();
    Map classMap = jsonConfig.getClassMap();

    if (beanClass == null) {
        return toBean(jsonObject);
    }
    if (classMap == null) {
        classMap = Collections.EMPTY_MAP;
    }

    Object bean = null;
    try {
        if (beanClass.isInterface()) {
            if (!Map.class.isAssignableFrom(beanClass)) {
                throw new JSONException("beanClass is an interface. " + beanClass);
            } else {
                bean = new HashMap();
            }
        } else {
            bean = jsonConfig.getNewBeanInstanceStrategy().newInstance(beanClass, jsonObject);
        }
    } catch (JSONException jsone) {
        throw jsone;
    } catch (Exception e) {
        throw new JSONException(e);
    }

    Map props = JSONUtils.getProperties(jsonObject);
    PropertyFilter javaPropertyFilter = jsonConfig.getJavaPropertyFilter();
    for (Iterator entries = jsonObject.names(jsonConfig).iterator(); entries.hasNext();) {
        String name = (String) entries.next();
        Class type = (Class) props.get(name);
        Object value = jsonObject.get(name);
        if (javaPropertyFilter != null && javaPropertyFilter.apply(bean, name, value)) {
            continue;
        }
        String key = Map.class.isAssignableFrom(beanClass)
                && jsonConfig.isSkipJavaIdentifierTransformationInMapKeys() ? name
                        : JSONUtils.convertToJavaIdentifier(name, jsonConfig);
        PropertyNameProcessor propertyNameProcessor = jsonConfig.findJavaPropertyNameProcessor(beanClass);
        if (propertyNameProcessor != null) {
            key = propertyNameProcessor.processPropertyName(beanClass, key);
        }
        try {
            if (Map.class.isAssignableFrom(beanClass)) {
                // no type info available for conversion
                if (JSONUtils.isNull(value)) {
                    setProperty(bean, key, value, jsonConfig);
                } else if (value instanceof JSONArray) {
                    setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig, name,
                            classMap, List.class), jsonConfig);
                } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type)
                        || JSONUtils.isNumber(type) || JSONUtils.isString(type)
                        || JSONFunction.class.isAssignableFrom(type)) {
                    if (jsonConfig.isHandleJettisonEmptyElement() && "".equals(value)) {
                        setProperty(bean, key, null, jsonConfig);
                    } else {
                        setProperty(bean, key, value, jsonConfig);
                    }
                } else {
                    Class targetClass = resolveClass(classMap, key, name, type);
                    JsonConfig jsc = jsonConfig.copy();
                    jsc.setRootClass(targetClass);
                    jsc.setClassMap(classMap);
                    if (targetClass != null) {
                        setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig);
                    } else {
                        setProperty(bean, key, toBean((JSONObject) value), jsonConfig);
                    }
                }
            } else {
                PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(bean, key);
                if (pd != null && pd.getWriteMethod() == null) {
                    log.info("Property '" + key + "' of " + bean.getClass() + " has no write method. SKIPPED.");
                    continue;
                }

                if (pd != null) {
                    Class targetType = pd.getPropertyType();
                    if (!JSONUtils.isNull(value)) {
                        if (value instanceof JSONArray) {
                            if (List.class.isAssignableFrom(pd.getPropertyType())) {
                                setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig,
                                        name, classMap, pd.getPropertyType()), jsonConfig);
                            } else if (Set.class.isAssignableFrom(pd.getPropertyType())) {
                                setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig,
                                        name, classMap, pd.getPropertyType()), jsonConfig);
                            } else {
                                setProperty(bean, key, convertPropertyValueToArray(key, value, targetType,
                                        jsonConfig, classMap), jsonConfig);
                            }
                        } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type)
                                || JSONUtils.isNumber(type) || JSONUtils.isString(type)
                                || JSONFunction.class.isAssignableFrom(type)) {
                            if (pd != null) {
                                if (jsonConfig.isHandleJettisonEmptyElement() && "".equals(value)) {
                                    setProperty(bean, key, null, jsonConfig);
                                } else if (!targetType.isInstance(value)) {
                                    setProperty(bean, key, morphPropertyValue(key, value, type, targetType),
                                            jsonConfig);
                                } else {
                                    setProperty(bean, key, value, jsonConfig);
                                }
                            } else if (beanClass == null || bean instanceof Map) {
                                setProperty(bean, key, value, jsonConfig);
                            } else {
                                log.warn("Tried to assign property " + key + ":" + type.getName()
                                        + " to bean of class " + bean.getClass().getName());
                            }
                        } else {
                            if (jsonConfig.isHandleJettisonSingleElementArray()) {
                                JSONArray array = new JSONArray().element(value, jsonConfig);
                                Class newTargetClass = resolveClass(classMap, key, name, type);
                                JsonConfig jsc = jsonConfig.copy();
                                jsc.setRootClass(newTargetClass);
                                jsc.setClassMap(classMap);
                                if (targetType.isArray()) {
                                    setProperty(bean, key, JSONArray.toArray(array, jsc), jsonConfig);
                                } else if (JSONArray.class.isAssignableFrom(targetType)) {
                                    setProperty(bean, key, array, jsonConfig);
                                } else if (List.class.isAssignableFrom(targetType)
                                        || Set.class.isAssignableFrom(targetType)) {
                                    jsc.setCollectionType(targetType);
                                    setProperty(bean, key, JSONArray.toCollection(array, jsc), jsonConfig);
                                } else {
                                    setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig);
                                }
                            } else {
                                if (targetType == Object.class || targetType.isInterface()) {
                                    Class targetTypeCopy = targetType;
                                    targetType = findTargetClass(key, classMap);
                                    targetType = targetType == null ? findTargetClass(name, classMap)
                                            : targetType;
                                    targetType = targetType == null && targetTypeCopy.isInterface()
                                            ? targetTypeCopy
                                            : targetType;
                                }
                                JsonConfig jsc = jsonConfig.copy();
                                jsc.setRootClass(targetType);
                                jsc.setClassMap(classMap);
                                setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig);
                            }
                        }
                    } else {
                        if (type.isPrimitive()) {
                            // assume assigned default value
                            log.warn("Tried to assign null value to " + key + ":" + type.getName());
                            setProperty(bean, key, JSONUtils.getMorpherRegistry().morph(type, null),
                                    jsonConfig);
                        } else {
                            setProperty(bean, key, null, jsonConfig);
                        }
                    }
                } else {
                    if (!JSONUtils.isNull(value)) {
                        if (value instanceof JSONArray) {
                            setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig,
                                    name, classMap, List.class), jsonConfig);
                        } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type)
                                || JSONUtils.isNumber(type) || JSONUtils.isString(type)
                                || JSONFunction.class.isAssignableFrom(type)) {
                            if (beanClass == null || bean instanceof Map
                                    || jsonConfig.getPropertySetStrategy() != null
                                    || !jsonConfig.isIgnorePublicFields()) {
                                setProperty(bean, key, value, jsonConfig);
                            } else {
                                log.warn("Tried to assign property " + key + ":" + type.getName()
                                        + " to bean of class " + bean.getClass().getName());
                            }
                        } else {
                            if (jsonConfig.isHandleJettisonSingleElementArray()) {
                                Class newTargetClass = resolveClass(classMap, key, name, type);
                                JsonConfig jsc = jsonConfig.copy();
                                jsc.setRootClass(newTargetClass);
                                jsc.setClassMap(classMap);
                                setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig);
                            } else {
                                setProperty(bean, key, value, jsonConfig);
                            }
                        }
                    } else {
                        if (type.isPrimitive()) {
                            // assume assigned default value
                            log.warn("Tried to assign null value to " + key + ":" + type.getName());
                            setProperty(bean, key, JSONUtils.getMorpherRegistry().morph(type, null),
                                    jsonConfig);
                        } else {
                            setProperty(bean, key, null, jsonConfig);
                        }
                    }
                }
            }
        } catch (JSONException jsone) {
            throw jsone;
        } catch (Exception e) {
            throw new JSONException("Error while setting property=" + name + " type " + type, e);
        }
    }

    return bean;
}

From source file:edu.ku.brc.af.ui.forms.FormHelper.java

/**
 * Helper for setting a value into a data object using reflection
 * @param fieldNames the field name(s)//from w  w w.j a  v a 2  s.c  om
 * @param dataObj the data object that will get the new value
 * @param newData the new data object
 * @param getter the getter to use
 * @param setter the setter to use
 */
public static void setFieldValue(final String fieldNames, final Object dataObj, final Object newData,
        final DataObjectGettable getter, final DataObjectSettable setter) {
    if (StringUtils.isNotEmpty(fieldNames)) {
        if (setter.usesDotNotation()) {
            int inx = fieldNames.indexOf(".");
            if (inx > -1) {
                String[] fileNameArray = StringUtils.split(fieldNames, '.');
                Object data = dataObj;
                for (int i = 0; i < fileNameArray.length; i++) {
                    String fieldName = fileNameArray[i];
                    if (i < fileNameArray.length - 1) {
                        data = getter.getFieldValue(data, fieldName);
                        if (data == null) {
                            try {
                                //log.debug("fieldName ["+fieldName+"]");
                                PropertyDescriptor descr = PropertyUtils.getPropertyDescriptor(dataObj,
                                        fieldName.trim());
                                Class<?> classObj = descr.getPropertyType();
                                Object newObj = classObj.newInstance();
                                //log.debug("New Obj ["+newObj+"] of type ["+ classObj +"]being added to ["+dataObj+"]");
                                if (newObj != null) {

                                    Method method = newObj.getClass().getMethod("initialize",
                                            new Class<?>[] {});
                                    method.invoke(newObj, new Object[] {});
                                    setter.setFieldValue(dataObj, fieldName, newObj);
                                    data = newObj;

                                    //log.debug("Inserting New Obj ["+newObj+"] at top of new DB ObjCache");

                                }
                            } catch (NoSuchMethodException ex) {
                                ex.printStackTrace();
                                edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(FormHelper.class,
                                        ex);

                            } catch (IllegalAccessException ex) {
                                ex.printStackTrace();
                                edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(FormHelper.class,
                                        ex);

                            } catch (InvocationTargetException ex) {
                                ex.printStackTrace();
                                edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(FormHelper.class,
                                        ex);

                            } catch (InstantiationException ex) {
                                ex.printStackTrace();
                                edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(FormHelper.class,
                                        ex);
                            }
                        }
                    } else {
                        //log.info("Data Obj ["+newData+"] being added to ["+data+"]");
                        setter.setFieldValue(data, fieldName, newData);
                    }
                }
            } else {
                //log.info("setFieldValue -  newData ["+newData+"] fieldNames["+fieldNames+"] set into ["+dataObj+"]");
                setter.setFieldValue(dataObj, fieldNames, newData);
            }
        } else {
            //log.info("setFieldValue -  newData ["+newData+"] fieldNames["+fieldNames+"] set into ["+dataObj+"]");
            setter.setFieldValue(dataObj, fieldNames, newData);
        }
    }
}

From source file:com.github.venkateshamurthy.designpatterns.builders.FluentBuilders.java

/**
 * Gets class type of field parameters in a class for which setters are to
 * be found//from www. j a va 2  s . com
 * 
 * @param thisPojoClass
 * @param ctClass
 * @param ctMethodSet
 *            can be a subset of setters for fields in this class
 * @return set of classes representing field types
 * @throws NotFoundException
 */
@SuppressWarnings("serial")
private Set<Class<?>> getPropertyClassTypes(final Class<?> thisPojoClass, final CtClass ctClass,
        final Set<CtMethod> ctMethodSet) throws NotFoundException {
    Set<Class<?>> set = new LinkedHashSet<>();
    try {
        final Object bean = thisPojoClass.newInstance(); // create an
                                                         // instance
        for (Field field : thisPojoClass.getDeclaredFields()) {
            if (field.isSynthetic()) {
                LOGGER.warning(field.getName() + " is syntheticlly added, so ignoring");
                continue;
            }
            PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(bean, field.getName());

            assert pd != null;
            if (pd != null) {
                if (pd.getPropertyType() != null) {
                    set.add(pd.getPropertyType()); // irrespective of
                                                   // CtMethod just add
                    final Method mutator = pd.getWriteMethod();
                    if (mutator != null && ctMethodSet.add(ctClass.getDeclaredMethod(mutator.getName()))) {
                        LOGGER.info(mutator.getName() + " is ADDED");
                    }
                }
            } else {
                LOGGER.warning("Unable to get Proprty (Field's class) Type for:" + field.getName());
            }

        }
    } catch (InstantiationException | IllegalAccessException | InvocationTargetException
            | NoSuchMethodException e) {
        throw new NotFoundException("Exception Not Found:", e);
    }
    return set;
}

From source file:com.complexible.pinto.RDFMapper.java

@SuppressWarnings("unchecked")
private <T> ResourceBuilder write(final T theValue) {
    // before we do anything, do we have a custom codec for this?
    RDFCodec aCodec = mCodecs.get(theValue.getClass());
    if (aCodec != null) {
        final Value aResult = aCodec.writeValue(theValue);

        if (aResult instanceof ResourceBuilder) {
            return (ResourceBuilder) aResult;
        } else {//from ww w .j  a  v  a 2 s.  co  m
            return new ResourceBuilder(id(theValue)).addType(getType(theValue)).addProperty(VALUE, aResult);
        }
    }

    final Resource aId = id(theValue);

    final IRI aType = getType(theValue);

    try {
        final ModelBuilder aGraph = new ModelBuilder(mValueFactory);

        ResourceBuilder aBuilder = aGraph.instance(aType, aId);

        for (Map.Entry<String, Object> aEntry : PropertyUtils.describe(theValue).entrySet()) {
            final PropertyDescriptor aDescriptor = PropertyUtils.getPropertyDescriptor(theValue,
                    aEntry.getKey());

            if (isIgnored(aDescriptor)) {
                continue;
            }

            final IRI aProperty = getProperty(aDescriptor);

            if (aProperty == null) {
                continue;
            }

            final Object aObj = aEntry.getValue();

            if (aObj != null) {
                setValue(aGraph, aBuilder, aDescriptor, aProperty, aObj);
            }
        }

        return aBuilder;
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
        Throwables.propagateIfInstanceOf(e, RDFMappingException.class);
        throw new RDFMappingException(e);
    }
}

From source file:com.ms.commons.summer.web.util.json.JsonBeanUtils.java

/**
 * Creates a bean from a JSONObject, with the specific configuration.
 *///www . j  a va  2 s  .  c  o  m
public static Object toBean(JSONObject jsonObject, Object root, JsonConfig jsonConfig) {
    if (jsonObject == null || jsonObject.isNullObject() || root == null) {
        return root;
    }

    Class rootClass = root.getClass();
    if (rootClass.isInterface()) {
        throw new JSONException("Root bean is an interface. " + rootClass);
    }

    Map classMap = jsonConfig.getClassMap();
    if (classMap == null) {
        classMap = Collections.EMPTY_MAP;
    }

    Map props = JSONUtils.getProperties(jsonObject);
    PropertyFilter javaPropertyFilter = jsonConfig.getJavaPropertyFilter();
    for (Iterator entries = jsonObject.names().iterator(); entries.hasNext();) {
        String name = (String) entries.next();
        Class type = (Class) props.get(name);
        Object value = jsonObject.get(name);
        if (javaPropertyFilter != null && javaPropertyFilter.apply(root, name, value)) {
            continue;
        }
        String key = JSONUtils.convertToJavaIdentifier(name, jsonConfig);
        try {
            PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(root, key);
            if (pd != null && pd.getWriteMethod() == null) {
                log.warn("Property '" + key + "' has no write method. SKIPPED.");
                continue;
            }

            if (!JSONUtils.isNull(value)) {
                if (value instanceof JSONArray) {
                    if (pd == null || List.class.isAssignableFrom(pd.getPropertyType())) {
                        Class targetClass = findTargetClass(key, classMap);
                        targetClass = targetClass == null ? findTargetClass(name, classMap) : targetClass;
                        Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(targetClass, null);
                        List list = JSONArray.toList((JSONArray) value, newRoot, jsonConfig);
                        setProperty(root, key, list, jsonConfig);
                    } else {
                        Class innerType = JSONUtils.getInnerComponentType(pd.getPropertyType());
                        Class targetInnerType = findTargetClass(key, classMap);
                        if (innerType.equals(Object.class) && targetInnerType != null
                                && !targetInnerType.equals(Object.class)) {
                            innerType = targetInnerType;
                        }
                        Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(innerType, null);
                        Object array = JSONArray.toArray((JSONArray) value, newRoot, jsonConfig);
                        if (innerType.isPrimitive() || JSONUtils.isNumber(innerType)
                                || Boolean.class.isAssignableFrom(innerType) || JSONUtils.isString(innerType)) {
                            array = JSONUtils.getMorpherRegistry()
                                    .morph(Array.newInstance(innerType, 0).getClass(), array);
                        } else if (!array.getClass().equals(pd.getPropertyType())) {
                            if (!pd.getPropertyType().equals(Object.class)) {
                                Morpher morpher = JSONUtils.getMorpherRegistry()
                                        .getMorpherFor(Array.newInstance(innerType, 0).getClass());
                                if (IdentityObjectMorpher.getInstance().equals(morpher)) {
                                    ObjectArrayMorpher beanMorpher = new ObjectArrayMorpher(
                                            new BeanMorpher(innerType, JSONUtils.getMorpherRegistry()));
                                    JSONUtils.getMorpherRegistry().registerMorpher(beanMorpher);
                                }
                                array = JSONUtils.getMorpherRegistry()
                                        .morph(Array.newInstance(innerType, 0).getClass(), array);
                            }
                        }
                        setProperty(root, key, array, jsonConfig);
                    }
                } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type)
                        || JSONUtils.isNumber(type) || JSONUtils.isString(type)
                        || JSONFunction.class.isAssignableFrom(type)) {
                    if (pd != null) {
                        if (jsonConfig.isHandleJettisonEmptyElement() && "".equals(value)) {
                            setProperty(root, key, null, jsonConfig);
                        } else if (!pd.getPropertyType().isInstance(value)) {
                            Morpher morpher = JSONUtils.getMorpherRegistry()
                                    .getMorpherFor(pd.getPropertyType());
                            if (IdentityObjectMorpher.getInstance().equals(morpher)) {
                                log.warn("Can't transform property '" + key + "' from " + type.getName()
                                        + " into " + pd.getPropertyType().getName()
                                        + ". Will register a default BeanMorpher");
                                JSONUtils.getMorpherRegistry().registerMorpher(
                                        new BeanMorpher(pd.getPropertyType(), JSONUtils.getMorpherRegistry()));
                            }
                            setProperty(root, key,
                                    JSONUtils.getMorpherRegistry().morph(pd.getPropertyType(), value),
                                    jsonConfig);
                        } else {
                            setProperty(root, key, value, jsonConfig);
                        }
                    } else if (root instanceof Map) {
                        setProperty(root, key, value, jsonConfig);
                    } else {
                        log.warn("Tried to assign property " + key + ":" + type.getName() + " to bean of class "
                                + root.getClass().getName());
                    }
                } else {
                    if (pd != null) {
                        Class targetClass = pd.getPropertyType();
                        if (jsonConfig.isHandleJettisonSingleElementArray()) {
                            JSONArray array = new JSONArray().element(value, jsonConfig);
                            Class newTargetClass = findTargetClass(key, classMap);
                            newTargetClass = newTargetClass == null ? findTargetClass(name, classMap)
                                    : newTargetClass;
                            Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(newTargetClass,
                                    null);
                            if (targetClass.isArray()) {
                                setProperty(root, key, JSONArray.toArray(array, newRoot, jsonConfig),
                                        jsonConfig);
                            } else if (Collection.class.isAssignableFrom(targetClass)) {
                                setProperty(root, key, JSONArray.toList(array, newRoot, jsonConfig),
                                        jsonConfig);
                            } else if (JSONArray.class.isAssignableFrom(targetClass)) {
                                setProperty(root, key, array, jsonConfig);
                            } else {
                                setProperty(root, key, toBean((JSONObject) value, newRoot, jsonConfig),
                                        jsonConfig);
                            }
                        } else {
                            if (targetClass == Object.class) {
                                targetClass = findTargetClass(key, classMap);
                                targetClass = targetClass == null ? findTargetClass(name, classMap)
                                        : targetClass;
                            }
                            Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(targetClass,
                                    null);
                            setProperty(root, key, toBean((JSONObject) value, newRoot, jsonConfig), jsonConfig);
                        }
                    } else if (root instanceof Map) {
                        Class targetClass = findTargetClass(key, classMap);
                        targetClass = targetClass == null ? findTargetClass(name, classMap) : targetClass;
                        Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(targetClass, null);
                        setProperty(root, key, toBean((JSONObject) value, newRoot, jsonConfig), jsonConfig);
                    } else {
                        log.warn("Tried to assign property " + key + ":" + type.getName() + " to bean of class "
                                + rootClass.getName());
                    }
                }
            } else {
                if (type.isPrimitive()) {
                    // assume assigned default value
                    log.warn("Tried to assign null value to " + key + ":" + type.getName());
                    setProperty(root, key, JSONUtils.getMorpherRegistry().morph(type, null), jsonConfig);
                } else {
                    setProperty(root, key, null, jsonConfig);
                }
            }
        } catch (JSONException jsone) {
            throw jsone;
        } catch (Exception e) {
            throw new JSONException("Error while setting property=" + name + " type " + type, e);
        }
    }

    return root;
}