org.springframework.beans.BeanWrapperImpl Java Examples

The following examples show how to use org.springframework.beans.BeanWrapperImpl. 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: WebLogicRequestUpgradeStrategy.java    From spring-analysis-note with MIT License 8 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 #2
Source File: QuartzSchedulerBeanRegistrar.java    From light-task-scheduler with Apache License 2.0 6 votes vote down vote up
@Override
public void registerCustomEditors(PropertyEditorRegistry registry) {
    if (!(registry instanceof BeanWrapperImpl)) {
        return;
    }

    BeanWrapperImpl beanWrapper = (BeanWrapperImpl) registry;

    Class<?> clazz = null;
    try {
        clazz = Class.forName(SchedulerFactoryBean, true, registry.getClass().getClassLoader());
    } catch (Throwable e) {
        LOGGER.info("cannot find class for " + SchedulerFactoryBean, e);
    }

    if (null == clazz
            || null == beanWrapper.getWrappedClass()
            || !clazz.isAssignableFrom(beanWrapper.getWrappedClass())) {
        return;
    }

    registry.registerCustomEditor(Object.class, "triggers",
            new QuartzSchedulerBeanTargetEditor(context));
}
 
Example #3
Source File: SpringValidatorAdapterTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
public boolean isValid(Object value, ConstraintValidatorContext context) {
	BeanWrapper beanWrapper = new BeanWrapperImpl(value);
	Object fieldValue = beanWrapper.getPropertyValue(field);
	Object comparingFieldValue = beanWrapper.getPropertyValue(comparingField);
	boolean matched = ObjectUtils.nullSafeEquals(fieldValue, comparingFieldValue);
	if (matched) {
		return true;
	}
	else {
		context.disableDefaultConstraintViolation();
		context.buildConstraintViolationWithTemplate(message)
				.addPropertyNode(field)
				.addConstraintViolation();
		return false;
	}
}
 
Example #4
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 #5
Source File: GroovyBeanDefinitionWrapper.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
protected AbstractBeanDefinition createBeanDefinition() {
	AbstractBeanDefinition bd = new GenericBeanDefinition();
	bd.setBeanClass(this.clazz);
	if (!CollectionUtils.isEmpty(this.constructorArgs)) {
		ConstructorArgumentValues cav = new ConstructorArgumentValues();
		for (Object constructorArg : this.constructorArgs) {
			cav.addGenericArgumentValue(constructorArg);
		}
		bd.setConstructorArgumentValues(cav);
	}
	if (this.parentName != null) {
		bd.setParentName(this.parentName);
	}
	this.definitionWrapper = new BeanWrapperImpl(bd);
	return bd;
}
 
Example #6
Source File: UifViewBeanWrapper.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
 * Overridden to copy property editor registration to the new bean wrapper.
 *
 * <p>This is necessary because spring only copies over the editors when a new bean wrapper is
 * created. The wrapper is then cached and use for subsequent calls. But the get calls could bring in
 * new custom editors we need to copy.</p>
 *
 * {@inheritDoc}
 */
@Override
protected BeanWrapperImpl getBeanWrapperForPropertyPath(String propertyPath) {
    BeanWrapperImpl beanWrapper = super.getBeanWrapperForPropertyPath(propertyPath);

    PropertyTokenHolder tokens = getPropertyNameTokens(propertyPath);
    String canonicalName = tokens.canonicalName;

    int pos = PropertyAccessorUtils.getFirstNestedPropertySeparatorIndex(canonicalName);
    if (pos != -1) {
        canonicalName = canonicalName.substring(0, pos);
    }

    copyCustomEditorsTo(beanWrapper, canonicalName);

    return beanWrapper;
}
 
Example #7
Source File: CustomEditorTests.java    From spring-analysis-note with MIT License 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 #8
Source File: BeanInfoTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testComplexObject() {
	ValueBean bean = new ValueBean();
	BeanWrapper bw = new BeanWrapperImpl(bean);
	Integer value = new Integer(1);

	bw.setPropertyValue("value", value);
	assertEquals("value not set correctly", bean.getValue(), value);

	value = new Integer(2);
	bw.setPropertyValue("value", value.toString());
	assertEquals("value not converted", bean.getValue(), value);

	bw.setPropertyValue("value", null);
	assertNull("value not null", bean.getValue());

	bw.setPropertyValue("value", "");
	assertNull("value not converted to null", bean.getValue());
}
 
Example #9
Source File: GroovyBeanDefinitionWrapper.java    From spring-analysis-note with MIT License 6 votes vote down vote up
protected AbstractBeanDefinition createBeanDefinition() {
	AbstractBeanDefinition bd = new GenericBeanDefinition();
	bd.setBeanClass(this.clazz);
	if (!CollectionUtils.isEmpty(this.constructorArgs)) {
		ConstructorArgumentValues cav = new ConstructorArgumentValues();
		for (Object constructorArg : this.constructorArgs) {
			cav.addGenericArgumentValue(constructorArg);
		}
		bd.setConstructorArgumentValues(cav);
	}
	if (this.parentName != null) {
		bd.setParentName(this.parentName);
	}
	this.definitionWrapper = new BeanWrapperImpl(bd);
	return bd;
}
 
Example #10
Source File: SearchableConvertUtils.java    From es with Apache License 2.0 6 votes vote down vote up
/**
 * @param search      查询条件
 * @param entityClass 实体类型
 * @param <T>
 */
public static <T> void convertSearchValueToEntityValue(final Searchable search, final Class<T> entityClass) {

    if (search.isConverted()) {
        return;
    }

    Collection<SearchFilter> searchFilters = search.getSearchFilters();
    BeanWrapperImpl beanWrapper = new BeanWrapperImpl(entityClass);
    beanWrapper.setAutoGrowNestedPaths(true);
    beanWrapper.setConversionService(getConversionService());

    for (SearchFilter searchFilter : searchFilters) {
        convertSearchValueToEntityValue(beanWrapper, searchFilter);


    }
}
 
Example #11
Source File: BeanUtils.java    From spring-content with Apache License 2.0 6 votes vote down vote up
/**
 * Sets object's field annotated with annotationClass to value only if the condition
 * matches.
 *
 * @param domainObj the object containing the field
 * @param annotationClass the annotation to look for
 * @param value the value to set
 * @param condition the condition that must be satisfied to allow the match
 */
public static void setFieldWithAnnotationConditionally(Object domainObj,
		Class<? extends Annotation> annotationClass, Object value,
		Condition condition) {

	Field field = findFieldWithAnnotation(domainObj, annotationClass);
	if (field != null && field.getAnnotation(annotationClass) != null
			&& condition.matches(field)) {
		try {
			PropertyDescriptor descriptor = org.springframework.beans.BeanUtils
					.getPropertyDescriptor(domainObj.getClass(), field.getName());
			if (descriptor != null) {
				BeanWrapper wrapper = new BeanWrapperImpl(domainObj);
				wrapper.setPropertyValue(field.getName(), value);
				return;
			}
			else {
				ReflectionUtils.setField(field, domainObj, value);
			}
			return;
		}
		catch (IllegalArgumentException iae) {
		}
	}
}
 
Example #12
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 #13
Source File: CustomEditorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testCharacterEditor() {
	CharBean cb = new CharBean();
	BeanWrapper bw = new BeanWrapperImpl(cb);

	bw.setPropertyValue("myChar", new Character('c'));
	assertEquals('c', cb.getMyChar());

	bw.setPropertyValue("myChar", "c");
	assertEquals('c', cb.getMyChar());

	bw.setPropertyValue("myChar", "\u0041");
	assertEquals('A', cb.getMyChar());

	bw.setPropertyValue("myChar", "\\u0022");
	assertEquals('"', cb.getMyChar());

	CharacterEditor editor = new CharacterEditor(false);
	editor.setAsText("M");
	assertEquals("M", editor.getAsText());
}
 
Example #14
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 #15
Source File: CustomEditorTests.java    From spring-analysis-note 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 #16
Source File: CustomEditorTests.java    From spring4-understanding with Apache License 2.0 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<TestBean>();
			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 #17
Source File: CmisRepositoryConfigurationImpl.java    From spring-content with Apache License 2.0 6 votes vote down vote up
@Override
public List getChildren(Object parent) {
	List<Object> children = new ArrayList<>();

	for (CrudRepository repo : repositories) {
		String parentProp = null;
		Iterable candidates = repo.findAll();
		for (Object candidate : candidates) {
			if (parentProp == null) {
				parentProp = CmisServiceBridge.findParentProperty(candidate);
			}
			if (parentProp != null) {
				BeanWrapper wrapper = new BeanWrapperImpl(candidate);
				PropertyDescriptor descriptor = wrapper.getPropertyDescriptor(parentProp);
				if (descriptor != null && descriptor.getReadMethod() != null) {
					Object actualParent = ReflectionUtils.invokeMethod(descriptor.getReadMethod(), candidate);
					if (Objects.equals(parent, actualParent)) {
						children.add(candidate);
					}
				}
			}
		}
	}

	return children;
}
 
Example #18
Source File: SpringValidatorAdapterTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
public boolean isValid(Object value, ConstraintValidatorContext context) {
	BeanWrapper beanWrapper = new BeanWrapperImpl(value);
	Object fieldValue = beanWrapper.getPropertyValue(field);
	Object comparingFieldValue = beanWrapper.getPropertyValue(comparingField);
	boolean matched = ObjectUtils.nullSafeEquals(fieldValue, comparingFieldValue);
	if (matched) {
		return true;
	}
	else {
		context.disableDefaultConstraintViolation();
		context.buildConstraintViolationWithTemplate(message)
				.addPropertyNode(field)
				.addConstraintViolation();
		return false;
	}
}
 
Example #19
Source File: AbstractAutowireCapableBeanFactory.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public Object autowire(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException {
	// Use non-singleton bean definition, to avoid registering bean as dependent bean.
	final RootBeanDefinition bd = new RootBeanDefinition(beanClass, autowireMode, dependencyCheck);
	bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
	if (bd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR) {
		return autowireConstructor(beanClass.getName(), bd, null, null).getWrappedInstance();
	}
	else {
		Object bean;
		final BeanFactory parent = this;
		if (System.getSecurityManager() != null) {
			bean = AccessController.doPrivileged((PrivilegedAction<Object>) () ->
					getInstantiationStrategy().instantiate(bd, null, parent),
					getAccessControlContext());
		}
		else {
			bean = getInstantiationStrategy().instantiate(bd, null, parent);
		}
		populateBean(beanClass.getName(), bd, new BeanWrapperImpl(bean));
		return bean;
	}
}
 
Example #20
Source File: AbstractAutowireCapableBeanFactory.java    From java-technology-stack 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 #21
Source File: TaskExecutorFactoryBean.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
	BeanWrapper bw = new BeanWrapperImpl(ThreadPoolTaskExecutor.class);
	determinePoolSizeRange(bw);
	if (this.queueCapacity != null) {
		bw.setPropertyValue("queueCapacity", this.queueCapacity);
	}
	if (this.keepAliveSeconds != null) {
		bw.setPropertyValue("keepAliveSeconds", this.keepAliveSeconds);
	}
	if (this.rejectedExecutionHandler != null) {
		bw.setPropertyValue("rejectedExecutionHandler", this.rejectedExecutionHandler);
	}
	if (this.beanName != null) {
		bw.setPropertyValue("threadNamePrefix", this.beanName + "-");
	}
	this.target = (TaskExecutor) bw.getWrappedInstance();
	if (this.target instanceof InitializingBean) {
		((InitializingBean) this.target).afterPropertiesSet();
	}
}
 
Example #22
Source File: BeanInfoTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testComplexObject() {
	ValueBean bean = new ValueBean();
	BeanWrapper bw = new BeanWrapperImpl(bean);
	Integer value = new Integer(1);

	bw.setPropertyValue("value", value);
	assertEquals("value not set correctly", bean.getValue(), value);

	value = new Integer(2);
	bw.setPropertyValue("value", value.toString());
	assertEquals("value not converted", bean.getValue(), value);

	bw.setPropertyValue("value", null);
	assertNull("value not null", bean.getValue());

	bw.setPropertyValue("value", "");
	assertNull("value not converted to null", bean.getValue());
}
 
Example #23
Source File: CustomEditorTests.java    From java-technology-stack with MIT License 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 #24
Source File: CustomEditorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testComplexObjectWithOldValueAccess() {
	TestBean tb = new TestBean();
	String newName = "Rod";
	String tbString = "Kerry_34";

	BeanWrapper bw = new BeanWrapperImpl(tb);
	bw.setExtractOldValueForEditor(true);
	bw.registerCustomEditor(ITestBean.class, new OldValueAccessingTestBeanEditor());
	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);
	ITestBean spouse = tb.getSpouse();

	bw.setPropertyValues(pvs);
	assertSame("Should have remained same object", spouse, tb.getSpouse());
}
 
Example #25
Source File: CustomEditorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testCustomEditorForSingleProperty() {
	TestBean tb = new TestBean();
	BeanWrapper bw = new BeanWrapperImpl(tb);
	bw.registerCustomEditor(String.class, "name", new PropertyEditorSupport() {
		@Override
		public void setAsText(String text) throws IllegalArgumentException {
			setValue("prefix" + text);
		}
	});
	bw.setPropertyValue("name", "value");
	bw.setPropertyValue("touchy", "value");
	assertEquals("prefixvalue", bw.getPropertyValue("name"));
	assertEquals("prefixvalue", tb.getName());
	assertEquals("value", bw.getPropertyValue("touchy"));
	assertEquals("value", tb.getTouchy());
}
 
Example #26
Source File: CustomEditorTests.java    From java-technology-stack with MIT License 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 #27
Source File: ControllerUtils.java    From wallride with Apache License 2.0 6 votes vote down vote up
public static MultiValueMap<String, String> convertBeanForQueryParams(Object target, ConversionService conversionService) {
	BeanWrapperImpl beanWrapper = new BeanWrapperImpl(target);
	beanWrapper.setConversionService(conversionService);
	MultiValueMap<String, String> queryParams = new LinkedMultiValueMap();
	for (PropertyDescriptor pd : beanWrapper.getPropertyDescriptors()) {
		if (beanWrapper.isWritableProperty(pd.getName())) {
			Object pv = beanWrapper.getPropertyValue(pd.getName());
			if (pv != null) {
				if (pv instanceof Collection) {
					if (!CollectionUtils.isEmpty((Collection) pv)) {
						for (Object element : (Collection) pv) {
							queryParams.set(pd.getName(), convertPropertyValueForString(target, pd, element));
						}
					}
				} else {
					queryParams.set(pd.getName(), convertPropertyValueForString(target, pd, pv));
				}
			}
		}
	}
	return queryParams;
}
 
Example #28
Source File: AbstractAutowireCapableBeanFactory.java    From lams with GNU General Public License v2.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 #29
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 #30
Source File: GetPropertyDescriptorsInterceptor.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Override
public Object afterMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes,
    Object ret) throws Throwable {

    PropertyDescriptor[] propertyDescriptors = (PropertyDescriptor[]) ret;

    Class<?> rootClass = ((BeanWrapperImpl) objInst).getRootClass();
    if (rootClass != null && EnhancedInstance.class.isAssignableFrom(rootClass)) {
        List<PropertyDescriptor> newPropertyDescriptors = new ArrayList<PropertyDescriptor>();
        for (PropertyDescriptor descriptor : propertyDescriptors) {
            if (!"skyWalkingDynamicField".equals(descriptor.getName())) {
                newPropertyDescriptors.add(descriptor);
            }
        }

        return newPropertyDescriptors.toArray(new PropertyDescriptor[newPropertyDescriptors.size()]);
    }

    return ret;
}