Java Code Examples for org.springframework.beans.MutablePropertyValues

The following examples show how to use org.springframework.beans.MutablePropertyValues. These examples are extracted from open source projects. 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
/**
 * 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 2
Source Project: cuba   Source File: WebRemoteProxyBeanCreator.java    License: 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 Project: spring4-understanding   Source File: DataBinderTests.java    License: 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 Project: java-technology-stack   Source File: AdvisorComponentDefinition.java    License: 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
/**
 * 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 6
@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 7
Source Project: spring-analysis-note   Source File: CustomEditorConfigurerTests.java    License: 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
@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 Project: spring-analysis-note   Source File: DateTimeFormattingTests.java    License: 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
/**
 * 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 Project: spring-analysis-note   Source File: DataBinderTests.java    License: 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
@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 Project: spring-analysis-note   Source File: DataBinderTests.java    License: 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 14
@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 15
Source Project: softservice   Source File: SnakeToCamelRequestDataBinder.java    License: 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 16
@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 17
Source Project: spring-analysis-note   Source File: SimpleWebApplicationContext.java    License: 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 18
Source Project: spring-analysis-note   Source File: DataBinderFieldAccessTests.java    License: 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 19
Source Project: java-technology-stack   Source File: DataBinderTests.java    License: 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
@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 21
@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 22
@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 23
@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 24
Source Project: spring-analysis-note   Source File: MoneyFormattingTests.java    License: 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 25
Source Project: java-technology-stack   Source File: JodaTimeFormattingTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testBindDateTimeWithSpecificFormatter() {
	JodaTimeFormatterRegistrar registrar = new JodaTimeFormatterRegistrar();
	registrar.setDateTimeFormatter(org.joda.time.format.DateTimeFormat.forPattern("yyyyMMddHHmmss"));
	setup(registrar);
	MutablePropertyValues propertyValues = new MutablePropertyValues();
	propertyValues.add("dateTime", "20091031130000");
	binder.bind(propertyValues);
	assertEquals(0, binder.getBindingResult().getErrorCount());
	assertEquals("20091031130000", binder.getBindingResult().getFieldValue("dateTime"));
}
 
Example 26
Source Project: niubi-job   Source File: JobDrivenBeanDefinitionParser.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
    AbstractBeanDefinition beanDefinition = new GenericBeanDefinition();
    MutablePropertyValues propertyValues = new MutablePropertyValues();
    beanDefinition.setBeanClass(SpringContextJobDriver.class);
    propertyValues.addPropertyValue("packagesToScan", element.getAttribute("packagesToScan"));
    beanDefinition.setPropertyValues(propertyValues);
    beanDefinition.setInitMethodName("init");
    BeanDefinitionReaderUtils.registerWithGeneratedName(beanDefinition, parserContext.getRegistry());
    return beanDefinition;
}
 
Example 27
@Test
public void testBindISODate() {
	MutablePropertyValues propertyValues = new MutablePropertyValues();
	propertyValues.add("isoDate", "2009-10-31");
	binder.bind(propertyValues);
	assertEquals(0, binder.getBindingResult().getErrorCount());
	assertEquals("2009-10-31", binder.getBindingResult().getFieldValue("isoDate"));
}
 
Example 28
Source Project: spring4-understanding   Source File: DataBinderTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testBindingWithFormatterAgainstFields() {
	TestBean tb = new TestBean();
	DataBinder binder = new DataBinder(tb);
	FormattingConversionService conversionService = new FormattingConversionService();
	DefaultConversionService.addDefaultConverters(conversionService);
	conversionService.addFormatterForFieldType(Float.class, new NumberStyleFormatter());
	binder.setConversionService(conversionService);
	binder.initDirectFieldAccess();
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("myFloat", "1,2");

	LocaleContextHolder.setLocale(Locale.GERMAN);
	try {
		binder.bind(pvs);
		assertEquals(new Float(1.2), tb.getMyFloat());
		assertEquals("1,2", binder.getBindingResult().getFieldValue("myFloat"));

		PropertyEditor editor = binder.getBindingResult().findEditor("myFloat", Float.class);
		assertNotNull(editor);
		editor.setValue(new Float(1.4));
		assertEquals("1,4", editor.getAsText());

		editor = binder.getBindingResult().findEditor("myFloat", null);
		assertNotNull(editor);
		editor.setAsText("1,6");
		assertEquals(new Float(1.6), editor.getValue());
	}
	finally {
		LocaleContextHolder.resetLocaleContext();
	}
}
 
Example 29
Source Project: spring-analysis-note   Source File: StaticApplicationContext.java    License: MIT License 5 votes vote down vote up
/**
 * Register a singleton bean with the underlying bean factory.
 * <p>For more advanced needs, register with the underlying BeanFactory directly.
 * @see #getDefaultListableBeanFactory
 */
public void registerSingleton(String name, Class<?> clazz, MutablePropertyValues pvs) throws BeansException {
	GenericBeanDefinition bd = new GenericBeanDefinition();
	bd.setBeanClass(clazz);
	bd.setPropertyValues(pvs);
	getDefaultListableBeanFactory().registerBeanDefinition(name, bd);
}
 
Example 30
Source Project: spring-analysis-note   Source File: JodaTimeFormattingTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testBindNestedLocalDateAnnotated() {
	MutablePropertyValues propertyValues = new MutablePropertyValues();
	propertyValues.add("children[0].localDateAnnotated", "Oct 31, 2009");
	binder.bind(propertyValues);
	assertEquals(0, binder.getBindingResult().getErrorCount());
	assertEquals("Oct 31, 2009", binder.getBindingResult().getFieldValue("children[0].localDateAnnotated"));
}