Search in sources :

Example 76 with BeanWrapperImpl

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

the class AbstractAutowireCapableBeanFactory method instantiateBean.

/**
	 * Instantiate the given bean using its default constructor.
	 * @param beanName the name of the bean
	 * @param mbd the bean definition for the bean
	 * @return BeanWrapper for the new instance
	 */
protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
    try {
        Object beanInstance;
        final BeanFactory parent = this;
        if (System.getSecurityManager() != null) {
            beanInstance = AccessController.doPrivileged(new PrivilegedAction<Object>() {

                @Override
                public Object run() {
                    return getInstantiationStrategy().instantiate(mbd, beanName, parent);
                }
            }, getAccessControlContext());
        } else {
            beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
        }
        BeanWrapper bw = new BeanWrapperImpl(beanInstance);
        initBeanWrapper(bw);
        return bw;
    } catch (Throwable ex) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
    }
}
Also used : BeanCreationException(org.springframework.beans.factory.BeanCreationException) BeanWrapper(org.springframework.beans.BeanWrapper) BeanWrapperImpl(org.springframework.beans.BeanWrapperImpl) PrivilegedAction(java.security.PrivilegedAction) AutowireCapableBeanFactory(org.springframework.beans.factory.config.AutowireCapableBeanFactory) BeanFactory(org.springframework.beans.factory.BeanFactory) ConfigurableBeanFactory(org.springframework.beans.factory.config.ConfigurableBeanFactory)

Example 77 with BeanWrapperImpl

use of org.springframework.beans.BeanWrapperImpl in project opennms by OpenNMS.

the class OnmsRestService method getBeanWrapperForClass.

protected static BeanWrapper getBeanWrapperForClass(final Class<?> criteriaClass) {
    final BeanWrapper wrapper = new BeanWrapperImpl(criteriaClass);
    wrapper.registerCustomEditor(XMLGregorianCalendar.class, new StringXmlCalendarPropertyEditor());
    wrapper.registerCustomEditor(java.util.Date.class, new ISO8601DateEditor());
    wrapper.registerCustomEditor(java.net.InetAddress.class, new InetAddressTypeEditor());
    wrapper.registerCustomEditor(OnmsSeverity.class, new OnmsSeverityEditor());
    wrapper.registerCustomEditor(PrimaryType.class, new PrimaryTypeEditor());
    return wrapper;
}
Also used : InetAddressTypeEditor(org.opennms.netmgt.model.InetAddressTypeEditor) BeanWrapper(org.springframework.beans.BeanWrapper) ISO8601DateEditor(org.opennms.web.api.ISO8601DateEditor) BeanWrapperImpl(org.springframework.beans.BeanWrapperImpl) PrimaryTypeEditor(org.opennms.netmgt.model.PrimaryTypeEditor) StringXmlCalendarPropertyEditor(org.opennms.netmgt.provision.persist.StringXmlCalendarPropertyEditor) OnmsSeverityEditor(org.opennms.netmgt.model.OnmsSeverityEditor)

Example 78 with BeanWrapperImpl

use of org.springframework.beans.BeanWrapperImpl in project MyPig by weifuchow.

the class BeanUtilsExt method getNullPropertyNames.

public static String[] getNullPropertyNames(Object source) {
    final BeanWrapper src = new BeanWrapperImpl(source);
    java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
    Set<String> emptyNames = new HashSet<String>();
    for (java.beans.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) HashSet(java.util.HashSet)

Example 79 with BeanWrapperImpl

use of org.springframework.beans.BeanWrapperImpl in project opennms by OpenNMS.

the class XmlTest method assertDepthEquals.

private static void assertDepthEquals(final int depth, final String propertyName, final Object expected, Object actual) {
    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<>();
    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 if (expected instanceof int[] || actual instanceof int[]) {
        final int[] expectedArray = (int[]) expected;
        final int[] actualArray = (int[]) actual;
        assertTrue(assertionMessage, Arrays.equals(expectedArray, actualArray));
    } else if (expected instanceof byte[] || actual instanceof byte[]) {
        final byte[] expectedArray = (byte[]) expected;
        final byte[] actualArray = (byte[]) actual;
        assertTrue(assertionMessage, Arrays.equals(expectedArray, actualArray));
    } else {
        expected.getClass().isPrimitive();
        assertEquals(assertionMessage, expected, actual);
    }
}
Also used : BeanWrapper(org.springframework.beans.BeanWrapper) BeanWrapperImpl(org.springframework.beans.BeanWrapperImpl) PropertyDescriptor(java.beans.PropertyDescriptor) TreeSet(java.util.TreeSet) XPathExpressionException(javax.xml.xpath.XPathExpressionException) IOException(java.io.IOException)

Example 80 with BeanWrapperImpl

use of org.springframework.beans.BeanWrapperImpl in project webanno by webanno.

the class PreferencesUtil method loadPreferences.

/**
 * Set annotation preferences of users for a given project such as window size, annotation
 * layers,... reading from the file system.
 *
 * @param aUsername
 *            The {@link User} for whom we need to read the preference (preferences are stored
 *            per user)
 * @param aRepositoryService the repository service.
 * @param aAnnotationService the annotation service.
 * @param aBModel
 *            The {@link AnnotatorState} that will be populated with preferences from the
 *            file
 * @param aMode the mode.
 * @throws BeansException hum?
 * @throws IOException hum?
 */
public static void loadPreferences(String aUsername, SettingsService aSettingsService, ProjectService aRepositoryService, AnnotationSchemaService aAnnotationService, AnnotatorState aBModel, Mode aMode) throws BeansException, IOException {
    AnnotationPreference preference = new AnnotationPreference();
    BeanWrapper wrapper = new BeanWrapperImpl(preference);
    // get annotation preference from file system
    try {
        Properties props = aRepositoryService.loadUserSettings(aUsername, aBModel.getProject());
        for (Entry<Object, Object> entry : props.entrySet()) {
            String property = entry.getKey().toString();
            int index = property.indexOf(".");
            String propertyName = property.substring(index + 1);
            String mode = property.substring(0, index);
            if (wrapper.isWritableProperty(propertyName) && mode.equals(aMode.getName())) {
                if (AnnotationPreference.class.getDeclaredField(propertyName).getGenericType() instanceof ParameterizedType) {
                    if (entry.getValue().toString().startsWith("[")) {
                        // its a list
                        List<String> value = Arrays.asList(StringUtils.replaceChars(entry.getValue().toString(), "[]", "").split(","));
                        if (!value.get(0).equals("")) {
                            wrapper.setPropertyValue(propertyName, value);
                        }
                    } else if (entry.getValue().toString().startsWith("{")) {
                        // its a map
                        String s = StringUtils.replaceChars(entry.getValue().toString(), "{}", "");
                        Map<String, String> value = Arrays.stream(s.split(",")).map(x -> x.split("=")).collect(Collectors.toMap(x -> x[0], x -> x[1]));
                        wrapper.setPropertyValue(propertyName, value);
                    }
                } else {
                    wrapper.setPropertyValue(propertyName, entry.getValue());
                }
            }
        }
        // set layers according to preferences
        List<AnnotationLayer> enabledLayers = aAnnotationService.listAnnotationLayer(aBModel.getProject()).stream().filter(// only allow enabled layers
        l -> l.isEnabled()).collect(Collectors.toList());
        List<Long> hiddenLayerIds = preference.getHiddenAnnotationLayerIds();
        enabledLayers = enabledLayers.stream().filter(l -> !hiddenLayerIds.contains(l.getId())).collect(Collectors.toList());
        aBModel.setAnnotationLayers(enabledLayers);
        // Get color preferences for each layer, init with legacy if not found
        Map<Long, ColoringStrategyType> colorPerLayer = preference.getColorPerLayer();
        for (AnnotationLayer layer : aAnnotationService.listAnnotationLayer(aBModel.getProject())) {
            if (!colorPerLayer.containsKey(layer.getId())) {
                colorPerLayer.put(layer.getId(), ColoringStrategyType.LEGACY);
            }
        }
    }// no preference found
     catch (Exception e) {
        // If no layer preferences are defined,
        // then just assume all enabled layers are preferred
        List<AnnotationLayer> enabledLayers = aAnnotationService.listAnnotationLayer(aBModel.getProject()).stream().filter(// only allow enabled layers
        l -> l.isEnabled()).collect(Collectors.toList());
        aBModel.setAnnotationLayers(enabledLayers);
        preference.setWindowSize(aSettingsService.getNumberOfSentences());
        // add default coloring strategy
        Map<Long, ColoringStrategyType> colorPerLayer = new HashMap<>();
        for (AnnotationLayer layer : aBModel.getAnnotationLayers()) {
            colorPerLayer.put(layer.getId(), ColoringStrategy.getBestInitialStrategy(aAnnotationService, layer, preference));
        }
        preference.setColorPerLayer(colorPerLayer);
    }
    aBModel.setPreferences(preference);
}
Also used : Arrays(java.util.Arrays) Properties(java.util.Properties) ProjectService(de.tudarmstadt.ukp.clarin.webanno.api.ProjectService) AnnotatorState(de.tudarmstadt.ukp.clarin.webanno.api.annotation.model.AnnotatorState) BeanWrapper(org.springframework.beans.BeanWrapper) IOException(java.io.IOException) HashMap(java.util.HashMap) BeansException(org.springframework.beans.BeansException) ColoringStrategy(de.tudarmstadt.ukp.clarin.webanno.api.annotation.coloring.ColoringStrategy) Mode(de.tudarmstadt.ukp.clarin.webanno.model.Mode) Collectors(java.util.stream.Collectors) StringUtils(org.apache.commons.lang3.StringUtils) BeanWrapperImpl(org.springframework.beans.BeanWrapperImpl) SettingsService(de.tudarmstadt.ukp.clarin.webanno.api.SettingsService) AnnotationSchemaService(de.tudarmstadt.ukp.clarin.webanno.api.AnnotationSchemaService) List(java.util.List) ParameterizedType(java.lang.reflect.ParameterizedType) User(de.tudarmstadt.ukp.clarin.webanno.security.model.User) AnnotationPreference(de.tudarmstadt.ukp.clarin.webanno.api.annotation.model.AnnotationPreference) AnnotationLayer(de.tudarmstadt.ukp.clarin.webanno.model.AnnotationLayer) Map(java.util.Map) Entry(java.util.Map.Entry) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) ColoringStrategyType(de.tudarmstadt.ukp.clarin.webanno.api.annotation.coloring.ColoringStrategy.ColoringStrategyType) BeanWrapperImpl(org.springframework.beans.BeanWrapperImpl) Properties(java.util.Properties) AnnotationLayer(de.tudarmstadt.ukp.clarin.webanno.model.AnnotationLayer) IOException(java.io.IOException) BeansException(org.springframework.beans.BeansException) ParameterizedType(java.lang.reflect.ParameterizedType) BeanWrapper(org.springframework.beans.BeanWrapper) List(java.util.List) AnnotationPreference(de.tudarmstadt.ukp.clarin.webanno.api.annotation.model.AnnotationPreference) HashMap(java.util.HashMap) Map(java.util.Map) ColoringStrategyType(de.tudarmstadt.ukp.clarin.webanno.api.annotation.coloring.ColoringStrategy.ColoringStrategyType)

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