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:org.springmodules.validation.bean.conf.loader.xml.SimpleValidationRuleElementHandlerRegistryTests.java

public void testFindHandler_WithNoSupportedHandler() throws Exception {

    PropertyDescriptor descriptor = BeanUtils.getPropertyDescriptor(
            org.springmodules.validation.bean.conf.loader.xml.SimpleValidationRuleElementHandlerRegistryTests.TestBean.class,
            "name");

    Element element = createElement("bla");
    handler1Control.expectAndReturn(handler1.supports(element,
            org.springmodules.validation.bean.conf.loader.xml.SimpleValidationRuleElementHandlerRegistryTests.TestBean.class,
            descriptor), false);//from ww w.  j a  va 2  s  .c o  m
    handler2Control.expectAndReturn(handler2.supports(element,
            org.springmodules.validation.bean.conf.loader.xml.SimpleValidationRuleElementHandlerRegistryTests.TestBean.class,
            descriptor), false);
    replay();
    assertEquals(null, registry.findPropertyHandler(element,
            org.springmodules.validation.bean.conf.loader.xml.SimpleValidationRuleElementHandlerRegistryTests.TestBean.class,
            descriptor));
    verify();
}

From source file:com.nortal.petit.orm.relation.RelationMapper.java

public RelationMapper(Class<T> target, Class<R> relation, String targetProperty, String relationProperty,
        String targetMapping, WherePart where) {
    Assert.notNull(target, "RelationMapper.construct: target is mandatory");
    Assert.notNull(relation, "RelationMapper.construct: relation is mandatory");
    Assert.isTrue(StringUtils.isNotEmpty(targetProperty) || StringUtils.isNotEmpty(relationProperty),
            "RelationMapper.construct: targetProperty or relationProperty is mandatory");

    this.relationClass = relation;

    this.targetMapper = BeanMappings.get(target);
    this.relationMapper = BeanMappings.get(relation);

    // Init target mapping property
    if (StringUtils.isEmpty(targetProperty)) {
        this.targetProperty = targetMapper.id();
    } else {/* w  w w  . ja  v a 2 s .co m*/
        this.targetProperty = targetMapper.props().get(targetProperty);
    }
    Assert.notNull(this.targetProperty, "RelationMapper.construct: targetProperty is mandatory");

    targetId = new PropertyFunction<T, Object>(this.targetProperty);

    // Init target mapping property
    if (StringUtils.isEmpty(relationProperty)) {
        this.relationProperty = relationMapper.id();
    } else {
        this.relationProperty = relationMapper.props().get(relationProperty);
    }
    Assert.notNull(this.relationProperty, "RelationMapper.construct: relationProperty is mandatory");

    relationId = new PropertyFunction<R, Object>(this.relationProperty);

    if (StringUtils.isNotEmpty(targetMapping)) {
        PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(target, targetMapping);
        this.associateMethod = pd.getWriteMethod();
    }

    // Mapping conditions
    this.where = where;
}

From source file:com.expedia.seiso.domain.meta.DynaItem.java

/**
 * Sets the specified property value on the underlying item.
 * //from   ww w .  ja  va2 s  .co  m
 * @param propertyName
 *            Property name
 * @param propertyValue
 *            Property value
 */
@SneakyThrows
public void setPropertyValue(@NonNull String propertyName, Object propertyValue) {
    val desc = BeanUtils.getPropertyDescriptor(itemClass, propertyName);
    val setter = desc.getWriteMethod();
    setter.invoke(item, propertyValue);
}

From source file:com.trigonic.utils.spring.cmdline.CommandLineMetaData.java

private <T extends Annotation> void checkWriteableProperty(T annotation, Class<?> beanClass, Field field) {
    PropertyDescriptor property = BeanUtils.getPropertyDescriptor(beanClass, field.getName());
    if (property == null || property.getWriteMethod() == null) {
        throw new BeanDefinitionStoreException("@" + annotation.getClass().getSimpleName()
                + " annotation cannot be applied to fields without matching setters");
    }/*ww  w .ja v a2s  .c om*/
}

From source file:com.expedia.seiso.domain.service.impl.ItemMerger.java

/**
 * @param src//  ww  w  .  j a  v  a2 s.  co m
 *            non-persistent data we want to merge into the persistent entity
 * @param dest
 *            persistent entity
 * @param assocClass
 * @param assocName
 */
@SneakyThrows
@SuppressWarnings("rawtypes")
private void mergeSingleAssociation(Item src, Item dest, Class assocClass, String assocName) {
    val itemDesc = BeanUtils.getPropertyDescriptor(src.getClass(), assocName);
    log.trace("src.class={}, dest.class={}, itemDesc={}", src.getClass().getName(), dest.getClass().getName(),
            itemDesc);

    val getter = itemDesc.getReadMethod();
    val setter = itemDesc.getWriteMethod();

    if (getter == null || setter == null) {
        log.trace("Skipping single association: {}", itemDesc.getName());
        return;
    }

    val assocData = (Item) getter.invoke(src);
    log.trace("assocData={}", assocData);

    Item persistentAssoc = null;
    if (assocData != null) {

        // FIXME This fails when the associated item isn't sufficiently hydrated to generate its item key. This
        // happens for example when trying to generate a NodeIpAddress key when we haven't loaded the backing Node.
        // Also happens with ServiceInstancePorts missing a backing service instance.
        // https://github.com/ExpediaDotCom/seiso/issues/54
        // 
        // Need to get away from using ItemKeys here, and use the URI instead. We need a way (besides controllers,
        // which help only at the top level) to resolve URIs into the objects that they reference.
        // 
        // In the meantime we'll just use the ID to support v1.

        if (assocClass == NodeIpAddress.class) {
            persistentAssoc = nodeIpAddressRepo.findOne(assocData.getId());
        } else if (assocClass == ServiceInstancePort.class) {
            persistentAssoc = serviceInstancePortRepo.findOne(assocData.getId());
        } else {
            val repoAdapter = repoAdapterLookup.getRepoAdapterFor(assocClass);
            val assocKey = assocData.itemKey();
            persistentAssoc = repoAdapter.find(assocKey);
        }
    }

    setter.invoke(dest, persistentAssoc);
}

From source file:com.zero.service.impl.BaseServiceImpl.java

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

    PropertyDescriptor[] targetPds = BeanUtils.getPropertyDescriptors(target.getClass());
    for (PropertyDescriptor targetPd : targetPds) {
        if (targetPd.getWriteMethod() != null) {
            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  .  j av  a2  s  .  c  o 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:org.springmodules.validation.bean.conf.loader.xml.SimpleValidationRuleElementHandlerRegistryTests.java

public void testSetExtraHandlers() throws Exception {

    PropertyDescriptor descriptor = BeanUtils.getPropertyDescriptor(
            org.springmodules.validation.bean.conf.loader.xml.SimpleValidationRuleElementHandlerRegistryTests.TestBean.class,
            "name");

    registry = new SimpleValidationRuleElementHandlerRegistry();
    registry.registerPropertyHandler(handler1);
    registry.setExtraPropertyHandlers(new PropertyValidationElementHandler[] { handler2 });
    Element element = createElement("bla");
    handler2Control.expectAndReturn(handler2.supports(element,
            org.springmodules.validation.bean.conf.loader.xml.SimpleValidationRuleElementHandlerRegistryTests.TestBean.class,
            descriptor), true);//w w w. ja  v  a2  s.com
    replay();
    assertSame(handler2, registry.findPropertyHandler(element,
            org.springmodules.validation.bean.conf.loader.xml.SimpleValidationRuleElementHandlerRegistryTests.TestBean.class,
            descriptor));
    verify();
}

From source file:org.grails.datastore.mapping.model.AbstractPersistentEntity.java

public boolean hasProperty(String name, Class type) {
    final PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(getJavaClass(), name);
    return pd != null && pd.getPropertyType().equals(type);
}

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

/**
 * Gets the value type of the given collection, as declared by the collection property type.
 *
 * @param beanType     bean class//from   w ww .j a  v  a 2s.  c o m
 * @param beanProperty name of property, which must be a collection
 * @return generic type declared for collection members
 */
public static Class getCollectionValueType(Class beanType, String beanProperty) {
    PropertyDescriptor descriptor = BeanUtils.getPropertyDescriptor(beanType, beanProperty);
    Class propertyType = descriptor.getPropertyType();
    Assert.PROGRAMMING.isTrue(Collection.class.isAssignableFrom(propertyType),
            "Bean property not a collection type: " + beanType + "." + beanProperty);

    Type genericPropertyType = descriptor.getReadMethod().getGenericReturnType();
    Class collectionValueType = null;
    if (genericPropertyType != null && genericPropertyType instanceof ParameterizedType) {
        Type[] typeArgs = ((ParameterizedType) genericPropertyType).getActualTypeArguments();
        if (typeArgs != null && typeArgs.length > 0) {
            if (typeArgs.length == 1) {
                collectionValueType = (Class) typeArgs[0];
            } else if (typeArgs.length == 2) {
                collectionValueType = (Class) typeArgs[1];
            } else {
                Assert.PROGRAMMING.fail("Collection type has more than two generic arguments");
            }
        }
    }

    return collectionValueType;
}

From source file:org.jdal.vaadin.ui.form.ConfigurableFieldFactory.java

/**
 * Try to find a field. It will tray the four configured maps in order:
 * <ol>/*from w ww  . ja  v a  2 s  .  com*/
 *  <li> propertyId to FieldBuilder map.</li>
 *  <li> propertyId to Field map.</li>
 *  <li> propertyClass to FieldBuilder map.</li>
 *  <li> propertyClass to Field map.</li>
 * </ol>
 * @param propertyId the propertyId
 * @param clazz the bean class holding the propertyId
 * @return Field or null if none configured
 */
@SuppressWarnings("unchecked")
protected Field getField(Object propertyId, Class<?> clazz) {
    // try id to builder map
    FieldBuilder builder = idBuilderMap.get(propertyId);
    if (builder != null) {
        if (log.isDebugEnabled())
            log.debug("Found FieldBuilder in idBuilderMap: [" + builder.getClass().getSimpleName() + "]");

        return builder.build(clazz, (String) propertyId);
    }

    // try id to class Map
    Class<? extends Field> fieldClass = idClassMap.get(propertyId);
    if (fieldClass != null) {
        if (log.isDebugEnabled())
            log.debug("Found FieldBuilder in idClassMap: [" + fieldClass.getSimpleName() + "]");
        return BeanUtils.instantiate(fieldClass);
    }

    // try class to builder map
    Class<?> propertyClass = BeanUtils.getPropertyDescriptor(clazz, (String) propertyId).getPropertyType();
    builder = (FieldBuilder) findByClass(propertyClass, classBuilderMap);
    if (builder != null) {
        if (log.isDebugEnabled())
            log.debug("Found FieldBuilder in classBuilderMap: [" + builder.getClass().getSimpleName() + "]");

        return builder.build(clazz, (String) propertyId);
    }

    // try class to field map
    fieldClass = (Class<? extends Field>) findByClass(propertyClass, classFieldMap);
    if (fieldClass != null) {
        if (log.isDebugEnabled())
            log.debug("Found FieldBuilder in classFieldMap: [" + fieldClass.getSimpleName() + "]");

        return BeanUtils.instantiate(fieldClass);
    }

    log.debug("Not found field for propertyId: " + propertyId);

    return null;
}