Automatic validation of method calls with JSR-303 (Appendix-C of the specification)

The recently approved Bean Validation Standard (JSR-303) left one great (and requested) feature out of the specification: method validation. This proposal defined an additional API for the Validator with methods that allowed validation of method/constructor parameters as well as the return value of methods. Thankfully, even though this spec didn’t make it to the final approved document, all constraint annotations accept parameter as target, so the door was left open for it to be implemented as an extra feature.
methodvalidation.tar

Apache BeanValidation

There are currently 2 implementations of the standard, Hibernate Validator and Apache BeanValidation (formerly agimatec-validator, and as of this march an Apache Incubator project). Of these two, only Apache BeanValidation supports the additional method validation API, so it is the only choice if you need that feature, and it’s what I will use as base for this example.

Method validation API

The proposed additional methods in the bean validation are the following:

<T> Set<ConstraintViolation<T>> validateParameters(Class<T> clazz, Method method,
                                                       Object[] parameterValues,
                                                       Class<?>... groups);
 
<T> Set<ConstraintViolation<T>> validateParameter(Class<T> clazz, Method method,
                                                   Object parameterValue,
                                                   int parameterIndex,
                                                   Class<?>... groups);
 
<T> Set<ConstraintViolation<T>> validateReturnedValue(Class<T> clazz, Method method,
                                                       Object returnedValue,
                                                       Class<?>... groups);
 
<T> Set<ConstraintViolation<T>> validateParameters(Class<T> clazz,
                                                    Constructor constructor,
                                                    Object[] parameterValues,
                                                    Class<?>... groups);
 
 
<T> Set<ConstraintViolation<T>> validateParameter(Class<T> clazz,
                                                   Constructor constructor,
                                                   Object parameterValue,
                                                   int parameterIndex,
                                                   Class<?>... groups);

So, to validate the parameters of a method call, one would call validateParameters with the holder class, the method description and the parameter values as parameters, and the output would be similar than when validating a bean.

And how do you specify the constraints? In the method declaration, as in this example:

@NotNull
@NotEmpty
public String operation(@NotNull @Pattern(regexp="[0-9]{2}") String param) {
   // Your code
   return val;
}

This enhanced method declaration indicates that the param value cannot be null, and must be matched by the regular expression [0-9]{2}. In the same way, the value returned by the function cannot be null or an empty string.

Automatic validation using AspectJ

Being one good example of a crosscutting concern, validation code can easily pollute all your application code and maintenance can become really difficult. So, a good way to implement it automatically is using AspectJ. This way, you will decide in a single place (the pointcut) what method and constructors you want to be validated, and the validation code will also be centralized in a single place (the advice).

The aspect implementing this functionality is as follows:

package net.carinae.methodvalidation;
 
import java.util.Arrays;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidationException;
import javax.validation.ValidatorFactory;
import org.apache.bval.jsr303.extensions.MethodValidator;
import org.aspectj.lang.reflect.ConstructorSignature;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
/**
 * Enforces correct parameters and return values on the adviced methods and constructors.
 * <p>
 * NOTE: Currently only works with Apache BeanValidation.
 * 
 * @author Carlos Vara
 */
public aspect MethodValidationAspect {
 
	final static Logger logger = LoggerFactory.getLogger(MethodValidationAspect.class);
 
	static private ValidatorFactory factory;
 
	static {
		factory = Validation.buildDefaultValidatorFactory();
	}
 
	static private MethodValidator getMethodValidator() {
		return factory.getValidator().unwrap(MethodValidator.class);
	}
 
 
	pointcut validatedMethodCall() : execution(@ValidatedMethodCall * *(..));
 
	pointcut validatedConstructorCall() : execution(@ValidatedConstructorCall * .new(..));
 
	pointcut validatedReturnValue() : validatedMethodCall() && execution(!void *(..));
 
 
	/**
	 * Validates the method parameters.
	 */
	before() : validatedMethodCall() {
 
		MethodSignature methodSignature = (MethodSignature)thisJoinPoint.getSignature();
 
		logger.trace("Validating call: {} with args {}", methodSignature.getMethod(), Arrays.toString(thisJoinPoint.getArgs()));
 
		Set<? extends ConstraintViolation<?>> validationErrors = getMethodValidator().validateParameters(thisJoinPoint.getThis().getClass(), methodSignature.getMethod(), thisJoinPoint.getArgs());
 
		if ( validationErrors.isEmpty() ) {
			logger.trace("Valid call");
		}
		else {
			logger.warn("Invalid call");
			RuntimeException ex = buildValidationException(validationErrors);
			throw ex;
		}
 
	}
 
 
	/**
	 * Validates the constructor parameters.
	 */
	before() : validatedConstructorCall() {
 
		ConstructorSignature constructorSignature = (ConstructorSignature)thisJoinPoint.getSignature();
 
		logger.trace("Validating constructor: {} with args {}", constructorSignature.getConstructor(), Arrays.toString(thisJoinPoint.getArgs()));
 
		Set<? extends ConstraintViolation<?>> validationErrors = getMethodValidator().validateParameters(thisJoinPoint.getThis().getClass(), constructorSignature.getConstructor(), thisJoinPoint.getArgs());
 
		if ( validationErrors.isEmpty() ) {
			logger.trace("Valid call");
		}
		else {
			logger.warn("Invalid call");
			RuntimeException ex = buildValidationException(validationErrors);
			throw ex;
		}
	}
 
 
	/**
	 * Validates the returned value of a method call.
	 * 
	 * @param ret The returned value
	 */
	after() returning(Object ret) : validatedReturnValue() {
 
		MethodSignature methodSignature = (MethodSignature)thisJoinPoint.getSignature();
 
		logger.trace("Validating returned value {} from call: {}", ret, methodSignature.getMethod());
 
		Set<? extends ConstraintViolation<?>> validationErrors = getMethodValidator().validateReturnedValue(thisJoinPoint.getThis().getClass(), methodSignature.getMethod(), ret);
 
		if ( validationErrors.isEmpty() ) {
			logger.info("Valid call");
		}
		else {
			logger.warn("Invalid call");
			RuntimeException ex = buildValidationException(validationErrors);
			throw ex;
		}
 
	}
 
 
	/**
	 * @param validationErrors The errors detected in a method/constructor call.
	 * @return A RuntimeException with information about the detected validation errors. 
	 */
	private RuntimeException buildValidationException(Set<? extends ConstraintViolation<?>> validationErrors) {
		StringBuilder sb = new StringBuilder();
		for (ConstraintViolation<?> cv : validationErrors ) {
			sb.append("\n" + cv.getPropertyPath() + "{" + cv.getInvalidValue() + "} : " + cv.getMessage());
		}
		return new ValidationException(sb.toString());
	}
 
}

I have defined 3 simple pointcuts (to advice parameter validation of method and constructors, and return value of methods), and I have used 2 custom made interfaces to annotate the methods in which I want validation to be performed. You may of course want to tweak those pointcuts to adapt to your environment. The code of the 2 interfaces is included in the packaged project.

Some gotchas

Take care that the current implementation of the method validation API is still experimental. As of this writing, many constraints still don’t work (I used a patched build for the @Size and @Pattern constraints to work), but it’s just a matter of time that all the features available for bean validation work as well for parameter validation.

If you want to start from a template, I have attached a simple maven project that shows the use of this technique and has the aspect and needed interfaces code in it.
Download it here: methodvalidation.tar.gz