Search in sources :

Example 81 with BeanWrapperImpl

use of org.springframework.beans.BeanWrapperImpl in project spring-data-commons by spring-projects.

the class DomainClassConverterIntegrationTests method findsRepositoryFactories.

@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void findsRepositoryFactories() {
    DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory() {

        @Override
        protected BeanWrapper instantiateBean(String beanName, RootBeanDefinition mbd) {
            return beanName.equals("repoFactory") ? new BeanWrapperImpl(factory) : super.instantiateBean(beanName, mbd);
        }
    };
    beanFactory.registerBeanDefinition("postProcessor", new RootBeanDefinition(PredictingProcessor.class));
    beanFactory.registerBeanDefinition("repoFactory", new RootBeanDefinition(RepositoryFactoryBeanSupport.class));
    doReturn(Person.class).when(information).getDomainType();
    doReturn(Serializable.class).when(information).getIdType();
    doReturn(PersonRepository.class).when(factory).getObjectType();
    doReturn(information).when(factory).getRepositoryInformation();
    GenericApplicationContext context = new GenericApplicationContext(beanFactory);
    context.refresh();
    assertThat(context.getBeansOfType(RepositoryFactoryInformation.class).values()).hasSize(1);
    DomainClassConverter converter = new DomainClassConverter(new DefaultConversionService());
    converter.setApplicationContext(context);
    assertThat(converter.matches(TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(Person.class))).isTrue();
}
Also used : RepositoryFactoryBeanSupport(org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport) GenericApplicationContext(org.springframework.context.support.GenericApplicationContext) BeanWrapperImpl(org.springframework.beans.BeanWrapperImpl) DefaultListableBeanFactory(org.springframework.beans.factory.support.DefaultListableBeanFactory) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) RepositoryFactoryInformation(org.springframework.data.repository.core.support.RepositoryFactoryInformation) DefaultConversionService(org.springframework.core.convert.support.DefaultConversionService) Test(org.junit.Test)

Example 82 with BeanWrapperImpl

use of org.springframework.beans.BeanWrapperImpl in project x-pipe by ctripcorp.

the class BeanUtils method getNullPropertyNames.

private static String[] getNullPropertyNames(Object source) {
    final BeanWrapper src = new BeanWrapperImpl(source);
    PropertyDescriptor[] pds = src.getPropertyDescriptors();
    Set<String> emptyNames = new HashSet<String>();
    for (PropertyDescriptor pd : pds) {
        Object srcValue = src.getPropertyValue(pd.getName());
        if (srcValue == null)
            emptyNames.add(pd.getName());
    }
    String[] result = new String[emptyNames.size()];
    return emptyNames.toArray(result);
}
Also used : BeanWrapper(org.springframework.beans.BeanWrapper) BeanWrapperImpl(org.springframework.beans.BeanWrapperImpl) PropertyDescriptor(java.beans.PropertyDescriptor) HashSet(java.util.HashSet)

Example 83 with BeanWrapperImpl

use of org.springframework.beans.BeanWrapperImpl in project service-proxy by membrane.

the class MCUtil method addXML.

private static void addXML(Object object, String id, XMLStreamWriter xew, SerializationContext sc) throws XMLStreamException {
    if (object == null)
        throw new InvalidParameterException("'object' must not be null.");
    Class<? extends Object> clazz = object.getClass();
    MCElement e = clazz.getAnnotation(MCElement.class);
    if (e == null)
        throw new IllegalArgumentException("'object' must be @MCElement-annotated.");
    BeanWrapperImpl src = new BeanWrapperImpl(object);
    xew.writeStartElement(e.name());
    if (id != null)
        xew.writeAttribute("id", id);
    HashSet<String> attributes = new HashSet<String>();
    for (Method m : clazz.getMethods()) {
        if (!m.getName().startsWith("set"))
            continue;
        String propertyName = AnnotUtils.dejavaify(m.getName().substring(3));
        MCAttribute a = m.getAnnotation(MCAttribute.class);
        if (a != null) {
            Object value = src.getPropertyValue(propertyName);
            String str;
            if (value == null)
                continue;
            else if (value instanceof String)
                str = (String) value;
            else if (value instanceof Boolean)
                str = ((Boolean) value).toString();
            else if (value instanceof Integer)
                str = ((Integer) value).toString();
            else if (value instanceof Long)
                str = ((Long) value).toString();
            else if (value instanceof Enum<?>)
                str = value.toString();
            else {
                MCElement el = value.getClass().getAnnotation(MCElement.class);
                if (el != null) {
                    str = defineBean(sc, value, null, true);
                } else {
                    str = "?";
                    sc.incomplete = true;
                }
            }
            if (a.attributeName().length() > 0)
                propertyName = a.attributeName();
            attributes.add(propertyName);
            xew.writeAttribute(propertyName, str);
        }
    }
    for (Method m : clazz.getMethods()) {
        if (!m.getName().startsWith("set"))
            continue;
        String propertyName = AnnotUtils.dejavaify(m.getName().substring(3));
        MCOtherAttributes o = m.getAnnotation(MCOtherAttributes.class);
        if (o != null) {
            Object value = src.getPropertyValue(propertyName);
            if (value instanceof Map<?, ?>) {
                Map<?, ?> map = (Map<?, ?>) value;
                for (Map.Entry<?, ?> entry : map.entrySet()) {
                    Object key = entry.getKey();
                    Object val = entry.getValue();
                    if (!(key instanceof String) || !(val instanceof String)) {
                        sc.incomplete = true;
                        key = "incompleteAttributes";
                        val = "?";
                    }
                    if (attributes.contains(key))
                        continue;
                    attributes.add((String) key);
                    xew.writeAttribute((String) key, (String) val);
                }
            } else {
                xew.writeAttribute("incompleteAttributes", "?");
                sc.incomplete = true;
            }
        }
    }
    List<Method> childElements = new ArrayList<Method>();
    for (Method m : clazz.getMethods()) {
        if (!m.getName().startsWith("set"))
            continue;
        String propertyName = AnnotUtils.dejavaify(m.getName().substring(3));
        MCChildElement c = m.getAnnotation(MCChildElement.class);
        if (c != null) {
            childElements.add(m);
        }
        MCTextContent t = m.getAnnotation(MCTextContent.class);
        if (t != null) {
            Object value = src.getPropertyValue(propertyName);
            if (value == null) {
                continue;
            } else if (value instanceof String) {
                xew.writeCharacters((String) value);
            } else {
                xew.writeCharacters("?");
                sc.incomplete = true;
            }
        }
    }
    Collections.sort(childElements, new Comparator<Method>() {

        @Override
        public int compare(Method o1, Method o2) {
            MCChildElement c1 = o1.getAnnotation(MCChildElement.class);
            MCChildElement c2 = o2.getAnnotation(MCChildElement.class);
            return c1.order() - c2.order();
        }
    });
    for (Method m : childElements) {
        String propertyName = AnnotUtils.dejavaify(m.getName().substring(3));
        Object value = src.getPropertyValue(propertyName);
        if (value != null) {
            if (value instanceof Collection<?>) {
                for (Object item : (Collection<?>) value) addXML(item, null, xew, sc);
            } else {
                addXML(value, null, xew, sc);
            }
        }
    }
    xew.writeEndElement();
}
Also used : MCChildElement(com.predic8.membrane.annot.MCChildElement) BeanWrapperImpl(org.springframework.beans.BeanWrapperImpl) ArrayList(java.util.ArrayList) InvalidParameterException(java.security.InvalidParameterException) MCElement(com.predic8.membrane.annot.MCElement) MCAttribute(com.predic8.membrane.annot.MCAttribute) HashSet(java.util.HashSet) MCTextContent(com.predic8.membrane.annot.MCTextContent) Method(java.lang.reflect.Method) MCOtherAttributes(com.predic8.membrane.annot.MCOtherAttributes) Collection(java.util.Collection) HashMap(java.util.HashMap) Map(java.util.Map)

Example 84 with BeanWrapperImpl

use of org.springframework.beans.BeanWrapperImpl in project data-prep by Talend.

the class BeanConversionService method copyBean.

/**
 * 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).
 */
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()]));
}
Also used : BeanWrapper(org.springframework.beans.BeanWrapper) Type(java.lang.reflect.Type) BeanWrapperImpl(org.springframework.beans.BeanWrapperImpl) PropertyDescriptor(java.beans.PropertyDescriptor) Method(java.lang.reflect.Method)

Example 85 with BeanWrapperImpl

use of org.springframework.beans.BeanWrapperImpl in project summerb by skarpushin.

the class GenericCrudServiceTestTemplate method testBeanWrapper.

@Test
public void testBeanWrapper() throws Exception {
    TestDto1 dto = new TestDto1();
    dto.setActive(true);
    dto.setEnv("uat");
    dto.setLinkToFullDonwload("link-to-full-download");
    dto.setMajorVersion(2);
    dto.setMinorVersion(1);
    BeanWrapperImpl w = new BeanWrapperImpl(dto);
    assertTrue(Integer.valueOf(2).equals(w.getPropertyValue("majorVersion")));
    assertTrue("link-to-full-download".equals(w.getPropertyValue("linkToFullDonwload")));
}
Also used : BeanWrapperImpl(org.springframework.beans.BeanWrapperImpl) Test(org.junit.Test)

Aggregations

BeanWrapperImpl (org.springframework.beans.BeanWrapperImpl)113 BeanWrapper (org.springframework.beans.BeanWrapper)75 Test (org.junit.jupiter.api.Test)32 NumberTestBean (org.springframework.beans.testfixture.beans.NumberTestBean)21 BooleanTestBean (org.springframework.beans.testfixture.beans.BooleanTestBean)20 Test (org.junit.Test)19 ITestBean (org.springframework.beans.testfixture.beans.ITestBean)17 IndexedTestBean (org.springframework.beans.testfixture.beans.IndexedTestBean)17 TestBean (org.springframework.beans.testfixture.beans.TestBean)17 PropertyDescriptor (java.beans.PropertyDescriptor)14 PropertyEditorSupport (java.beans.PropertyEditorSupport)14 Assertions.assertThatIllegalArgumentException (org.assertj.core.api.Assertions.assertThatIllegalArgumentException)14 MutablePropertyValues (org.springframework.beans.MutablePropertyValues)12 HashSet (java.util.HashSet)11 BeansException (org.springframework.beans.BeansException)9 ArrayList (java.util.ArrayList)5 Map (java.util.Map)5 BeanCreationException (org.springframework.beans.factory.BeanCreationException)5 ConstructorArgumentValues (org.springframework.beans.factory.config.ConstructorArgumentValues)5 IOException (java.io.IOException)4