List of usage examples for org.springframework.validation DataBinder bind
public void bind(PropertyValues pvs)
From source file:de.interseroh.report.controller.ParameterFormBinder.java
public void bind(final ParameterForm parameterForm, final MultiValueMap<String, String> requestParameters, BindingResult bindingResult) {/*from w w w . j a va 2 s .c om*/ final MutablePropertyValues mpvs = createPropertyValues(parameterForm, requestParameters); DataBinder dataBinder = new DataBinder(parameterForm, bindingResult.getObjectName()); dataBinder.bind(mpvs); bindingResult.addAllErrors(dataBinder.getBindingResult()); }
From source file:com.alibaba.dubbo.config.spring.beans.factory.annotation.DubboConfigBindingBeanPostProcessor.java
@Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (beanName.equals(this.beanName)) { DataBinder dataBinder = new DataBinder(bean); // TODO ignore invalid fields by annotation attribute dataBinder.setIgnoreInvalidFields(true); dataBinder.bind(propertyValues); if (log.isInfoEnabled()) { log.info("The properties of bean [name : " + beanName + "] have been binding by values : " + Arrays.asList(propertyValues.getPropertyValues())); }/* ww w . j a va2 s . c o m*/ } return bean; }
From source file:com.opensymphony.able.action.JpaCrudActionBeanTest.java
@Test public void testIntrospection() throws Exception { Person bug = new Person(); DataBinder binder = new DataBinder(bug); MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.addPropertyValue("id", "123456"); binder.bind(propertyValues); Assert.assertEquals(new Integer(123456), bug.getId()); TypeConverter typeConverter = new BeanWrapperImpl(); Object value = typeConverter.convertIfNecessary("123456", Integer.class); Assert.assertEquals(new Integer(123456), value); }
From source file:de.iew.web.controllers.IdentityController.java
@RequestMapping(value = "/loginerror.html") public ModelAndView loginError(HttpServletRequest request) { LoginForm loginForm = createLoginForm(); DataBinder binder = new DataBinder(loginForm); MutablePropertyValues mutablePropertyValues = new MutablePropertyValues(request.getParameterMap()); binder.bind(mutablePropertyValues); ModelAndView mav = new ModelAndView(this.viewScript); mav.addObject(this.loginFormModelKey, loginForm); mav.addObject("error", true); mav.addObject("loginErrorMessage", "errors.login.denied.message"); // Hole den Login Fehler und verffentliche die Fehlermeldungen Exception e = (Exception) request.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION); if (e instanceof ValidatingFormAuthenticationFilter.LoginFormValidationException) { ValidatingFormAuthenticationFilter.LoginFormValidationException ex = (ValidatingFormAuthenticationFilter.LoginFormValidationException) e; BindingResult res = ex.getErrors(); /*// www .j a v a 2s. c om Oh man :-D @see http://stackoverflow.com/questions/6704478/access-spring-mvc-bindingresult-from-within-a-view */ mav.addObject(BindingResult.MODEL_KEY_PREFIX + this.loginFormModelKey, res); } return mav; }
From source file:de.iew.web.utils.ValidatingFormAuthenticationFilter.java
@Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { LoginForm loginForm = new LoginForm(); /*//w w w. j a v a2 s .co m Validiere zuerst die Logindaten. Da wir hier in einem Filter sind, mssen wir die Validierung per Hand vornehmen. Das Validierungsergebnis wird dann im Fehlerfall durch eine Exception mitgeteilt. @see <a href="http://static.springsource.org/spring/docs/3.0.x/reference/validation.html">http://static.springsource.org/spring/docs/3.0.x/reference/validation.html</a> */ DataBinder binder = new DataBinder(loginForm); binder.setValidator(this.validator); MutablePropertyValues mutablePropertyValues = new MutablePropertyValues(request.getParameterMap()); binder.bind(mutablePropertyValues); binder.validate(); BindingResult results = binder.getBindingResult(); if (results.hasErrors()) { throw new LoginFormValidationException("validation failed", results); } return super.attemptAuthentication(request, response); }
From source file:cherry.foundation.type.format.CustomNumberFormatTest.java
private String parseAndPrint(String name, String value) throws BindException { Map<String, String> paramMap = new HashMap<>(); paramMap.put(name, value);//from ww w . j a v a 2 s . c o m Form form = new Form(); DataBinder binder = new DataBinder(form, "target"); binder.setConversionService(conversionService); binder.bind(new MutablePropertyValues(paramMap)); BindingResult binding = BindingResultUtils.getBindingResult(binder.close(), "target"); return (String) binding.getFieldValue(name); }
From source file:org.synyx.hades.extensions.web.PageableArgumentResolver.java
public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest) { if (methodParameter.getParameterType().equals(Pageable.class)) { assertPageableUniqueness(methodParameter); Pageable request = getDefaultFromAnnotationOrFallback(methodParameter); ServletRequest servletRequest = (ServletRequest) webRequest.getNativeRequest(); PropertyValues propertyValues = new ServletRequestParameterPropertyValues(servletRequest, getPrefix(methodParameter), separator); DataBinder binder = new ServletRequestDataBinder(request); binder.initDirectFieldAccess();/* w w w . j a va2s . co m*/ binder.registerCustomEditor(Sort.class, new SortPropertyEditor("sort.dir", propertyValues)); binder.bind(propertyValues); if (request.getPageNumber() > 0) { request = new PageRequest(request.getPageNumber() - 1, request.getPageSize(), request.getSort()); } return request; } return UNRESOLVED; }
From source file:org.agatom.springatom.cmp.wizards.core.AbstractWizardProcessor.java
private void doBind(final DataBinder binder, Map<String, Object> params) throws Exception { if (LOGGER.isDebugEnabled()) { LOGGER.debug(String.format( "Binding allowed request parameters in %s to form object with name '%s', pre-bind formObject toString = %s", params, binder.getObjectName(), binder.getTarget())); if (binder.getAllowedFields() != null && binder.getAllowedFields().length > 0) { LOGGER.debug(/*from w ww . j a va 2 s . c om*/ String.format("(Allowed fields are %s)", StylerUtils.style(binder.getAllowedFields()))); } else { LOGGER.debug("(Any field is allowed)"); } } binder.bind(new MutablePropertyValues(params)); if (LOGGER.isDebugEnabled()) { LOGGER.debug(String.format( "Binding completed for form object with name '%s', post-bind formObject toString = %s", binder.getObjectName(), binder.getTarget())); LOGGER.debug(String.format("There are [%d] errors, details: %s", binder.getBindingResult().getErrorCount(), binder.getBindingResult().getAllErrors())); } }
From source file:utils.play.BugWorkaroundForm.java
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override// w w w . j a va 2s .c o m
public Form<T> bind(final Map<String, String> data, final String... allowedFields) {
DataBinder dataBinder = null;
Map<String, String> objectData = data;
if (rootName == null) {
dataBinder = new DataBinder(blankInstance());
} else {
dataBinder = new DataBinder(blankInstance(), rootName);
objectData = new HashMap<String, String>();
for (String key : data.keySet()) {
if (key.startsWith(rootName + ".")) {
objectData.put(key.substring(rootName.length() + 1), data.get(key));
}
}
}
if (allowedFields.length > 0) {
dataBinder.setAllowedFields(allowedFields);
}
SpringValidatorAdapter validator = new SpringValidatorAdapter(Validation.getValidator());
dataBinder.setValidator(validator);
dataBinder.setConversionService(play.data.format.Formatters.conversion);
dataBinder.setAutoGrowNestedPaths(true);
dataBinder.bind(new MutablePropertyValues(objectData));
Set<ConstraintViolation<Object>> validationErrors = validator.validate(dataBinder.getTarget());
BindingResult result = dataBinder.getBindingResult();
for (ConstraintViolation<Object> violation : validationErrors) {
String field = violation.getPropertyPath().toString();
FieldError fieldError = result.getFieldError(field);
if (fieldError == null || !fieldError.isBindingFailure()) {
try {
result.rejectValue(field,
violation.getConstraintDescriptor().getAnnotation().annotationType().getSimpleName(),
getArgumentsForConstraint(result.getObjectName(), field,
violation.getConstraintDescriptor()),
violation.getMessage());
} catch (NotReadablePropertyException ex) {
throw new IllegalStateException("JSR-303 validated property '" + field
+ "' does not have a corresponding accessor for data binding - "
+ "check your DataBinder's configuration (bean property versus direct field access)",
ex);
}
}
}
if (result.hasErrors()) {
Map<String, List<ValidationError>> errors = new HashMap<String, List<ValidationError>>();
for (FieldError error : result.getFieldErrors()) {
String key = error.getObjectName() + "." + error.getField();
System.out.println("Error field:" + key);
if (key.startsWith("target.") && rootName == null) {
key = key.substring(7);
}
List<Object> arguments = new ArrayList<>();
for (Object arg : error.getArguments()) {
if (!(arg instanceof org.springframework.context.support.DefaultMessageSourceResolvable)) {
arguments.add(arg);
}
}
if (!errors.containsKey(key)) {
errors.put(key, new ArrayList<ValidationError>());
}
errors.get(key).add(new ValidationError(key,
error.isBindingFailure() ? "error.invalid" : error.getDefaultMessage(), arguments));
}
return new Form(rootName, backedType, data, errors, F.Option.None());
} else {
Object globalError = null;
if (result.getTarget() != null) {
try {
java.lang.reflect.Method v = result.getTarget().getClass().getMethod("validate");
globalError = v.invoke(result.getTarget());
} catch (NoSuchMethodException e) {
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
if (globalError != null) {
Map<String, List<ValidationError>> errors = new HashMap<String, List<ValidationError>>();
if (globalError instanceof String) {
errors.put("", new ArrayList<ValidationError>());
errors.get("").add(new ValidationError("", (String) globalError, new ArrayList()));
} else if (globalError instanceof List) {
for (ValidationError error : (List<ValidationError>) globalError) {
List<ValidationError> errorsForKey = errors.get(error.key());
if (errorsForKey == null) {
errors.put(error.key(), errorsForKey = new ArrayList<ValidationError>());
}
errorsForKey.add(error);
}
} else if (globalError instanceof Map) {
errors = (Map<String, List<ValidationError>>) globalError;
}
if (result.getTarget() != null) {
return new Form(rootName, backedType, data, errors, F.Option.Some((T) result.getTarget()));
} else {
return new Form(rootName, backedType, data, errors, F.Option.None());
}
}
return new Form(rootName, backedType, new HashMap<String, String>(data),
new HashMap<String, List<ValidationError>>(errors), F.Option.Some((T) result.getTarget()));
}
}
From source file:org.gvnix.web.json.DataBinderDeserializer.java
/** * Deserializes JSON content into Map<String, String> format and then uses a * Spring {@link DataBinder} to bind the data from JSON message to JavaBean * objects./*from ww w . ja v a 2 s . com*/ * <p/> * It is a workaround for issue * https://jira.springsource.org/browse/SPR-6731 that should be removed from * next gvNIX releases when that issue will be resolved. * * @param parser Parsed used for reading JSON content * @param ctxt Context that can be used to access information about this * deserialization activity. * * @return Deserializer value */ @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public Object deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException, JsonProcessingException { JsonToken t = parser.getCurrentToken(); MutablePropertyValues propertyValues = new MutablePropertyValues(); // Get target from DataBinder from local thread. If its a bean // collection // prepares array index for property names. Otherwise continue. DataBinder binder = (DataBinder) ThreadLocalUtil .getThreadVariable(BindingResult.MODEL_KEY_PREFIX.concat("JSON_DataBinder")); Object target = binder.getTarget(); // For DstaBinderList instances, contentTarget contains the final bean // for binding. DataBinderList is just a simple wrapper to deserialize // bean wrapper using DataBinder Object contentTarget = null; if (t == JsonToken.START_OBJECT) { String prefix = null; if (target instanceof DataBinderList) { prefix = binder.getObjectName().concat("[").concat(Integer.toString(((Collection) target).size())) .concat("]."); // BeanWrapperImpl cannot create new instances if generics // don't specify content class, so do it by hand contentTarget = BeanUtils.instantiateClass(((DataBinderList) target).getContentClass()); ((Collection) target).add(contentTarget); } else if (target instanceof Map) { // TODO LOGGER.warn("Map deserialization not implemented yet!"); } Map<String, String> obj = readObject(parser, ctxt, prefix); propertyValues.addPropertyValues(obj); } else { LOGGER.warn("Deserialization for non-object not implemented yet!"); return null; // TODO? } // bind to the target object binder.bind(propertyValues); // Note there is no need to validate the target object because // RequestResponseBodyMethodProcessor.resolveArgument() does it on top // of including BindingResult as Model attribute // For DAtaBinderList the contentTarget contains the final bean to // make the binding, so we must return it if (contentTarget != null) { return contentTarget; } return binder.getTarget(); }