List of usage examples for org.springframework.validation DataBinder getBindingResult
public BindingResult getBindingResult()
From source file:de.interseroh.report.controller.ParameterFormBinder.java
public void bind(final ParameterForm parameterForm, final MultiValueMap<String, String> requestParameters, BindingResult bindingResult) {/*from w ww .j a v a 2 s . co m*/ final MutablePropertyValues mpvs = createPropertyValues(parameterForm, requestParameters); DataBinder dataBinder = new DataBinder(parameterForm, bindingResult.getObjectName()); dataBinder.bind(mpvs); bindingResult.addAllErrors(dataBinder.getBindingResult()); }
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 a 2s . c om*/ 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:org.agatom.springatom.cmp.wizards.core.AbstractWizardProcessor.java
/** * If {@link org.springframework.validation.DataBinder#getBindingResult()}} contains any errors then this method * will update {@code localResult} with : * <ol>/*from ww w. j a va2 s. co m*/ * <li>{@link org.springframework.validation.ObjectError} to {@link org.agatom.springatom.cmp.wizards.data.result.WizardResult#addBindingError(org.springframework.validation.ObjectError)}</li> * <li>{@link org.agatom.springatom.cmp.wizards.data.result.FeedbackMessage} to {@link org.agatom.springatom.cmp.wizards.data.result.WizardResult#addFeedbackMessage(FeedbackMessage)}</li> * </ol> * * @param binder current binder * @param locale current locale * @param localResult current result * * @see org.agatom.springatom.cmp.wizards.data.result.FeedbackMessage#newError() * @see org.agatom.springatom.cmp.wizards.data.result.FeedbackType * @see org.springframework.validation.Errors * @see #getBindErrorFM(org.springframework.validation.ObjectError, java.util.Locale) */ private void addErrorsToResultIfAny(final DataBinder binder, final Locale locale, final WizardResult localResult) { final Errors errors = binder.getBindingResult(); if (errors.hasErrors()) { final Object contextObject = binder.getTarget(); LOGGER.warn(String.format("Found %d binding bindingResult for context object=%s", errors.getErrorCount(), contextObject)); for (final ObjectError objectError : errors.getAllErrors()) { localResult.addFeedbackMessage(this.getBindErrorFM(objectError, locale)); localResult.addBindingError(objectError); } } }
From source file:org.agatom.springatom.cmp.wizards.core.AbstractWizardProcessor.java
@SuppressWarnings("UnusedAssignment") private void doValidate(final WizardResult result, final DataBinder binder, String step, final Map<String, Object> formData, final Locale locale) throws Exception { final Object target = binder.getTarget(); if (!StringUtils.hasText(step)) { // Wizard submission, because step is null step = this.stepHelperDelegate.getLastStep(); if (!this.stepHelperDelegate.isValidationEnabled(step)) { // reset the step again step = null;/*from ww w . j a va 2s.co m*/ } } try { final BindingResult bindingResult = binder.getBindingResult(); boolean alreadyValidate = false; if (this.localValidator != null) { if (LOGGER.isDebugEnabled()) { LOGGER.debug(String.format("Validating via Validator instance=%s", this.localValidator)); } this.validationService.validate(this.localValidator, bindingResult, result); alreadyValidate = true; } if (!alreadyValidate) { final ValidationBean bean = new ValidationBean(); bean.setPartialResult(result); bean.setStepId(step); bean.setCommandBean(bindingResult.getTarget()); bean.setCommandBeanName(this.getContextObjectName()); bean.setFormData(formData); bean.setBindingModel(formData); if (this.validationService.canValidate(bean)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug( String.format("Validating via validation service for validationBean=%s", bean)); } this.validationService.validate(bean); alreadyValidate = true; } } /* Will validate only if not yet validated it is not step submission and wizard is allowed to validate * This a last opportunity to validate however unlike validation via * - localValidator * - validationService * this validation will be run only if * - not yet validated * - current (or last) step has validation flag set * - entire wizard has validation flag set */ if (!alreadyValidate && this.isValidationEnabledForStep(step) && this.isValidationEnabled()) { LOGGER.debug(String.format( "Not yet validated (tried localValidator and via validationService), assuming that is wizard submission due to step===null, validating through binder")); final Validator validator = binder.getValidator(); if (validator != null) { final long startTime = System.nanoTime(); validator.validate(target, bindingResult); final long endTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime); result.addDebugData(WizardDebugDataKeys.VALIDATION_TIME, endTime); result.addDebugData(WizardDebugDataKeys.VALIDATOR, ClassUtils.getShortName(validator.getClass())); } } if (LOGGER.isDebugEnabled()) { final Set<Message> messages = result.getValidationMessages(); final short count = (short) (messages == null ? 0 : messages.size()); LOGGER.debug(String.format("Validation completed, found %d validation errors", count)); } } catch (Exception exp) { // Catch any validation exception and add it as an error LOGGER.error("Validation failed either via [localValidator,validationService,binder#validator", exp); result.addError(exp); result.addFeedbackMessage(FeedbackMessage.newError() .setTitle(this.messageSource.getMessage("sa.wiz.validationError.title", locale)) .setMessage(this.messageSource.getMessage("sa.wiz.validationError.msg", new Object[] { target.toString() }, locale))); } }
From source file:utils.play.BugWorkaroundForm.java
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override/* www .ja v a 2 s . com*/
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.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 www . j a v a 2 s . c o m 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:org.uimafit.component.initialize.ConfigurationParameterInitializer.java
/** * Initialize a component from an {@link UimaContext} This code can be a little confusing * because the configuration parameter annotations are used in two contexts: in describing the * component and to initialize member variables from a {@link UimaContext}. Here we are * performing the latter task. It is important to remember that the {@link UimaContext} passed * in to this method may or may not have been derived using reflection of the annotations (i.e. * using {@link ConfigurationParameterFactory} via e.g. a call to a AnalysisEngineFactory.create * method). It is just as possible for the description of the component to come directly from an * XML descriptor file. So, for example, just because a configuration parameter specifies a * default value, this does not mean that the passed in context will have a value for that * configuration parameter. It should be possible for a descriptor file to specify its own value * or to not provide one at all. If the context does not have a configuration parameter, then * the default value provided by the developer as specified by the defaultValue element of the * {@link ConfigurationParameter} will be used. See comments in the code for additional details. * * @param component the component to initialize. * @param context a UIMA context with configuration parameters. *//*from www .j av a 2 s . com*/ public static void initialize(final Object component, final UimaContext context) throws ResourceInitializationException { MutablePropertyValues values = new MutablePropertyValues(); List<String> mandatoryValues = new ArrayList<String>(); for (Field field : ReflectionUtil.getFields(component)) { // component.getClass().getDeclaredFields()) if (ConfigurationParameterFactory.isConfigurationParameterField(field)) { org.uimafit.descriptor.ConfigurationParameter annotation = field .getAnnotation(org.uimafit.descriptor.ConfigurationParameter.class); Object parameterValue; String parameterName = ConfigurationParameterFactory.getConfigurationParameterName(field); // Obtain either from the context - or - if the context does not provide the // parameter, check if there is a default value. Note there are three possibilities: // 1) Parameter present and set // 2) Parameter present and set to null (null value) // 3) Parameter not present (also provided as null value by UIMA) // Unfortunately we cannot make a difference between case 2 and 3 since UIMA does // not allow us to actually get a list of the parameters set in the context. We can // only get a list of the declared parameters. Thus we have to rely on the null // value. parameterValue = context.getConfigParameterValue(parameterName); if (parameterValue == null) { parameterValue = ConfigurationParameterFactory.getDefaultValue(field); } if (parameterValue != null) { values.addPropertyValue(field.getName(), parameterValue); } // TODO does this check really belong here? It seems that // this check is already performed by UIMA if (annotation.mandatory()) { mandatoryValues.add(field.getName()); // if (parameterValue == null) { // final String key = ResourceInitializationException.CONFIG_SETTING_ABSENT; // throw new ResourceInitializationException(key, // new Object[] { configurationParameterName }); // } } // else { // if (parameterValue == null) { // continue; // } // } // final Object fieldValue = convertValue(field, parameterValue); // try { // setParameterValue(component, field, fieldValue); // } // catch (Exception e) { // throw new ResourceInitializationException(e); // } } } DataBinder binder = new DataBinder(component) { @Override protected void checkRequiredFields(MutablePropertyValues mpvs) { String[] requiredFields = getRequiredFields(); if (!ObjectUtils.isEmpty(requiredFields)) { Map<String, PropertyValue> propertyValues = new HashMap<String, PropertyValue>(); PropertyValue[] pvs = mpvs.getPropertyValues(); for (PropertyValue pv : pvs) { String canonicalName = PropertyAccessorUtils.canonicalPropertyName(pv.getName()); propertyValues.put(canonicalName, pv); } for (String field : requiredFields) { PropertyValue pv = propertyValues.get(field); boolean empty = (pv == null || pv.getValue() == null); // For our purposes, empty Strings or empty String arrays do not count as // empty. Empty is only "null". // if (!empty) { // if (pv.getValue() instanceof String) { // empty = !StringUtils.hasText((String) pv.getValue()); // } // else if (pv.getValue() instanceof String[]) { // String[] values = (String[]) pv.getValue(); // empty = (values.length == 0 || !StringUtils.hasText(values[0])); // } // } if (empty) { // Use bind error processor to create FieldError. getBindingErrorProcessor().processMissingFieldError(field, getInternalBindingResult()); // Remove property from property values to bind: // It has already caused a field error with a rejected value. if (pv != null) { mpvs.removePropertyValue(pv); propertyValues.remove(field); } } } } } }; binder.initDirectFieldAccess(); PropertyEditorUtil.registerUimaFITEditors(binder); binder.setRequiredFields(mandatoryValues.toArray(new String[mandatoryValues.size()])); binder.bind(values); if (binder.getBindingResult().hasErrors()) { StringBuilder sb = new StringBuilder(); sb.append("Errors initializing [" + component.getClass() + "]"); for (ObjectError error : binder.getBindingResult().getAllErrors()) { if (sb.length() > 0) { sb.append("\n"); } sb.append(error.getDefaultMessage()); } throw new IllegalArgumentException(sb.toString()); } }
From source file:org.cloudfoundry.identity.uaa.config.YamlBindingTests.java
private BindingResult bind(Object target, String values) { YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean(); factory.setResources(new ByteArrayResource[] { new ByteArrayResource(values.getBytes()) }); Map<Object, Object> map = factory.getObject(); DataBinder binder = new DataBinder(target) { @Override//from w w w .j a v a 2 s. c om protected void doBind(MutablePropertyValues mpvs) { modifyProperties(mpvs, getTarget()); super.doBind(mpvs); } private void modifyProperties(MutablePropertyValues mpvs, Object target) { List<PropertyValue> list = mpvs.getPropertyValueList(); BeanWrapperImpl bw = new BeanWrapperImpl(target); for (int i = 0; i < list.size(); i++) { PropertyValue pv = list.get(i); String name = pv.getName(); StringBuilder builder = new StringBuilder(); for (String key : StringUtils.delimitedListToStringArray(name, ".")) { if (builder.length() != 0) { builder.append("."); } builder.append(key); String base = builder.toString(); Class<?> type = bw.getPropertyType(base); if (type != null && Map.class.isAssignableFrom(type)) { String suffix = name.substring(base.length()); Map<String, Object> nested = new LinkedHashMap<String, Object>(); if (bw.getPropertyValue(base) != null) { @SuppressWarnings("unchecked") Map<String, Object> existing = (Map<String, Object>) bw.getPropertyValue(base); nested = existing; } else { bw.setPropertyValue(base, nested); } Map<String, Object> value = nested; String[] tree = StringUtils.delimitedListToStringArray(suffix, "."); for (int j = 1; j < tree.length - 1; j++) { String subtree = tree[j]; value.put(subtree, nested); value = nested; } String refName = base + suffix.replaceAll("\\.([a-zA-Z0-9]*)", "[$1]"); mpvs.setPropertyValueAt(new PropertyValue(refName, pv.getValue()), i); break; } } } } }; binder.setIgnoreUnknownFields(false); LocalValidatorFactoryBean validatorFactoryBean = new LocalValidatorFactoryBean(); validatorFactoryBean.afterPropertiesSet(); binder.setValidator(validatorFactoryBean); binder.bind(new MutablePropertyValues(map)); binder.validate(); return binder.getBindingResult(); }
From source file:de.siegmar.securetransfer.controller.SendController.java
/** * Process the send form.//from www. j a v a 2s . c o m */ @PostMapping public ModelAndView create(final HttpServletRequest req, final RedirectAttributes redirectAttributes) throws IOException, FileUploadException { if (!ServletFileUpload.isMultipartContent(req)) { throw new IllegalStateException("No multipart request!"); } // Create encryptionKey and initialization vector (IV) to encrypt data final KeyIv encryptionKey = messageService.newEncryptionKey(); // secret shared with receiver using the link - not stored in database final String linkSecret = messageService.newRandomId(); final DataBinder binder = initBinder(); final List<SecretFile> tmpFiles = handleStream(req, encryptionKey, binder); final EncryptMessageCommand command = (EncryptMessageCommand) binder.getTarget(); final BindingResult errors = binder.getBindingResult(); if (!errors.hasErrors() && command.getMessage() == null && (tmpFiles == null || tmpFiles.isEmpty())) { errors.reject(null, "Neither message nor files submitted"); } if (errors.hasErrors()) { return new ModelAndView(FORM_SEND_MSG, binder.getBindingResult().getModel()); } final String senderId = messageService.storeMessage(command.getMessage(), tmpFiles, encryptionKey, HashCode.fromString(linkSecret).asBytes(), command.getPassword(), Instant.now().plus(command.getExpirationDays(), ChronoUnit.DAYS)); redirectAttributes.addFlashAttribute("messageSent", true).addFlashAttribute("message", command.getMessage()); return new ModelAndView("redirect:/send/" + senderId).addObject("linkSecret", linkSecret); }
From source file:de.siegmar.securetransfer.controller.SendController.java
private List<SecretFile> handleStream(final HttpServletRequest req, final KeyIv encryptionKey, final DataBinder binder) throws FileUploadException, IOException { final BindingResult errors = binder.getBindingResult(); final MutablePropertyValues propertyValues = new MutablePropertyValues(); final List<SecretFile> tmpFiles = new ArrayList<>(); @SuppressWarnings("checkstyle:anoninnerlength") final AbstractMultipartVisitor visitor = new AbstractMultipartVisitor() { private OptionalInt expiration = OptionalInt.empty(); @Override/*ww w.j ava2 s .c o m*/ void emitField(final String name, final String value) { propertyValues.addPropertyValue(name, value); if ("expirationDays".equals(name)) { expiration = OptionalInt.of(Integer.parseInt(value)); } } @Override void emitFile(final String fileName, final InputStream inStream) { final Integer expirationDays = expiration .orElseThrow(() -> new IllegalStateException("No expirationDays configured")); tmpFiles.add(messageService.encryptFile(fileName, inStream, encryptionKey, Instant.now().plus(expirationDays, ChronoUnit.DAYS))); } }; try { visitor.processRequest(req); binder.bind(propertyValues); binder.validate(); } catch (final IllegalStateException ise) { errors.reject(null, ise.getMessage()); } return tmpFiles; }