View Javadoc
1   /*
2    * Copyright 2009-2010 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.springframework.batch.admin.web;
17  
18  import static org.junit.Assert.assertEquals;
19  
20  import java.beans.PropertyEditorSupport;
21  import java.util.Collections;
22  import java.util.HashMap;
23  import java.util.Map;
24  
25  import org.junit.Test;
26  import org.springframework.beans.MutablePropertyValues;
27  import org.springframework.web.bind.WebDataBinder;
28  import org.springframework.web.util.WebUtils;
29  
30  public class MultiBinderTests {
31  
32  	public static class TestBean {
33  		private String name;
34  
35  		public String getName() {
36  			return name;
37  		}
38  
39  		public void setName(String name) {
40  			this.name = name;
41  		}
42  
43  	}
44  
45  	@Test
46  	public void testVanillaBinding() throws Exception {
47  		WebDataBinder binder = new WebDataBinder(new TestBean(), "bean");
48  		binder.bind(new MutablePropertyValues(Collections.singletonMap("name", "foo")));
49  		TestBean bean = (TestBean) binder.getTarget();
50  		assertEquals("foo", bean.getName());
51  	}
52  
53  	@Test
54  	public void testModifiedBinding() throws Exception {
55  		WebDataBinder binder = new WebDataBinder(new TestBean(), "bean");
56  		binder.registerCustomEditor(String.class, "name", new PropertyEditorSupport() {
57  			@Override
58  			public void setAsText(String text) throws IllegalArgumentException {
59  				setValue(text.replace("name_", ""));
60  			}
61  		});
62  		// This is all very well but not actually what we want
63  		binder.bind(new MutablePropertyValues(Collections.singletonMap("name", "name_foo")));
64  		TestBean bean = (TestBean) binder.getTarget();
65  		assertEquals("foo", bean.getName());
66  	}
67  
68  	@Test
69  	public void testPrefixBinding() throws Exception {
70  		WebDataBinder binder = new WebDataBinder(new TestBean(), "bean");
71  		Map<String,String> values = new HashMap<String, String>();
72  		values.put("name_foo", "rubbish");
73  		// This is what we need...
74  		values.put("name", WebUtils.findParameterValue(values, "name"));
75  		binder.bind(new MutablePropertyValues(values));
76  		TestBean bean = (TestBean) binder.getTarget();
77  		assertEquals("foo", bean.getName());
78  	}
79  
80  }