Example usage for java.beans PropertyDescriptor getReadMethod

List of usage examples for java.beans PropertyDescriptor getReadMethod

Introduction

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

Prototype

public synchronized Method getReadMethod() 

Source Link

Document

Gets the method that should be used to read the property value.

Usage

From source file:net.solarnetwork.node.util.ClassUtils.java

/**
 * Get a Map of non-null <em>simple</em> bean properties for an object.
 * /*from   w  ww  . j  a  v  a  2s. c o m*/
 * @param o
 *        the object to inspect
 * @param ignore
 *        a set of property names to ignore (optional)
 * @return Map (never <em>null</em>)
 * @since 1.1
 */
public static Map<String, Object> getSimpleBeanProperties(Object o, Set<String> ignore) {
    if (ignore == null) {
        ignore = DEFAULT_BEAN_PROP_NAME_IGNORE;
    }
    Map<String, Object> result = new LinkedHashMap<String, Object>();
    BeanWrapper bean = new BeanWrapperImpl(o);
    PropertyDescriptor[] props = bean.getPropertyDescriptors();
    for (PropertyDescriptor prop : props) {
        if (prop.getReadMethod() == null) {
            continue;
        }
        String propName = prop.getName();
        if (ignore != null && ignore.contains(propName)) {
            continue;
        }
        Class<?> propType = bean.getPropertyType(propName);
        if (!(propType.isPrimitive() || propType.isEnum() || String.class.isAssignableFrom(propType)
                || Number.class.isAssignableFrom(propType) || Character.class.isAssignableFrom(propType)
                || Byte.class.isAssignableFrom(propType) || Date.class.isAssignableFrom(propType))) {
            continue;
        }
        Object propValue = bean.getPropertyValue(propName);
        if (propValue == null) {
            continue;
        }
        if (propType.isEnum()) {
            propValue = propValue.toString();
        } else if (Date.class.isAssignableFrom(propType)) {
            propValue = ((Date) propValue).getTime();
        }
        result.put(propName, propValue);
    }
    return result;
}

From source file:org.archive.crawler.restlet.XmlMarshaller.java

/**
 * generate nested XML structure for a bean {@code obj}. enclosing element
 * will not be generated if {@code key} is empty. each readable JavaBeans property
 * is mapped to an nested element named after its name. Those properties
 * annotated with {@link XmlTransient} are ignored.
 * @param xmlWriter XmlWriter//from   w  w w .  jav a  2 s  .  c o m
 * @param key name of enclosing element
 * @param obj bean
 * @throws SAXException
 */
protected static void marshalBean(XmlWriter xmlWriter, String key, Object obj) throws SAXException {
    if (!StringUtils.isEmpty(key))
        xmlWriter.startElement(key);
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass(), Object.class);
        PropertyDescriptor[] props = beanInfo.getPropertyDescriptors();
        XmlType xmlType = obj.getClass().getAnnotation(XmlType.class);
        if (xmlType != null) {
            String[] propOrder = xmlType.propOrder();
            if (propOrder != null) {
                // TODO: should cache this sorted version?
                orderProperties(props, propOrder);
            }
        }
        for (PropertyDescriptor prop : props) {
            Method m = prop.getReadMethod();
            if (m == null || m.getAnnotation(XmlTransient.class) != null)
                continue;
            try {
                Object propValue = m.invoke(obj);
                if (propValue != null && !"".equals(propValue)) {
                    marshal(xmlWriter, prop.getName(), propValue);
                }
            } catch (Exception ex) {
                // generate empty element, for now. generate comment?
                xmlWriter.emptyElement(prop.getName());
            }
        }
    } catch (IntrospectionException ex) {
        // ignored, for now.
    }
    if (!StringUtils.isEmpty(key))
        xmlWriter.endElement(key);
}

From source file:gov.nih.nci.cabig.ctms.web.WebTools.java

public static SortedMap<String, Object> requestPropertiesToMap(HttpServletRequest request) {
    BeanWrapper wrapped = new BeanWrapperImpl(request);
    SortedMap<String, Object> map = new TreeMap<String, Object>();
    for (PropertyDescriptor descriptor : wrapped.getPropertyDescriptors()) {
        String name = descriptor.getName();
        if (!EXCLUDED_REQUEST_PROPERTIES.contains(name) && descriptor.getReadMethod() != null) {
            Object propertyValue;
            try {
                propertyValue = wrapped.getPropertyValue(name);
            } catch (InvalidPropertyException e) {
                log.debug("Exception reading request property " + name, e);
                propertyValue = e.getMostSpecificCause();
            }//from   w  ww  .ja v  a 2  s.  co m
            map.put(name, propertyValue);
        }
    }
    return map;
}

From source file:com.cloudera.csd.validation.references.components.ReflectionHelper.java

/**
 * The value of the property is returned for the target object.
 *
 * @param targetObject the target object.
 * @param propertyName the property name.
 * @param clazz the class of the value./*www .ja va 2s .  c  o  m*/
 * @param <T> the type of the value.
 * @return the value of the property
 */
@Nullable
public static <T> T propertyValueByName(Object targetObject, String propertyName, Class<T> clazz) {
    try {
        PropertyDescriptor desc = PropertyUtils.getPropertyDescriptor(targetObject, propertyName);
        Object result = invokeMethod(desc.getReadMethod(), targetObject);
        return (T) result;
    } catch (IllegalAccessException e) {
        throw new IllegalStateException("Could not invoke " + propertyName, e);
    } catch (InvocationTargetException e) {
        throw new IllegalStateException("Could not invoke " + propertyName, e);
    } catch (NoSuchMethodException e) {
        throw new IllegalStateException("Could not invoke " + propertyName, e);
    }
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.common.vbb.impl.util.VisualVariableHelper.java

private static VisualVariable getVVAnnotation(PropertyDescriptor vvCandidate) {
    VisualVariable vvAnnotation = null;/*ww w.j a  v  a2 s . c  o  m*/
    if (vvCandidate.getReadMethod() != null) {
        vvAnnotation = AnnotationUtils.findAnnotation(vvCandidate.getReadMethod(), VisualVariable.class);
    }
    if (vvAnnotation == null && vvCandidate.getWriteMethod() != null) {
        vvAnnotation = AnnotationUtils.findAnnotation(vvCandidate.getWriteMethod(), VisualVariable.class);
    }
    return vvAnnotation;
}

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.
 * /*ww  w . j  av a  2 s  .co  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:net.solarnetwork.util.ClassUtils.java

/**
 * Get a Map of non-null bean properties for an object.
 * //from   w ww  . j a  v  a2 s. c  o  m
 * @param o the object to inspect
 * @param ignore a set of property names to ignore (optional)
 * @return Map (never null)
 */
public static Map<String, Object> getBeanProperties(Object o, Set<String> ignore) {
    if (ignore == null) {
        ignore = DEFAULT_BEAN_PROP_NAME_IGNORE;
    }
    Map<String, Object> result = new LinkedHashMap<String, Object>();
    BeanWrapper bean = PropertyAccessorFactory.forBeanPropertyAccess(o);
    PropertyDescriptor[] props = bean.getPropertyDescriptors();
    for (PropertyDescriptor prop : props) {
        if (prop.getReadMethod() == null) {
            continue;
        }
        String propName = prop.getName();
        if (ignore != null && ignore.contains(propName)) {
            continue;
        }
        Object propValue = bean.getPropertyValue(propName);
        if (propValue == null) {
            continue;
        }
        result.put(propName, propValue);
    }
    return result;
}

From source file:net.solarnetwork.util.ClassUtils.java

/**
 * Copy non-null bean properties from one object to another.
 * //w  w w  .java2 s . c  om
 * @param src the object to copy values from
 * @param dest the object to copy values to
 * @param ignore a set of property names to ignore (optional)
 * @param emptyStringToNull if <em>true</em> then String values that 
 * are empty or contain only whitespace will be treated as if they
 * where <em>null</em>
 */
public static void copyBeanProperties(Object src, Object dest, Set<String> ignore, boolean emptyStringToNull) {
    if (ignore == null) {
        ignore = DEFAULT_BEAN_PROP_NAME_IGNORE;
    }
    BeanWrapper bean = PropertyAccessorFactory.forBeanPropertyAccess(src);
    BeanWrapper to = PropertyAccessorFactory.forBeanPropertyAccess(dest);
    PropertyDescriptor[] props = bean.getPropertyDescriptors();
    for (PropertyDescriptor prop : props) {
        if (prop.getReadMethod() == null) {
            continue;
        }
        String propName = prop.getName();
        if (ignore != null && ignore.contains(propName)) {
            continue;
        }
        Object propValue = bean.getPropertyValue(propName);
        if (propValue == null || (emptyStringToNull && (propValue instanceof String)
                && !StringUtils.hasText((String) propValue))) {
            continue;
        }
        if (to.isWritableProperty(propName)) {
            to.setPropertyValue(propName, propValue);
        }
    }
}

From source file:net.solarnetwork.util.ClassUtils.java

/**
 * Get a Map of non-null bean properties for an object.
 * //from   w w  w .  j  av a2 s  . c  om
 * @param o the object to inspect
 * @param ignore a set of property names to ignore (optional)
 * @param serializeIgnore if <em>true</em> test for the {@link SerializeIgnore}
 * annotation for ignoring properties
 * @return Map (never null)
 */
public static Map<String, Object> getBeanProperties(Object o, Set<String> ignore, boolean serializeIgnore) {
    if (o == null) {
        return null;
    }
    if (ignore == null) {
        ignore = DEFAULT_BEAN_PROP_NAME_IGNORE;
    }
    Map<String, Object> result = new LinkedHashMap<String, Object>();
    BeanWrapper bean = PropertyAccessorFactory.forBeanPropertyAccess(o);
    PropertyDescriptor[] props = bean.getPropertyDescriptors();
    for (PropertyDescriptor prop : props) {
        if (prop.getReadMethod() == null) {
            continue;
        }
        String propName = prop.getName();
        if (ignore != null && ignore.contains(propName)) {
            continue;
        }
        Object propValue = bean.getPropertyValue(propName);
        if (propValue == null) {
            continue;
        }
        if (serializeIgnore) {
            Method getter = prop.getReadMethod();
            if (getter != null && getter.isAnnotationPresent(SerializeIgnore.class)) {
                continue;
            }
        }
        result.put(propName, propValue);
    }
    return result;
}

From source file:org.zkybase.cmdb.util.ReflectionUtils.java

public static <T, U> U copySimpleProperties(T from, U to) {
    try {/*from  w  w  w  .  jav a  2 s.c o m*/
        PropertyDescriptor[] fromDescs = BeanUtils.getPropertyDescriptors(from.getClass());
        for (PropertyDescriptor fromDesc : fromDescs) {
            String propName = fromDesc.getName();
            PropertyDescriptor toDesc = BeanUtils.getPropertyDescriptor(to.getClass(), propName);
            if (toDesc != null) {
                Method readMethod = fromDesc.getReadMethod();
                Object value = readMethod.invoke(from);
                boolean write = (value instanceof Long || value instanceof String);
                if (write) {
                    Method writeMethod = toDesc.getWriteMethod();
                    writeMethod.invoke(to, value);
                }
            }
        }
        return to;
    } catch (InvocationTargetException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}