Example usage for java.beans PropertyDescriptor getPropertyType

List of usage examples for java.beans PropertyDescriptor getPropertyType

Introduction

In this page you can find the example usage for java.beans PropertyDescriptor getPropertyType.

Prototype

public synchronized Class<?> getPropertyType() 

Source Link

Document

Returns the Java type info for the property.

Usage

From source file:com.subakva.formicid.options.ParameterHandler.java

public void handleOption(Task task, String optionName, Object value) {
    HashMap<String, PropertyDescriptor> properties = getWritableProperties(task.getClass());
    PropertyDescriptor descriptor = properties.get(optionName.toLowerCase());
    if (descriptor == null) {
        throw new RuntimeException("Unknown property for " + task.getTaskType() + " task: " + optionName);
    }/*from  w  w  w  . ja  v a  2s. com*/
    Class<?> type = descriptor.getPropertyType();
    Converter converter = container.getConverter(type);
    Object converted = converter.convert(type, value);
    try {
        task.log("converting property: " + descriptor.getName(), Project.MSG_DEBUG);
        task.log("converter: " + converter, Project.MSG_DEBUG);
        task.log("converted: " + converted, Project.MSG_DEBUG);

        descriptor.getWriteMethod().invoke(task, new Object[] { converted });
    } catch (IllegalArgumentException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.ocs.dynamo.importer.impl.BaseImporter.java

@SuppressWarnings("unchecked")
private Object getFieldValue(PropertyDescriptor d, U unit, XlsField field) {
    Object obj = null;/*ww  w .  jav  a2  s . com*/
    if (String.class.equals(d.getPropertyType())) {
        String value = getStringValueWithDefault(unit, field);
        if (value != null) {
            value = value.trim();
        }
        obj = StringUtils.isEmpty(value) ? null : value;
    } else if (d.getPropertyType().isEnum()) {
        String value = getStringValueWithDefault(unit, field);
        if (value != null) {
            value = value.trim();
            try {
                obj = Enum.valueOf(d.getPropertyType().asSubclass(Enum.class), value.toUpperCase());
            } catch (IllegalArgumentException ex) {
                throw new OCSImportException(
                        "Value " + value + " cannot be translated to a valid enumeration value", ex);
            }
        }

    } else if (Number.class.isAssignableFrom(d.getPropertyType())) {
        // numeric field

        Double value = getNumericValueWithDefault(unit, field);
        if (value != null) {

            // if the field represents a percentage but it is
            // received as a
            // fraction, we multiply it by 100
            if (field.percentage()) {
                if (isPercentageCorrectionSupported()) {
                    value = PERCENTAGE_FACTOR * value;
                }
            }

            // illegal negative value
            if (field.cannotBeNegative() && value < 0.0) {
                throw new OCSImportException(
                        "Negative value " + value + " found for field '" + d.getName() + "'");
            }

            if (Integer.class.equals(d.getPropertyType())) {
                obj = new Integer(value.intValue());
            } else if (BigDecimal.class.equals(d.getPropertyType())) {
                obj = BigDecimal.valueOf(value.doubleValue());
            } else {
                // by default, use a double
                obj = value;
            }
        }
    } else if (Boolean.class.isAssignableFrom(d.getPropertyType())) {
        return getBooleanValueWithDefault(unit, field);
    }
    return obj;
}

From source file:com.alibaba.stonelab.toolkit.sqltester.BeanInitBuilder.java

/**
 * <pre>//from w w w .  j  av  a 2s .co  m
 * build logic 
 * TODO:
 * 1.?,
 * 2.JDK Enum?
 * 
 * </pre>
 * 
 * @param count
 * @return
 */
private List<T> doBuild(int count) {
    List<T> ret = new ArrayList<T>();
    for (int i = 0; i < count; i++) {
        T t = null;
        try {
            t = clz.newInstance();
        } catch (Exception e) {
            throw new BuildException("new instance error.", e);
        }
        PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(clz);
        for (PropertyDescriptor des : descriptors) {
            try {
                // ?
                if (Number.class.isAssignableFrom(des.getPropertyType())) {
                    PropertyUtils.setProperty(t, des.getName(),
                            DEFAULT_VALUE_NUMBER.get(des.getPropertyType()));
                }
                // String?
                if (String.class.isAssignableFrom(des.getPropertyType())) {
                    if (count == 1) {
                        PropertyUtils.setProperty(t, des.getName(), des.getName());
                    } else {
                        PropertyUtils.setProperty(t, des.getName(), des.getName() + i);
                    }
                }
                // date?
                if (Date.class.isAssignableFrom(des.getPropertyType())) {
                    PropertyUtils.setProperty(t, des.getName(), DEFAULT_VALUE_DATE);
                }
                // JDK?
                if (Enum.class.isAssignableFrom(des.getPropertyType())) {
                    if (des.getPropertyType().getEnumConstants().length >= 1) {
                        PropertyUtils.setProperty(t, des.getName(),
                                des.getPropertyType().getEnumConstants()[0]);
                    }
                }
            } catch (Exception e) {
                throw new BuildException("build error.", e);
            }
        }
        // 
        ret.add(t);
    }
    return ret;
}

From source file:org.kuali.rice.kns.util.BeanPropertyComparator.java

/**
 * Compare two JavaBeans by the properties given to the constructor. If no propertues
 * //from  ww  w .  j  a  va2 s  . c o m
 * @param o1 Object The first bean to get data from to compare against
 * @param o2 Object The second bean to get data from to compare
 * @return int negative or positive based on order
 */
public int compare(Object o1, Object o2) {
    int compared = 0;

    try {
        for (Iterator i = propertyNames.iterator(); (compared == 0) && i.hasNext();) {
            String currentProperty = i.next().toString();

            // choose appropriate comparator
            Comparator currentComparator = null;
            try {
                PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(o1,
                        currentProperty);
                Class propertyClass = propertyDescriptor.getPropertyType();
                if (propertyClass.equals(String.class)) {
                    currentComparator = this.stringComparator;
                } else if (TypeUtils.isBooleanClass(propertyClass)) {
                    currentComparator = this.booleanComparator;
                } else {
                    currentComparator = this.genericComparator;
                }
            } catch (NullPointerException e) {
                throw new BeanComparisonException(
                        "unable to find property '" + o1.getClass().getName() + "." + currentProperty + "'", e);
            }

            // compare the values
            Object value1 = PropertyUtils.getProperty(o1, currentProperty);
            Object value2 = PropertyUtils.getProperty(o2, currentProperty);
            /* Begin Null Support Fix */
            if (value1 == null && value2 == null)
                return 0;
            else if (value1 == null)
                return -1;
            else if (value2 == null)
                return 1;
            /* End Null Support Fix*/
            compared = currentComparator.compare(value1, value2);
        }
    } catch (IllegalAccessException e) {
        throw new BeanComparisonException("unable to compare property values", e);
    } catch (NoSuchMethodException e) {
        throw new BeanComparisonException("unable to compare property values", e);
    } catch (InvocationTargetException e) {
        throw new BeanComparisonException("unable to compare property values", e);
    }

    return compared;
}

From source file:com.fmguler.ven.QueryMapper.java

protected void mapRecursively(ResultSet rs, Set columns, String tableName, Class objectClass, List parentList) {
    try {//from   w  w w .  ja v a 2s  .c o  m
        if (!columns.contains(tableName + "_id"))
            return; //this object does not exist in the columns
        Object id = rs.getObject(tableName + "_id");
        if (id == null)
            return; //this object exists in the columns but null, probably because of left join

        //create bean wrapper for the object class
        BeanWrapperImpl wr = new BeanWrapperImpl(objectClass); //already caches class introspection (CachedIntrospectionResults.forClass())
        wr.setPropertyValue("id", id); //set the id property
        Object object = wr.getWrappedInstance();
        boolean map = true;

        //check if this object exists in the parent list (since SQL joins are cartesian products, do not create new object if this row is just the same as previous)
        for (Iterator it = parentList.iterator(); it.hasNext();) {
            Object objectInList = (Object) it.next();
            if (objectIdEquals(objectInList, id)) {
                wr.setWrappedInstance(objectInList); //already exists in the list, use that instance
                map = false; // and do not map again
                break;
            }
        }
        if (map)
            parentList.add(object); //could not find in the parent list, add the new object

        PropertyDescriptor[] pdArr = wr.getPropertyDescriptors();
        for (int i = 0; i < pdArr.length; i++) {
            PropertyDescriptor pd = pdArr[i];
            Class fieldClass = pd.getPropertyType(); //field class
            String fieldName = Convert.toDB(pd.getName()); //field name
            Object fieldValue = wr.getPropertyValue(pd.getName());
            String columnName = tableName + "_" + fieldName;

            //database class (primitive property)
            if (map && dbClasses.contains(fieldClass)) {
                if (columns.contains(columnName)) {
                    if (debug)
                        System.out.println(">>field is found: " + columnName);
                    wr.setPropertyValue(pd.getName(), rs.getObject(columnName));
                } else {
                    if (debug)
                        System.out.println("--field not found: " + columnName);
                }
                continue; //if this is a primitive property, it cannot be an object or list
            }

            //many to one association (object property)
            if (fieldClass.getPackage() != null && domainPackages.contains(fieldClass.getPackage().getName())) {
                if (columns.contains(columnName + "_id")) {
                    if (debug)
                        System.out.println(">>object is found " + columnName);
                    List list = new ArrayList(1); //we know there will be single result
                    if (!map)
                        list.add(fieldValue); //otherwise we cannot catch one to many assc. (lists) of many to one (object) assc.
                    mapRecursively(rs, columns, columnName, fieldClass, list);
                    if (list.size() > 0)
                        wr.setPropertyValue(pd.getName(), list.get(0));
                } else {
                    if (debug)
                        System.out.println("--object not found: " + columnName);
                }
            }

            //one to many association (list property)
            if (fieldValue instanceof List) { //Note: here recurring row's list property is mapped and add to parent's list
                if (columns.contains(columnName + "_id")) {
                    Class elementClass = VenList.findElementClass((List) fieldValue);
                    if (debug)
                        System.out.println(">>list is found " + columnName);
                    mapRecursively(rs, columns, columnName, elementClass, (List) fieldValue);
                } else {
                    if (debug)
                        System.out.println("--list not found: " + columnName);
                }
            }
        }
    } catch (Exception ex) {
        System.out.println("Ven - error while mapping row, table: " + tableName + " object class: "
                + objectClass + " error: " + ex.getMessage());
        if (debug) {
            ex.printStackTrace();
        }
    }
}

From source file:org.ambraproject.testutils.DummyHibernateDataStore.java

@Override
@SuppressWarnings("unchecked")
public <T> T get(final Class<T> clazz, final Serializable id) {
    return (T) hibernateTemplate.execute(new HibernateCallback() {
        @Override/*  ww  w  .  j  a  v a 2  s .c  o  m*/
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            T object = (T) session.get(clazz, id);
            if (object == null) {
                return null;
            } else {
                //Load up all the object's collection attributes in a session to make sure they aren't lazy-loaded
                BeanWrapper wrapper = new BeanWrapperImpl(object);
                for (PropertyDescriptor propertyDescriptor : wrapper.getPropertyDescriptors()) {
                    if (Collection.class.isAssignableFrom(propertyDescriptor.getPropertyType())) {
                        Iterator iterator = ((Collection) wrapper
                                .getPropertyValue(propertyDescriptor.getName())).iterator();
                        while (iterator.hasNext()) {
                            iterator.next();
                        }
                    }
                }
            }
            return object;
        }
    });
}

From source file:org.codehaus.groovy.grails.commons.GrailsClassUtils.java

/**
 * Retrieves all the properties of the given class which are assignable to the given type
 *
 * @param clazz             The class to retrieve the properties from
 * @param propertySuperType The type of the properties you wish to retrieve
 * @return An array of PropertyDescriptor instances
 *///w ww .j  ava2  s  .  co  m
public static PropertyDescriptor[] getPropertiesAssignableToType(Class<?> clazz, Class<?> propertySuperType) {
    if (clazz == null || propertySuperType == null)
        return new PropertyDescriptor[0];

    Set<PropertyDescriptor> properties = new HashSet<PropertyDescriptor>();
    try {
        for (PropertyDescriptor descriptor : BeanUtils.getPropertyDescriptors(clazz)) {
            if (propertySuperType.isAssignableFrom(descriptor.getPropertyType())) {
                properties.add(descriptor);
            }
        }
    } catch (Exception e) {
        return new PropertyDescriptor[0];
    }
    return properties.toArray(new PropertyDescriptor[properties.size()]);
}

From source file:org.codehaus.groovy.grails.commons.GrailsClassUtils.java

/**
 * Returns the type of the given property contained within the specified class
 *
 * @param clazz The class which contains the property
 * @param propertyName The name of the property
 *
 * @return The property type or null if none exists
 */// ww w .j  av a  2 s . com
public static Class<?> getPropertyType(Class<?> clazz, String propertyName) {
    if (clazz == null || StringUtils.isBlank(propertyName)) {
        return null;
    }

    try {
        PropertyDescriptor desc = BeanUtils.getPropertyDescriptor(clazz, propertyName);
        if (desc != null) {
            return desc.getPropertyType();
        }
        return null;
    } catch (Exception e) {
        // if there are any errors in instantiating just return null for the moment
        return null;
    }
}

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;/*  ww w .  j  a  va2 s. com*/
    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.mule.module.netsuite.api.model.expression.filter.FilterExpressionBuilder.java

private void convertAndSet(Object argument, String propertyName, Object attribute) throws Exception {
    PropertyDescriptor descriptor = newDescriptor(propertyName, attribute);

    try {//  w  ww . ja v  a  2s.  co  m
        descriptor.getWriteMethod().invoke(attribute,
                convert(argument, descriptor.getPropertyType(), attribute.getClass()));
    } catch (Exception e) {
        throw new IllegalArgumentException(String.format("Can not set property %s of class %s with value %s",
                propertyName, attribute.getClass().getSimpleName(), argument), e);
    }
}