|
1
|
|
|
package io.github.ro4.check; |
|
2
|
|
|
|
|
3
|
|
|
import io.github.ro4.ExpressionException; |
|
4
|
|
|
import io.github.ro4.constant.MagicMark; |
|
5
|
|
|
import io.github.ro4.Context; |
|
6
|
|
|
import org.springframework.beans.factory.BeanFactory; |
|
7
|
|
|
import org.springframework.context.expression.BeanFactoryResolver; |
|
8
|
|
|
import org.springframework.expression.spel.standard.SpelExpressionParser; |
|
9
|
|
|
import org.springframework.expression.spel.support.StandardEvaluationContext; |
|
10
|
|
|
|
|
11
|
1 |
|
public class SpELChecker implements Checker { |
|
12
|
1 |
|
private static final SpelExpressionParser PARSER = new SpelExpressionParser(); |
|
13
|
|
|
|
|
14
|
1 |
|
private BeanFactory beanFactory = null; |
|
15
|
|
|
|
|
16
|
1 |
|
public SpELChecker() { |
|
17
|
|
|
|
|
18
|
1 |
|
} |
|
19
|
|
|
|
|
20
|
1 |
|
public SpELChecker(BeanFactory beanFactory) { |
|
21
|
1 |
|
this.beanFactory = beanFactory; |
|
22
|
1 |
|
} |
|
23
|
|
|
|
|
24
|
|
|
@Override |
|
25
|
|
|
public boolean pass(Context ctx) { |
|
26
|
1 |
|
if (!ctx.hasAttribute(MagicMark.EXPRESSION)) { |
|
27
|
1 |
|
throw new ExpressionException("expression not found"); |
|
28
|
|
|
} |
|
29
|
1 |
|
StandardEvaluationContext spELCtx = new StandardEvaluationContext(); |
|
30
|
|
|
// ugly design, temporary work |
|
31
|
1 |
|
if (null != beanFactory) { |
|
32
|
1 |
|
spELCtx.setBeanResolver(new BeanFactoryResolver(beanFactory)); |
|
33
|
|
|
} |
|
34
|
1 |
|
for (String s : ctx.attributeNames()) { |
|
35
|
1 |
|
spELCtx.setVariable(s, ctx.getAttribute(s)); |
|
36
|
|
|
} |
|
37
|
1 |
|
String expression = (String) ctx.getAttribute(MagicMark.EXPRESSION); |
|
38
|
1 |
|
assert expression != null; |
|
39
|
1 |
|
return Boolean.TRUE.equals(PARSER.parseExpression(expression).getValue(spELCtx, Boolean.TYPE)); |
|
40
|
|
|
} |
|
41
|
|
|
} |
|
42
|
|
|
|