org.springframework.beans.MutablePropertyValues Java Examples

The following examples show how to use org.springframework.beans.MutablePropertyValues. 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: MoneyFormattingTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testAmountWithNumberFormat1() {
	FormattedMoneyHolder1 bean = new FormattedMoneyHolder1();
	DataBinder binder = new DataBinder(bean);
	binder.setConversionService(conversionService);

	MutablePropertyValues propertyValues = new MutablePropertyValues();
	propertyValues.add("amount", "$10.50");
	binder.bind(propertyValues);
	assertEquals(0, binder.getBindingResult().getErrorCount());
	assertEquals("$10.50", binder.getBindingResult().getFieldValue("amount"));
	assertTrue(bean.getAmount().getNumber().doubleValue() == 10.5d);
	assertEquals("USD", bean.getAmount().getCurrency().getCurrencyCode());

	LocaleContextHolder.setLocale(Locale.CANADA);
	binder.bind(propertyValues);
	LocaleContextHolder.setLocale(Locale.US);
	assertEquals(0, binder.getBindingResult().getErrorCount());
	assertEquals("$10.50", binder.getBindingResult().getFieldValue("amount"));
	assertTrue(bean.getAmount().getNumber().doubleValue() == 10.5d);
	assertEquals("CAD", bean.getAmount().getCurrency().getCurrencyCode());
}
 
Example #2
Source File: WebRemoteProxyBeanCreator.java    From cuba with Apache License 2.0 6 votes vote down vote up
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    String useLocal = AppContext.getProperty("cuba.useLocalServiceInvocation");

    if (Boolean.valueOf(useLocal)) {
        log.info("Configuring proxy beans for local service invocations: {}", services.keySet());

        BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
        for (Map.Entry<String, String> entry : services.entrySet()) {
            String name = entry.getKey();
            String serviceInterface = entry.getValue();
            BeanDefinition definition = new RootBeanDefinition(serviceProxyClass);
            MutablePropertyValues propertyValues = definition.getPropertyValues();
            propertyValues.add("serviceName", name);
            propertyValues.add("serviceInterface", serviceInterface);
            registry.registerBeanDefinition(name, definition);

            log.debug("Configured proxy bean {} of type {}", name, serviceInterface);
        }

        processSubstitutions(beanFactory);
    } else {
        super.postProcessBeanFactory(beanFactory);
    }
}
 
Example #3
Source File: DataBinderTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testEditorForNestedIndexedField() {
	IndexedTestBean tb = new IndexedTestBean();
	tb.getArray()[0].setNestedIndexedBean(new IndexedTestBean());
	tb.getArray()[1].setNestedIndexedBean(new IndexedTestBean());
	DataBinder binder = new DataBinder(tb, "tb");
	binder.registerCustomEditor(String.class, "array.nestedIndexedBean.list.name", new PropertyEditorSupport() {
		@Override
		public void setAsText(String text) throws IllegalArgumentException {
			setValue("list" + text);
		}
		@Override
		public String getAsText() {
			return ((String) getValue()).substring(4);
		}
	});
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("array[0].nestedIndexedBean.list[0].name", "test1");
	pvs.add("array[1].nestedIndexedBean.list[1].name", "test2");
	binder.bind(pvs);
	assertEquals("listtest1", ((TestBean)tb.getArray()[0].getNestedIndexedBean().getList().get(0)).getName());
	assertEquals("listtest2", ((TestBean)tb.getArray()[1].getNestedIndexedBean().getList().get(1)).getName());
	assertEquals("test1", binder.getBindingResult().getFieldValue("array[0].nestedIndexedBean.list[0].name"));
	assertEquals("test2", binder.getBindingResult().getFieldValue("array[1].nestedIndexedBean.list[1].name"));
}
 
Example #4
Source File: AdvisorComponentDefinition.java    From java-technology-stack with MIT License 6 votes vote down vote up
public AdvisorComponentDefinition(
		String advisorBeanName, BeanDefinition advisorDefinition, @Nullable BeanDefinition pointcutDefinition) {

	Assert.notNull(advisorBeanName, "'advisorBeanName' must not be null");
	Assert.notNull(advisorDefinition, "'advisorDefinition' must not be null");
	this.advisorBeanName = advisorBeanName;
	this.advisorDefinition = advisorDefinition;

	MutablePropertyValues pvs = advisorDefinition.getPropertyValues();
	BeanReference adviceReference = (BeanReference) pvs.get("adviceBeanName");
	Assert.state(adviceReference != null, "Missing 'adviceBeanName' property");

	if (pointcutDefinition != null) {
		this.beanReferences = new BeanReference[] {adviceReference};
		this.beanDefinitions = new BeanDefinition[] {advisorDefinition, pointcutDefinition};
		this.description = buildDescription(adviceReference, pointcutDefinition);
	}
	else {
		BeanReference pointcutReference = (BeanReference) pvs.get("pointcut");
		Assert.state(pointcutReference != null, "Missing 'pointcut' property");
		this.beanReferences = new BeanReference[] {adviceReference, pointcutReference};
		this.beanDefinitions = new BeanDefinition[] {advisorDefinition};
		this.description = buildDescription(adviceReference, pointcutReference);
	}
}
 
Example #5
Source File: BaseBeanFactory.java    From geomajas-project-server with GNU Affero General Public License v3.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
public List<BeanDefinitionHolder> createBeans(Map<String, Object> parameters) throws RuntimeConfigException {
	GenericBeanDefinition def = new GenericBeanDefinition();
	def.setBeanClassName(className);
	MutablePropertyValues propertyValues = new MutablePropertyValues();
	List<NamedObject> namedObjects = new ArrayList<NamedObject>();
	if (checkCollection(BEAN_REFS, NamedObject.class, parameters) != Priority.NONE) {
		namedObjects.addAll((Collection) parameters.get(BEAN_REFS));
	}
	for (String name : parameters.keySet()) {
		if (!ignoredParams.contains(name)) {
			propertyValues.addPropertyValue(name, beanDefinitionDtoConverterService
					.createBeanMetadataElementByIntrospection(parameters.get(name), namedObjects));
		}
	}
	def.setPropertyValues(propertyValues);
	BeanDefinitionHolder holder = new BeanDefinitionHolder(def, (String) parameters.get(BEAN_NAME));
	List<BeanDefinitionHolder> holders = new ArrayList<BeanDefinitionHolder>();
	holders.add(holder);
	return holders;
}
 
Example #6
Source File: AbstractAutowireCapableBeanFactory.java    From lams with GNU General Public License v2.0 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 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.isDebugEnabled()) {
				logger.debug("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 #7
Source File: CustomEditorConfigurerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testCustomEditorConfigurerWithEditorAsClass() throws ParseException {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	CustomEditorConfigurer cec = new CustomEditorConfigurer();
	Map<Class<?>, Class<? extends PropertyEditor>> editors = new HashMap<>();
	editors.put(Date.class, MyDateEditor.class);
	cec.setCustomEditors(editors);
	cec.postProcessBeanFactory(bf);

	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("date", "2.12.1975");
	RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
	bd.setPropertyValues(pvs);
	bf.registerBeanDefinition("tb", bd);

	TestBean tb = (TestBean) bf.getBean("tb");
	DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.GERMAN);
	assertEquals(df.parse("2.12.1975"), tb.getDate());
}
 
Example #8
Source File: MoneyFormattingTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testAmountAndUnit() {
	MoneyHolder bean = new MoneyHolder();
	DataBinder binder = new DataBinder(bean);
	binder.setConversionService(conversionService);

	MutablePropertyValues propertyValues = new MutablePropertyValues();
	propertyValues.add("amount", "USD 10.50");
	propertyValues.add("unit", "USD");
	binder.bind(propertyValues);
	assertEquals(0, binder.getBindingResult().getErrorCount());
	assertEquals("USD10.50", binder.getBindingResult().getFieldValue("amount"));
	assertEquals("USD", binder.getBindingResult().getFieldValue("unit"));
	assertTrue(bean.getAmount().getNumber().doubleValue() == 10.5d);
	assertEquals("USD", bean.getAmount().getCurrency().getCurrencyCode());

	LocaleContextHolder.setLocale(Locale.CANADA);
	binder.bind(propertyValues);
	LocaleContextHolder.setLocale(Locale.US);
	assertEquals(0, binder.getBindingResult().getErrorCount());
	assertEquals("USD10.50", binder.getBindingResult().getFieldValue("amount"));
	assertEquals("USD", binder.getBindingResult().getFieldValue("unit"));
	assertTrue(bean.getAmount().getNumber().doubleValue() == 10.5d);
	assertEquals("USD", bean.getAmount().getCurrency().getCurrencyCode());
}
 
Example #9
Source File: DateTimeFormattingTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("deprecation")
public void testBindInstantFromJavaUtilDate() {
	TimeZone defaultZone = TimeZone.getDefault();
	TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
	try {
		MutablePropertyValues propertyValues = new MutablePropertyValues();
		propertyValues.add("instant", new Date(109, 9, 31, 12, 0));
		binder.bind(propertyValues);
		assertEquals(0, binder.getBindingResult().getErrorCount());
		assertTrue(binder.getBindingResult().getFieldValue("instant").toString().startsWith("2009-10-31"));
	}
	finally {
		TimeZone.setDefault(defaultZone);
	}
}
 
Example #10
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 #11
Source File: DataBinderTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testBindingWithDisallowedFields() throws BindException {
	TestBean rod = new TestBean();
	DataBinder binder = new DataBinder(rod);
	binder.setDisallowedFields("age");
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("name", "Rod");
	pvs.add("age", "32x");

	binder.bind(pvs);
	binder.close();
	assertTrue("changed name correctly", rod.getName().equals("Rod"));
	assertTrue("did not change age", rod.getAge() == 0);
	String[] disallowedFields = binder.getBindingResult().getSuppressedFields();
	assertEquals(1, disallowedFields.length);
	assertEquals("age", disallowedFields[0]);
}
 
Example #12
Source File: JcaListenerContainerParser.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
protected MutablePropertyValues parseCommonContainerProperties(Element containerEle, ParserContext parserContext) {
	MutablePropertyValues properties = super.parseCommonContainerProperties(containerEle, parserContext);

	Integer acknowledgeMode = parseAcknowledgeMode(containerEle, parserContext);
	if (acknowledgeMode != null) {
		properties.add("acknowledgeMode", acknowledgeMode);
	}

	String concurrency = containerEle.getAttribute(CONCURRENCY_ATTRIBUTE);
	if (StringUtils.hasText(concurrency)) {
		properties.add("concurrency", concurrency);
	}

	String prefetch = containerEle.getAttribute(PREFETCH_ATTRIBUTE);
	if (StringUtils.hasText(prefetch)) {
		properties.add("prefetchSize", new Integer(prefetch));
	}

	return properties;
}
 
Example #13
Source File: CustomEditorConfigurerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testCustomEditorConfigurerWithEditorAsClass() throws ParseException {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	CustomEditorConfigurer cec = new CustomEditorConfigurer();
	Map<Class<?>, Class<? extends PropertyEditor>> editors = new HashMap<Class<?>, Class<? extends PropertyEditor>>();
	editors.put(Date.class, MyDateEditor.class);
	cec.setCustomEditors(editors);
	cec.postProcessBeanFactory(bf);

	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("date", "2.12.1975");
	RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
	bd.setPropertyValues(pvs);
	bf.registerBeanDefinition("tb", bd);

	TestBean tb = (TestBean) bf.getBean("tb");
	DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.GERMAN);
	assertEquals(df.parse("2.12.1975"), tb.getDate());
}
 
Example #14
Source File: ExtendedServletRequestDataBinder.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Merge URI variables into the property values to use for data binding.
 */
@Override
@SuppressWarnings("unchecked")
protected void addBindValues(MutablePropertyValues mpvs, ServletRequest request) {
	String attr = HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE;
	Map<String, String> uriVars = (Map<String, String>) request.getAttribute(attr);
	if (uriVars != null) {
		for (Entry<String, String> entry : uriVars.entrySet()) {
			if (mpvs.contains(entry.getKey())) {
				logger.warn("Skipping URI variable '" + entry.getKey()
						+ "' since the request contains a bind value with the same name.");
			}
			else {
				mpvs.addPropertyValue(entry.getKey(), entry.getValue());
			}
		}
	}
}
 
Example #15
Source File: StaticApplicationContextTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
protected ConfigurableApplicationContext createContext() throws Exception {
	StaticApplicationContext parent = new StaticApplicationContext();
	Map<String, String> m = new HashMap<>();
	m.put("name", "Roderick");
	parent.registerPrototype("rod", TestBean.class, new MutablePropertyValues(m));
	m.put("name", "Albert");
	parent.registerPrototype("father", TestBean.class, new MutablePropertyValues(m));
	parent.refresh();
	parent.addApplicationListener(parentListener) ;

	parent.getStaticMessageSource().addMessage("code1", Locale.getDefault(), "message1");

	this.sac = new StaticApplicationContext(parent);
	sac.registerSingleton("beanThatListens", BeanThatListens.class, new MutablePropertyValues());
	sac.registerSingleton("aca", ACATester.class, new MutablePropertyValues());
	sac.registerPrototype("aca-prototype", ACATester.class, new MutablePropertyValues());
	PropertiesBeanDefinitionReader reader = new PropertiesBeanDefinitionReader(sac.getDefaultListableBeanFactory());
	reader.loadBeanDefinitions(new ClassPathResource("testBeans.properties", getClass()));
	sac.refresh();
	sac.addApplicationListener(listener);

	sac.getStaticMessageSource().addMessage("code2", Locale.getDefault(), "message2");

	return sac;
}
 
Example #16
Source File: DefaultListableBeanFactoryTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testExpressionInStringArray() {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	BeanExpressionResolver beanExpressionResolver = mock(BeanExpressionResolver.class);
	given(beanExpressionResolver.evaluate(eq("#{foo}"), any(BeanExpressionContext.class)))
			.willReturn("classpath:/org/springframework/beans/factory/xml/util.properties");
	bf.setBeanExpressionResolver(beanExpressionResolver);

	RootBeanDefinition rbd = new RootBeanDefinition(PropertiesFactoryBean.class);
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("locations", new String[]{"#{foo}"});
	rbd.setPropertyValues(pvs);
	bf.registerBeanDefinition("myProperties", rbd);
	Properties properties = (Properties) bf.getBean("myProperties");
	assertEquals("bar", properties.getProperty("foo"));
}
 
Example #17
Source File: SpringBeanAutowiringSupportTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testProcessInjectionBasedOnServletContext() {
	StaticWebApplicationContext wac = new StaticWebApplicationContext();
	AnnotationConfigUtils.registerAnnotationConfigProcessors(wac);

	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("name", "tb");
	wac.registerSingleton("testBean", TestBean.class, pvs);

	MockServletContext sc = new MockServletContext();
	wac.setServletContext(sc);
	wac.refresh();
	sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);

	InjectionTarget target = new InjectionTarget();
	SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(target, sc);
	assertTrue(target.testBean instanceof TestBean);
	assertEquals("tb", target.name);
}
 
Example #18
Source File: DefaultListableBeanFactoryTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testCustomEditor() {
	DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
	lbf.addPropertyEditorRegistrar(new PropertyEditorRegistrar() {
		@Override
		public void registerCustomEditors(PropertyEditorRegistry registry) {
			NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
			registry.registerCustomEditor(Float.class, new CustomNumberEditor(Float.class, nf, true));
		}
	});
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("myFloat", "1,1");
	RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
	bd.setPropertyValues(pvs);
	lbf.registerBeanDefinition("testBean", bd);
	TestBean testBean = (TestBean) lbf.getBean("testBean");
	assertTrue(testBean.getMyFloat().floatValue() == 1.1f);
}
 
Example #19
Source File: DataBinderTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testBindingWithNestedObjectCreation() {
	TestBean tb = new TestBean();

	DataBinder binder = new DataBinder(tb, "person");
	binder.registerCustomEditor(ITestBean.class, new PropertyEditorSupport() {
		@Override
		public void setAsText(String text) throws IllegalArgumentException {
			setValue(new TestBean());
		}
	});

	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("spouse", "someValue");
	pvs.add("spouse.name", "test");
	binder.bind(pvs);

	assertNotNull(tb.getSpouse());
	assertEquals("test", tb.getSpouse().getName());
}
 
Example #20
Source File: DataBinderFieldAccessTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void bindingNoErrorsNotIgnoreUnknown() throws Exception {
	FieldAccessBean rod = new FieldAccessBean();
	DataBinder binder = new DataBinder(rod, "person");
	binder.initDirectFieldAccess();
	binder.setIgnoreUnknownFields(false);
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.addPropertyValue(new PropertyValue("name", "Rod"));
	pvs.addPropertyValue(new PropertyValue("age", new Integer(32)));
	pvs.addPropertyValue(new PropertyValue("nonExisting", "someValue"));

	try {
		binder.bind(pvs);
		fail("Should have thrown NotWritablePropertyException");
	}
	catch (NotWritablePropertyException ex) {
		// expected
	}
}
 
Example #21
Source File: SimpleWebApplicationContext.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public void refresh() throws BeansException {
	registerSingleton("/locale.do", LocaleChecker.class);

	addMessage("test", Locale.ENGLISH, "test message");
	addMessage("test", Locale.CANADA, "Canadian & test message");
	addMessage("testArgs", Locale.ENGLISH, "test {0} message {1}");
	addMessage("testArgsFormat", Locale.ENGLISH, "test {0} message {1,number,#.##} X");

	registerSingleton(UiApplicationContextUtils.THEME_SOURCE_BEAN_NAME, DummyThemeSource.class);

	registerSingleton("handlerMapping", BeanNameUrlHandlerMapping.class);
	registerSingleton("viewResolver", InternalResourceViewResolver.class);

	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("location", "org/springframework/web/context/WEB-INF/sessionContext.xml");
	registerSingleton("viewResolver2", XmlViewResolver.class, pvs);

	super.refresh();
}
 
Example #22
Source File: SpringBeanAutowiringSupportTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testProcessInjectionBasedOnServletContext() {
	StaticWebApplicationContext wac = new StaticWebApplicationContext();
	AnnotationConfigUtils.registerAnnotationConfigProcessors(wac);

	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("name", "tb");
	wac.registerSingleton("testBean", TestBean.class, pvs);

	MockServletContext sc = new MockServletContext();
	wac.setServletContext(sc);
	wac.refresh();
	sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);

	InjectionTarget target = new InjectionTarget();
	SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(target, sc);
	assertTrue(target.testBean instanceof TestBean);
	assertEquals("tb", target.name);
}
 
Example #23
Source File: SnakeToCamelRequestDataBinder.java    From softservice with MIT License 6 votes vote down vote up
protected void addBindValues(MutablePropertyValues mpvs, ServletRequest request) {
    super.addBindValues(mpvs, request);

    //处理JsonProperty注释的对象
    Class<?> targetClass = getTarget().getClass();
    Field[] fields = targetClass.getDeclaredFields();
    for (Field field : fields) {
        JsonProperty jsonPropertyAnnotation = field.getAnnotation(JsonProperty.class);
        if (jsonPropertyAnnotation != null && mpvs.contains(jsonPropertyAnnotation.value())) {
            if (!mpvs.contains(field.getName())) {
                mpvs.add(field.getName(), mpvs.getPropertyValue(jsonPropertyAnnotation.value()).getValue());
            }
        }
    }

    List<PropertyValue> covertValues = new ArrayList<PropertyValue>();
    for (PropertyValue propertyValue : mpvs.getPropertyValueList()) {
        if(propertyValue.getName().contains("_")) {
            String camelName = SnakeToCamelRequestParameterUtil.convertSnakeToCamel(propertyValue.getName());
            if (!mpvs.contains(camelName)) {
                covertValues.add(new PropertyValue(camelName, propertyValue.getValue()));
            }
        }
    }
    mpvs.getPropertyValueList().addAll(covertValues);
}
 
Example #24
Source File: DataBinderTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testBindingWithAllowedFieldsUsingAsterisks() throws BindException {
	TestBean rod = new TestBean();
	DataBinder binder = new DataBinder(rod, "person");
	binder.setAllowedFields("nam*", "*ouchy");

	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("name", "Rod");
	pvs.add("touchy", "Rod");
	pvs.add("age", "32x");

	binder.bind(pvs);
	binder.close();

	assertTrue("changed name correctly", "Rod".equals(rod.getName()));
	assertTrue("changed touchy correctly", "Rod".equals(rod.getTouchy()));
	assertTrue("did not change age", rod.getAge() == 0);
	String[] disallowedFields = binder.getBindingResult().getSuppressedFields();
	assertEquals(1, disallowedFields.length);
	assertEquals("age", disallowedFields[0]);

	Map<?,?> m = binder.getBindingResult().getModel();
	assertTrue("There is one element in map", m.size() == 2);
	TestBean tb = (TestBean) m.get("person");
	assertTrue("Same object", tb.equals(rod));
}
 
Example #25
Source File: JodaTimeFormattingTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testBindISODateTime() {
	MutablePropertyValues propertyValues = new MutablePropertyValues();
	propertyValues.add("isoDateTime", "2009-10-31T12:00:00.000Z");
	binder.bind(propertyValues);
	assertEquals(0, binder.getBindingResult().getErrorCount());
	assertEquals("2009-10-31T07:00:00.000-05:00", binder.getBindingResult().getFieldValue("isoDateTime"));
}
 
Example #26
Source File: DataBinderTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testNestedGrowingList() {
	Form form = new Form();
	DataBinder binder = new DataBinder(form, "form");
	MutablePropertyValues mpv = new MutablePropertyValues();
	mpv.add("f[list][0]", "firstValue");
	mpv.add("f[list][1]", "secondValue");
	binder.bind(mpv);
	assertFalse(binder.getBindingResult().hasErrors());
	@SuppressWarnings("unchecked")
	List<Object> list = (List<Object>) form.getF().get("list");
	assertEquals("firstValue", list.get(0));
	assertEquals("secondValue", list.get(1));
	assertEquals(2, list.size());
}
 
Example #27
Source File: AutoProxyCreatorTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testAutoProxyCreatorWithFallbackToDynamicProxy() {
	StaticApplicationContext sac = new StaticApplicationContext();

	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("proxyFactoryBean", "false");
	sac.registerSingleton("testAutoProxyCreator", TestAutoProxyCreator.class, pvs);

	sac.registerSingleton("noInterfaces", NoInterfaces.class);
	sac.registerSingleton("containerCallbackInterfacesOnly", ContainerCallbackInterfacesOnly.class);
	sac.registerSingleton("singletonNoInterceptor", CustomProxyFactoryBean.class);
	sac.registerSingleton("singletonToBeProxied", CustomProxyFactoryBean.class);
	sac.registerPrototype("prototypeToBeProxied", SpringProxyFactoryBean.class);

	sac.refresh();

	MessageSource messageSource = (MessageSource) sac.getBean("messageSource");
	NoInterfaces noInterfaces = (NoInterfaces) sac.getBean("noInterfaces");
	ContainerCallbackInterfacesOnly containerCallbackInterfacesOnly =
			(ContainerCallbackInterfacesOnly) sac.getBean("containerCallbackInterfacesOnly");
	ITestBean singletonNoInterceptor = (ITestBean) sac.getBean("singletonNoInterceptor");
	ITestBean singletonToBeProxied = (ITestBean) sac.getBean("singletonToBeProxied");
	ITestBean prototypeToBeProxied = (ITestBean) sac.getBean("prototypeToBeProxied");
	assertFalse(AopUtils.isCglibProxy(messageSource));
	assertTrue(AopUtils.isCglibProxy(noInterfaces));
	assertTrue(AopUtils.isCglibProxy(containerCallbackInterfacesOnly));
	assertFalse(AopUtils.isCglibProxy(singletonNoInterceptor));
	assertFalse(AopUtils.isCglibProxy(singletonToBeProxied));
	assertFalse(AopUtils.isCglibProxy(prototypeToBeProxied));

	TestAutoProxyCreator tapc = (TestAutoProxyCreator) sac.getBean("testAutoProxyCreator");
	assertEquals(0, tapc.testInterceptor.nrOfInvocations);
	singletonNoInterceptor.getName();
	assertEquals(0, tapc.testInterceptor.nrOfInvocations);
	singletonToBeProxied.getAge();
	assertEquals(1, tapc.testInterceptor.nrOfInvocations);
	prototypeToBeProxied.getSpouse();
	assertEquals(2, tapc.testInterceptor.nrOfInvocations);
}
 
Example #28
Source File: DataBinder.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Check the given property values against the allowed fields,
 * removing values for fields that are not allowed.
 * @param mpvs the property values to be bound (can be modified)
 * @see #getAllowedFields
 * @see #isAllowed(String)
 */
protected void checkAllowedFields(MutablePropertyValues mpvs) {
	PropertyValue[] pvs = mpvs.getPropertyValues();
	for (PropertyValue pv : pvs) {
		String field = PropertyAccessorUtils.canonicalPropertyName(pv.getName());
		if (!isAllowed(field)) {
			mpvs.removePropertyValue(pv);
			getBindingResult().recordSuppressedField(field);
			if (logger.isDebugEnabled()) {
				logger.debug("Field [" + field + "] has been removed from PropertyValues " +
						"and will not be bound, because it has not been found in the list of allowed fields");
			}
		}
	}
}
 
Example #29
Source File: JodaTimeFormattingTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testBindLocalTime() {
	MutablePropertyValues propertyValues = new MutablePropertyValues();
	propertyValues.add("localTime", "12:00 PM");
	binder.bind(propertyValues);
	assertEquals(0, binder.getBindingResult().getErrorCount());
	assertEquals("12:00 PM", binder.getBindingResult().getFieldValue("localTime"));
}
 
Example #30
Source File: BeanDefinitionVisitor.java    From spring-analysis-note with MIT License 5 votes vote down vote up
protected void visitPropertyValues(MutablePropertyValues pvs) {
	PropertyValue[] pvArray = pvs.getPropertyValues();
	for (PropertyValue pv : pvArray) {
		Object newVal = resolveValue(pv.getValue());
		if (!ObjectUtils.nullSafeEquals(newVal, pv.getValue())) {
			pvs.add(pv.getName(), newVal);
		}
	}
}