org.springframework.beans.propertyeditors.StringTrimmerEditor#org.springframework.validation.DataBinder源码实例Demo

下面列出了org.springframework.beans.propertyeditors.StringTrimmerEditor#org.springframework.validation.DataBinder 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@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 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 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;
}
 
@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 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 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;
}
 
/**
 * 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;
}
 
@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 "";
            }
        }
    });
}
 
/**
 * 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;
}
 
@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 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;
}
 
源代码19 项目: entando-core   文件: UserController.java
@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);
}
 
源代码20 项目: entando-core   文件: PageService.java
@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;
}
 
源代码21 项目: entando-core   文件: PageService.java
@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);
    }
}
 
源代码22 项目: es   文件: FormModelMethodArgumentResolver.java
/**
 * 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;
}
 
源代码23 项目: dubbo-2.6.5   文件: DefaultDubboConfigBinder.java
@Override
public <C extends AbstractConfig> void bind(String prefix, C dubboConfig) {
    DataBinder dataBinder = new DataBinder(dubboConfig);
    // Set ignored*
    dataBinder.setIgnoreInvalidFields(isIgnoreInvalidFields());
    dataBinder.setIgnoreUnknownFields(isIgnoreUnknownFields());
    // Get properties under specified prefix from PropertySources
    Map<String, Object> properties = getSubProperties(getPropertySources(), prefix);
    // Convert Map to MutablePropertyValues
    MutablePropertyValues propertyValues = new MutablePropertyValues(properties);
    // Bind
    dataBinder.bind(propertyValues);
}
 
源代码24 项目: dubbo-2.6.5   文件: ReferenceBeanBuilder.java
@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));

}
 
@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 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 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());
}
 
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);
}
 
@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);
}