|
1
|
|
|
package io.github.ro4.annotation; |
|
2
|
|
|
|
|
3
|
|
|
import io.github.ro4.CheckTemplate; |
|
4
|
|
|
import io.github.ro4.Context; |
|
5
|
|
|
import io.github.ro4.check.CheckResult; |
|
6
|
|
|
import io.github.ro4.check.ExceptionProvider; |
|
7
|
|
|
import io.github.ro4.constant.MagicMark; |
|
8
|
|
|
import org.aopalliance.intercept.MethodInterceptor; |
|
9
|
|
|
import org.aopalliance.intercept.MethodInvocation; |
|
10
|
|
|
import org.springframework.validation.BindingResult; |
|
11
|
|
|
|
|
12
|
1 |
|
public class CheckableMethodInterceptor implements MethodInterceptor { |
|
13
|
|
|
|
|
14
|
|
|
private CheckTemplate checkTemplate; |
|
15
|
|
|
|
|
16
|
|
|
private ExceptionProvider<?> exceptionProvider; |
|
17
|
|
|
|
|
18
|
|
|
public void setCheckTemplate(CheckTemplate checkTemplate) { |
|
19
|
1 |
|
this.checkTemplate = checkTemplate; |
|
20
|
1 |
|
} |
|
21
|
|
|
|
|
22
|
|
|
public void setExceptionProvider(ExceptionProvider<?> exceptionProvider) { |
|
23
|
1 |
|
this.exceptionProvider = exceptionProvider; |
|
24
|
1 |
|
} |
|
25
|
|
|
|
|
26
|
|
|
@Override |
|
27
|
|
|
public Object invoke(MethodInvocation methodInvocation) throws Throwable { |
|
28
|
1 |
|
Checkable anno = methodInvocation.getMethod().getAnnotation(Checkable.class); |
|
29
|
1 |
|
boolean stopOnFirstFailure = anno.stopOnFirstFailure(); |
|
30
|
1 |
|
Object[] args = methodInvocation.getArguments(); |
|
31
|
1 |
|
BindingResult bindingResult = new CheckResult(methodInvocation.getMethod().getName()); |
|
32
|
1 |
|
for (CheckRule checkRule : anno.value()) { |
|
33
|
1 |
|
Context ctx = new Context(); |
|
34
|
1 |
|
for (int i = 0; i < args.length; i++) { |
|
35
|
1 |
|
ctx.setAttribute(MagicMark.ARGS_NAME + i, args[i]); |
|
36
|
|
|
} |
|
37
|
1 |
|
ctx.setAttribute(MagicMark.EXPRESSION, checkRule.expression()); |
|
38
|
1 |
|
ctx.setAttribute(MagicMark.MESSAGE, checkRule.message()); |
|
39
|
1 |
|
if (checkTemplate.check(ctx)) { |
|
40
|
1 |
|
continue; |
|
41
|
|
|
} |
|
42
|
1 |
|
bindingResult.reject(checkRule.field(), checkRule.message()); |
|
43
|
1 |
|
if (stopOnFirstFailure) { |
|
44
|
|
|
break; |
|
45
|
|
|
} |
|
46
|
|
|
} |
|
47
|
1 |
|
if (bindingResult.hasErrors()) { |
|
48
|
1 |
|
RuntimeException throwable = exceptionProvider.produce(bindingResult); |
|
49
|
1 |
|
if (throwable != null) { |
|
50
|
1 |
|
throw throwable; |
|
51
|
|
|
} |
|
52
|
|
|
} |
|
53
|
1 |
|
return methodInvocation.proceed(); |
|
54
|
|
|
} |
|
55
|
|
|
} |