Example usage for org.springframework.beans BeanWrapper getPropertyDescriptor

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

Introduction

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

Prototype

PropertyDescriptor getPropertyDescriptor(String propertyName) throws InvalidPropertyException;

Source Link

Document

Obtain the property descriptor for a specific property of the wrapped object.

Usage

From source file:org.opennms.core.test.xml.XmlTest.java

private static void assertDepthEquals(final int depth, final String propertyName, final Object expected,
        Object actual) {//from  w w  w. j a  v a2s . c  o m
    if (expected == null && actual == null) {
        return;
    } else if (expected == null) {
        fail("expected " + propertyName + " was null but actual was not!");
    } else if (actual == null) {
        fail("actual " + propertyName + " was null but expected was not!");
    }

    final String assertionMessage = propertyName == null
            ? ("Top-level objects (" + expected.getClass().getName() + ") do not match.")
            : ("Properties " + propertyName + " do not match.");
    if (expected.getClass().getName().startsWith("java") || actual.getClass().getName().startsWith("java")) {
        // java primitives, just do assertEquals
        if (expected instanceof Object[] || actual instanceof Object[]) {
            assertTrue(assertionMessage, Arrays.equals((Object[]) expected, (Object[]) actual));
        } else {
            assertEquals(assertionMessage, expected, actual);
        }
        return;
    }

    final BeanWrapper expectedWrapper = new BeanWrapperImpl(expected);
    final BeanWrapper actualWrapper = new BeanWrapperImpl(actual);

    final Set<String> properties = new TreeSet<String>();
    for (final PropertyDescriptor descriptor : expectedWrapper.getPropertyDescriptors()) {
        properties.add(descriptor.getName());
    }
    for (final PropertyDescriptor descriptor : actualWrapper.getPropertyDescriptors()) {
        properties.add(descriptor.getName());
    }

    properties.remove("class");

    for (final String property : properties) {
        final PropertyDescriptor expectedDescriptor = expectedWrapper.getPropertyDescriptor(property);
        final PropertyDescriptor actualDescriptor = actualWrapper.getPropertyDescriptor(property);

        if (expectedDescriptor != null && actualDescriptor != null) {
            // both have descriptors, so walk the sub-objects
            Object expectedValue = null;
            Object actualValue = null;
            try {
                expectedValue = expectedWrapper.getPropertyValue(property);
            } catch (final Exception e) {
            }
            try {
                actualValue = actualWrapper.getPropertyValue(property);
            } catch (final Exception e) {
            }

            assertDepthEquals(depth + 1, property, expectedValue, actualValue);
        } else if (expectedDescriptor != null) {
            fail("Should have '" + property + "' property on actual object, but there was none!");
        } else if (actualDescriptor != null) {
            fail("Should have '" + property + "' property on expected object, but there was none!");
        }

    }

    if (expected instanceof Object[] || actual instanceof Object[]) {
        final Object[] expectedArray = (Object[]) expected;
        final Object[] actualArray = (Object[]) actual;
        assertTrue(assertionMessage, Arrays.equals(expectedArray, actualArray));
    } else if (expected instanceof long[] || actual instanceof long[]) {
        final long[] expectedArray = (long[]) expected;
        final long[] actualArray = (long[]) actual;
        assertTrue(assertionMessage, Arrays.equals(expectedArray, actualArray));
    } else {
        expected.getClass().isPrimitive();
        assertEquals(assertionMessage, expected, actual);
    }
}

From source file:org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.java

/**
 * Abstract method defining "autowire by type" (bean properties by type) behavior.
 * <p>This is like PicoContainer default, in which there must be exactly one bean
 * of the property type in the bean factory. This makes bean factories simple to
 * configure for small namespaces, but doesn't work as well as standard Spring
 * behavior for bigger applications./*from   w w  w. j a  v  a2s .  c  om*/
 * @param beanName the name of the bean to autowire by type
 * @param mbd the merged bean definition to update through autowiring
 * @param bw the BeanWrapper from which we can obtain information about the bean
 * @param pvs the PropertyValues to register wired objects with
 */
protected void autowireByType(String beanName, AbstractBeanDefinition mbd, BeanWrapper bw,
        MutablePropertyValues pvs) {

    TypeConverter converter = getCustomTypeConverter();
    if (converter == null) {
        converter = bw;
    }

    Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
    String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
    for (String propertyName : propertyNames) {
        try {
            PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
            // Don't try autowiring by type for type Object: never makes sense,
            // even if it technically is a unsatisfied, non-simple property.
            if (Object.class != pd.getPropertyType()) {
                MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
                // Do not allow eager init for type matching in case of a prioritized post-processor.
                boolean eager = !PriorityOrdered.class.isInstance(bw.getWrappedInstance());
                DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
                Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
                if (autowiredArgument != null) {
                    pvs.add(propertyName, autowiredArgument);
                }
                for (String autowiredBeanName : autowiredBeanNames) {
                    registerDependentBean(autowiredBeanName, beanName);
                    if (logger.isTraceEnabled()) {
                        logger.trace("Autowiring by type from bean name '" + beanName + "' via property '"
                                + propertyName + "' to bean named '" + autowiredBeanName + "'");
                    }
                }
                autowiredBeanNames.clear();
            }
        } catch (BeansException ex) {
            throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex);
        }
    }
}

From source file:org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.java

/**
 * Convert the given value for the specified target property.
 *///w  ww .  jav  a  2 s.  c  o  m
@Nullable
private Object convertForProperty(@Nullable Object value, String propertyName, BeanWrapper bw,
        TypeConverter converter) {

    if (converter instanceof BeanWrapperImpl) {
        return ((BeanWrapperImpl) converter).convertForProperty(value, propertyName);
    } else {
        PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
        MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
        return converter.convertIfNecessary(value, pd.getPropertyType(), methodParam);
    }
}

From source file:org.talend.dataprep.conversions.BeanConversionService.java

/**
 * The {@link BeanUtils#copyProperties(java.lang.Object, java.lang.Object)} method does <b>NOT</b> check if parametrized type
 * are compatible when copying values, this helper method performs this additional check and ignore copy of those values.
 *
 * @param source The source bean (from which values are read).
 * @param converted The target bean (to which values are written).
 *///from w  w w.  j ava2 s  . co  m
private static void copyBean(Object source, Object converted) {
    // Find property(ies) to ignore during copy.
    List<String> discardedProperties = new LinkedList<>();
    final BeanWrapper sourceBean = new BeanWrapperImpl(source);
    final BeanWrapper targetBean = new BeanWrapperImpl(converted);
    final PropertyDescriptor[] sourceProperties = sourceBean.getPropertyDescriptors();
    for (PropertyDescriptor sourceProperty : sourceProperties) {
        if (targetBean.isWritableProperty(sourceProperty.getName())) {
            final PropertyDescriptor targetProperty = targetBean
                    .getPropertyDescriptor(sourceProperty.getName());
            final Class<?> sourcePropertyType = sourceProperty.getPropertyType();
            final Class<?> targetPropertyType = targetProperty.getPropertyType();
            final Method readMethod = sourceProperty.getReadMethod();
            if (readMethod != null) {
                final Type sourceReturnType = readMethod.getGenericReturnType();
                final Method targetPropertyWriteMethod = targetProperty.getWriteMethod();
                if (targetPropertyWriteMethod != null) {
                    final Type targetReturnType = targetPropertyWriteMethod.getParameters()[0]
                            .getParameterizedType();
                    boolean valid = Object.class.equals(targetPropertyType)
                            || sourcePropertyType.equals(targetPropertyType)
                                    && sourceReturnType.equals(targetReturnType);
                    if (!valid) {
                        discardedProperties.add(sourceProperty.getName());
                    }
                }
            } else {
                discardedProperties.add(sourceProperty.getName());
            }
        }
    }

    // Perform copy
    BeanUtils.copyProperties(source, converted,
            discardedProperties.toArray(new String[discardedProperties.size()]));
}