com.github.carlomicieli.rest.ValidatorAspect.java Source code

Java tutorial

Introduction

Here is the source code for com.github.carlomicieli.rest.ValidatorAspect.java

Source

/*
 * Copyright 2012 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 com.github.carlomicieli.rest;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 
 * @author Carlo Micieli
 *
 */
@Aspect
public class ValidatorAspect {
    private @Autowired Validator validator;

    @Before("execution(* *(@com.github.carlomicieli.rest.Valid(*)))")
    public void validate(JoinPoint jp) throws NoSuchMethodException {

        Set<ConstraintViolation<?>> violations = new HashSet<ConstraintViolation<?>>();

        Method methodSignature = ((MethodSignature) jp.getSignature()).getMethod();

        Method targetMethod = jp.getTarget().getClass().getMethod(methodSignature.getName(),
                methodSignature.getParameterTypes());

        Annotation[][] annotationParameters = targetMethod.getParameterAnnotations();

        for (int i = 0; i < annotationParameters.length; i++) {
            Annotation[] annotations = annotationParameters[i];
            for (Annotation a : annotations) {
                if (a.annotationType().equals(Valid.class)) {
                    Object arg = jp.getArgs()[i];
                    violations.addAll(validator.validate(arg));
                }
            }
        }

        if (!violations.isEmpty()) {
            throw new ConstraintViolationException(violations);
        }
    }

}