Example usage for org.springframework.validation FieldError isBindingFailure

List of usage examples for org.springframework.validation FieldError isBindingFailure

Introduction

In this page you can find the example usage for org.springframework.validation FieldError isBindingFailure.

Prototype

public boolean isBindingFailure() 

Source Link

Document

Return whether this error represents a binding failure (like a type mismatch); otherwise it is a validation failure.

Usage

From source file:com.br.uepb.validator.adapter.CustomConstraintSpringValidatorAdapter.java

@Override
protected void processConstraintViolations(Set<ConstraintViolation<Object>> violations, Errors errors) {
    for (ConstraintViolation<Object> violation : violations) {
        String field = violation.getPropertyPath().toString();
        FieldError fieldError = errors.getFieldError(field);
        if (fieldError == null || !fieldError.isBindingFailure()) {
            try {
                String errorCode = violation.getConstraintDescriptor().getAnnotation().annotationType()
                        .getSimpleName();
                Object[] errorArgs = getArgumentsForConstraint(errors.getObjectName(), field,
                        violation.getConstraintDescriptor());
                if (errors instanceof BindingResult) {
                    // can do custom FieldError registration with invalid value from ConstraintViolation,
                    // as necessary for Hibernate Validator compatibility (non-indexed set path in field)
                    BindingResult bindingResult = (BindingResult) errors;
                    String[] errorCodes = bindingResult.resolveMessageCodes(errorCode, field);
                    String nestedField = bindingResult.getNestedPath() + field;
                    ObjectError error;/* w w  w . ja  v  a  2 s. c o m*/
                    if ("".equals(nestedField)) {
                        error = new ObjectError(errors.getObjectName(), errorCodes, errorArgs,
                                violation.getMessage());
                    } else {
                        Object invalidValue = violation.getInvalidValue();
                        if (!"".equals(field) && invalidValue == violation.getLeafBean()) {
                            // bean constraint with property path: retrieve the actual property value
                            invalidValue = bindingResult.getRawFieldValue(field);
                        }
                        if (violation.getMessage() != null && violation.getMessage().startsWith("{")
                                && violation.getMessage().endsWith("}")) {
                            String keyMessage = violation.getMessage();
                            keyMessage = keyMessage.replace("{", "");
                            keyMessage = keyMessage.replace("}", "");
                            List<String> temp = new ArrayList<String>(Arrays.asList(errorCodes));
                            temp.add(keyMessage);
                            errorCodes = temp.toArray(new String[temp.size()]);
                            error = new FieldError(errors.getObjectName(), nestedField, invalidValue, false,
                                    errorCodes, errorArgs, violation.getMessage());
                        } else {
                            error = new FieldError(errors.getObjectName(), nestedField, invalidValue, false,
                                    errorCodes, errorArgs, violation.getMessage());
                        }
                    }
                    bindingResult.addError(error);
                } else {
                    // got no BindingResult - can only do standard rejectValue call
                    // with automatic extraction of the current field value
                    if (violation.getMessage() != null && violation.getMessage().startsWith("{")
                            && violation.getMessage().endsWith("}")) {
                        String keyMessage = violation.getMessage();
                        keyMessage = keyMessage.replace("{", "");
                        keyMessage = keyMessage.replace("}", "");
                        errors.rejectValue(field, keyMessage);
                    } else {
                        errors.rejectValue(field, errorCode, errorArgs, violation.getMessage());
                    }
                }
            } catch (NotReadablePropertyException ex) {
                throw new IllegalStateException("JSR-303 validated property '" + field
                        + "' does not have a corresponding accessor for Spring data binding - "
                        + "check your DataBinder's configuration (bean property versus direct field access)",
                        ex);
            }
        }
    }
}

From source file:com.company.simple.util.validator.GlobeValidator.java

protected void processConstraintViolations(Set<ConstraintViolation<Object>> violations, Errors errors) {
    for (ConstraintViolation<Object> violation : violations) {
        String field = violation.getPropertyPath().toString();
        FieldError fieldError = errors.getFieldError(field);
        if (fieldError == null || !fieldError.isBindingFailure()) {
            try {
                ConstraintDescriptor<?> cd = violation.getConstraintDescriptor();
                String errorCode = cd.getAnnotation().annotationType().getSimpleName();
                Object[] errorArgs = getArgumentsForConstraint(errors.getObjectName(), field, cd);
                if (errors instanceof BindingResult) {
                    // Can do custom FieldError registration with invalid value from ConstraintViolation,
                    // as necessary for Hibernate Validator compatibility (non-indexed set path in field)
                    BindingResult bindingResult = (BindingResult) errors;
                    String nestedField = bindingResult.getNestedPath() + field;
                    if ("".equals(nestedField)) {
                        String[] errorCodes = bindingResult.resolveMessageCodes(errorCode);
                        bindingResult.addError(new ObjectError(errors.getObjectName(), errorCodes, errorArgs,
                                violation.getMessage()));
                    } else {
                        Object invalidValue = violation.getInvalidValue();
                        if (!"".equals(field) && (invalidValue == violation.getLeafBean()
                                || (field.contains(".") && !field.contains("[]")))) {
                            // Possibly a bean constraint with property path: retrieve the actual property value.
                            // However, explicitly avoid this for "address[]" style paths that we can't handle.
                            invalidValue = bindingResult.getRawFieldValue(field);
                        }//ww  w .  ja  v a  2  s. c  o m
                        String[] errorCodes = bindingResult.resolveMessageCodes(errorCode, field);
                        bindingResult.addError(new FieldError(errors.getObjectName(), nestedField, invalidValue,
                                false, errorCodes, errorArgs, violation.getMessage()));
                    }
                } else {
                    // got no BindingResult - can only do standard rejectValue call
                    // with automatic extraction of the current field value
                    errors.rejectValue(field, errorCode, errorArgs, violation.getMessage());
                }
            } catch (NotReadablePropertyException ex) {
                throw new IllegalStateException("JSR-303 validated property '" + field
                        + "' does not have a corresponding accessor for Spring data binding - "
                        + "check your DataBinder's configuration (bean property versus direct field access)",
                        ex);
            }
        }
    }
}

From source file:utils.play.BugWorkaroundForm.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override//from   ww w .  java2  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:com.asual.summer.core.ErrorResolver.java

public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
        Exception e) {//  w  w  w  .  ja v a 2 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:org.tonguetied.web.CountryValidatorTest.java

/**
 * Test method for {@link org.tonguetied.web.CountryValidator#validate(java.lang.Object, org.springframework.validation.Errors)}.
 *///from  www.ja  v a2 s .  c  o m
@Test
public final void testValidateInvalidObject() {
    CountryValidator validator = new CountryValidator();
    validator.setKeywordService(keywordService);
    Errors errors = new BindException(this.country, "country");
    validator.validate(this.country, errors);

    assertFalse(errors.getAllErrors().isEmpty());
    FieldError error = errors.getFieldError(fieldName);
    if (FIELD_NAME.equals(fieldName)) {
        assertEquals(this.country.getName(), error.getRejectedValue());
    } else if (FIELD_CODE.equals(fieldName)) {
        assertEquals(this.country.getCode(), error.getRejectedValue());
    }
    assertFalse(error.isBindingFailure());
}

From source file:org.tonguetied.web.LanguageValidatorTest.java

/**
 * Test method for {@link org.tonguetied.web.LanguageValidator#validate(java.lang.Object, org.springframework.validation.Errors)}.
 *///from w  ww .  j  a va 2  s  .  c om
@Test
public final void testValidateInvalidObject() {
    LanguageValidator validator = new LanguageValidator();
    validator.setKeywordService(keywordService);
    Errors errors = new BindException(this.language, "language");
    validator.validate(this.language, errors);

    assertFalse(errors.getAllErrors().isEmpty());
    FieldError error = errors.getFieldError(fieldName);
    if (FIELD_NAME.equals(fieldName)) {
        assertEquals(this.language.getName(), error.getRejectedValue());
    } else if (FIELD_CODE.equals(fieldName)) {
        assertEquals(this.language.getCode(), error.getRejectedValue());
    }
    assertFalse(error.isBindingFailure());
}

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  w  w.  j  a  va2  s.c om*/
 * @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:org.tonguetied.web.KeywordTranslationValidatorTest.java

/**
 * Test method for {@link org.tonguetied.web.KeywordValidator#validate(java.lang.Object, org.springframework.validation.Errors)}.
 *//*  w ww. j a v  a 2  s.  com*/
@Test
public final void testValidate() {
    KeywordValidator validator = new KeywordValidator();
    final Keyword keyword = new Keyword();
    keyword.setTranslations(translations);
    Errors errors = new BindException(keyword, "keyword");
    validator.validateDuplicates(translations, predicate, errors);

    assertFalse(errors.getAllErrors().isEmpty());
    FieldError error = errors.getFieldError(fieldName);
    if (FIELD_TRANSLATIONS.equals(fieldName)) {
        assertEquals(translations, error.getRejectedValue());
        assertEquals(1, errors.getErrorCount());
    } else {
        fail("cannot match error field");
    }
    assertFalse(error.isBindingFailure());
}

From source file:org.tonguetied.web.ChangePasswordFormValidatorTest.java

/**
 * Test method for {@link org.tonguetied.web.ChangePasswordFormValidator#validate(java.lang.Object, org.springframework.validation.Errors)}.
 */// w w w .j av  a  2s .c  o  m
@Test
public final void testValidateInvalidObject() {
    ChangePasswordFormValidator validator = new ChangePasswordFormValidator();
    Errors errors = new BindException(this.form, "changePasswordForm");
    validator.validate(this.form, errors);

    assertFalse(errors.getAllErrors().isEmpty());
    FieldError error = errors.getFieldError(fieldName);
    if (FIELD_NEW_PASSWORD.equals(fieldName)) {
        assertEquals(this.form.getNewPassword(), error.getRejectedValue());
    }
    if (FIELD_NEW_REPEATED_PASSWORD.equals(fieldName)) {
        assertEquals(this.form.getNewRepeatedPassword(), error.getRejectedValue());
    }
    assertFalse(error.isBindingFailure());
}

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
 * /* www. j av a 2 s. c  o 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;
}