Example usage for org.springframework.beans BeanUtils getPropertyDescriptor

List of usage examples for org.springframework.beans BeanUtils getPropertyDescriptor

Introduction

In this page you can find the example usage for org.springframework.beans BeanUtils getPropertyDescriptor.

Prototype

@Nullable
public static PropertyDescriptor getPropertyDescriptor(Class<?> clazz, String propertyName)
        throws BeansException 

Source Link

Document

Retrieve the JavaBeans PropertyDescriptors for the given property.

Usage

From source file:net.groupbuy.service.impl.BaseServiceImpl.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private void copyProperties(Object source, Object target, String[] ignoreProperties) throws BeansException {
    Assert.notNull(source, "Source must not be null");
    Assert.notNull(target, "Target must not be null");

    PropertyDescriptor[] targetPds = BeanUtils.getPropertyDescriptors(target.getClass());
    List<String> ignoreList = (ignoreProperties != null) ? Arrays.asList(ignoreProperties) : null;
    for (PropertyDescriptor targetPd : targetPds) {
        if (targetPd.getWriteMethod() != null
                && (ignoreProperties == null || (!ignoreList.contains(targetPd.getName())))) {
            PropertyDescriptor sourcePd = BeanUtils.getPropertyDescriptor(source.getClass(),
                    targetPd.getName());
            if (sourcePd != null && sourcePd.getReadMethod() != null) {
                try {
                    Method readMethod = sourcePd.getReadMethod();
                    if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                        readMethod.setAccessible(true);
                    }//from w w  w  . ja  v  a 2 s  .co  m
                    Object sourceValue = readMethod.invoke(source);
                    Object targetValue = readMethod.invoke(target);
                    if (sourceValue != null && targetValue != null && targetValue instanceof Collection) {
                        Collection collection = (Collection) targetValue;
                        collection.clear();
                        collection.addAll((Collection) sourceValue);
                    } else {
                        Method writeMethod = targetPd.getWriteMethod();
                        if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                            writeMethod.setAccessible(true);
                        }
                        writeMethod.invoke(target, sourceValue);
                    }
                } catch (Throwable ex) {
                    throw new FatalBeanException("Could not copy properties from source to target", ex);
                }
            }
        }
    }
}

From source file:de.extra.client.core.annotation.PropertyPlaceholderPluginConfigurer.java

private void setPluginProperties(final ConfigurableListableBeanFactory beanFactory, final Properties properties,
        final String beanName, final Class<?> clazz) {
    final PluginConfiguration annotationConfigutation = clazz.getAnnotation(PluginConfiguration.class);
    final MutablePropertyValues mutablePropertyValues = beanFactory.getBeanDefinition(beanName)
            .getPropertyValues();//from  ww w .  j  av a 2 s. co  m

    for (final PropertyDescriptor property : BeanUtils.getPropertyDescriptors(clazz)) {
        final Method setter = property.getWriteMethod();
        PluginValue valueAnnotation = null;
        if (setter != null && setter.isAnnotationPresent(PluginValue.class)) {
            valueAnnotation = setter.getAnnotation(PluginValue.class);
        }
        if (valueAnnotation != null) {
            final String key = extractKey(annotationConfigutation, valueAnnotation, clazz);
            final String value = resolvePlaceholder(key, properties, SYSTEM_PROPERTIES_MODE_FALLBACK);
            if (StringUtils.isEmpty(value)) {
                throw new BeanCreationException(beanName,
                        "No such property=[" + key + "] found in properties.");
            }
            if (LOG.isDebugEnabled()) {
                LOG.debug("setting property=[" + clazz.getName() + "." + property.getName() + "] value=[" + key
                        + "=" + value + "]");
            }
            mutablePropertyValues.addPropertyValue(property.getName(), value);
        }
    }

    for (final Field field : clazz.getDeclaredFields()) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("examining field=[" + clazz.getName() + "." + field.getName() + "]");
        }
        if (field.isAnnotationPresent(PluginValue.class)) {
            final PluginValue valueAnnotation = field.getAnnotation(PluginValue.class);
            final PropertyDescriptor property = BeanUtils.getPropertyDescriptor(clazz, field.getName());

            if (property == null || property.getWriteMethod() == null) {
                throw new BeanCreationException(beanName,
                        "setter for property=[" + clazz.getName() + "." + field.getName() + "] not available.");
            }
            final String key = extractKey(annotationConfigutation, valueAnnotation, clazz);
            String value = resolvePlaceholder(key, properties, SYSTEM_PROPERTIES_MODE_FALLBACK);
            if (value == null) {
                // DEFAULT Value suchen
                final int separatorIndex = key.indexOf(VALUE_SEPARATOR);
                if (separatorIndex != -1) {
                    final String actualPlaceholder = key.substring(0, separatorIndex);
                    final String defaultValue = key.substring(separatorIndex + VALUE_SEPARATOR.length());
                    value = resolvePlaceholder(actualPlaceholder, properties, SYSTEM_PROPERTIES_MODE_FALLBACK);
                    if (value == null) {
                        value = defaultValue;
                    }
                }
            }

            if (value != null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("setting property=[" + clazz.getName() + "." + field.getName() + "] value=[" + key
                            + "=" + value + "]");
                }
                mutablePropertyValues.addPropertyValue(field.getName(), value);
            } else if (!ignoreNullValues) {
                throw new BeanCreationException(beanName,
                        "No such property=[" + key + "] found in properties.");
            }
        }
    }
}

From source file:com.bstek.dorado.data.entity.PropertyPathUtils.java

public static Class<?> getPropertyTypeByPath(Class<?> beanType, String propertyPath) throws Exception {
    String[] paths = StringUtils.split(propertyPath, '.');
    Class<?> type = beanType;
    for (int i = 0; i < paths.length; i++) {
        String path = paths[i];// www  .  j  ava2 s  . c  om
        PropertyDescriptor propertyDescriptor = BeanUtils.getPropertyDescriptor(type, path);
        if (propertyDescriptor != null) {
            type = propertyDescriptor.getPropertyType();
        } else {
            type = null;
            break;
        }
    }
    return type;
}

From source file:com.nortal.petit.beanmapper.BeanMappingFactoryImpl.java

private <B> Collection<PropertyDescriptor> findPropertyDescriptors(Class<B> clazz) {
    Set<PropertyDescriptor> result = new LinkedHashSet<PropertyDescriptor>();

    Collection<String> fieldNames = collectFieldNames(clazz);
    for (String fieldName : fieldNames) {
        PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(clazz, fieldName);
        if (pd != null) {
            result.add(pd);// w  ww . j ava 2 s  . co  m
        }
    }

    return result;
}

From source file:org.obiba.magma.beans.BeanVariableValueSourceFactory.java

/**
 * Finds the type ({@code Class}) for a given {@code propertyName} which may denote a nested property (property path
 * e.g: a.b.c) or mapped property (attribute[key]) or a combination of both (e.g.: a.b[c].d).
 *
 * @param propertyName// w w  w. j a  v a2s .  c om
 * @return
 */
@SuppressWarnings({ "OverlyLongMethod", "PMD.NcssMethodCount" })
protected Class<?> getPropertyType(String propertyName) {
    // Has a property type been explicitly declared? If so, use it.
    Class<?> declaredPropertyType = propertyNameToPropertyType.get(propertyName);
    if (declaredPropertyType != null) {
        return declaredPropertyType;
    }

    Class<?> currentType = getBeanClass();
    String propertyPath = propertyName;

    // Loop as long as the propertyPath designates a nested property
    while (PropertyAccessorUtils.isNestedOrIndexedProperty(propertyPath)) {
        int pos = PropertyAccessorUtils.getFirstNestedPropertySeparatorIndex(propertyPath);

        String nestedProperty = pos > -1 ? propertyPath.substring(0, pos) : propertyPath;

        // Check whether this is a mapped property (a[b])
        if (PropertyAccessorUtils.isNestedOrIndexedProperty(nestedProperty)) {
            // We cannot determine the type of these properties through reflection (even when they contain type parameters
            // i.e. Map<String, String>).
            // The type of these properties has to be specified through configuration
            currentType = getMapAttributeType(PropertyAccessorUtils.getPropertyName(nestedProperty));
            if (pos == -1) {
                return currentType;
            }
            propertyPath = propertyPath.substring(pos + 1);
        } else {
            PropertyDescriptor currentProperty = BeanUtils.getPropertyDescriptor(currentType, nestedProperty);
            if (currentProperty == null) {
                throw new IllegalArgumentException("Invalid path '" + propertyName + "' for type "
                        + getBeanClass().getName() + ": nested property '" + nestedProperty
                        + "' does not exist on type " + currentType.getName());
            }
            // Change the current type so it points to the nested type
            currentType = currentProperty.getPropertyType();
            // Extract the nested type's property path from the original path
            propertyPath = propertyPath.substring(pos + 1);
        }
    }

    // propertyPath is a direct reference to a property of the currentType (no longer a path)
    PropertyDescriptor descriptor = BeanUtils.getPropertyDescriptor(currentType, propertyPath);
    if (descriptor == null) {
        throw new IllegalArgumentException(
                "Invalid path '" + propertyName + "' for type " + getBeanClass().getName() + ": property '"
                        + propertyPath + "' does not exist on type " + currentType.getName());
    }
    return descriptor.getPropertyType();
}

From source file:com.expressui.core.util.BeanPropertyType.java

private void initPropertyAnnotations() {
    PropertyDescriptor descriptor = BeanUtils.getPropertyDescriptor(containerType, id);
    if (descriptor != null) {
        Method method = descriptor.getReadMethod();
        if (method != null) {
            Annotation[] readMethodAnnotations = method.getAnnotations();
            Collections.addAll(annotations, readMethodAnnotations);
        }/*from w  w w  .j  a va  2  s  .c om*/
    }
}

From source file:com.lakeside.data.sqldb.BaseDao.java

/**
 * ?//from  www  . jav  a  2  s  .c  om
 * @param entity
 * @return
 */
public T merge(final T entity) {
    Assert.notNull(entity, "entity?");
    Session session = getSession();
    String idName = getIdName();
    PropertyDescriptor idp = BeanUtils.getPropertyDescriptor(entityClass, idName);
    PK idvalue = null;
    try {
        idvalue = (PK) idp.getReadMethod().invoke(entity);
    } catch (Exception e) {
        throw new FatalBeanException("Could not copy properties from source to target", e);
    }
    T dest = null;
    if (idvalue != null) {
        dest = (T) session.get(entityClass, idvalue);
    }
    if (dest != null) {
        // merge the properties
        PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(entityClass);
        for (PropertyDescriptor p : descriptors) {
            if (p.getWriteMethod() != null) {
                try {
                    Method readMethod = p.getReadMethod();
                    if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                        readMethod.setAccessible(true);
                    }
                    Object value = readMethod.invoke(entity);
                    if (value == null) {
                        continue;
                    }
                    Method writeMethod = p.getWriteMethod();
                    if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                        writeMethod.setAccessible(true);
                    }
                    writeMethod.invoke(dest, value);
                } catch (Throwable ex) {
                    throw new FatalBeanException("Could not copy properties from source to target", ex);
                }
            }
        }
    } else {
        // destination object is empty, save the entity object parameted
        dest = entity;
    }
    session.saveOrUpdate(dest);
    logger.debug("merge entity: {}", entity);
    return dest;
}

From source file:com.urbanmania.spring.beans.factory.config.annotations.PropertyAnnotationAndPlaceholderConfigurer.java

private void processAnnotatedProperties(Properties properties, String name, MutablePropertyValues mpv,
        Class<?> clazz) {//from w w  w.java2 s. c  o  m
    // TODO support proxies
    if (clazz != null && clazz.getPackage() != null) {
        if (basePackage != null && !clazz.getPackage().getName().startsWith(basePackage)) {
            return;
        }

        log.info("Configuring properties for bean=" + name + "[" + clazz + "]");

        for (PropertyDescriptor property : BeanUtils.getPropertyDescriptors(clazz)) {
            if (log.isLoggable(Level.FINE))
                log.fine("examining property=[" + clazz.getName() + "." + property.getName() + "]");
            Method setter = property.getWriteMethod();
            Method getter = property.getReadMethod();
            Property annotation = null;
            if (setter != null && setter.isAnnotationPresent(Property.class)) {
                annotation = setter.getAnnotation(Property.class);
            } else if (setter != null && getter != null && getter.isAnnotationPresent(Property.class)) {
                annotation = getter.getAnnotation(Property.class);
            } else if (setter == null && getter != null && getter.isAnnotationPresent(Property.class)) {
                throwBeanConfigurationException(clazz, property.getName());
            }
            if (annotation != null) {
                setProperty(properties, name, mpv, clazz, property, annotation);
            }
        }

        for (Field field : clazz.getDeclaredFields()) {
            if (log.isLoggable(Level.FINE))
                log.fine("examining field=[" + clazz.getName() + "." + field.getName() + "]");
            if (field.isAnnotationPresent(Property.class)) {
                Property annotation = field.getAnnotation(Property.class);
                PropertyDescriptor property = BeanUtils.getPropertyDescriptor(clazz, field.getName());

                if (property == null || property.getWriteMethod() == null) {
                    throwBeanConfigurationException(clazz, field.getName());
                }

                setProperty(properties, name, mpv, clazz, property, annotation);
            }
        }
    }
}

From source file:grails.plugin.searchable.internal.SearchableUtils.java

/**
 * If the given domain class property is a generic collection, this method
 * returns the element type of that collection. Otherwise, it returns
 * <code>null</code>./*  w w w  . j  av a  2  s .c o  m*/
 */
public static Class getElementClass(GrailsDomainClassProperty property) {
    PropertyDescriptor descriptor = BeanUtils.getPropertyDescriptor(property.getDomainClass().getClazz(),
            property.getName());
    Type type = descriptor.getReadMethod().getGenericReturnType();
    if (type instanceof ParameterizedType) {
        for (Type argType : ((ParameterizedType) type).getActualTypeArguments()) {
            return (Class) argType;
        }
    }

    return null;
}

From source file:com.expedia.seiso.web.controller.delegate.BasicItemDelegate.java

/**
 * Returns an item property value./*from   w w  w  .  j ava  2 s .  c  o m*/
 * 
 * @param apiVersion
 *            API version
 * @param repoKey
 *            repository key
 * @param itemKey
 *            item key
 * @param propKey
 *            property key
 * @param view
 *            view key
 * @return returns the item property value, which is either a single item or a list of items, depending on the item
 *         property value type
 */
public Object getProperty(@NonNull ApiVersion apiVersion, @NonNull String repoKey, @NonNull String itemKey,
        @NonNull String propKey, String view) {

    log.trace("Getting item property: /{}/{}/{}", repoKey, itemKey, propKey);
    val itemClass = itemMetaLookup.getItemClass(repoKey);
    val itemMeta = itemMetaLookup.getItemMeta(itemClass);
    val item = itemService.find(new SimpleItemKey(itemClass, itemKey));
    val dynaItem = new DynaItem(item);
    val propName = itemMeta.getPropertyName(propKey);
    val propValue = dynaItem.getPropertyValue(propName);

    // Use the metamodel to route processing, as opposed to using `propValue instanceof Item` etc. That way we can
    // handle null values too. See https://github.com/ExpediaDotCom/seiso/issues/32
    val propDesc = BeanUtils.getPropertyDescriptor(itemClass, propName);
    val propClass = propDesc.getPropertyType();
    if (Item.class.isAssignableFrom(propClass)) {
        return getItemProperty(apiVersion, (Item) propValue, view);
    } else if (List.class.isAssignableFrom(propClass)) {
        // FIXME Need pagination here!
        // E.g., dataCenter.serviceInstances and environment.serviceInstances are too long.
        // FIXME Also potentially need projections here.
        // E.g., /service-instance/:key/nodes doesn't include embedded IP addresses, which the service instance
        // details page needs.
        return getListProperty(apiVersion, (List<?>) propValue, view);
    } else {
        String msg = "Resource assembly for type " + propClass.getName() + " not supported";
        throw new UnsupportedOperationException(msg);
    }

    // Do we need to handle paging property lists here?
    // Usually property lists will be reasonably short. But it is easy to imagine real cases where this isn't true,
    // such as a service instance with hundreds of nodes.
}