Java Code Examples for org.springframework.beans.MutablePropertyValues#add()

The following examples show how to use org.springframework.beans.MutablePropertyValues#add() . 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: DataBinderTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testBindingErrorWithFormatter() {
	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);
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("myFloat", "1x2");

	LocaleContextHolder.setLocale(Locale.GERMAN);
	try {
		binder.bind(pvs);
		assertEquals(new Float(0.0), tb.getMyFloat());
		assertEquals("1x2", binder.getBindingResult().getFieldValue("myFloat"));
		assertTrue(binder.getBindingResult().hasFieldErrors("myFloat"));
	}
	finally {
		LocaleContextHolder.resetLocaleContext();
	}
}
 
Example 2
Source File: DataBinderTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testTrackDisallowedFields() throws Exception {
	TestBean testBean = new TestBean();
	DataBinder binder = new DataBinder(testBean, "testBean");
	binder.setAllowedFields("name", "age");

	String name = "Rob Harrop";
	String beanName = "foobar";

	MutablePropertyValues mpvs = new MutablePropertyValues();
	mpvs.add("name", name);
	mpvs.add("beanName", beanName);
	binder.bind(mpvs);

	assertEquals(name, testBean.getName());
	String[] disallowedFields = binder.getBindingResult().getSuppressedFields();
	assertEquals(1, disallowedFields.length);
	assertEquals("beanName", disallowedFields[0]);
}
 
Example 3
Source File: DataBinderTests.java    From java-technology-stack 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 4
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 5
Source File: DataBinderTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testCustomEditorForPrimitiveProperty() {
	TestBean tb = new TestBean();
	DataBinder binder = new DataBinder(tb, "tb");

	binder.registerCustomEditor(int.class, "age", new PropertyEditorSupport() {
		@Override
		public void setAsText(String text) throws IllegalArgumentException {
			setValue(new Integer(99));
		}
		@Override
		public String getAsText() {
			return "argh";
		}
	});

	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("age", "");
	binder.bind(pvs);

	assertEquals("argh", binder.getBindingResult().getFieldValue("age"));
	assertEquals(99, tb.getAge());
}
 
Example 6
Source File: ServletContextSupportTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("resource")
public void testServletContextAttributeFactoryBean() {
	MockServletContext sc = new MockServletContext();
	sc.setAttribute("myAttr", "myValue");

	StaticWebApplicationContext wac = new StaticWebApplicationContext();
	wac.setServletContext(sc);
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("attributeName", "myAttr");
	wac.registerSingleton("importedAttr", ServletContextAttributeFactoryBean.class, pvs);
	wac.refresh();

	Object value = wac.getBean("importedAttr");
	assertEquals("myValue", value);
}
 
Example 7
Source File: JodaTimeFormattingTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testBindDateTimeAnnotatedDefault() {
	MutablePropertyValues propertyValues = new MutablePropertyValues();
	propertyValues.add("dateTimeAnnotatedDefault", new DateTime(2009, 10, 31, 12, 0, ISOChronology.getInstanceUTC()));
	binder.bind(propertyValues);
	assertEquals(0, binder.getBindingResult().getErrorCount());
	String value = binder.getBindingResult().getFieldValue("dateTimeAnnotatedDefault").toString();
	assertTrue(value.startsWith("10/31/09"));
}
 
Example 8
Source File: MulCommonBaseServiceParser.java    From zxl with Apache License 2.0 5 votes vote down vote up
private BeanDefinition buildDataSourceBeanDefinition(Element element, String name) {
	AbstractBeanDefinition beanDefinition = new GenericBeanDefinition();
	beanDefinition.setAttribute(ID_ATTRIBUTE, name + DATA_SOURCE_SUFFIX);
	beanDefinition.setBeanClass(SimpleDataSource.class);
	MutablePropertyValues propertyValues = new MutablePropertyValues();
	propertyValues.add("name", name);
	beanDefinition.setPropertyValues(propertyValues);
	return beanDefinition;
}
 
Example 9
Source File: DataBinderTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testAutoGrowWithinCustomLimit() {
	TestBean testBean = new TestBean();
	DataBinder binder = new DataBinder(testBean, "testBean");
	binder.setAutoGrowCollectionLimit(10);

	MutablePropertyValues mpvs = new MutablePropertyValues();
	mpvs.add("friends[4]", "");
	binder.bind(mpvs);

	assertEquals(5, testBean.getFriends().size());
}
 
Example 10
Source File: DataBinderTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testNestedBindingWithDefaultConversionNoErrors() throws Exception {
	TestBean rod = new TestBean(new TestBean());
	DataBinder binder = new DataBinder(rod, "person");
	assertTrue(binder.isIgnoreUnknownFields());
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("spouse.name", "Kerry");
	pvs.add("spouse.jedi", "on");

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

	assertEquals("Kerry", rod.getSpouse().getName());
	assertTrue(((TestBean) rod.getSpouse()).isJedi());
}
 
Example 11
Source File: JodaTimeFormattingTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testBindLongAnnotated() {
	MutablePropertyValues propertyValues = new MutablePropertyValues();
	propertyValues.add("millisAnnotated", "10/31/09");
	binder.bind(propertyValues);
	assertEquals(0, binder.getBindingResult().getErrorCount());
	assertEquals("10/31/09", binder.getBindingResult().getFieldValue("millisAnnotated"));
}
 
Example 12
Source File: BeanExtender.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * @see org.springframework.beans.factory.config.BeanFactoryPostProcessor#postProcessBeanFactory(org.springframework.beans.factory.config.ConfigurableListableBeanFactory)
 */
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
{
    ParameterCheck.mandatory("beanName", beanName);
    ParameterCheck.mandatory("extendingBeanName", extendingBeanName);

    // check for bean name
    if (!beanFactory.containsBean(beanName))
    {
        throw new NoSuchBeanDefinitionException("Can't find bean '" + beanName + "' to be extended.");
    }

    // check for extending bean
    if (!beanFactory.containsBean(extendingBeanName))
    {
        throw new NoSuchBeanDefinitionException("Can't find bean '" + extendingBeanName + "' that is going to extend original bean definition.");
    }

    // get the bean definitions
    BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
    BeanDefinition extendingBeanDefinition = beanFactory.getBeanDefinition(extendingBeanName);

    // update class
    if (StringUtils.isNotBlank(extendingBeanDefinition.getBeanClassName()) &&
        !beanDefinition.getBeanClassName().equals(extendingBeanDefinition.getBeanClassName()))
    {
        beanDefinition.setBeanClassName(extendingBeanDefinition.getBeanClassName());
    }

    // update properties
    MutablePropertyValues properties = beanDefinition.getPropertyValues();
    MutablePropertyValues extendingProperties = extendingBeanDefinition.getPropertyValues();
    for (PropertyValue propertyValue : extendingProperties.getPropertyValueList())
    {
        properties.add(propertyValue.getName(), propertyValue.getValue());
    }
}
 
Example 13
Source File: DataBinderTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testBindingNoErrors() throws BindException {
	TestBean rod = new TestBean();
	DataBinder binder = new DataBinder(rod, "person");
	assertTrue(binder.isIgnoreUnknownFields());
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("name", "Rod");
	pvs.add("age", "032");
	pvs.add("nonExisting", "someValue");

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

	assertTrue("changed name correctly", rod.getName().equals("Rod"));
	assertTrue("changed age correctly", rod.getAge() == 32);

	Map<?, ?> map = binder.getBindingResult().getModel();
	assertTrue("There is one element in map", map.size() == 2);
	TestBean tb = (TestBean) map.get("person");
	assertTrue("Same object", tb.equals(rod));

	BindingResult other = new BeanPropertyBindingResult(rod, "person");
	assertEquals(other, binder.getBindingResult());
	assertEquals(binder.getBindingResult(), other);
	BindException ex = new BindException(other);
	assertEquals(ex, other);
	assertEquals(other, ex);
	assertEquals(ex, binder.getBindingResult());
	assertEquals(binder.getBindingResult(), ex);

	other.reject("xxx");
	assertTrue(!other.equals(binder.getBindingResult()));
}
 
Example 14
Source File: JodaTimeFormattingTests.java    From spring-analysis-note with 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"));
}
 
Example 15
Source File: DateFormattingTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testBindDateAnnotatedWithError() {
	MutablePropertyValues propertyValues = new MutablePropertyValues();
	propertyValues.add("dateAnnotated", "Oct X31, 2009");
	binder.bind(propertyValues);
	assertEquals(1, binder.getBindingResult().getFieldErrorCount("dateAnnotated"));
	assertEquals("Oct X31, 2009", binder.getBindingResult().getFieldValue("dateAnnotated"));
}
 
Example 16
Source File: EventPublicationInterceptorTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testExpectedBehavior() throws Exception {
	TestBean target = new TestBean();
	final TestListener listener = new TestListener();

	class TestContext extends StaticApplicationContext {
		@Override
		protected void onRefresh() throws BeansException {
			addApplicationListener(listener);
		}
	}

	StaticApplicationContext ctx = new TestContext();
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("applicationEventClass", TestEvent.class.getName());
	// should automatically receive applicationEventPublisher reference
	ctx.registerSingleton("publisher", EventPublicationInterceptor.class, pvs);
	ctx.registerSingleton("otherListener", FactoryBeanTestListener.class);
	ctx.refresh();

	EventPublicationInterceptor interceptor =
			(EventPublicationInterceptor) ctx.getBean("publisher");
	ProxyFactory factory = new ProxyFactory(target);
	factory.addAdvice(0, interceptor);

	ITestBean testBean = (ITestBean) factory.getProxy();

	// invoke any method on the advised proxy to see if the interceptor has been invoked
	testBean.getAge();

	// two events: ContextRefreshedEvent and TestEvent
	assertTrue("Interceptor must have published 2 events", listener.getEventCount() == 2);
	TestListener otherListener = (TestListener) ctx.getBean("&otherListener");
	assertTrue("Interceptor must have published 2 events", otherListener.getEventCount() == 2);
}
 
Example 17
Source File: JodaTimeFormattingTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testBindDateTime() {
	MutablePropertyValues propertyValues = new MutablePropertyValues();
	propertyValues.add("dateTime", new DateTime(2009, 10, 31, 12, 0, ISOChronology.getInstanceUTC()));
	binder.bind(propertyValues);
	assertEquals(0, binder.getBindingResult().getErrorCount());
	String value = binder.getBindingResult().getFieldValue("dateTime").toString();
	assertTrue(value.startsWith("10/31/09"));
}
 
Example 18
Source File: DataBinderTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testBindingWithAllowedFields() throws BindException {
	TestBean rod = new TestBean();
	DataBinder binder = new DataBinder(rod);
	binder.setAllowedFields("name", "myparam");
	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);
}
 
Example 19
Source File: ResourcesBeanDefinitionParser.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Nullable
private String registerResourceHandler(ParserContext context, Element element,
		RuntimeBeanReference pathHelperRef, @Nullable Object source) {

	String locationAttr = element.getAttribute("location");
	if (!StringUtils.hasText(locationAttr)) {
		context.getReaderContext().error("The 'location' attribute is required.", context.extractSource(element));
		return null;
	}

	RootBeanDefinition resourceHandlerDef = new RootBeanDefinition(ResourceHttpRequestHandler.class);
	resourceHandlerDef.setSource(source);
	resourceHandlerDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);

	MutablePropertyValues values = resourceHandlerDef.getPropertyValues();
	values.add("urlPathHelper", pathHelperRef);
	values.add("locationValues", StringUtils.commaDelimitedListToStringArray(locationAttr));

	String cacheSeconds = element.getAttribute("cache-period");
	if (StringUtils.hasText(cacheSeconds)) {
		values.add("cacheSeconds", cacheSeconds);
	}

	Element cacheControlElement = DomUtils.getChildElementByTagName(element, "cache-control");
	if (cacheControlElement != null) {
		CacheControl cacheControl = parseCacheControl(cacheControlElement);
		values.add("cacheControl", cacheControl);
	}

	Element resourceChainElement = DomUtils.getChildElementByTagName(element, "resource-chain");
	if (resourceChainElement != null) {
		parseResourceChain(resourceHandlerDef, context, resourceChainElement, source);
	}

	Object manager = MvcNamespaceUtils.getContentNegotiationManager(context);
	if (manager != null) {
		values.add("contentNegotiationManager", manager);
	}

	String beanName = context.getReaderContext().generateBeanName(resourceHandlerDef);
	context.getRegistry().registerBeanDefinition(beanName, resourceHandlerDef);
	context.registerComponent(new BeanComponentDefinition(resourceHandlerDef, beanName));
	return beanName;
}
 
Example 20
Source File: AbstractListenerContainerParser.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
protected MutablePropertyValues parseCommonContainerProperties(Element containerEle, ParserContext parserContext) {
	MutablePropertyValues properties = new MutablePropertyValues();

	String destinationType = containerEle.getAttribute(DESTINATION_TYPE_ATTRIBUTE);
	boolean pubSubDomain = false;
	boolean subscriptionDurable = false;
	boolean subscriptionShared = false;
	if (DESTINATION_TYPE_SHARED_DURABLE_TOPIC.equals(destinationType)) {
		pubSubDomain = true;
		subscriptionDurable = true;
		subscriptionShared = true;
	}
	else if (DESTINATION_TYPE_SHARED_TOPIC.equals(destinationType)) {
		pubSubDomain = true;
		subscriptionShared = true;
	}
	else if (DESTINATION_TYPE_DURABLE_TOPIC.equals(destinationType)) {
		pubSubDomain = true;
		subscriptionDurable = true;
	}
	else if (DESTINATION_TYPE_TOPIC.equals(destinationType)) {
		pubSubDomain = true;
	}
	else if ("".equals(destinationType) || DESTINATION_TYPE_QUEUE.equals(destinationType)) {
		// the default: queue
	}
	else {
		parserContext.getReaderContext().error("Invalid listener container 'destination-type': only " +
				"\"queue\", \"topic\", \"durableTopic\", \"sharedTopic\", \"sharedDurableTopic\" supported.", containerEle);
	}
	properties.add("pubSubDomain", pubSubDomain);
	properties.add("subscriptionDurable", subscriptionDurable);
	properties.add("subscriptionShared", subscriptionShared);

	boolean replyPubSubDomain = false;
	String replyDestinationType = containerEle.getAttribute(RESPONSE_DESTINATION_TYPE_ATTRIBUTE);
	if (DESTINATION_TYPE_TOPIC.equals(replyDestinationType)) {
		replyPubSubDomain = true;
	}
	else if (DESTINATION_TYPE_QUEUE.equals(replyDestinationType)) {
		replyPubSubDomain = false;
	}
	else if (!StringUtils.hasText(replyDestinationType)) {
		replyPubSubDomain = pubSubDomain; // the default: same value as pubSubDomain
	}
	else if (StringUtils.hasText(replyDestinationType)) {
		parserContext.getReaderContext().error("Invalid listener container 'response-destination-type': only " +
				"\"queue\", \"topic\" supported.", containerEle);
	}
	properties.add("replyPubSubDomain", replyPubSubDomain);

	if (containerEle.hasAttribute(CLIENT_ID_ATTRIBUTE)) {
		String clientId = containerEle.getAttribute(CLIENT_ID_ATTRIBUTE);
		if (!StringUtils.hasText(clientId)) {
			parserContext.getReaderContext().error(
					"Listener 'client-id' attribute contains empty value.", containerEle);
		}
		properties.add("clientId", clientId);
	}

	if (containerEle.hasAttribute(MESSAGE_CONVERTER_ATTRIBUTE)) {
		String messageConverter = containerEle.getAttribute(MESSAGE_CONVERTER_ATTRIBUTE);
		if (!StringUtils.hasText(messageConverter)) {
			parserContext.getReaderContext().error(
					"listener container 'message-converter' attribute contains empty value.", containerEle);
		}
		else {
			properties.add("messageConverter", new RuntimeBeanReference(messageConverter));
		}
	}

	return properties;
}