org.springmodules.validation.bean.BeanValidator Maven / Gradle / Ivy
/*
* Copyright 2004-2005 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
*
* http://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.springmodules.validation.bean;
import java.lang.reflect.Array;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.springmodules.validation.bean.conf.BeanValidationConfiguration;
import org.springmodules.validation.bean.conf.CascadeValidation;
import org.springmodules.validation.bean.conf.loader.BeanValidationConfigurationLoader;
import org.springmodules.validation.bean.conf.loader.xml.DefaultXmlBeanValidationConfigurationLoader;
import org.springmodules.validation.bean.converter.ErrorCodeConverter;
import org.springmodules.validation.bean.converter.ModelAwareErrorCodeConverter;
import org.springmodules.validation.bean.rule.ValidationRule;
import org.springmodules.validation.util.condition.Condition;
/**
* An {@link org.springmodules.validation.validator.AbstractTypeSpecificValidator} implementation that applies all validation rules
* on a bean of a specific type, based on an appropriate {@link org.springmodules.validation.bean.conf.BeanValidationConfiguration}. The validation
* configuration is loaded per bean type by the configured {@link BeanValidationConfigurationLoader}.
*
* @author Uri Boness
*/
public class BeanValidator extends RuleBasedValidator {
private final static Log logger = LogFactory.getLog(BeanValidator.class);
private final static String PROPERTY_KEY_PREFIX = "[";
private final static String PROPERTY_KEY_SUFFIX = "]";
private BeanValidationConfigurationLoader configurationLoader;
private ErrorCodeConverter errorCodeConverter;
/**
* Constructs a new BeanValidator. By default the
* {@link org.springmodules.validation.bean.conf.loader.SimpleBeanValidationConfigurationLoader} is
* used as the bean validation configuration loader.
*/
public BeanValidator() {
this(new DefaultXmlBeanValidationConfigurationLoader());
}
/**
* Constructs a new BeanValidator for the given bean class using the given validation configuration loader.
*
* @param configurationLoader The {@link org.springmodules.validation.bean.conf.loader.BeanValidationConfigurationLoader} that is used to load the bean validation
* configuration.
*/
public BeanValidator(BeanValidationConfigurationLoader configurationLoader) {
this.configurationLoader = configurationLoader;
errorCodeConverter = new ModelAwareErrorCodeConverter();
}
/**
* This validator supports only those classes that are supported by the validation configuration loader it uses.
*
* @see org.springmodules.validation.bean.RuleBasedValidator#supports(Class)
* @see org.springmodules.validation.bean.conf.loader.BeanValidationConfigurationLoader#supports(Class)
*/
public boolean supports(Class clazz) {
return configurationLoader.supports(clazz) || super.supports(clazz);
}
/**
* Applies all validation rules as defined in the {@link org.springmodules.validation.bean.conf.BeanValidationConfiguration} retrieved for the given
* bean from the configured {@link org.springmodules.validation.bean.conf.loader.BeanValidationConfigurationLoader}.
*
* @see Validator#validate(Object, org.springframework.validation.Errors)
*/
public void validate(Object obj, Errors errors) {
// validation the object graph using the class validation manager.
validateObjectGraphConstraints(obj, obj, errors, new HashSet());
// applying the registered validation rules.
super.validate(obj, errors);
}
//============================================== Setter/Getter =====================================================
/**
* Sets the error code converter this validator will use to resolve the error codes to be registered with the
* {@link Errors} object.
*
* @param errorCodeConverter The error code converter this validator will use to resolve the error
* different error codes.
*/
public void setErrorCodeConverter(ErrorCodeConverter errorCodeConverter) {
this.errorCodeConverter = errorCodeConverter;
}
/**
* Sets the bean validation configuration loader this validator will use to load the bean validation configurations.
*
* @param configurationLoader The loader this validator will use to load the bean validation configurations.
*/
public void setConfigurationLoader(BeanValidationConfigurationLoader configurationLoader) {
this.configurationLoader = configurationLoader;
}
//=============================================== Helper Methods ===================================================
/**
* 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).
*/
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
© 2015 - 2025 Weber Informatics LLC | Privacy Policy