org.springframework.beans.BeanWrapper Java Examples

The following examples show how to use org.springframework.beans.BeanWrapper. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BSAbstractMultiCheckedElementTag.java    From dubai with MIT License 6 votes vote down vote up
/**
 * Copy & Paste, 无修正.
 */
private void writeObjectEntry(TagWriter tagWriter, String valueProperty, String labelProperty, Object item,
		int itemIndex) throws JspException {

	BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(item);
	Object renderValue;
	if (valueProperty != null) {
		renderValue = wrapper.getPropertyValue(valueProperty);
	} else if (item instanceof Enum) {
		renderValue = ((Enum<?>) item).name();
	} else {
		renderValue = item;
	}
	Object renderLabel = (labelProperty != null ? wrapper.getPropertyValue(labelProperty) : item);
	writeElementTag(tagWriter, item, renderValue, renderLabel, itemIndex);
}
 
Example #2
Source File: AbstractMultiCheckedElementTag.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private void writeObjectEntry(TagWriter tagWriter, @Nullable String valueProperty,
		@Nullable String labelProperty, Object item, int itemIndex) throws JspException {

	BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(item);
	Object renderValue;
	if (valueProperty != null) {
		renderValue = wrapper.getPropertyValue(valueProperty);
	}
	else if (item instanceof Enum) {
		renderValue = ((Enum<?>) item).name();
	}
	else {
		renderValue = item;
	}
	Object renderLabel = (labelProperty != null ? wrapper.getPropertyValue(labelProperty) : item);
	writeElementTag(tagWriter, item, renderValue, renderLabel, itemIndex);
}
 
Example #3
Source File: CustomEditorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testCustomEditorForSingleNestedProperty() {
	TestBean tb = new TestBean();
	tb.setSpouse(new TestBean());
	BeanWrapper bw = new BeanWrapperImpl(tb);
	bw.registerCustomEditor(String.class, "spouse.name", new PropertyEditorSupport() {
		@Override
		public void setAsText(String text) throws IllegalArgumentException {
			setValue("prefix" + text);
		}
	});
	bw.setPropertyValue("spouse.name", "value");
	bw.setPropertyValue("touchy", "value");
	assertEquals("prefixvalue", bw.getPropertyValue("spouse.name"));
	assertEquals("prefixvalue", tb.getSpouse().getName());
	assertEquals("value", bw.getPropertyValue("touchy"));
	assertEquals("value", tb.getTouchy());
}
 
Example #4
Source File: TilesConfigurer.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
protected DefinitionsFactory createDefinitionsFactory(TilesApplicationContext applicationContext,
		TilesRequestContextFactory contextFactory, LocaleResolver resolver) {
	if (definitionsFactoryClass != null) {
		DefinitionsFactory factory = BeanUtils.instantiate(definitionsFactoryClass);
		if (factory instanceof TilesApplicationContextAware) {
			((TilesApplicationContextAware) factory).setApplicationContext(applicationContext);
		}
		BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(factory);
		if (bw.isWritableProperty("localeResolver")) {
			bw.setPropertyValue("localeResolver", resolver);
		}
		if (bw.isWritableProperty("definitionDAO")) {
			bw.setPropertyValue("definitionDAO",
					createLocaleDefinitionDao(applicationContext, contextFactory, resolver));
		}
		if (factory instanceof Refreshable) {
			((Refreshable) factory).refresh();
		}
		return factory;
	}
	else {
		return super.createDefinitionsFactory(applicationContext, contextFactory, resolver);
	}
}
 
Example #5
Source File: AnyOneNotBlankConstraintValidator.java    From onetwo with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
	BeanWrapper bw = SpringUtils.newBeanWrapper(value);
	return Stream.of(fields).anyMatch(field->{
		Object propValue = bw.getPropertyValue(field);
		if(propValue instanceof String){
			return StringUtils.isNotBlank(propValue.toString());
		}
		return propValue!=null;
	});
	
	/*String fieldString = StringUtils.join(this.fields, ", ");
	context.disableDefaultConstraintViolation();
	String messageTemplate = context.getDefaultConstraintMessageTemplate();
	ConstraintViolationBuilder builder = context.buildConstraintViolationWithTemplate(messageTemplate);*/
}
 
Example #6
Source File: WebLogicRequestUpgradeStrategy.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
protected void handleSuccess(HttpServletRequest request, HttpServletResponse response,
		UpgradeInfo upgradeInfo, TyrusUpgradeResponse upgradeResponse) throws IOException, ServletException {

	response.setStatus(upgradeResponse.getStatus());
	upgradeResponse.getHeaders().forEach((key, value) -> response.addHeader(key, Utils.getHeaderFromList(value)));

	AsyncContext asyncContext = request.startAsync();
	asyncContext.setTimeout(-1L);

	Object nativeRequest = getNativeRequest(request);
	BeanWrapper beanWrapper = new BeanWrapperImpl(nativeRequest);
	Object httpSocket = beanWrapper.getPropertyValue("connection.connectionHandler.rawConnection");
	Object webSocket = webSocketHelper.newInstance(request, httpSocket);
	webSocketHelper.upgrade(webSocket, httpSocket, request.getServletContext());

	response.flushBuffer();

	boolean isProtected = request.getUserPrincipal() != null;
	Writer servletWriter = servletWriterHelper.newInstance(webSocket, isProtected);
	Connection connection = upgradeInfo.createConnection(servletWriter, noOpCloseListener);
	new BeanWrapperImpl(webSocket).setPropertyValue("connection", connection);
	new BeanWrapperImpl(servletWriter).setPropertyValue("connection", connection);
	webSocketHelper.registerForReadEvent(webSocket);
}
 
Example #7
Source File: TilesConfigurer.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
protected DefinitionsFactory createDefinitionsFactory(ApplicationContext applicationContext,
		LocaleResolver resolver) {

	if (definitionsFactoryClass != null) {
		DefinitionsFactory factory = BeanUtils.instantiateClass(definitionsFactoryClass);
		if (factory instanceof ApplicationContextAware) {
			((ApplicationContextAware) factory).setApplicationContext(applicationContext);
		}
		BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(factory);
		if (bw.isWritableProperty("localeResolver")) {
			bw.setPropertyValue("localeResolver", resolver);
		}
		if (bw.isWritableProperty("definitionDAO")) {
			bw.setPropertyValue("definitionDAO", createLocaleDefinitionDao(applicationContext, resolver));
		}
		return factory;
	}
	else {
		return super.createDefinitionsFactory(applicationContext, resolver);
	}
}
 
Example #8
Source File: CustomEditorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testComplexObject() {
	TestBean tb = new TestBean();
	String newName = "Rod";
	String tbString = "Kerry_34";

	BeanWrapper bw = new BeanWrapperImpl(tb);
	bw.registerCustomEditor(ITestBean.class, new TestBeanEditor());
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.addPropertyValue(new PropertyValue("age", new Integer(55)));
	pvs.addPropertyValue(new PropertyValue("name", newName));
	pvs.addPropertyValue(new PropertyValue("touchy", "valid"));
	pvs.addPropertyValue(new PropertyValue("spouse", tbString));
	bw.setPropertyValues(pvs);
	assertTrue("spouse is non-null", tb.getSpouse() != null);
	assertTrue("spouse name is Kerry and age is 34",
			tb.getSpouse().getName().equals("Kerry") && tb.getSpouse().getAge() == 34);
}
 
Example #9
Source File: TilesConfigurer.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected DefinitionsFactory createDefinitionsFactory(TilesApplicationContext applicationContext,
		TilesRequestContextFactory contextFactory, LocaleResolver resolver) {
	if (definitionsFactoryClass != null) {
		DefinitionsFactory factory = BeanUtils.instantiate(definitionsFactoryClass);
		if (factory instanceof TilesApplicationContextAware) {
			((TilesApplicationContextAware) factory).setApplicationContext(applicationContext);
		}
		BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(factory);
		if (bw.isWritableProperty("localeResolver")) {
			bw.setPropertyValue("localeResolver", resolver);
		}
		if (bw.isWritableProperty("definitionDAO")) {
			bw.setPropertyValue("definitionDAO",
					createLocaleDefinitionDao(applicationContext, contextFactory, resolver));
		}
		if (factory instanceof Refreshable) {
			((Refreshable) factory).refresh();
		}
		return factory;
	}
	else {
		return super.createDefinitionsFactory(applicationContext, contextFactory, resolver);
	}
}
 
Example #10
Source File: CustomEditorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testCharacterEditorWithAllowEmpty() {
	CharBean cb = new CharBean();
	BeanWrapper bw = new BeanWrapperImpl(cb);
	bw.registerCustomEditor(Character.class, new CharacterEditor(true));

	bw.setPropertyValue("myCharacter", new Character('c'));
	assertEquals(new Character('c'), cb.getMyCharacter());

	bw.setPropertyValue("myCharacter", "c");
	assertEquals(new Character('c'), cb.getMyCharacter());

	bw.setPropertyValue("myCharacter", "\u0041");
	assertEquals(new Character('A'), cb.getMyCharacter());

	bw.setPropertyValue("myCharacter", " ");
	assertEquals(new Character(' '), cb.getMyCharacter());

	bw.setPropertyValue("myCharacter", "");
	assertNull(cb.getMyCharacter());
}
 
Example #11
Source File: CustomEditorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testIndexedPropertiesWithListPropertyEditor() {
	IndexedTestBean bean = new IndexedTestBean();
	BeanWrapper bw = new BeanWrapperImpl(bean);
	bw.registerCustomEditor(List.class, "list", new PropertyEditorSupport() {
		@Override
		public void setAsText(String text) throws IllegalArgumentException {
			List<TestBean> result = new ArrayList<>();
			result.add(new TestBean("list" + text, 99));
			setValue(result);
		}
	});
	bw.setPropertyValue("list", "1");
	assertEquals("list1", ((TestBean) bean.getList().get(0)).getName());
	bw.setPropertyValue("list[0]", "test");
	assertEquals("test", bean.getList().get(0));
}
 
Example #12
Source File: TilesConfigurer.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
protected DefinitionsFactory createDefinitionsFactory(ApplicationContext applicationContext,
		LocaleResolver resolver) {

	if (definitionsFactoryClass != null) {
		DefinitionsFactory factory = BeanUtils.instantiate(definitionsFactoryClass);
		if (factory instanceof ApplicationContextAware) {
			((ApplicationContextAware) factory).setApplicationContext(applicationContext);
		}
		BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(factory);
		if (bw.isWritableProperty("localeResolver")) {
			bw.setPropertyValue("localeResolver", resolver);
		}
		if (bw.isWritableProperty("definitionDAO")) {
			bw.setPropertyValue("definitionDAO", createLocaleDefinitionDao(applicationContext, resolver));
		}
		return factory;
	}
	else {
		return super.createDefinitionsFactory(applicationContext, resolver);
	}
}
 
Example #13
Source File: AutowiringSpringBeanJobFactory.java    From syncope with Apache License 2.0 6 votes vote down vote up
@Override
protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
    Object job = beanFactory.getBean(bundle.getJobDetail().getKey().getName());
    if (isEligibleForPropertyPopulation(job)) {
        BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(job);
        MutablePropertyValues pvs = new MutablePropertyValues();
        if (this.schedulerContext != null) {
            pvs.addPropertyValues(this.schedulerContext);
        }
        pvs.addPropertyValues(bundle.getJobDetail().getJobDataMap());
        pvs.addPropertyValues(bundle.getTrigger().getJobDataMap());
        if (this.ignoredUnknownProperties != null) {
            for (String propName : this.ignoredUnknownProperties) {
                if (pvs.contains(propName) && !bw.isWritableProperty(propName)) {
                    pvs.removePropertyValue(propName);
                }
            }
            bw.setPropertyValues(pvs);
        } else {
            bw.setPropertyValues(pvs, true);
        }
    }
    return job;
}
 
Example #14
Source File: OptionWriter.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Renders the inner '{@code option}' tags using the supplied {@link Collection} of
 * objects as the source. The value of the {@link #valueProperty} field is used
 * when rendering the '{@code value}' of the '{@code option}' and the value of the
 * {@link #labelProperty} property is used when rendering the label.
 */
private void doRenderFromCollection(Collection<?> optionCollection, TagWriter tagWriter) throws JspException {
	for (Object item : optionCollection) {
		BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(item);
		Object value;
		if (this.valueProperty != null) {
			value = wrapper.getPropertyValue(this.valueProperty);
		}
		else if (item instanceof Enum) {
			value = ((Enum<?>) item).name();
		}
		else {
			value = item;
		}
		Object label = (this.labelProperty != null ? wrapper.getPropertyValue(this.labelProperty) : item);
		renderOption(tagWriter, item, value, label);
	}
}
 
Example #15
Source File: AbstractAutowireCapableBeanFactory.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Fill in any missing property values with references to
 * other beans in this factory if autowire is set to "byName".
 * @param beanName the name of the bean we're wiring up.
 * Useful for debugging messages; not used functionally.
 * @param mbd 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 autowireByName(
		String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {

	String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
	for (String propertyName : propertyNames) {
		if (containsBean(propertyName)) {
			Object bean = getBean(propertyName);
			pvs.add(propertyName, bean);
			registerDependentBean(propertyName, beanName);
			if (logger.isTraceEnabled()) {
				logger.trace("Added autowiring by name from bean name '" + beanName +
						"' via property '" + propertyName + "' to bean named '" + propertyName + "'");
			}
		}
		else {
			if (logger.isTraceEnabled()) {
				logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName +
						"' by name: no matching bean found");
			}
		}
	}
}
 
Example #16
Source File: AbstractAutowireCapableBeanFactory.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Fill in any missing property values with references to
 * other beans in this factory if autowire is set to "byName".
 * @param beanName the name of the bean we're wiring up.
 * Useful for debugging messages; not used functionally.
 * @param mbd 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 autowireByName(
		String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {

	String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
	for (String propertyName : propertyNames) {
		if (containsBean(propertyName)) {
			Object bean = getBean(propertyName);
			pvs.add(propertyName, bean);
			registerDependentBean(propertyName, beanName);
			if (logger.isTraceEnabled()) {
				logger.trace("Added autowiring by name from bean name '" + beanName +
						"' via property '" + propertyName + "' to bean named '" + propertyName + "'");
			}
		}
		else {
			if (logger.isTraceEnabled()) {
				logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName +
						"' by name: no matching bean found");
			}
		}
	}
}
 
Example #17
Source File: AbstractAutowireCapableBeanFactory.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Instantiate the given bean using its default constructor.
 * @param beanName the name of the bean
 * @param mbd the bean definition for the bean
 * @return a 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((PrivilegedAction<Object>) () ->
					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);
	}
}
 
Example #18
Source File: CustomEditorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testCharacterEditorWithAllowEmpty() {
	CharBean cb = new CharBean();
	BeanWrapper bw = new BeanWrapperImpl(cb);
	bw.registerCustomEditor(Character.class, new CharacterEditor(true));

	bw.setPropertyValue("myCharacter", new Character('c'));
	assertEquals(new Character('c'), cb.getMyCharacter());

	bw.setPropertyValue("myCharacter", "c");
	assertEquals(new Character('c'), cb.getMyCharacter());

	bw.setPropertyValue("myCharacter", "\u0041");
	assertEquals(new Character('A'), cb.getMyCharacter());

	bw.setPropertyValue("myCharacter", " ");
	assertEquals(new Character(' '), cb.getMyCharacter());

	bw.setPropertyValue("myCharacter", "");
	assertNull(cb.getMyCharacter());
}
 
Example #19
Source File: AbstractAutowireCapableBeanFactory.java    From blog_demos with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
	}
}
 
Example #20
Source File: CustomEditorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testCustomEditorForAllNestedStringProperties() {
	TestBean tb = new TestBean();
	tb.setSpouse(new TestBean());
	BeanWrapper bw = new BeanWrapperImpl(tb);
	bw.registerCustomEditor(String.class, new PropertyEditorSupport() {
		@Override
		public void setAsText(String text) throws IllegalArgumentException {
			setValue("prefix" + text);
		}
	});
	bw.setPropertyValue("spouse.name", "value");
	bw.setPropertyValue("touchy", "value");
	assertEquals("prefixvalue", bw.getPropertyValue("spouse.name"));
	assertEquals("prefixvalue", tb.getSpouse().getName());
	assertEquals("prefixvalue", bw.getPropertyValue("touchy"));
	assertEquals("prefixvalue", tb.getTouchy());
}
 
Example #21
Source File: AbstractAutowireCapableBeanFactory.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public Object configureBean(Object existingBean, String beanName) throws BeansException {
	markBeanAsCreated(beanName);
	BeanDefinition mbd = getMergedBeanDefinition(beanName);
	RootBeanDefinition bd = null;
	if (mbd instanceof RootBeanDefinition) {
		RootBeanDefinition rbd = (RootBeanDefinition) mbd;
		bd = (rbd.isPrototype() ? rbd : rbd.cloneBeanDefinition());
	}
	if (bd == null) {
		bd = new RootBeanDefinition(mbd);
	}
	if (!bd.isPrototype()) {
		bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
		bd.allowCaching = ClassUtils.isCacheSafe(ClassUtils.getUserClass(existingBean), getBeanClassLoader());
	}
	BeanWrapper bw = new BeanWrapperImpl(existingBean);
	initBeanWrapper(bw);
	populateBean(beanName, bd, bw);
	return initializeBean(beanName, existingBean, bd);
}
 
Example #22
Source File: AbstractAutowireCapableBeanFactory.java    From blog_demos with Apache License 2.0 6 votes vote down vote up
/**
 * Extract a filtered set of PropertyDescriptors from the given BeanWrapper,
 * excluding ignored dependency types or properties defined on ignored dependency interfaces.
 * @param bw the BeanWrapper the bean was created with
 * @param cache whether to cache filtered PropertyDescriptors for the given bean Class
 * @return the filtered PropertyDescriptors
 * @see #isExcludedFromDependencyCheck
 * @see #filterPropertyDescriptorsForDependencyCheck(BeanWrapper)
 */
protected PropertyDescriptor[] filterPropertyDescriptorsForDependencyCheck(BeanWrapper bw, boolean cache) {
	PropertyDescriptor[] filtered = this.filteredPropertyDescriptorsCache.get(bw.getWrappedClass());
	if (filtered == null) {
		if (cache) {
			synchronized (this.filteredPropertyDescriptorsCache) {
				filtered = this.filteredPropertyDescriptorsCache.get(bw.getWrappedClass());
				if (filtered == null) {
					filtered = filterPropertyDescriptorsForDependencyCheck(bw);
					this.filteredPropertyDescriptorsCache.put(bw.getWrappedClass(), filtered);
				}
			}
		}
		else {
			filtered = filterPropertyDescriptorsForDependencyCheck(bw);
		}
	}
	return filtered;
}
 
Example #23
Source File: ConvertedDatatablesData.java    From springlets with Apache License 2.0 6 votes vote down vote up
private static Map<String, Object> convert(Object value, ConversionService conversionService) {

    BeanWrapper bean = new BeanWrapperImpl(value);
    PropertyDescriptor[] properties = bean.getPropertyDescriptors();
    Map<String, Object> convertedValue = new HashMap<>(properties.length);

    for (int i = 0; i < properties.length; i++) {
      String name = properties[i].getName();
      Object propertyValue = bean.getPropertyValue(name);
      if (propertyValue != null
          && conversionService.canConvert(propertyValue.getClass(), String.class)) {
        TypeDescriptor source = bean.getPropertyTypeDescriptor(name);
        String convertedPropertyValue =
            (String) conversionService.convert(propertyValue, source, TYPE_STRING);
        convertedValue.put(name, convertedPropertyValue);
      }
    }

    return convertedValue;
  }
 
Example #24
Source File: CukeUtils.java    From objectlabkit with Apache License 2.0 6 votes vote down vote up
private static <T> String convertToString(final List<T> actualRowValues, final List<String> propertiesToCompare) {
    final List<List<Object>> rawRows = new ArrayList<>();
    rawRows.add(propertiesToCompare.stream().collect(Collectors.toList()));

    for (final T actualRow : actualRowValues) {
        final BeanWrapper src = new BeanWrapperImpl(actualRow);
        rawRows.add(propertiesToCompare.stream().map(p -> {
            final Object propertyValue = src.getPropertyValue(p);
            if (propertyValue == null) {
                return "";
            } else if (src.getPropertyTypeDescriptor(p).getObjectType().isAssignableFrom(BigDecimal.class)) {
                return ((BigDecimal) propertyValue).stripTrailingZeros().toPlainString();
            }
            return propertyValue;
        }).collect(Collectors.toList()));
    }
    return DataTable.create(rawRows).toString();
}
 
Example #25
Source File: CustomEditorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testArrayToStringConversion() throws PropertyVetoException {
	TestBean tb = new TestBean();
	BeanWrapper bw = new BeanWrapperImpl(tb);
	bw.registerCustomEditor(String.class, new PropertyEditorSupport() {
		@Override
		public void setAsText(String text) throws IllegalArgumentException {
			setValue("-" + text + "-");
		}
	});
	bw.setPropertyValue("name", new String[] {"a", "b"});
	assertEquals("-a,b-", tb.getName());
}
 
Example #26
Source File: ConfigurationImpl.java    From walkmod-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void populate(Object element, Map<?, ?> parameters) {
    if (element != null) {
        BeanWrapper bw = new BeanWrapperImpl(element);
        if (this.parameters != null) {
            bw.setPropertyValues(this.parameters);
        }
        bw.setPropertyValues(parameters);
    }
}
 
Example #27
Source File: BeanConversionService.java    From data-prep with Apache License 2.0 5 votes vote down vote up
private static List<String> getDiscardedProperties(Object source, Object converted) {
    final String cacheKey = source.getClass().getName() + " to " + converted.getClass().getName();
    if (discardedPropertiesCache.containsKey(cacheKey)) {
        return discardedPropertiesCache.get(cacheKey);
    }

    final 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());
            }
        }
    }
    discardedPropertiesCache.put(cacheKey, unmodifiableList(discardedProperties));

    return discardedProperties;
}
 
Example #28
Source File: QuartzJobBean.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * This implementation applies the passed-in job data map as bean property
 * values, and delegates to {@code executeInternal} afterwards.
 * @see #executeInternal
 */
@Override
public final void execute(JobExecutionContext context) throws JobExecutionException {
	try {
		BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
		MutablePropertyValues pvs = new MutablePropertyValues();
		pvs.addPropertyValues(context.getScheduler().getContext());
		pvs.addPropertyValues(context.getMergedJobDataMap());
		bw.setPropertyValues(pvs, true);
	}
	catch (SchedulerException ex) {
		throw new JobExecutionException(ex);
	}
	executeInternal(context);
}
 
Example #29
Source File: BeanUtil.java    From newbee-mall with GNU General Public License v3.0 5 votes vote down vote up
public static <T> T toBean(Map<String, Object> map, Class<T> beanType) {
    BeanWrapper beanWrapper = new BeanWrapperImpl(beanType);
    map.forEach((key, value) -> {
        if (beanWrapper.isWritableProperty(key)) {
            beanWrapper.setPropertyValue(key, value);
        }
    });
    return (T) beanWrapper.getWrappedInstance();
}
 
Example #30
Source File: AbstractAutowireCapableBeanFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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.
 * @param beanName the name of the bean to autowire by type
 * @param mbd the merged bean definition to update through autowiring
 * @param bw 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<String>(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.isAssignableFrom(bw.getWrappedClass());
				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.isDebugEnabled()) {
						logger.debug("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);
		}
	}
}