View Javadoc
1   package org.imageconverter.util.validation;
2   
3   import javax.validation.ConstraintViolationException;
4   import javax.validation.Validation;
5   import javax.validation.ValidatorFactory;
6   
7   import org.aspectj.lang.ProceedingJoinPoint;
8   import org.aspectj.lang.annotation.Around;
9   import org.aspectj.lang.annotation.Aspect;
10  import org.aspectj.lang.reflect.MethodSignature;
11  import org.springframework.stereotype.Component;
12  
13  /**
14   * Aspect to use beans validation on application.
15   * 
16   * @author Fernando Romulo da Silva
17   */
18  @Aspect
19  @Component
20  public class ValidatorAspect {
21  
22      private final ValidatorFactory validatorFactory;
23  
24      /**
25       * Default constructor.
26       */
27      ValidatorAspect() {
28  	validatorFactory = Validation.buildDefaultValidatorFactory();
29      }
30  
31      /**
32       * Execute the around with valition contraints for methods.
33       * 
34       * @param point The object that support around advice in @AJ aspects
35       * @return The metho's return
36       * @throws Throwable If something wrong happens
37       */
38      @Around("execution(@javax.validation.constraints.* public * * (..))")
39      public Object afterReturning(final ProceedingJoinPoint point) throws Throwable {
40  
41  	final var theReturnValue = point.proceed();
42  
43  	final var theSignature = (MethodSignature) point.getSignature();
44  	final var theValidator = validatorFactory.getValidator().forExecutables();
45  	final var theViolations = theValidator.validateReturnValue(point.getTarget(), theSignature.getMethod(), theReturnValue);
46  
47  	if (!theViolations.isEmpty()) {
48  	    throw new ConstraintViolationException(theViolations);
49  	}
50  
51  	return theReturnValue;
52      }
53  
54      /**
55       * Execute the around with valition contraints for attributes.
56       * 
57       * @param point The object that support around advice in @AJ aspects
58       * @return The metho's return
59       * @throws Throwable If something wrong happens
60       */
61      @Around("execution(public * * (.., @javax.validation.constraints..* (*), ..))")
62      public Object pointcutMethodArgument(final ProceedingJoinPoint point) throws Throwable {
63  
64  	final var theSignature = (MethodSignature) point.getSignature();
65  	final var theValidator = validatorFactory.getValidator().forExecutables();
66  	final var theViolations = theValidator.validateParameters(point.getTarget(), theSignature.getMethod(), point.getArgs());
67  
68  	if (!theViolations.isEmpty()) {
69  	    throw new ConstraintViolationException(theViolations);
70  	}
71  
72  	return point.proceed();
73      }
74  
75  }