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
15
16
17
18 @Aspect
19 @Component
20 public class ValidatorAspect {
21
22 private final ValidatorFactory validatorFactory;
23
24
25
26
27 ValidatorAspect() {
28 validatorFactory = Validation.buildDefaultValidatorFactory();
29 }
30
31
32
33
34
35
36
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
56
57
58
59
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 }