下面列出了org.springframework.beans.MutablePropertyValues#add ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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();
}
}
@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]);
}
@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]);
}
@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;
}
@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());
}
@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);
}
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;
}
@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);
}
@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"));
}
@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);
}
@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"));
}
@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"));
}
@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()));
}
/**
* @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());
}
}
@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"));
}
@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());
}
@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());
}
@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"));
}
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;
}
@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;
}