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.handpay.ibenefit.framework.util.WebUtils.java

public static Map<String, Object> getSearchParameterMap(HttpServletRequest request, Class DomainObjecClass) {
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Map<String, Object> parameterMap = new HashMap();
    Map requestMap = getParametersStartingWith(request, DEFAULT_SEARCH_PREFIX);
    boolean matchAll = true;
    PropertyDescriptor[] beandesc = PropertyUtils.getPropertyDescriptors(DomainObjecClass);
    for (int i = 0; i < beandesc.length; i++) {
        PropertyDescriptor descriptor = beandesc[i];
        String propertyName = descriptor.getName();
        Class propertyClass = descriptor.getPropertyType();
        if ("class".equals(propertyName)) {
            continue;
        }//from  ww  w .jav  a 2s . c om
        if (propertyClass == Date.class) {
            String after = (String) requestMap.get(propertyName + "After");
            if (after != null && after.trim().length() > 0) {
                try {
                    Date afterDate = dateFormat.parse(after);
                    parameterMap.put(propertyName + "After", afterDate);
                } catch (Exception e) {
                }
            }
            String befor = (String) requestMap.get(propertyName + "Befor");
            if (befor != null && befor.trim().length() > 0) {
                try {
                    Date beforDate = dateFormat.parse(befor);
                    // to the end of the day
                    long dayTail = beforDate.getTime() + 24 * 3600 * 1000 - 1;
                    parameterMap.put(propertyName + "Befor", new Date(dayTail));
                } catch (Exception e) {
                }
            }
        } else if (propertyClass == String.class) {
            String value = (String) requestMap.get(propertyName);
            if (value != null && value.trim().length() > 0) {
                if (matchAll) {
                    parameterMap.put(propertyName, "%" + value + "%");
                } else {
                    parameterMap.put(propertyName, value + "%");
                }
            }
        } else if (propertyClass == Long.class) {
            String value = (String) requestMap.get(propertyName);
            if (value != null && value.trim().length() > 0) {
                parameterMap.put(propertyName, Long.parseLong(value));
            }
        } else if (propertyClass == Integer.class) {
            String value = (String) requestMap.get(propertyName);
            if (value != null && value.trim().length() > 0) {
                parameterMap.put(propertyName, Integer.parseInt(value));
            }
        } else if (propertyClass == Double.class) {
            String value = (String) requestMap.get(propertyName);
            if (value != null && value.trim().length() > 0) {
                parameterMap.put(propertyName, Double.parseDouble(value));
            }
        } else if (propertyClass == Float.class) {
            String value = (String) requestMap.get(propertyName);
            if (value != null && value.trim().length() > 0) {
                parameterMap.put(propertyName, Float.parseFloat(value));
            }
        } else if (propertyClass == Boolean.class) {
            String value = (String) requestMap.get(propertyName);
            if (value != null && value.trim().length() > 0) {
                parameterMap.put(propertyName, Boolean.parseBoolean(value));
            }
        }
    }
    return parameterMap;
}

From source file:org.springjutsu.validation.util.PathUtils.java

/**
 * Determine the class of each step in the selected path on the target class. 
 * @param clazz Class to check /* w  w w  .j  a  v  a2  s.c  om*/
 * @param path Path to check
 * @param unwrapCollectionTypes if true returns the parameterized collection type
 * @return array of classes for each step of path.
 */
public static Class<?>[] getClassesForPathTokens(Class<?> clazz, String path, boolean unwrapCollectionTypes) {
    if (path == null || path.trim().isEmpty()) {
        return null;
    }
    Class<?> intermediateClass = clazz;
    String[] pathTokens = path.split("\\.");
    Class<?>[] pathClasses = new Class<?>[pathTokens.length];

    for (int i = 0; i < pathTokens.length; i++) {
        String token = pathTokens[i];
        token = token.replaceAll("\\[[^\\]]+\\]$", "");
        PropertyDescriptor descriptor = BeanUtils.getPropertyDescriptor(intermediateClass, token);
        if (descriptor == null) {
            return null;
        } else if (List.class.isAssignableFrom(descriptor.getPropertyType())) {
            intermediateClass = TypeDescriptor.nested(ReflectionUtils.findField(intermediateClass, token), 1)
                    .getObjectType();
        } else if (descriptor.getPropertyType().isArray()) {
            intermediateClass = descriptor.getPropertyType().getComponentType();
        } else {
            intermediateClass = descriptor.getPropertyType();
        }
        if (unwrapCollectionTypes) {
            pathClasses[i] = intermediateClass;
        } else {
            pathClasses[i] = descriptor.getPropertyType();
        }
    }
    return pathClasses;
}

From source file:edu.duke.cabig.c3pr.webservice.integration.BeanUtils.java

/**
 * This methods performs deep comparison of two objects of the same class.
 * Comparison is performed only on properties exposed via the standard
 * JavaBean mechanism. Properties of primitive types, wrappers,
 * {@link String}, {@link CharSequence}, {@link Date}, {@link Enum} are
 * compared directly using {@link Object#equals(Object)}; other complex
 * properties are compared recursively. Elements of {@link Collection}
 * properties are iterated and compared.
 * //from   w  w  w.  j  a va 2s .  c o m
 * @param <T>
 * @param obj1
 * @param obj2
 * @return
 * @throws NullPointerException
 *             if any of the parameters is null.
 */
public static <T> boolean deepCompare(T obj1, T obj2) {
    if (obj1 == obj2) {
        return true;
    }
    // if it's a "simple" object, do direct comparison.
    for (Class<?> cls : DIRECTLY_COMPARABLE_TYPES) {
        if (cls.isAssignableFrom(obj1.getClass())) {
            if (!obj1.equals(obj2)) {
                log.info("Values don't match: " + obj1 + " and " + obj2);
                System.out.println();
                System.out.println("Values don't match: " + obj1 + " and " + obj2);
                return false;
            } else {
                return true;
            }
        }
    }
    try {
        PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(obj1.getClass());
        for (PropertyDescriptor pd : descriptors) {
            // ignore properties which cannot be read.
            if (pd.getReadMethod() != null) {
                Class<?> type = pd.getPropertyType();
                // this check will skip Object.getClass().
                if (SKIP_TYPES.contains(type)) {
                    continue;
                }
                String name = pd.getName();
                Object v1 = PropertyUtils.getSimpleProperty(obj1, name);
                Object v2 = PropertyUtils.getSimpleProperty(obj2, name);
                if (v1 == v2 || (v1 == null && v2 == null)) {
                    continue;
                }
                if ((v1 == null && v2 != null) || (v1 != null && v2 == null)) {
                    log.info("Values don't match: " + v1 + " and " + v2);
                    System.out.println();
                    System.out.println("Values don't match: " + v1 + " and " + v2);
                    return false;
                }
                // Collections need special handling.
                if (Collection.class.isAssignableFrom(type)) {
                    List l1 = new ArrayList((Collection) v1);
                    List l2 = new ArrayList((Collection) v2);
                    if (l1.size() != l2.size()) {
                        log.info("Collection sizes don't match:" + l1 + l2);
                        System.out.println();
                        System.out.println("Collection sizes don't match:" + l1 + ", " + l2);
                        return false;
                    }
                    for (int i = 0; i < l1.size(); i++) {
                        Object el1 = l1.get(i);
                        boolean equals = false;
                        for (int j = 0; j < l2.size(); j++) {
                            Object el2 = l2.get(j);
                            if (deepCompare(el1, el2)) {
                                if (i == j) {
                                    System.out.println("Values matched at the same index in collections");
                                } else {
                                    System.out.println("Values matched at the different index in collections");
                                }
                                equals = true;
                                break;
                            }
                        }
                        if (!equals) {
                            return false;
                        }
                    }

                } else if (!deepCompare(v1, v2)) {
                    return false;
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(ExceptionUtils.getFullStackTrace(e));
    }
    return true;
}

From source file:no.abmu.test.utilh3.DomainTestHelper.java

public static Object populateBean(Object obj)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(obj);

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

        if (propertyDescriptor.getName().equals("id")) {
            continue;
        } else if (propertyDescriptor.getName().equals("valueAsString")) {
            continue;
        } else if (P_TYPES.contains(propertyDescriptor.getPropertyType())
                && propertyDescriptor.getWriteMethod() != null) {
            Object obje;//w w w  . java  2  s  .  c o m
            //                obje=ConvertUtils.convert(String.valueOf(System.currentTimeMillis()
            //                +(long)(Math.random()*100d)),propertyDescriptor.getPropertyType());
            obje = ConvertUtils.convert(
                    String.valueOf((int) (System.currentTimeMillis() + (int) (Math.random() * 100d))),
                    propertyDescriptor.getPropertyType());
            PropertyUtils.setProperty(obj, propertyDescriptor.getName(), obje);
        }
    }
    return obj;
}

From source file:org.jdal.text.FormatUtils.java

/**
 * Get a formatter for class and property name
 * @param clazz the class/*  ww w.  j  a  v  a  2  s.co m*/
 * @param propertyName the property name
 * @return the formatter or null if none
 */
public static Formatter<?> getFormatter(Class<?> clazz, String propertyName) {
    PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(clazz, propertyName);
    if (pd != null) {
        NumberFormat format = getAnnotation(pd, NumberFormat.class);
        if (format != null) {
            return (Formatter<?>) numberFormatFactory.getPrinter(format, pd.getPropertyType());
        }

        PeriodFormat periodFormat = getAnnotation(pd, PeriodFormat.class);
        if (periodFormat != null)
            return new PeriodFormatter();
    }

    return null;
}

From source file:org.openlegacy.utils.ProxyUtil.java

@SuppressWarnings("unchecked")
public static <T> T getTargetObject(Object proxy, boolean deep) {

    if (proxy == null) {
        return null;
    }//from   w  ww  . j  ava  2s.  c om

    while (proxy instanceof Advised) {
        try {
            if (deep) {
                // invoke all getters
                PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(proxy);
                for (PropertyDescriptor propertyDescriptor : properties) {
                    try {
                        Class<?> propertyType = propertyDescriptor.getPropertyType();
                        if (propertyType != null && !TypesUtil.isPrimitive(propertyType)) {
                            Method readMethod = propertyDescriptor.getReadMethod();
                            if (readMethod != null) {
                                readMethod.invoke(proxy);
                            }
                        }
                    } catch (Exception e) {
                        throw (new RuntimeException(e));
                    }
                }
            }
            proxy = ((Advised) proxy).getTargetSource().getTarget();
        } catch (Exception e) {
            throw (new IllegalStateException(e));
        }
    }

    if (deep) {
        DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(proxy);
        PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(proxy);
        for (PropertyDescriptor propertyDescriptor : properties) {
            try {
                Object value = propertyDescriptor.getReadMethod().invoke(proxy);
                Object afterValue = getTargetObject(value, false);
                if (value != afterValue) {
                    fieldAccessor.setPropertyValue(propertyDescriptor.getName(), afterValue);
                }
            } catch (Exception e) {
                throw (new RuntimeException(e));
            }
        }
    }
    return (T) proxy;
}

From source file:Main.java

private static void setterValue(PropertyDescriptor property, Object mapValue, Object object)
        throws InvocationTargetException, IllegalAccessException, ParseException {
    Method setter = property.getWriteMethod();
    if (mapValue == null) {
        setter.invoke(object, mapValue);
        return;//from  w w  w .  j a  v a2 s.c  o  m
    }

    Class propertyType = property.getPropertyType();
    String type = propertyType.getName();
    String value = mapValue.toString();

    if (type.equals("java.lang.String")) {
        setter.invoke(object, value);
    } else if (type.equals("java.lang.Integer")) {
        setter.invoke(object, Integer.parseInt(value));
    } else if (type.equals("java.lang.Long")) {
        setter.invoke(object, Long.parseLong(value));
    } else if (type.equals("java.math.BigDecimal")) {
        setter.invoke(object, BigDecimal.valueOf(Double.parseDouble(value)));
    } else if (type.equals("java.math.BigInteger")) {
        setter.invoke(object, BigInteger.valueOf(Long.parseLong(value)));
    } else if (type.equals("java.util.Date")) {
        setter.invoke(object, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(value));
    } else if (type.equals("java.lang.Boolean")) {
        setter.invoke(object, Boolean.valueOf(value));
    } else if (type.equals("java.lang.Float")) {
        setter.invoke(object, Float.parseFloat(value));
    } else if (type.equals("java.lang.Double")) {
        setter.invoke(object, Double.parseDouble(value));
    } else if (type.equals("java.lang.byte[]")) {
        setter.invoke(object, value.getBytes());
    } else {
        setter.invoke(object, value);
    }
}

From source file:no.abmu.test.domainmodels.DomainTestHelper.java

public static Object populateBean(Object obj)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(obj);

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

        if (propertyDescriptor.getName().equals("id")) {
            continue;
        } else if (propertyDescriptor.getName().equals("valueAsString")) {
            continue;
        } else if (P_TYPES.contains(propertyDescriptor.getPropertyType())
                && propertyDescriptor.getWriteMethod() != null) {

            Object obje;/*w  ww . j  a  v a 2s  .  c  o m*/
            //                obje=ConvertUtils.convert(String.valueOf(System.currentTimeMillis()
            //                +(long)(Math.random()*100d)),propertyDescriptor.getPropertyType());
            obje = ConvertUtils.convert(
                    String.valueOf((int) (System.currentTimeMillis() + (int) (Math.random() * 100d))),
                    propertyDescriptor.getPropertyType());
            PropertyUtils.setProperty(obj, propertyDescriptor.getName(), obje);
        }
    }
    return obj;
}

From source file:de.micromata.genome.jpa.PropertyEntityCopier.java

static EntityCopyStatus copyPropertyDefault(IEmgr<?> emgr, PropertyDescriptor pd, Class<?> iface, Object target,
        Object source) {/*  w w  w. j  av  a 2 s .  co  m*/
    List<Class<? extends EntityCopier>> copierClazzes = emgr.getEmgrFactory()
            .getRegisteredCopierForBean(pd.getPropertyType());
    if (copierClazzes.isEmpty() == true) {
        return copyPropertyRaw(pd, target, source);
    }
    EntityCopyStatus ret = EntityCopyStatus.NONE;
    for (Class<? extends EntityCopier> copierClazz : copierClazzes) {
        EntityCopier copier = PrivateBeanUtils.createInstance(copierClazz);
        ret = ret.combine(copier.copyTo(emgr, iface, target, source));
    }
    return ret;
}

From source file:org.apache.syncope.core.misc.jexl.JexlUtils.java

public static JexlContext addFieldsToContext(final Object object, final JexlContext jexlContext) {
    JexlContext context = jexlContext == null ? new MapContext() : jexlContext;

    try {// w  ww . jav  a2s  .  c  o m
        for (PropertyDescriptor desc : Introspector.getBeanInfo(object.getClass()).getPropertyDescriptors()) {
            Class<?> type = desc.getPropertyType();
            String fieldName = desc.getName();

            if ((!fieldName.startsWith("pc")) && (!ArrayUtils.contains(IGNORE_FIELDS, fieldName))
                    && (!Iterable.class.isAssignableFrom(type)) && (!type.isArray())) {

                try {
                    Object fieldValue;
                    if (desc.getReadMethod() == null) {
                        final Field field = object.getClass().getDeclaredField(fieldName);
                        field.setAccessible(true);
                        fieldValue = field.get(object);
                    } else {
                        fieldValue = desc.getReadMethod().invoke(object);
                    }

                    context.set(fieldName,
                            fieldValue == null ? StringUtils.EMPTY
                                    : (type.equals(Date.class) ? DataFormat.format((Date) fieldValue, false)
                                            : fieldValue));

                    LOG.debug("Add field {} with value {}", fieldName, fieldValue);
                } catch (Exception iae) {
                    LOG.error("Reading '{}' value error", fieldName, iae);
                }
            }
        }
    } catch (IntrospectionException ie) {
        LOG.error("Reading class attributes error", ie);
    }

    if (object instanceof Any) {
        Any<?, ?, ?> any = (Any<?, ?, ?>) object;
        if (any.getRealm() != null) {
            context.set("realm", any.getRealm().getName());
        }
    }

    return context;
}