@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()); }
@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()); }
@Test public void testAmountWithNumberFormat3() { FormattedMoneyHolder3 bean = new FormattedMoneyHolder3(); DataBinder binder = new DataBinder(bean); binder.setConversionService(conversionService); MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("amount", "10%"); binder.bind(propertyValues); assertEquals(0, binder.getBindingResult().getErrorCount()); assertEquals("10%", binder.getBindingResult().getFieldValue("amount")); assertTrue(bean.getAmount().getNumber().doubleValue() == 0.1d); assertEquals("USD", bean.getAmount().getCurrency().getCurrencyCode()); }
@Test public void testAmountWithNumberFormat5() { FormattedMoneyHolder5 bean = new FormattedMoneyHolder5(); DataBinder binder = new DataBinder(bean); binder.setConversionService(conversionService); MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("amount", "USD 10.50"); binder.bind(propertyValues); assertEquals(0, binder.getBindingResult().getErrorCount()); assertEquals("USD 010.500", 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("USD 010.500", binder.getBindingResult().getFieldValue("amount")); assertTrue(bean.getAmount().getNumber().doubleValue() == 10.5d); assertEquals("USD", bean.getAmount().getCurrency().getCurrencyCode()); }
@Before public void setUp() { DefaultConversionService.addDefaultConverters(conversionService); conversionService.setEmbeddedValueResolver(new StringValueResolver() { @Override public String resolveStringValue(String strVal) { if ("${pattern}".equals(strVal)) { return "#,##.00"; } else { return strVal; } } }); conversionService.addFormatterForFieldType(Number.class, new NumberStyleFormatter()); conversionService.addFormatterForFieldAnnotation(new NumberFormatAnnotationFormatterFactory()); LocaleContextHolder.setLocale(Locale.US); binder = new DataBinder(new TestBean()); binder.setConversionService(conversionService); }
/** * Create a model attribute from a String request value (e.g. URI template * variable, request parameter) using type conversion. * <p>The default implementation converts only if there a registered * {@link Converter} that can perform the conversion. * @param sourceValue the source value to create the model attribute from * @param attributeName the name of the attribute, never {@code null} * @param methodParam the method parameter * @param binderFactory for creating WebDataBinder instance * @param request the current request * @return the created model attribute, or {@code null} * @throws Exception */ protected Object createAttributeFromRequestValue(String sourceValue, String attributeName, MethodParameter methodParam, WebDataBinderFactory binderFactory, NativeWebRequest request) throws Exception { DataBinder binder = binderFactory.createBinder(request, null, attributeName); ConversionService conversionService = binder.getConversionService(); if (conversionService != null) { TypeDescriptor source = TypeDescriptor.valueOf(String.class); TypeDescriptor target = new TypeDescriptor(methodParam); if (conversionService.canConvert(source, target)) { return binder.convertIfNecessary(sourceValue, methodParam.getParameterType(), methodParam); } } return null; }
@Test public void testPlaceholdersErrorInNonEnumerable() { TestBean target = new TestBean(); DataBinder binder = new DataBinder(target); this.propertySources.addFirst(new PropertySource<Object>("application", "STUFF") { @Override public Object getProperty(String name) { return new Object(); } }); binder.bind(new PropertySourcesPropertyValues(this.propertySources, (Collection<String>) null, Collections.singleton("name"))); assertThat(target.getName()).isNull(); }
@Test public void testFirstCollectionPropertyWinsNestedAttributes() throws Exception { ListTestBean target = new ListTestBean(); DataBinder binder = new DataBinder(target); Map<String, Object> first = new LinkedHashMap<String, Object>(); first.put("list[0].description", "another description"); Map<String, Object> second = new LinkedHashMap<String, Object>(); second.put("list[0].name", "first name"); second.put("list[0].description", "first description"); second.put("list[1].name", "second name"); second.put("list[1].description", "second description"); this.propertySources.addFirst(new MapPropertySource("s", second)); this.propertySources.addFirst(new MapPropertySource("f", first)); binder.bind(new PropertySourcesPropertyValues(this.propertySources)); target.getList(); assertThat(target.getList()).hasSize(1); assertThat(target.getList().get(0).getDescription()) .isEqualTo("another description"); assertThat(target.getList().get(0).getName()).isNull(); }
protected Object createAttributeFromRequestValue(String sourceValue, String attributeName, MethodParameter parameter, WebDataBinderFactory binderFactory, NativeWebRequest request) throws Exception { DataBinder binder = binderFactory.createBinder(request, null, attributeName); ConversionService conversionService = binder.getConversionService(); if (conversionService != null) { TypeDescriptor source = TypeDescriptor.valueOf(String.class); TypeDescriptor target = new TypeDescriptor(parameter); if (conversionService.canConvert(source, target)) { return binder.convertIfNecessary(sourceValue, parameter.getParameterType(), parameter); } } return null; }
/** * Create a model attribute from a String request value (e.g. URI template * variable, request parameter) using type conversion. * <p>The default implementation converts only if there a registered * {@link org.springframework.core.convert.converter.Converter} that can perform the conversion. * * @param sourceValue the source value to create the model attribute from * @param attributeName the name of the attribute, never {@code null} * @param parameter the method parameter * @param binderFactory for creating WebDataBinder instance * @param request the current request * @return the created model attribute, or {@code null} * @throws Exception */ protected Object createAttributeFromRequestValue(String sourceValue, String attributeName, MethodParameter parameter, WebDataBinderFactory binderFactory, NativeWebRequest request) throws Exception { DataBinder binder = binderFactory.createBinder(request, null, attributeName); ConversionService conversionService = binder.getConversionService(); if (conversionService != null) { TypeDescriptor source = TypeDescriptor.valueOf(String.class); TypeDescriptor target = new TypeDescriptor(parameter); if (conversionService.canConvert(source, target)) { return binder.convertIfNecessary(sourceValue, parameter.getParameterType(), parameter); } } return null; }
/** * Create a model attribute from a String request value (e.g. URI template * variable, request parameter) using type conversion. * <p>The default implementation converts only if there a registered * {@link Converter} that can perform the conversion. * @param sourceValue the source value to create the model attribute from * @param attributeName the name of the attribute, never {@code null} * @param parameter the method parameter * @param binderFactory for creating WebDataBinder instance * @param request the current request * @return the created model attribute, or {@code null} * @throws Exception */ protected Object createAttributeFromRequestValue(String sourceValue, String attributeName, MethodParameter parameter, WebDataBinderFactory binderFactory, NativeWebRequest request) throws Exception { DataBinder binder = binderFactory.createBinder(request, null, attributeName); ConversionService conversionService = binder.getConversionService(); if (conversionService != null) { TypeDescriptor source = TypeDescriptor.valueOf(String.class); TypeDescriptor target = new TypeDescriptor(parameter); if (conversionService.canConvert(source, target)) { return binder.convertIfNecessary(sourceValue, parameter.getParameterType(), parameter); } } return null; }
@Test public void testPlaceholdersErrorInNonEnumerable() { TestBean target = new TestBean(); DataBinder binder = new DataBinder(target); this.propertySources.addFirst(new PropertySource<Object>("application", "STUFF") { @Override public Object getProperty(String name) { return new Object(); } }); binder.bind(new PropertySourcesPropertyValues(this.propertySources, (Collection<String>) null, Collections.singleton("name"))); assertEquals(null, target.getName()); }
@Test public void testSave() throws Exception { request = newPost("/userform.html"); // set updated properties first since adding them later will // result in multiple parameters with the same name getting sent User user = ((UserManager) applicationContext.getBean("userManager")).getUser("-1"); user.setConfirmPassword(user.getPassword()); user.setLastName("Updated Last Name"); request.setRemoteUser(user.getUsername()); BindingResult errors = new DataBinder(user).getBindingResult(); c.onSubmit(user, errors, request, new MockHttpServletResponse()); assertFalse(errors.hasErrors()); assertNotNull(request.getSession().getAttribute("successMessages")); }
@Before public void setUp() { DefaultConversionService.addDefaultConverters(conversionService); conversionService.setEmbeddedValueResolver(new StringValueResolver() { @Override public String resolveStringValue(String strVal) { if ("${pattern}".equals(strVal)) { return "#,##.00"; } else { return strVal; } } }); conversionService.addFormatterForFieldType(Number.class, new NumberFormatter()); conversionService.addFormatterForFieldAnnotation(new NumberFormatAnnotationFormatterFactory()); LocaleContextHolder.setLocale(Locale.US); binder = new DataBinder(new TestBean()); binder.setConversionService(conversionService); }
private void setUp(JodaTimeFormatterRegistrar registrar) { conversionService = new FormattingConversionService(); DefaultConversionService.addDefaultConverters(conversionService); registrar.registerFormatters(conversionService); JodaTimeBean bean = new JodaTimeBean(); bean.getChildren().add(new JodaTimeBean()); binder = new DataBinder(bean); binder.setConversionService(conversionService); LocaleContextHolder.setLocale(Locale.US); JodaTimeContext context = new JodaTimeContext(); context.setTimeZone(DateTimeZone.forID("-05:00")); JodaTimeContextHolder.setJodaTimeContext(context); }
public void testBindTagWithIndexedPropertiesAndCustomEditor() throws JspException { PageContext pc = createPageContext(); IndexedTestBean tb = new IndexedTestBean(); DataBinder binder = new ServletRequestDataBinder(tb, "tb"); binder.registerCustomEditor(TestBean.class, null, new PropertyEditorSupport() { @Override public String getAsText() { return "something"; } }); Errors errors = binder.getBindingResult(); errors.rejectValue("array[0]", "code1", "message1"); errors.rejectValue("array[0]", "code2", "message2"); pc.getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "tb", errors); BindTag tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb.array[0]"); assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); assertTrue("Has status variable", status != null); assertTrue("Correct expression", "array[0]".equals(status.getExpression())); // because of the custom editor getValue() should return a String assertTrue("Value is TestBean", status.getValue() instanceof String); assertTrue("Correct value", "something".equals(status.getValue())); }
@Test public void testValidation() throws BindException{ Employee employee = new Employee(); DataBinder binder = new DataBinder(employee); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.addPropertyValue("empId", "AA1000"); pvs.addPropertyValue("empName", "Nobody"); pvs.addPropertyValue("empAge", 10); binder.bind(pvs); Validator validator = new EmployeeValidator(); Errors errors = binder.getBindingResult(); validator.validate(employee, errors); assertFalse(errors.hasFieldErrors("empId")); assertFalse(errors.hasFieldErrors("empName")); assertTrue(errors.hasFieldErrors("empAge")); }
private ResponseEntity<String> validate(Object dto) { final DataBinder binder = new DataBinder(dto); binder.setValidator(mvcValidator); binder.validate(); return ResponseEntity.ok(binder.getBindingResult().hasErrors() ? BODY_INVALID_VALUE : BODY_VALID_VALUE); }
@Test public void testAmountWithNumberFormat2() { FormattedMoneyHolder2 bean = new FormattedMoneyHolder2(); 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.5", binder.getBindingResult().getFieldValue("amount")); assertTrue(bean.getAmount().getNumber().doubleValue() == 10.5d); assertEquals("USD", bean.getAmount().getCurrency().getCurrencyCode()); }
@Test public void testAmountWithNumberFormat4() { FormattedMoneyHolder4 bean = new FormattedMoneyHolder4(); DataBinder binder = new DataBinder(bean); binder.setConversionService(conversionService); MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("amount", "010.500"); binder.bind(propertyValues); assertEquals(0, binder.getBindingResult().getErrorCount()); assertEquals("010.500", binder.getBindingResult().getFieldValue("amount")); assertTrue(bean.getAmount().getNumber().doubleValue() == 10.5d); assertEquals("USD", bean.getAmount().getCurrency().getCurrencyCode()); }
@Test public void testBindDateWithoutErrorFallingBackToDateConstructor() { DataBinder binder = new DataBinder(new JodaTimeBean()); MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("date", "Sat, 12 Aug 1995 13:30:00 GMT"); binder.bind(propertyValues); assertEquals(0, binder.getBindingResult().getErrorCount()); }
private void setUp(DateTimeFormatterRegistrar registrar) { conversionService = new FormattingConversionService(); DefaultConversionService.addDefaultConverters(conversionService); registrar.registerFormatters(conversionService); DateTimeBean bean = new DateTimeBean(); bean.getChildren().add(new DateTimeBean()); binder = new DataBinder(bean); binder.setConversionService(conversionService); LocaleContextHolder.setLocale(Locale.US); DateTimeContext context = new DateTimeContext(); context.setTimeZone(ZoneId.of("-05:00")); DateTimeContextHolder.setDateTimeContext(context); }
private void setUp(DateFormatterRegistrar registrar) { DefaultConversionService.addDefaultConverters(conversionService); registrar.registerFormatters(conversionService); SimpleDateBean bean = new SimpleDateBean(); bean.getChildren().add(new SimpleDateBean()); binder = new DataBinder(bean); binder.setConversionService(conversionService); LocaleContextHolder.setLocale(Locale.US); }
@Override public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { DataBinder dataBinder = binderFactory.createBinder(webRequest, null, null); ModelMap redirectAttributes = new RedirectAttributesModelMap(dataBinder); mavContainer.setRedirectModel(redirectAttributes); return redirectAttributes; }
@Before public void setup() { this.conversionService = new DefaultFormattingConversionService(); DataBinder dataBinder = new DataBinder(null); dataBinder.setConversionService(conversionService); this.redirectAttributes = new RedirectAttributesModelMap(dataBinder); }
@Test public void bindTagWithIndexedPropertiesAndCustomEditor() throws JspException { PageContext pc = createPageContext(); IndexedTestBean tb = new IndexedTestBean(); DataBinder binder = new ServletRequestDataBinder(tb, "tb"); binder.registerCustomEditor(TestBean.class, null, new PropertyEditorSupport() { @Override public String getAsText() { return "something"; } }); Errors errors = binder.getBindingResult(); errors.rejectValue("array[0]", "code1", "message1"); errors.rejectValue("array[0]", "code2", "message2"); pc.getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "tb", errors); BindTag tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb.array[0]"); assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); assertTrue("Has status variable", status != null); assertTrue("Correct expression", "array[0]".equals(status.getExpression())); // because of the custom editor getValue() should return a String assertTrue("Value is TestBean", status.getValue() instanceof String); assertTrue("Correct value", "something".equals(status.getValue())); }
@Test public void testPlaceholdersBinding() { TestBean target = new TestBean(); DataBinder binder = new DataBinder(target); binder.bind(new PropertySourcesPropertyValues(this.propertySources)); assertThat(target.getName()).isEqualTo("bar"); }
@Test public void testPlaceholdersBindingNonEnumerable() { FooBean target = new FooBean(); DataBinder binder = new DataBinder(target); binder.bind(new PropertySourcesPropertyValues(this.propertySources, (Collection<String>) null, Collections.singleton("foo"))); assertThat(target.getFoo()).isEqualTo("bar"); }
@Test public void testPlaceholdersBindingWithError() { TestBean target = new TestBean(); DataBinder binder = new DataBinder(target); this.propertySources.addFirst(new MapPropertySource("another", Collections.<String, Object>singletonMap("something", "${nonexistent}"))); binder.bind(new PropertySourcesPropertyValues(this.propertySources)); assertThat(target.getName()).isEqualTo("bar"); }
@Test public void testCollectionProperty() throws Exception { ListBean target = new ListBean(); DataBinder binder = new DataBinder(target); Map<String, Object> map = new LinkedHashMap<String, Object>(); map.put("list[0]", "v0"); map.put("list[1]", "v1"); this.propertySources.addFirst(new MapPropertySource("values", map)); binder.bind(new PropertySourcesPropertyValues(this.propertySources)); assertThat(target.getList()).containsExactly("v0", "v1"); }
@Test public void testFirstCollectionPropertyWins() throws Exception { ListBean target = new ListBean(); DataBinder binder = new DataBinder(target); Map<String, Object> first = new LinkedHashMap<String, Object>(); first.put("list[0]", "f0"); Map<String, Object> second = new LinkedHashMap<String, Object>(); second.put("list[0]", "s0"); second.put("list[1]", "s1"); this.propertySources.addFirst(new MapPropertySource("s", second)); this.propertySources.addFirst(new MapPropertySource("f", first)); binder.bind(new PropertySourcesPropertyValues(this.propertySources)); assertThat(target.getList()).containsExactly("f0"); }
private BindingResult bind(DataBinder binder, Object target, String values) throws Exception { Properties properties = PropertiesLoaderUtils .loadProperties(new ByteArrayResource(values.getBytes())); binder.bind(new MutablePropertyValues(properties)); binder.validate(); return binder.getBindingResult(); }
protected void init() { this.configurationWrapper = new BeanWrapperImpl(this.configuration); this.parameterFields = getParameterFields(this.configuration); this.dataBinder = new DataBinder(this.configuration, "Configuration"); allowFieldsForDataBinding(); registerPropertyEditors(); checkForValidator(); }