Example usage for org.springframework.validation BindingResult resolveMessageCodes

List of usage examples for org.springframework.validation BindingResult resolveMessageCodes

Introduction

In this page you can find the example usage for org.springframework.validation BindingResult resolveMessageCodes.

Prototype

String[] resolveMessageCodes(String errorCode, String field);

Source Link

Document

Resolve the given error code into message codes for the given field.

Usage

From source file:org.jdal.ui.bind.ControlBindingErrorProcessor.java

/** 
 * Add a ControlError instead FieldError to hold component that has failed.
 * @param control/*from   w  ww.  j  a v  a 2  s. c om*/
 * @param ex
 * @param bindingResult
 */
public void processPropertyAccessException(Object control, PropertyAccessException ex,
        BindingResult bindingResult) {
    // Create field error with the exceptions's code, e.g. "typeMismatch".
    String field = ex.getPropertyName();
    String[] codes = bindingResult.resolveMessageCodes(ex.getErrorCode(), field);
    Object[] arguments = getArgumentsForBindError(bindingResult.getObjectName(), field);
    Object rejectedValue = ex.getValue();
    if (rejectedValue != null && rejectedValue.getClass().isArray()) {
        rejectedValue = StringUtils.arrayToCommaDelimitedString(ObjectUtils.toObjectArray(rejectedValue));
    }
    bindingResult.addError(new ControlError(control, bindingResult.getObjectName(), field, rejectedValue, true,
            codes, arguments, ex.getLocalizedMessage()));
}

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;/*ww w  . java 2s .  c om*/
                    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:org.codehaus.groovy.grails.validation.AbstractConstraint.java

public void rejectValueWithDefaultMessage(Object target, Errors errors, String defaultMessage, String[] codes,
        Object[] args) {/*w w  w  .j a  v a2 s.  c  o  m*/
    BindingResult result = (BindingResult) errors;
    Set<String> newCodes = new LinkedHashSet<String>();

    if (args.length > 1 && messageSource != null) {
        if ((args[0] instanceof String) && (args[1] instanceof Class<?>)) {
            final Locale locale = LocaleContextHolder.getLocale();
            final Class<?> constrainedClass = (Class<?>) args[1];
            final String fullClassName = constrainedClass.getName();

            String classNameCode = fullClassName + ".label";
            String resolvedClassName = messageSource.getMessage(classNameCode, null, fullClassName, locale);
            final String classAsPropertyName = GrailsNameUtils.getPropertyName(constrainedClass);

            if (resolvedClassName.equals(fullClassName)) {
                // try short version
                classNameCode = classAsPropertyName + ".label";
                resolvedClassName = messageSource.getMessage(classNameCode, null, fullClassName, locale);
            }

            // update passed version
            if (!resolvedClassName.equals(fullClassName)) {
                args[1] = resolvedClassName;
            }

            String propertyName = (String) args[0];
            String propertyNameCode = fullClassName + '.' + propertyName + ".label";
            String resolvedPropertyName = messageSource.getMessage(propertyNameCode, null, propertyName,
                    locale);
            if (resolvedPropertyName.equals(propertyName)) {
                propertyNameCode = classAsPropertyName + '.' + propertyName + ".label";
                resolvedPropertyName = messageSource.getMessage(propertyNameCode, null, propertyName, locale);
            }

            // update passed version
            if (!resolvedPropertyName.equals(propertyName)) {
                args[0] = resolvedPropertyName;
            }
        }
    }

    //Qualified class name is added first to match before unqualified class (which is still resolved for backwards compatibility)
    newCodes.addAll(Arrays.asList(result.resolveMessageCodes(
            constraintOwningClass.getName() + '.' + constraintPropertyName + '.' + getName() + ".error",
            constraintPropertyName)));
    newCodes.addAll(Arrays.asList(result.resolveMessageCodes(
            classShortName + '.' + constraintPropertyName + '.' + getName() + ".error",
            constraintPropertyName)));
    for (String code : codes) {
        newCodes.addAll(Arrays.asList(result.resolveMessageCodes(
                constraintOwningClass.getName() + '.' + constraintPropertyName + '.' + code,
                constraintPropertyName)));
        newCodes.addAll(Arrays.asList(result.resolveMessageCodes(
                classShortName + '.' + constraintPropertyName + '.' + code, constraintPropertyName)));
        //We resolve the error code on it's own last so that a global code doesn't override a class/field specific error
        newCodes.addAll(Arrays.asList(result.resolveMessageCodes(code, constraintPropertyName)));
    }

    FieldError error = new FieldError(errors.getObjectName(), errors.getNestedPath() + constraintPropertyName,
            getPropertyValue(errors, target), false, newCodes.toArray(new String[newCodes.size()]), args,
            defaultMessage);
    ((BindingResult) errors).addError(error);
}