List of usage examples for org.springframework.validation Errors getObjectName
String getObjectName();
From source file:io.curly.commons.web.ModelErrors.java
@JsonCreator public ModelErrors(Errors errors) { log.debug("New API Error status -- Errors {}", HttpStatus.BAD_REQUEST, errors.getObjectName()); this.errors = new HashMap<>(); this.errors.put(STATUS_CODE, HttpStatus.BAD_REQUEST.toString()); errors.getAllErrors().forEach(// ww w. j a va 2 s. co m objectError -> this.errors.put(objectError.getObjectName(), objectError.getDefaultMessage())); }
From source file:org.toobsframework.exception.ValidationException.java
public String getMessage() { StringBuffer sb = new StringBuffer(); if (this.errors != null) { Iterator errIter = errors.iterator(); while (errIter.hasNext()) { Errors err = (Errors) errIter.next(); sb.append("Validation error for object " + err.getObjectName() + "\n"); for (int i = 0; i < err.getAllErrors().size(); i++) { ObjectError objErr = (ObjectError) err.getAllErrors().get(i); sb.append(objErr.getDefaultMessage() + "\n"); }/* ww w . j ava2 s.c o m*/ } } return sb.toString(); }
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;/*from w ww . j av a2s . co 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); }/*from w w w . j a v a2 s . co 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: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 a 2 s. co 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); }
From source file:org.springframework.validation.SimpleErrors.java
@Override public void addAllErrors(Errors errors) { Assert.notNull(errors, "No errors to add"); if (ExtendedStringUtils.safeCompare(getObjectName(), errors.getObjectName()) != 0) { throw new IllegalArgumentException("addErrors(" + getObjectName() + ") mismatched argument object name: " + errors.getObjectName()); }//from w w w. j a va 2 s . c o m Collection<? extends ObjectError> glbl = errors.getGlobalErrors(); if (ExtendedCollectionUtils.size(glbl) > 0) { globalErrors.addAll(glbl); } Collection<? extends FieldError> flds = errors.getFieldErrors(); if (ExtendedCollectionUtils.size(flds) > 0) { fieldErrors.addAll(flds); } }
From source file:org.springmodules.validation.bean.BeanValidator.java
/** * The heart of this validator. This is a recursive method that validates the given object (object) under the * context of the given object graph root (root). The validation rules to be applied are loaded using the * configured {@link org.springmodules.validation.bean.conf.loader.BeanValidationConfigurationLoader}. All errors are registered with the given {@link Errors} * object under the context of the object graph root. * * @param root The root of the object graph. * @param obj The object to be validated * @param errors The {@link Errors} instance where the validation errors will be registered. * @param validatedObjects keeps track of all the validated objects (to prevent revalidating the same objects when * a circular relationship exists). *//*from w ww . j a v a 2 s . co m*/ protected void validateObjectGraphConstraints(Object root, Object obj, Errors errors, Set validatedObjects) { // cannot load any validation rules for null values if (obj == null) { return; } // if this object was already validated, the skipping this valiation. if (validatedObjects.contains(obj)) { if (logger.isDebugEnabled()) { logger.debug("Skipping validation of object in path '" + errors.getObjectName() + "' for it was already validated"); } return; } if (logger.isDebugEnabled()) { logger.debug("Validating object in path '" + errors.getNestedPath() + "'"); } // loading the bean validation configuration based on the validated object class. Class clazz = obj.getClass(); BeanValidationConfiguration configuration = configurationLoader.loadConfiguration(clazz); if (configuration == null) { return; // no validation configuration for this object, then there's nothing to validate. } // applying all the validation rules for the object and registering the object as "validated" applyBeanValidation(configuration, obj, errors); validatedObjects.add(obj); // after all the validation rules where applied, checking what properties of the object require their own // validation and recursively calling this method on them. CascadeValidation[] cascadeValidations = configuration.getCascadeValidations(); BeanWrapper wrapper = wrapBean(obj); for (int i = 0; i < cascadeValidations.length; i++) { CascadeValidation cascadeValidation = cascadeValidations[i]; Condition applicabilityCondition = cascadeValidation.getApplicabilityCondition(); if (!applicabilityCondition.check(obj)) { continue; } String propertyName = cascadeValidation.getPropertyName(); Class propertyType = wrapper.getPropertyType(propertyName); Object propertyValue = wrapper.getPropertyValue(propertyName); // if the property value is not there nothing to validate. if (propertyValue == null) { continue; } // if the property is an array of a collection, then iterating on it and validating each element. Note that // the error codes that are registered for arrays/collection elements follow the pattern supported by // spring's PropertyAccessor. Also note that just before each recursive call, the context of the validation // is appropriately adjusted using errors.pushNestedPath(...), and after each call it is being adjusted back // using errors.popNestedPath(). if (propertyType.isArray()) { validateArrayProperty(root, propertyValue, propertyName, errors, validatedObjects); } else if (List.class.isAssignableFrom(propertyType) || Set.class.isAssignableFrom(propertyType)) { validateListOrSetProperty(root, (Collection) propertyValue, propertyName, errors, validatedObjects); } else if (Map.class.isAssignableFrom(propertyType)) { validateMapProperty(root, ((Map) propertyValue), propertyName, errors, validatedObjects); } else { // if the object is just a normal object (not an array or a collection), then applying its // validation rules. validatedSubBean(root, propertyValue, propertyName, errors, validatedObjects); } } }