Introduce Validator.validateObject(Object) with returned Errors

Includes failOnError method on Errors interface for use with validateObject.
Declares many Errors methods as default methods for lean SimpleErrors class.

Closes gh-19877
This commit is contained in:
Juergen Hoeller
2023-07-19 21:56:44 +02:00
parent 9571aa1c68
commit 10cb2322e9
6 changed files with 576 additions and 296 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -28,13 +28,14 @@ import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
/**
* Abstract implementation of the {@link Errors} interface. Provides common
* access to evaluated errors; however, does not define concrete management
* Abstract implementation of the {@link Errors} interface.
* Provides nested path handling but does not define concrete management
* of {@link ObjectError ObjectErrors} and {@link FieldError FieldErrors}.
*
* @author Juergen Hoeller
* @author Rossen Stoyanchev
* @since 2.5.3
* @see AbstractBindingResult
*/
@SuppressWarnings("serial")
public abstract class AbstractErrors implements Errors, Serializable {
@@ -81,8 +82,8 @@ public abstract class AbstractErrors implements Errors, Serializable {
nestedPath = "";
}
nestedPath = canonicalFieldName(nestedPath);
if (nestedPath.length() > 0 && !nestedPath.endsWith(Errors.NESTED_PATH_SEPARATOR)) {
nestedPath += Errors.NESTED_PATH_SEPARATOR;
if (nestedPath.length() > 0 && !nestedPath.endsWith(NESTED_PATH_SEPARATOR)) {
nestedPath += NESTED_PATH_SEPARATOR;
}
this.nestedPath = nestedPath;
}
@@ -97,7 +98,7 @@ public abstract class AbstractErrors implements Errors, Serializable {
}
else {
String path = getNestedPath();
return (path.endsWith(Errors.NESTED_PATH_SEPARATOR) ?
return (path.endsWith(NESTED_PATH_SEPARATOR) ?
path.substring(0, path.length() - NESTED_PATH_SEPARATOR.length()) : path);
}
}
@@ -112,117 +113,19 @@ public abstract class AbstractErrors implements Errors, Serializable {
return field;
}
@Override
public void reject(String errorCode) {
reject(errorCode, null, null);
}
@Override
public void reject(String errorCode, String defaultMessage) {
reject(errorCode, null, defaultMessage);
}
@Override
public void rejectValue(@Nullable String field, String errorCode) {
rejectValue(field, errorCode, null, null);
}
@Override
public void rejectValue(@Nullable String field, String errorCode, String defaultMessage) {
rejectValue(field, errorCode, null, defaultMessage);
}
@Override
public boolean hasErrors() {
return !getAllErrors().isEmpty();
}
@Override
public int getErrorCount() {
return getAllErrors().size();
}
@Override
public List<ObjectError> getAllErrors() {
List<ObjectError> result = new ArrayList<>();
result.addAll(getGlobalErrors());
result.addAll(getFieldErrors());
return Collections.unmodifiableList(result);
}
@Override
public boolean hasGlobalErrors() {
return (getGlobalErrorCount() > 0);
}
@Override
public int getGlobalErrorCount() {
return getGlobalErrors().size();
}
@Override
@Nullable
public ObjectError getGlobalError() {
List<ObjectError> globalErrors = getGlobalErrors();
return (!globalErrors.isEmpty() ? globalErrors.get(0) : null);
}
@Override
public boolean hasFieldErrors() {
return (getFieldErrorCount() > 0);
}
@Override
public int getFieldErrorCount() {
return getFieldErrors().size();
}
@Override
@Nullable
public FieldError getFieldError() {
List<FieldError> fieldErrors = getFieldErrors();
return (!fieldErrors.isEmpty() ? fieldErrors.get(0) : null);
}
@Override
public boolean hasFieldErrors(String field) {
return (getFieldErrorCount(field) > 0);
}
@Override
public int getFieldErrorCount(String field) {
return getFieldErrors(field).size();
}
@Override
public List<FieldError> getFieldErrors(String field) {
List<FieldError> fieldErrors = getFieldErrors();
List<FieldError> result = new ArrayList<>();
String fixedField = fixedField(field);
for (FieldError error : fieldErrors) {
if (isMatchingFieldError(fixedField, error)) {
result.add(error);
for (FieldError fieldError : fieldErrors) {
if (isMatchingFieldError(fixedField, fieldError)) {
result.add(fieldError);
}
}
return Collections.unmodifiableList(result);
}
@Override
@Nullable
public FieldError getFieldError(String field) {
List<FieldError> fieldErrors = getFieldErrors(field);
return (!fieldErrors.isEmpty() ? fieldErrors.get(0) : null);
}
@Override
@Nullable
public Class<?> getFieldType(String field) {
Object value = getFieldValue(field);
return (value != null ? value.getClass() : null);
}
/**
* Check whether the given FieldError matches the given field.
* @param field the field that we are looking up FieldErrors for

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,29 +17,33 @@
package org.springframework.validation;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Stream;
import org.springframework.beans.PropertyAccessor;
import org.springframework.lang.Nullable;
/**
* Stores and exposes information about data-binding and validation
* errors for a specific object.
* Stores and exposes information about data-binding and validation errors
* for a specific object.
*
* <p>Field names can be properties of the target object (e.g. "name"
* when binding to a customer object), or nested fields in case of
* subobjects (e.g. "address.street"). Supports subtree navigation
* via {@link #setNestedPath(String)}: for example, an
* {@code AddressValidator} validates "address", not being aware
* that this is a subobject of customer.
* <p>Field names are typically properties of the target object (e.g. "name"
* when binding to a customer object). Implementations may also support nested
* fields in case of nested objects (e.g. "address.street"), in conjunction
* with subtree navigation via {@link #setNestedPath}: for example, an
* {@code AddressValidator} may validate "address", not being aware that this
* is a nested object of a top-level customer object.
*
* <p>Note: {@code Errors} objects are single-threaded.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @see #setNestedPath
* @see BindException
* @see DataBinder
* @see Validator
* @see ValidationUtils
* @see SimpleErrors
* @see BindingResult
*/
public interface Errors {
@@ -63,18 +67,26 @@ public interface Errors {
* subtrees. Reject calls prepend the given path to the field names.
* <p>For example, an address validator could validate the subobject
* "address" of a customer object.
* <p>The default implementation throws {@code UnsupportedOperationException}
* since not all {@code Errors} implementations support nested paths.
* @param nestedPath nested path within this object,
* e.g. "address" (defaults to "", {@code null} is also acceptable).
* Can end with a dot: both "address" and "address." are valid.
* @see #getNestedPath()
*/
void setNestedPath(String nestedPath);
default void setNestedPath(String nestedPath) {
throw new UnsupportedOperationException(getClass().getSimpleName() + " does not support nested paths");
}
/**
* Return the current nested path of this {@link Errors} object.
* <p>Returns a nested path with a dot, i.e. "address.", for easy
* building of concatenated paths. Default is an empty String.
* @see #setNestedPath(String)
*/
String getNestedPath();
default String getNestedPath() {
return "";
}
/**
* Push the given sub path onto the nested path stack.
@@ -85,32 +97,44 @@ public interface Errors {
* for subobjects without having to worry about a temporary path holder.
* <p>For example: current path "spouse.", pushNestedPath("child") &rarr;
* result path "spouse.child."; popNestedPath() &rarr; "spouse." again.
* <p>The default implementation throws {@code UnsupportedOperationException}
* since not all {@code Errors} implementations support nested paths.
* @param subPath the sub path to push onto the nested path stack
* @see #popNestedPath
* @see #popNestedPath()
*/
void pushNestedPath(String subPath);
default void pushNestedPath(String subPath) {
throw new UnsupportedOperationException(getClass().getSimpleName() + " does not support nested paths");
}
/**
* Pop the former nested path from the nested path stack.
* @throws IllegalStateException if there is no former nested path on the stack
* @see #pushNestedPath
* @see #pushNestedPath(String)
*/
void popNestedPath() throws IllegalStateException;
default void popNestedPath() throws IllegalStateException {
throw new IllegalStateException("Cannot pop nested path: no nested path on stack");
}
/**
* Register a global error for the entire target object,
* using the given error description.
* @param errorCode error code, interpretable as a message key
* @see #reject(String, Object[], String)
*/
void reject(String errorCode);
default void reject(String errorCode) {
reject(errorCode, null, null);
}
/**
* Register a global error for the entire target object,
* using the given error description.
* @param errorCode error code, interpretable as a message key
* @param defaultMessage fallback default message
* @see #reject(String, Object[], String)
*/
void reject(String errorCode, String defaultMessage);
default void reject(String errorCode, String defaultMessage) {
reject(errorCode, null, defaultMessage);
}
/**
* Register a global error for the entire target object,
@@ -119,6 +143,7 @@ public interface Errors {
* @param errorArgs error arguments, for argument binding via MessageFormat
* (can be {@code null})
* @param defaultMessage fallback default message
* @see #rejectValue(String, String, Object[], String)
*/
void reject(String errorCode, @Nullable Object[] errorArgs, @Nullable String defaultMessage);
@@ -132,9 +157,11 @@ public interface Errors {
* global error if the current object is the top object.
* @param field the field name (may be {@code null} or empty String)
* @param errorCode error code, interpretable as a message key
* @see #getNestedPath()
* @see #rejectValue(String, String, Object[], String)
*/
void rejectValue(@Nullable String field, String errorCode);
default void rejectValue(@Nullable String field, String errorCode) {
rejectValue(field, errorCode, null, null);
}
/**
* Register a field error for the specified field of the current object
@@ -147,9 +174,11 @@ public interface Errors {
* @param field the field name (may be {@code null} or empty String)
* @param errorCode error code, interpretable as a message key
* @param defaultMessage fallback default message
* @see #getNestedPath()
* @see #rejectValue(String, String, Object[], String)
*/
void rejectValue(@Nullable String field, String errorCode, String defaultMessage);
default void rejectValue(@Nullable String field, String errorCode, String defaultMessage) {
rejectValue(field, errorCode, null, defaultMessage);
}
/**
* Register a field error for the specified field of the current object
@@ -164,7 +193,7 @@ public interface Errors {
* @param errorArgs error arguments, for argument binding via MessageFormat
* (can be {@code null})
* @param defaultMessage fallback default message
* @see #getNestedPath()
* @see #reject(String, Object[], String)
*/
void rejectValue(@Nullable String field, String errorCode,
@Nullable Object[] errorArgs, @Nullable String defaultMessage);
@@ -178,110 +207,169 @@ public interface Errors {
* <p>Note that the passed-in {@code Errors} instance is supposed
* to refer to the same target object, or at least contain compatible errors
* that apply to the target object of this {@code Errors} instance.
* <p>The default implementation throws {@code UnsupportedOperationException}
* since not all {@code Errors} implementations support {@code #addAllErrors}.
* @param errors the {@code Errors} instance to merge in
* @see #getAllErrors()
*/
void addAllErrors(Errors errors);
default void addAllErrors(Errors errors) {
throw new UnsupportedOperationException(getClass().getSimpleName() + " does not support addAllErrors");
}
/**
* Return if there were any errors.
* Throw the mapped exception with a message summarizing the recorded errors.
* @param messageToException a function mapping the message to the exception,
* e.g. {@code IllegalArgumentException::new} or {@code IllegalStateException::new}
* @param <T> the exception type to be thrown
* @since 6.1
* @see #toString()
*/
boolean hasErrors();
default <T extends Throwable> void failOnError(Function<String, T> messageToException) throws T {
if (hasErrors()) {
throw messageToException.apply(toString());
}
}
/**
* BReturn if there were any errors.
* @see #hasGlobalErrors()
* @see #hasFieldErrors()
*/
default boolean hasErrors() {
return (!getGlobalErrors().isEmpty() || !getFieldErrors().isEmpty());
}
/**
* Return the total number of errors.
* @see #getGlobalErrorCount()
* @see #getFieldErrorCount()
*/
int getErrorCount();
default int getErrorCount() {
return (getGlobalErrors().size() + getFieldErrors().size());
}
/**
* Get all errors, both global and field ones.
* @return a list of {@link ObjectError} instances
* @see #getGlobalErrors()
* @see #getFieldErrors()
*/
List<ObjectError> getAllErrors();
default List<ObjectError> getAllErrors() {
return Stream.concat(getGlobalErrors().stream(), getFieldErrors().stream()).toList();
}
/**
* Are there any global errors?
* @return {@code true} if there are any global errors
* @see #hasFieldErrors()
*/
boolean hasGlobalErrors();
default boolean hasGlobalErrors() {
return !getGlobalErrors().isEmpty();
}
/**
* Return the number of global errors.
* @return the number of global errors
* @see #getFieldErrorCount()
*/
int getGlobalErrorCount();
default int getGlobalErrorCount() {
return getGlobalErrors().size();
}
/**
* Get all global errors.
* @return a list of {@link ObjectError} instances
* @see #getFieldErrors()
*/
List<ObjectError> getGlobalErrors();
/**
* Get the <i>first</i> global error, if any.
* @return the global error, or {@code null}
* @see #getFieldError()
*/
@Nullable
ObjectError getGlobalError();
default ObjectError getGlobalError() {
return getGlobalErrors().stream().findFirst().orElse(null);
}
/**
* Are there any field errors?
* @return {@code true} if there are any errors associated with a field
* @see #hasGlobalErrors()
*/
boolean hasFieldErrors();
default boolean hasFieldErrors() {
return !getFieldErrors().isEmpty();
}
/**
* Return the number of errors associated with a field.
* @return the number of errors associated with a field
* @see #getGlobalErrorCount()
*/
int getFieldErrorCount();
default int getFieldErrorCount() {
return getFieldErrors().size();
}
/**
* Get all errors associated with a field.
* @return a List of {@link FieldError} instances
* @see #getGlobalErrors()
*/
List<FieldError> getFieldErrors();
/**
* Get the <i>first</i> error associated with a field, if any.
* @return the field-specific error, or {@code null}
* @see #getGlobalError()
*/
@Nullable
FieldError getFieldError();
default FieldError getFieldError() {
return getFieldErrors().stream().findFirst().orElse(null);
}
/**
* Are there any errors associated with the given field?
* @param field the field name
* @return {@code true} if there were any errors associated with the given field
* @see #hasFieldErrors()
*/
boolean hasFieldErrors(String field);
default boolean hasFieldErrors(String field) {
return (getFieldError(field) != null);
}
/**
* Return the number of errors associated with the given field.
* @param field the field name
* @return the number of errors associated with the given field
* @see #getFieldErrorCount()
*/
int getFieldErrorCount(String field);
default int getFieldErrorCount(String field) {
return getFieldErrors(field).size();
}
/**
* Get all errors associated with the given field.
* <p>Implementations should support not only full field names like
* "name" but also pattern matches like "na*" or "address.*".
* <p>Implementations may support not only full field names like
* "address.street" but also pattern matches like "address.*".
* @param field the field name
* @return a List of {@link FieldError} instances
* @see #getFieldErrors()
*/
List<FieldError> getFieldErrors(String field);
default List<FieldError> getFieldErrors(String field) {
return getFieldErrors().stream().filter(error -> field.equals(error.getField())).toList();
}
/**
* Get the first error associated with the given field, if any.
* @param field the field name
* @return the field-specific error, or {@code null}
* @see #getFieldError()
*/
@Nullable
FieldError getFieldError(String field);
default FieldError getFieldError(String field) {
return getFieldErrors().stream().filter(error -> field.equals(error.getField())).findFirst().orElse(null);
}
/**
* Return the current value of the given field, either the current
@@ -290,6 +378,7 @@ public interface Errors {
* even if there were type mismatches.
* @param field the field name
* @return the current value of the given field
* @see #getFieldType(String)
*/
@Nullable
Object getFieldValue(String field);
@@ -301,8 +390,18 @@ public interface Errors {
* associated descriptor.
* @param field the field name
* @return the type of the field, or {@code null} if not determinable
* @see #getFieldValue(String)
*/
@Nullable
Class<?> getFieldType(String field);
default Class<?> getFieldType(String field) {
return Optional.ofNullable(getFieldValue(field)).map(Object::getClass).orElse(null);
}
/**
* Return a summary of the recorded errors,
* e.g. for inclusion in an exception message.
* @see #failOnError(Function)
*/
String toString();
}

View File

@@ -0,0 +1,181 @@
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.validation;
import java.beans.PropertyDescriptor;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.BeanUtils;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
/**
* A simple implementation of the {@link Errors} interface, managing global
* errors and field errors for a top-level target object. Flexibly retrieves
* field values through bean property getter methods, and automatically
* falls back to raw field access if necessary.
*
* <p>Note that this {@link Errors} implementation comes without support for
* nested paths. It is exclusively designed for the validation of individual
* top-level objects, not aggregating errors from multiple sources.
* If this is insufficient for your purposes, use a binding-capable
* {@link Errors} implementation such as {@link BeanPropertyBindingResult}.
*
* @author Juergen Hoeller
* @since 6.1
* @see Validator#validateObject(Object)
* @see BeanPropertyBindingResult
* @see DirectFieldBindingResult
*/
@SuppressWarnings("serial")
public class SimpleErrors implements Errors, Serializable {
private final Object target;
private final String objectName;
private final List<ObjectError> globalErrors = new ArrayList<>();
private final List<FieldError> fieldErrors = new ArrayList<>();
/**
* Create a new {@link SimpleErrors} holder for the given target,
* using the simple name of the target class as the object name.
* @param target the target to wrap
*/
public SimpleErrors(Object target) {
Assert.notNull(target, "Target must not be null");
this.target = target;
this.objectName = this.target.getClass().getSimpleName();
}
/**
* Create a new {@link SimpleErrors} holder for the given target.
* @param target the target to wrap
* @param objectName the name of the target object for error reporting
*/
public SimpleErrors(Object target, String objectName) {
Assert.notNull(target, "Target must not be null");
this.target = target;
this.objectName = objectName;
}
@Override
public String getObjectName() {
return this.objectName;
}
@Override
public void reject(String errorCode, @Nullable Object[] errorArgs, @Nullable String defaultMessage) {
this.globalErrors.add(new ObjectError(getObjectName(), new String[] {errorCode}, errorArgs, defaultMessage));
}
@Override
public void rejectValue(@Nullable String field, String errorCode,
@Nullable Object[] errorArgs, @Nullable String defaultMessage) {
if (!StringUtils.hasLength(field)) {
reject(errorCode, errorArgs, defaultMessage);
return;
}
Object newVal = getFieldValue(field);
this.fieldErrors.add(new FieldError(getObjectName(), field, newVal, false,
new String[] {errorCode}, errorArgs, defaultMessage));
}
@Override
public void addAllErrors(Errors errors) {
this.globalErrors.addAll(errors.getGlobalErrors());
this.fieldErrors.addAll(errors.getFieldErrors());
}
@Override
public List<ObjectError> getGlobalErrors() {
return this.globalErrors;
}
@Override
public List<FieldError> getFieldErrors() {
return this.fieldErrors;
}
@Override
@Nullable
public Object getFieldValue(String field) {
PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(this.target.getClass(), field);
if (pd != null && pd.getReadMethod() != null) {
return ReflectionUtils.invokeMethod(pd.getReadMethod(), this.target);
}
Field rawField = ReflectionUtils.findField(this.target.getClass(), field);
if (rawField != null) {
ReflectionUtils.makeAccessible(rawField);
return ReflectionUtils.getField(rawField, this.target);
}
throw new IllegalArgumentException("Cannot retrieve value for field '" + field +
"' - neither a getter method nor a raw field found");
}
@Override
public Class<?> getFieldType(String field) {
PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(this.target.getClass(), field);
if (pd != null) {
return pd.getPropertyType();
}
Field rawField = ReflectionUtils.findField(this.target.getClass(), field);
if (rawField != null) {
return rawField.getType();
}
return null;
}
@Override
public boolean equals(@Nullable Object other) {
return (this == other || (other instanceof SimpleErrors that &&
ObjectUtils.nullSafeEquals(this.target, that.target) &&
this.globalErrors.equals(that.globalErrors) &&
this.fieldErrors.equals(that.fieldErrors)));
}
@Override
public int hashCode() {
return this.target.hashCode();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (ObjectError error : this.globalErrors) {
sb.append('\n').append(error);
}
for (ObjectError error : this.fieldErrors) {
sb.append('\n').append(error);
}
return sb.toString();
}
}

View File

@@ -48,16 +48,17 @@ import java.util.function.BiConsumer;
* }
* });</pre>
*
* <p>See also the Spring reference manual for a fuller discussion of
* the {@code Validator} interface and its role in an enterprise
* application.
* <p>See also the Spring reference manual for a fuller discussion of the
* {@code Validator} interface and its role in an enterprise application.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Toshiaki Maki
* @author Arjen Poutsma
* @see SmartValidator
* @see Errors
* @see ValidationUtils
* @see DataBinder#setValidator
*/
public interface Validator {
@@ -77,17 +78,43 @@ public interface Validator {
boolean supports(Class<?> clazz);
/**
* Validate the supplied {@code target} object, which must be
* of a {@link Class} for which the {@link #supports(Class)} method
* typically has (or would) return {@code true}.
* Validate the given {@code target} object which must be of a
* {@link Class} for which the {@link #supports(Class)} method
* typically has returned (or would return) {@code true}.
* <p>The supplied {@link Errors errors} instance can be used to report
* any resulting validation errors.
* any resulting validation errors, typically as part of a larger
* binding process which this validator is meant to participate in.
* Binding errors have typically been pre-registered with the
* {@link Errors errors} instance before this invocation already.
* @param target the object that is to be validated
* @param errors contextual state about the validation process
* @see ValidationUtils
*/
void validate(Object target, Errors errors);
/**
* Validate the given {@code target} object individually.
* <p>Delegates to the common {@link #validate(Object, Errors)} method.
* The returned {@link Errors errors} instance can be used to report
* any resulting validation errors for the specific target object, e.g.
* {@code if (validator.validateObject(target).hasErrors()) ...} or
* {@code validator.validateObject(target).failOnError(IllegalStateException::new));}.
* <p>Note: This validation call comes with limitations in the {@link Errors}
* implementation used, in particular no support for nested paths.
* If this is insufficient for your purposes, call the regular
* {@link #validate(Object, Errors)} method with a binding-capable
* {@link Errors} implementation such as {@link BeanPropertyBindingResult}.
* @param target the object that is to be validated
* @return resulting errors from the validation of the given object
* @since 6.1
* @see SimpleErrors
*/
default Errors validateObject(Object target) {
Errors errors = new SimpleErrors(target);
validate(target, errors);
return errors;
}
/**
* Return a {@code Validator} that checks whether the target object