org.springframework.validation.DataBinder Java Examples

The following examples show how to use org.springframework.validation.DataBinder. 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: MoneyFormattingTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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 #2
Source File: PageService.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public PageConfigurationDto restorePageConfiguration(String pageCode) {
    try {
        IPage pageD = this.loadPage(pageCode, STATUS_DRAFT);
        if (null == pageD) {
            throw new ResourceNotFoundException(ERRCODE_PAGE_NOT_FOUND, "page", pageCode);
        }
        IPage pageO = this.loadPage(pageCode, STATUS_ONLINE);
        if (null == pageO) {
            DataBinder binder = new DataBinder(pageCode);
            BindingResult bindingResult = binder.getBindingResult();
            bindingResult.reject(ERRCODE_STATUS_INVALID, new String[]{pageCode}, "page.status.invalid");
            throw new ValidationGenericException(bindingResult);
        }
        pageD.setMetadata(pageO.getMetadata());
        pageD.setWidgets(pageO.getWidgets());
        this.getPageManager().updatePage(pageD);
        PageConfigurationDto pageConfigurationDto = new PageConfigurationDto(pageO, STATUS_ONLINE);
        return pageConfigurationDto;
    } catch (ApsSystemException e) {
        logger.error("Error restoring page {} configuration", pageCode, e);
        throw new RestServerError("error in restoring page configuration", e);
    }
}
 
Example #3
Source File: PageService.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public PageDto getPage(String pageCode, String status) {
    IPage page = this.loadPage(pageCode, status);
    if (null == page) {
        logger.warn("no page found with code {} and status {}", pageCode, status);
        DataBinder binder = new DataBinder(pageCode);
        BindingResult bindingResult = binder.getBindingResult();
        String errorCode = status.equals(STATUS_DRAFT) ? ERRCODE_PAGE_NOT_FOUND : ERRCODE_PAGE_ONLY_DRAFT;
        bindingResult.reject(errorCode, new String[]{pageCode, status}, "page.NotFound");
        throw new ResourceNotFoundException(bindingResult);
    }
    String token = this.getPageTokenManager().encrypt(pageCode);
    PageDto pageDto = this.getDtoBuilder().convert(page);
    pageDto.setToken(token);
    pageDto.setReferences(this.getReferencesInfo(page));
    return pageDto;
}
 
Example #4
Source File: MoneyFormattingTests.java    From spring-analysis-note with 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 #5
Source File: UserController.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@RestAccessControl(permission = Permission.MANAGE_USERS)
@RequestMapping(value = "/{target:.+}/authorities", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<SimpleRestResponse> deleteUserAuthorities(@ModelAttribute("user") UserDetails user, @PathVariable String target) throws ApsSystemException {
    logger.debug("user {} requesting delete authorities for username {}", user.getUsername(), target);
    DataBinder binder = new DataBinder(target);
    BindingResult bindingResult = binder.getBindingResult();
    //field validations
    if (bindingResult.hasErrors()) {
        throw new ValidationGenericException(bindingResult);
    }
    //business validations
    getUserValidator().validateUpdateSelf(target, user.getUsername(), bindingResult);
    if (bindingResult.hasErrors()) {
        throw new ValidationGenericException(bindingResult);
    }
    this.getUserService().deleteUserAuthorities(target);
    return new ResponseEntity<>(new SimpleRestResponse<>(new ArrayList<>()), HttpStatus.OK);
}
 
Example #6
Source File: MoneyFormattingTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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 #7
Source File: MoneyFormattingTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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());
}
 
Example #8
Source File: NumberFormattingTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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);
}
 
Example #9
Source File: FormModelMethodArgumentResolver.java    From es with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #10
Source File: ServletModelAttributeMethodProcessor.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * 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} if no suitable
 * conversion found
 */
@Nullable
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;
}
 
Example #11
Source File: MoneyFormattingTests.java    From java-technology-stack with 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 #12
Source File: ServletModelAttributeMethodProcessor.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #13
Source File: MoneyFormattingTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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());
}
 
Example #14
Source File: NumberFormattingTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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);
}
 
Example #15
Source File: NumberFormattingTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #16
Source File: MoneyFormattingTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #17
Source File: ServletModelAttributeMethodProcessor.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * 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} if no suitable
 * conversion found
 */
@Nullable
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;
}
 
Example #18
Source File: MoneyFormattingTests.java    From spring4-understanding with Apache License 2.0 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 #19
Source File: FormModelMethodArgumentResolver.java    From distributed-transaction-process with MIT License 6 votes vote down vote up
/**
 * 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;
}
 
Example #20
Source File: MyBeanWrapperFieldSetMapper.java    From SpringBootBucket with MIT License 6 votes vote down vote up
@Override
protected void initBinder(DataBinder binder) {
    binder.registerCustomEditor(Timestamp.class, new PropertyEditorSupport() {
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            if (StringUtils.isNotEmpty(text)) {
                setValue(DateUtil.parseTimestamp(text));
            } else {
                setValue(null);
            }
        }

        @Override
        public String getAsText() throws IllegalArgumentException {
            Object date = getValue();
            if (date != null) {
                return DateUtil.formatTimestamp((Timestamp) date);
            } else {
                return "";
            }
        }
    });
}
 
Example #21
Source File: MoneyFormattingTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 #22
Source File: ServletModelAttributeMethodProcessor.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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} if no suitable
 * conversion found
 * @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;
}
 
Example #23
Source File: JodaTimeFormattingTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #24
Source File: BaseItemProcessor.java    From spring-boot-doma2-sample with Apache License 2.0 5 votes vote down vote up
@Override
public O process(I item) {
    val validator = getValidator();
    val context = BatchContextHolder.getContext();

    // 対象件数を加算する
    context.increaseTotalCount();

    if (validator != null) {
        val binder = new DataBinder(item);
        binder.setValidator(validator);
        binder.validate();

        val result = binder.getBindingResult();
        if (result.hasErrors()) {
            // バリデーションエラーがある場合
            onValidationError(context, result, item);

            // エラー件数をカウントする
            increaseErrorCount(context, result, item);

            // nullを返すとItemWriterに渡されない
            return null;
        }
    }

    // 実処理
    O output = doProcess(context, item);

    // 処理件数をカウントする
    increaseProcessCount(context, item);

    return output;
}
 
Example #25
Source File: ReferenceBeanBuilder.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
@Override
protected void preConfigureBean(Reference reference, ReferenceBean referenceBean) {
    Assert.notNull(interfaceClass, "The interface class must set first!");
    DataBinder dataBinder = new DataBinder(referenceBean);
    // Register CustomEditors for special fields
    dataBinder.registerCustomEditor(String.class, "filter", new StringTrimmerEditor(true));
    dataBinder.registerCustomEditor(String.class, "listener", new StringTrimmerEditor(true));
    dataBinder.registerCustomEditor(Map.class, "parameters", new PropertyEditorSupport() {

        public void setAsText(String text) throws java.lang.IllegalArgumentException {
            // Trim all whitespace
            String content = StringUtils.trimAllWhitespace(text);
            if (!StringUtils.hasText(content)) { // No content , ignore directly
                return;
            }
            // replace "=" to ","
            content = StringUtils.replace(content, "=", ",");
            // replace ":" to ","
            content = StringUtils.replace(content, ":", ",");
            // String[] to Map
            Map<String, String> parameters = CollectionUtils.toStringMap(commaDelimitedListToStringArray(content));
            setValue(parameters);
        }
    });

    // Bind annotation attributes
    dataBinder.bind(new AnnotationPropertyValuesAdapter(reference, applicationContext.getEnvironment(), IGNORE_FIELD_NAMES));

}
 
Example #26
Source File: EntityController.java    From QuickProject with Apache License 2.0 5 votes vote down vote up
public Entity parseModel(HttpServletRequest request) {
    Object o = null;
    try {
        o = getEntityClass().newInstance();
    } catch (Exception e) {
        throw new RuntimeException("无法创建类的实例:" + getEntityClass());
    }
    DataBinder dataBinder = new DataBinder(o);
    dataBinder.registerCustomEditor(Time.class, new TimeEditor());
    MutablePropertyValues mpvs = new ServletRequestParameterPropertyValues(request);
    dataBinder.bind(mpvs);

    return (Entity) o;
}
 
Example #27
Source File: MoneyFormattingTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #28
Source File: MoneyFormattingTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #29
Source File: ApiConsumerServiceImpl.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void validateForCreate(ApiConsumer consumer) throws ApsSystemException {

        if (consumerManager.getConsumerRecord(consumer.getKey()) != null) {
            DataBinder binder = new DataBinder(consumer);
            BindingResult bindingResult = binder.getBindingResult();
            bindingResult.reject(ERRCODE_CONSUMER_ALREADY_EXISTS, new String[]{consumer.getKey()}, "api.consumer.exists");
            throw new ValidationConflictException(bindingResult);
        }
    }
 
Example #30
Source File: MoneyFormattingTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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());
}