Example usage for java.beans PropertyDescriptor getName

List of usage examples for java.beans PropertyDescriptor getName

Introduction

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

Prototype

public String getName() 

Source Link

Document

Gets the programmatic name of this feature.

Usage

From source file:com.mycomm.dao.mydao.base.MyDaoSupport.java

/**
 * ?,hibernate???select count(o) from Xxx
 * o?BUG,hibernatejpql??sqlselect//from w ww.j a  v  a  2s.  c  o m
 * count(field1,field2,...),count()
 *
 * @param <E>
 * @param clazz
 * @return
 */
protected static <E> String getCountField(Class<E> clazz) {
    String out = "o";
    try {
        PropertyDescriptor[] propertyDescriptors = Introspector.getBeanInfo(clazz).getPropertyDescriptors();
        for (PropertyDescriptor propertydesc : propertyDescriptors) {
            Method method = propertydesc.getReadMethod();
            if (method != null && method.isAnnotationPresent(EmbeddedId.class)) {
                PropertyDescriptor[] ps = Introspector.getBeanInfo(propertydesc.getPropertyType())
                        .getPropertyDescriptors();
                out = "o." + propertydesc.getName() + "."
                        + (!ps[1].getName().equals("class") ? ps[1].getName() : ps[0].getName());
                break;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return out;
}

From source file:edu.duke.cabig.c3pr.utils.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  ww  .j  a va  2s.  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);
                        Object el2 = l2.get(i);
                        if (!deepCompare(el1, el2)) {
                            return false;
                        }
                    }

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

From source file:com.frank.search.solr.server.support.SolrClientUtils.java

/**
 * Solr property names do not match the getters/setters used for them. Check
 * on any write method, try to find the according property and set the value
 * for it. Will ignore all other, and nested properties
 * //w ww . j  av  a2  s.co  m
 * @param source
 * @param target
 */
private static void copyProperties(SolrClient source, SolrClient target) {
    BeanWrapperImpl wrapperImpl = new BeanWrapperImpl(source);
    for (PropertyDescriptor pd : wrapperImpl.getPropertyDescriptors()) {
        Method writer = pd.getWriteMethod();
        if (writer != null) {
            try {
                Field property = ReflectionUtils.findField(source.getClass(), pd.getName());
                if (property != null) {
                    ReflectionUtils.makeAccessible(property);
                    Object o = ReflectionUtils.getField(property, source);
                    if (o != null) {
                        writer.invoke(target, o);
                    }
                }
            } catch (Exception e) {
                logger.warn("Could not copy property value for: " + pd.getName(), e);
            }
        }
    }
}

From source file:com.wavemaker.json.type.reflect.ReflectTypeUtils.java

/**
 * Initializes a TypeDefinition from a given class. The first entry in the return list is the TypeDefinition for the
 * parameter class; any entries after that (if any) are TypeDefinitions for any other types that were required as
 * fields for that root TypeDefinition./* w  w w .  j a  v a 2s .  c  om*/
 * 
 * @param klass The Class object to describe.
 * @param typeState The TypeState for the current operation.
 * @param strict True indicates that processing should stop on ambiguous entries; false indicates that null should
 *        be entered.
 * @return A list of TypeDefinitions; the first entry is the root (corresponding with the klass parameter), any
 *         other entries in the list were required to describe the root TypeDefinition's fields. The return may also
 *         be null, if sufficient information was not provided to determine the type.
 */
public static TypeDefinition getTypeDefinition(Type type, TypeState typeState, boolean strict) {

    Class<?> klass;

    // we already know about this type; we're done
    if (typeState.isTypeKnown(ReflectTypeUtils.getTypeName(type))) {
        return typeState.getType(ReflectTypeUtils.getTypeName(type));
    }

    // if the type is Object, return null, we can't figure out anything more
    if (type instanceof Class && Object.class.equals(type)) {
        return null;
    }

    // if we don't have enough information, return null
    if (!strict) {
        if (type instanceof Class && Map.class.isAssignableFrom((Class<?>) type)
                && !Properties.class.isAssignableFrom((Class<?>) type)) {
            if (!JSON.class.isAssignableFrom((Class<?>) type)) {
                logger.warn(MessageResource.JSON_TYPE_NOGENERICS.getMessage(type));
            }
            return null;
        } else if (type instanceof Class && List.class.isAssignableFrom((Class<?>) type)) {
            if (!JSON.class.isAssignableFrom((Class<?>) type)) {
                logger.warn(MessageResource.JSON_TYPE_NOGENERICS.getMessage(type));
            }
            return null;
        }
    }

    TypeDefinition ret;

    if (type instanceof Class && Properties.class.isAssignableFrom((Class<?>) type)) {
        MapReflectTypeDefinition mtdret = new MapReflectTypeDefinition();
        mtdret.setTypeName(ReflectTypeUtils.getTypeName(type));
        mtdret.setShortName(ReflectTypeUtils.getShortName(type));
        typeState.addType(mtdret);

        klass = (Class<?>) type;
        mtdret.setKlass(klass);

        TypeDefinition stringType = getTypeDefinition(String.class, typeState, false);
        mtdret.setKeyFieldDefinition(new GenericFieldDefinition(stringType));
        mtdret.setValueFieldDefinition(new GenericFieldDefinition(stringType));

        ret = mtdret;
    } else if (type instanceof Class && JSONUtils.isPrimitive((Class<?>) type)) {
        PrimitiveReflectTypeDefinition ptret;
        if (((Class<?>) type).isEnum()) {
            ptret = new EnumPrimitiveReflectTypeDefinition();
        } else {
            ptret = new PrimitiveReflectTypeDefinition();
        }

        ptret.setTypeName(ReflectTypeUtils.getTypeName(type));
        ptret.setShortName(ReflectTypeUtils.getShortName(type));
        typeState.addType(ptret);

        klass = (Class<?>) type;
        ptret.setKlass(klass);

        ret = ptret;
    } else if (type instanceof Class) {
        klass = (Class<?>) type;

        if (Collection.class.isAssignableFrom(klass)) {
            throw new WMRuntimeException(MessageResource.JSON_TYPE_NOGENERICS, klass);
        } else if (klass.isArray()) {
            throw new WMRuntimeException(MessageResource.JSON_USE_FIELD_FOR_ARRAY, klass);
        } else if (Map.class.isAssignableFrom(klass)) {
            throw new WMRuntimeException(MessageResource.JSON_TYPE_NOGENERICS, klass);
        } else if (ClassUtils.isPrimitiveOrWrapper(klass) || CharSequence.class.isAssignableFrom(klass)) {
            PrimitiveReflectTypeDefinition ptret = new PrimitiveReflectTypeDefinition();
            ptret.setTypeName(ReflectTypeUtils.getTypeName(type));
            ptret.setShortName(ReflectTypeUtils.getShortName(type));
            typeState.addType(ptret);

            ptret.setKlass(klass);

            ret = ptret;
        } else {
            ObjectReflectTypeDefinition otret = new ObjectReflectTypeDefinition();
            otret.setTypeName(ReflectTypeUtils.getTypeName(type));
            otret.setShortName(ReflectTypeUtils.getShortName(type));
            otret.setKlass(klass);
            typeState.addType(otret);

            PropertyUtilsBean pub = ((ReflectTypeState) typeState).getPropertyUtilsBean();
            PropertyDescriptor[] pds = pub.getPropertyDescriptors(klass);
            otret.setFields(new LinkedHashMap<String, FieldDefinition>(pds.length));

            for (PropertyDescriptor pd : pds) {
                if (pd.getName().equals("class")) {
                    continue;
                }

                Type paramType;
                if (pd.getReadMethod() != null) {
                    paramType = pd.getReadMethod().getGenericReturnType();
                } else if (pd.getWriteMethod() != null) {
                    paramType = pd.getWriteMethod().getGenericParameterTypes()[0];
                } else {
                    logger.warn("No getter in type " + pd.getName());
                    continue;
                }

                otret.getFields().put(pd.getName(),
                        getFieldDefinition(paramType, typeState, strict, pd.getName()));
            }

            ret = otret;
        }
    } else if (type instanceof ParameterizedType) {
        ParameterizedType pt = (ParameterizedType) type;

        if (pt.getRawType() instanceof Class && Map.class.isAssignableFrom((Class<?>) pt.getRawType())) {
            MapReflectTypeDefinition mtdret = new MapReflectTypeDefinition();
            mtdret.setTypeName(ReflectTypeUtils.getTypeName(type));
            mtdret.setShortName(ReflectTypeUtils.getShortName(type));
            typeState.addType(mtdret);

            Type[] types = pt.getActualTypeArguments();

            mtdret.setKeyFieldDefinition(getFieldDefinition(types[0], typeState, strict, null));
            mtdret.setValueFieldDefinition(getFieldDefinition(types[1], typeState, strict, null));
            mtdret.setKlass((Class<?>) pt.getRawType());

            ret = mtdret;
        } else {
            throw new WMRuntimeException(MessageResource.JSON_TYPE_UNKNOWNRAWTYPE, pt.getOwnerType(), pt);
        }
    } else {
        throw new WMRuntimeException(MessageResource.JSON_TYPE_UNKNOWNPARAMTYPE, type,
                type != null ? type.getClass() : null);
    }

    return ret;
}

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  ww.  ja  v 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:jp.go.nict.langrid.p2pgridbasis.data.langrid.converter.ConvertUtil.java

public static void decode(DataAttributes from, Object to) throws DataConvertException {
    setLangridConverter();//  ww w.j a  v  a2  s.c  om
    logger.debug("##### decode #####");
    try {
        for (PropertyDescriptor descriptor : PropertyUtils.getPropertyDescriptors(to)) {
            logger.debug(
                    "Name : " + descriptor.getName() + " / PropertyType : " + descriptor.getPropertyType());
            Object value = from.getValue(descriptor.getName());
            if (PropertyUtils.isWriteable(to, descriptor.getName()) && value != null) {
                //Write OK
                try {
                    Converter converter = ConvertUtils.lookup(descriptor.getPropertyType());
                    if (!ignoreProps.contains(descriptor.getName())) {
                        if (converter == null) {
                            logger.error("no converter is registered : " + descriptor.getName() + " "
                                    + descriptor.getPropertyType());
                        } else {
                            Object obj = converter.convert(descriptor.getPropertyType(), value);
                            PropertyUtils.setProperty(to, descriptor.getName(), obj);
                        }
                    }
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                    logger.info(e.getMessage());
                } catch (NoSuchMethodException e) {
                    logger.info(e.getMessage());
                }
            } else {
                if (value != null) {
                    //Write NG
                    logger.debug("isWriteable = false");
                } else {
                    //Write NG
                    logger.debug("value = null");
                }
            }
        }
    } catch (IllegalAccessException e) {
        throw new DataConvertException(e);
    } catch (InvocationTargetException e) {
        throw new DataConvertException(e);
    }
}

From source file:com.clican.pluto.common.util.BeanUtils.java

/**
 * ??Mapmapkey??,value//from  w w  w  .ja v  a  2  s  . c o m
 * <p>
 *  bean id  name 100  zhangsan ? id=100,name="zhangsan"Map
 * </p>
 * 
 * @param <Bean>
 * @param bean
 * @return
 */
public static <Bean> Map<String, Object> convertBeanToMap(Bean bean) {
    if (bean == null)
        return null;

    PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
    PropertyDescriptor[] psArray = propertyUtilsBean.getPropertyDescriptors(bean.getClass());
    List<String> properties = new ArrayList<String>();
    for (PropertyDescriptor ps : psArray) {
        properties.add(ps.getName());
    }

    Map<String, Object> map = new HashMap<String, Object>();
    for (String property : properties) {
        // ?class?map
        if ("class".equals(property)) {
            continue;
        }
        String methodName = StringUtils.getGetMethodName(property);
        try {
            Method method = bean.getClass().getMethod(methodName, new Class<?>[] {});
            Object propertyValue = method.invoke(bean, new Object[] {});
            if (propertyValue != null) {
                map.put(property, propertyValue);
            }
        } catch (Exception e) {
            log.error("", e);
        }
    }
    return map;
}

From source file:org.hellojavaer.testcase.generator.TestCaseGenerator.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private static <T> void checkBeanValidity(Class<T> clazz, List<String> excludeFieldList,
        int recursiveCycleLimit) {
    PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(clazz);
    boolean validBean = false;
    for (PropertyDescriptor pd : pds) {
        if (pd.getWriteMethod() != null && pd.getReadMethod() != null && //
                (excludeFieldList != null && !excludeFieldList.contains(pd.getName())
                        || excludeFieldList == null) //
        ) {// w  ww. j  ava 2  s. co m
            validBean = true;
            // just set write ,read for user control
            if (!Modifier.isPublic(pd.getWriteMethod().getDeclaringClass().getModifiers())) {
                pd.getWriteMethod().setAccessible(true);
            }

            Class fieldClazz = pd.getPropertyType();
            if (!TypeUtil.isBaseType(fieldClazz)) {
                try {
                    // ????
                    if (recursiveCycleLimit == 0 && fieldClazz == clazz) {
                        throw new RuntimeException("recursive cycle limit is 0! field[" + pd.getName()
                                + "] may cause recursive, please add this field[" + pd.getName()
                                + "] to exclude list or set recursiveCycleLimit more than 0 .");
                    } else if (!fieldClazz.isAssignableFrom(clazz)) {
                        checkBeanValidity(fieldClazz, null, 999999999);
                    }
                } catch (Exception e) {
                    throw new RuntimeException("Unknown Class " + fieldClazz.getName() + " for field "
                            + pd.getName() + " ! please add this field[" + pd.getName() + "] to exclude list.",
                            e);
                }
            }
        }
    }
    if (!validBean) {
        throw new RuntimeException(
                "Invalid Bean Class[" + clazz.getName() + "], for it has not getter setter methods!");
    }
}

From source file:org.agiso.core.i18n.util.I18nUtils.java

private static String findGetterFieldCode(Class<?> c, String field, boolean reflectionCheck)
        throws IntrospectionException {
    for (PropertyDescriptor pd : Introspector.getBeanInfo(c).getPropertyDescriptors()) {
        if (pd.getName().equals(field)) {
            final Method g = pd.getReadMethod();
            if (g != null) {
                // Jeli jest adnotacja I18n na metodzie odczytujcej pole, to pobieranie
                // pobieranie jej klucza (okrelonego przez 'value') lub klucza domylnego:
                if (g.isAnnotationPresent(I18n.class)) {
                    if (g.getAnnotation(I18n.class).value().length() > 0) {
                        return g.getAnnotation(I18n.class).value();
                    } else {
                        return g.getDeclaringClass().getName() + CODE_SEPARATOR + field;
                    }//from  ww w  .  ja va  2 s. c  o  m
                } else if (reflectionCheck) {
                    // Pole nie jest opisane adnotacj I18n. Jeli do wyszukania maj by
                    // wykorzystane mechanizmy refleksji, to sprawdzamy interfejsy i nadklas:
                    for (Class<?> i : c.getInterfaces()) {
                        String i18nCode = findGetterFieldCode(i, field, false);
                        if (i18nCode != null) {
                            return i18nCode;
                        }
                    }
                    Class<?> s = c.getSuperclass();
                    if (s != null) {
                        return findGetterFieldCode(s, field, true);
                    }
                }
            }
        }
    }
    if (reflectionCheck) {
        for (Class<?> i : c.getInterfaces()) {
            String i18nCode = findGetterFieldCode(i, field, false);
            if (i18nCode != null) {
                return i18nCode;
            }
        }
    }

    return null;
}

From source file:io.github.moosbusch.lumpi.util.LumpiUtil.java

public static Set<String> getBeanPropertyNames(Class<?> beanClass) {
    Set<String> result = new HashSet<>();
    BeanInfo beanInfo = null;/* w w w  .ja v  a 2  s  . com*/

    try {
        beanInfo = Introspector.getBeanInfo(beanClass);
    } catch (IntrospectionException ex) {
        Logger.getLogger(LumpiUtil.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        if (beanInfo != null) {
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

            if (ArrayUtils.isNotEmpty(propertyDescriptors)) {
                for (PropertyDescriptor pd : propertyDescriptors) {
                    result.add(pd.getName());
                }
            }
        }
    }

    return result;
}