1 package info.ejava.examples.ejb.interceptor.interceptors;
2
3 import info.ejava.examples.ejb.interceptor.ejb.InvalidParam;
4
5
6 import java.util.ArrayList;
7 import java.util.Arrays;
8 import java.util.List;
9 import java.util.Set;
10
11 import javax.annotation.PostConstruct;
12 import javax.annotation.PreDestroy;
13 import javax.inject.Inject;
14 import javax.interceptor.AroundInvoke;
15 import javax.interceptor.InvocationContext;
16 import javax.validation.ConstraintViolation;
17 import javax.validation.Validator;
18
19 import org.slf4j.Logger;
20 import org.slf4j.LoggerFactory;
21
22 public class ValidatorInterceptor {
23 private static Logger logger = LoggerFactory.getLogger(ValidatorInterceptor.class);
24 @Inject
25 private Validator validator;
26
27 private Class<?>[] groups;
28
29 protected ValidatorInterceptor() {}
30 public ValidatorInterceptor(Class<?>[] groups) {
31 this.groups = groups;
32 }
33
34 @PostConstruct
35 public void init() {
36 logger.debug("{}:init({}, groups={})", getClass().getSimpleName(), super.hashCode(), Arrays.toString(groups));
37 }
38 @PreDestroy
39 public void destroy() {
40 logger.debug("{}:destroy({})", getClass().getSimpleName(), super.hashCode());
41 }
42
43 @AroundInvoke
44 public Object invoke(InvocationContext ctx) throws Exception {
45 logger.debug("validating method: {}, groups: {}", ctx.getMethod(), Arrays.toString(groups));
46 try {
47
48 for (Object param: ctx.getParameters()) {
49 logger.debug("validating param: {}, groups: {}", param, Arrays.toString(groups));
50 Set<ConstraintViolation<Object>> violations = validator.validate(param, groups);
51 if (!violations.isEmpty()) {
52 Exception ex = new InvalidParam(param.toString(), getErrors(violations));
53 logger.debug("aborting call, found error: {}", ex.getMessage());
54 throw ex;
55 }
56 }
57 return ctx.proceed();
58 } finally {
59
60 }
61 }
62
63 private List<String> getErrors(Set<ConstraintViolation<Object>> violations) {
64 List<String> errors = new ArrayList<String>(violations.size());
65 for (ConstraintViolation<Object> v: violations) {
66 errors.add(v.toString());
67 }
68 return errors;
69 }
70 }