List of usage examples for org.springframework.validation FieldError getArguments
@Override
@Nullable
public Object[] getArguments()
From source file:jetx.ext.springmvc.SpringMvcFunctions.java
/** * ??/*from w w w . j a v a 2 s . c om*/ */ public static List<String> fieldErrors(JetPageContext ctx, String fieldName) { Errors errors = FunctionUtils.findErrors(ctx.getContext()); if (errors == null) { return EMPTY_STRING_LIST; } List<FieldError> fes = errors.getFieldErrors(fieldName); List<String> msgs = new ArrayList<String>(0); for (FieldError fe : fes) { String[] codes = fe.getCodes(); String defaultMsg = fe.getDefaultMessage(); Object[] args = fe.getArguments(); Locale locale = getLocale(ctx); MessageSource ms = getMessageSource(ctx); if (codes == null || codes.length == 0 || ms == null) { msgs.add(defaultMsg); } else { String msg = null; for (int i = 0; i < codes.length; i++) { try { msg = ms.getMessage(codes[i], args, locale); } catch (NoSuchMessageException e) { // } if (msg == null) { msg = defaultMsg; } } msgs.add(msg); } } return Collections.unmodifiableList(msgs); }
From source file:it.f2informatica.core.validator.utils.ErrorMessageResolver.java
public List<ErrorMessage> resolveErrorCodes(List<FieldError> fieldErrors, final Locale locale) { return Lists.newArrayList(Iterables.transform(fieldErrors, new Function<FieldError, ErrorMessage>() { @Override//w w w . j a va 2s . c om public ErrorMessage apply(FieldError input) { String errorCode = input.getCode(); String errorMessage = messageSource.getMessage(errorCode, input.getArguments(), locale); String field = Iterables.getFirst(Arrays.asList(input.getField().split("\\.")), ""); return new ErrorMessage(field, errorCode, errorMessage); } })); }
From source file:com.mitchellbosecke.pebble.spring.extension.function.bindingresult.GetFieldErrorsFunction.java
@Override public Object execute(Map<String, Object> args) { List<String> results = new ArrayList<>(); String formName = (String) args.get(PARAM_FORM_NAME); String field = (String) args.get(PARAM_FIELD_NAME); if (field == null) { throw new IllegalArgumentException("Field parameter is required in GetFieldErrorsFunction"); }/*from w w w . j ava 2 s .co m*/ EvaluationContext context = (EvaluationContext) args.get("_context"); Locale locale = context.getLocale(); BindingResult bindingResult = this.getBindingResult(formName, context); if (bindingResult != null) { for (FieldError error : bindingResult.getFieldErrors(field)) { String msg = this.messageSource.getMessage(error.getCode(), error.getArguments(), error.getDefaultMessage(), locale); if (msg != null) { results.add(msg); } } } return results; }
From source file:org.tonguetied.web.KeywordValidator.java
/** * This validation method checks if the set of {@link Translation}s for a * {@link Keyword} contains duplicate entries of the business key. * // ww w . j a va 2 s . c o m * @param translations the set of {@link Translation}s to validate * @param errors contextual state about the validation process (never null) */ protected void validateDuplicates(SortedSet<Translation> translations, Errors errors) { Collection<Translation> output; TranslationPredicate predicate; List<FieldError> fieldErrors; if (translations.size() > 1) { for (Translation translation : translations) { predicate = new TranslationPredicate(translation.getBundle(), translation.getCountry(), translation.getLanguage()); output = CollectionUtils.select(translations, predicate); if (output.size() > 1) { final String[] errorArgs = new String[] { getLanguageName(translation.getLanguage()), getCountryName(translation.getCountry()), getBundleName(translation.getBundle()) }; fieldErrors = errors.getFieldErrors(FIELD_TRANSLATIONS); boolean containsError = false; for (FieldError error : fieldErrors) { containsError = containsError || Arrays.equals(error.getArguments(), errorArgs); } if (!containsError) { errors.rejectValue(FIELD_TRANSLATIONS, "error.duplicate.translations", errorArgs, "default"); } } } } }
From source file:com.asual.summer.core.ErrorResolver.java
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) {/*from w w w . j a va2 s .c o m*/ if (e instanceof BindException) { BindException be = (BindException) e; Map<String, Map<String, Object>> errors = new HashMap<String, Map<String, Object>>(); for (FieldError fe : (List<FieldError>) be.getFieldErrors()) { Map<String, Object> error = new HashMap<String, Object>(); Object[] args = fe.getArguments(); String key = fe.isBindingFailure() ? fe.getCodes()[2].replaceFirst("typeMismatch", "conversion") : "validation." + fe.getCodes()[2]; String message = ResourceUtils.getMessage(key, args); if (message == null) { if (!fe.isBindingFailure()) { if (key.split("\\.").length > 3) { message = ResourceUtils .getMessage(key.substring(0, key.indexOf(".", key.indexOf(".") + 1)) + key.substring(key.lastIndexOf(".")), args); } if (message == null && key.split("\\.").length > 2) { message = ResourceUtils .getMessage(key.substring(0, key.indexOf(".", key.indexOf(".") + 1)), args); } } else if (fe.isBindingFailure() && key.split("\\.").length > 2) { message = ResourceUtils.getMessage( key.substring(0, key.indexOf(".")) + key.substring(key.lastIndexOf(".")), args); } else { message = fe.getDefaultMessage(); } } error.put("message", message != null ? message : "Error (" + key + ")"); error.put("value", fe.getRejectedValue()); errors.put(fe.getField(), error); } for (ObjectError oe : (List<ObjectError>) be.getGlobalErrors()) { Map<String, Object> error = new HashMap<String, Object>(); Object[] args = oe.getArguments(); String key = "global" + (oe.getCodes() != null ? "." + oe.getCodes()[2] : ""); String message = ResourceUtils.getMessage(key, args); if (message == null) { if (key.split("\\.").length > 3) { message = ResourceUtils.getMessage(key.substring(0, key.indexOf(".", key.indexOf(".") + 1)) + key.substring(key.lastIndexOf(".")), args); } if (message == null && key.split("\\.").length > 2) { message = ResourceUtils.getMessage(key.substring(0, key.indexOf(".", key.indexOf(".") + 1)), args); } if (message == null) { message = oe.getDefaultMessage(); } } error.put("message", message != null ? message : "Error (" + key + ")"); error.put("value", oe.getObjectName()); errors.put(oe.getObjectName(), error); } String form = (String) RequestUtils.getParameter("_form"); if (form != null) { if (request.getAttribute(ERRORS) == null) { request.setAttribute(ERRORS, errors); request.setAttribute(be.getObjectName(), be.getTarget()); return new ModelAndView(new InternalResourceView( form.concat(form.contains("?") ? "&" : "?").concat("_error=true"))); } } else { List<String> pairs = new ArrayList<String>(); for (String key : errors.keySet()) { pairs.add(key + "=" + errors.get(key).get("message")); } try { response.sendError(HttpServletResponse.SC_BAD_REQUEST, StringUtils.join(pairs, ";")); } catch (IOException ioe) { logger.error(ioe.getMessage(), ioe); } } } return null; }
From source file:ch.ralscha.extdirectspring.bean.ExtDirectResponseBuilder.java
/** * Adds an "errors" property in the response if there are any errors in the * bindingResult. Sets the success flag to false if there are errors. * * @param locale//from ww w . j a v a 2 s.c o m * @param messageSource * @param bindingResult * @return this instance */ public ExtDirectResponseBuilder addErrors(Locale locale, MessageSource messageSource, final BindingResult bindingResult) { if (bindingResult != null && bindingResult.hasFieldErrors()) { Map<String, List<String>> errorMap = new HashMap<String, List<String>>(); for (FieldError fieldError : bindingResult.getFieldErrors()) { String message = fieldError.getDefaultMessage(); if (messageSource != null) { Locale loc = locale != null ? locale : Locale.getDefault(); message = messageSource.getMessage(fieldError.getCode(), fieldError.getArguments(), loc); } List<String> fieldErrors = errorMap.get(fieldError.getField()); if (fieldErrors == null) { fieldErrors = new ArrayList<String>(); errorMap.put(fieldError.getField(), fieldErrors); } fieldErrors.add(message); } if (errorMap.isEmpty()) { addResultProperty("success", Boolean.TRUE); } else { addResultProperty("errors", errorMap); addResultProperty("success", Boolean.FALSE); } } return this; }
From source file:utils.play.BugWorkaroundForm.java
@SuppressWarnings({ "unchecked", "rawtypes" }) @Override/*w w w . j a va 2 s . c om*/ 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:tv.arte.resteventapi.web.errors.GlobalDefaultExceptionHandler.java
/** * Handle all exceptions of type {@link BindException} thrown by (or passing trough) the Controller's layer * //from w ww . j a va 2 s . co m * @param response The HttpServletResponse * @param e Thrown RestEventApiValidationException * @return * @throws Exception */ @ExceptionHandler(value = BindException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public ModelAndView springBindExceptionExceptionHandler(HttpServletRequest request, BindException e) throws Exception { RestEventApiStandardResponse<RestEventApiMessage> restEventApiStandardResponse = new RestEventApiStandardResponse<RestEventApiMessage>(); Locale userLocale = request.getLocale(); String descriprionNotAvailableDefaultMessage = RestEventApiError.PRE_DEFINED.RIA_ERR_G_DESC_NOT_AVAILABLE .getDefaultMessageText(); for (ObjectError globalError : e.getGlobalErrors()) { restEventApiStandardResponse.addError(new RestEventApiMessage(globalError.getDefaultMessage(), this.messageSource.getMessage(globalError.getCode(), globalError.getArguments(), descriprionNotAvailableDefaultMessage, userLocale))); } for (FieldError fieldError : e.getFieldErrors()) { String messageCode = null; String defaultMessageText = null; if (fieldError.isBindingFailure()) { messageCode = RestEventApiError.PRE_DEFINED.RIA_ERR_V_BINDING.getCode(); defaultMessageText = RestEventApiError.PRE_DEFINED.RIA_ERR_V_BINDING.getDefaultMessageText(); } else { //TODO: Find an appropriate way to search pre-defined RestEventAPiError messageCode = fieldError.getDefaultMessage(); defaultMessageText = descriprionNotAvailableDefaultMessage; } restEventApiStandardResponse .addError(new FieldValidationError(messageCode, this.messageSource.getMessage(messageCode, fieldError.getArguments(), defaultMessageText, userLocale), fieldError.getField())); } ModelAndView mav = new ModelAndView(); mav.addObject(restEventApiStandardResponse); mav.setView(restEventApiDefaultErrorView); return mav; }
From source file:tv.arte.resteventapi.web.errors.GlobalDefaultExceptionHandler.java
/** * Handle all exceptions of type {@link ImageRepositoryException} thrown by (or passing trough) the Controller's layer * /*ww w.ja v a2s . co m*/ * @param response The HttpServletResponse * @param e Thrown RestEventApiValidationException * @return * @throws Exception */ @ExceptionHandler(value = MethodArgumentNotValidException.class) public ModelAndView restEventApiMethodArgumentNotValidExceptionHandler(HttpServletRequest request, MethodArgumentNotValidException e) throws Exception { RestEventApiStandardResponse<RestEventApiMessage> restEventApiStandardResponse = new RestEventApiStandardResponse<RestEventApiMessage>(); Locale userLocale = request.getLocale(); String descriprionNotAvailableDefaultMessage = RestEventApiError.PRE_DEFINED.RIA_ERR_G_DESC_NOT_AVAILABLE .getDefaultMessageText(); for (ObjectError globalError : e.getBindingResult().getGlobalErrors()) { restEventApiStandardResponse.addError(new RestEventApiMessage(globalError.getDefaultMessage(), this.messageSource.getMessage(globalError.getCode(), globalError.getArguments(), descriprionNotAvailableDefaultMessage, userLocale))); } for (FieldError fieldError : e.getBindingResult().getFieldErrors()) { String messageCode = null; String defaultMessageText = null; if (fieldError.isBindingFailure()) { messageCode = RestEventApiError.PRE_DEFINED.RIA_ERR_V_BINDING.getCode(); defaultMessageText = RestEventApiError.PRE_DEFINED.RIA_ERR_V_BINDING.getDefaultMessageText(); } else { //TODO: Find an appropriate way to search pre-defined RestEventAPiError messageCode = fieldError.getDefaultMessage(); defaultMessageText = descriprionNotAvailableDefaultMessage; } restEventApiStandardResponse .addError(new FieldValidationError(messageCode, this.messageSource.getMessage(messageCode, fieldError.getArguments(), defaultMessageText, userLocale), fieldError.getField())); } ModelAndView mav = new ModelAndView(); mav.addObject(restEventApiStandardResponse); mav.setView(restEventApiDefaultErrorView); return mav; }