1
2
3
4
5
6
7
8
9
10
11
12
13
14 package ch.qos.logback.core.boolex;
15
16 import java.util.ArrayList;
17 import java.util.List;
18
19 import org.codehaus.janino.ScriptEvaluator;
20
21
22
23
24
25
26
27
28 abstract public class JaninoEventEvaluatorBase<E> extends EventEvaluatorBase<E> {
29
30 static Class EXPRESSION_TYPE = boolean.class;
31 static Class[] THROWN_EXCEPTIONS = new Class[1];
32
33 static public final int ERROR_THRESHOLD = 4;
34 static {
35 THROWN_EXCEPTIONS[0] = EvaluationException.class;
36 }
37
38 private String expression;
39
40 ScriptEvaluator scriptEvaluator;
41 private int errorCount = 0;
42
43 abstract protected String getDecoratedExpression();
44
45 abstract protected String[] getParameterNames();
46
47 abstract protected Class[] getParameterTypes();
48
49 abstract protected Object[] getParameterValues(E event);
50
51 protected List<Matcher> matcherList = new ArrayList<Matcher>();
52
53 @Override
54 public void start() {
55 try {
56 assert context != null;
57 scriptEvaluator = new ScriptEvaluator(getDecoratedExpression(), EXPRESSION_TYPE,
58 getParameterNames(), getParameterTypes(), THROWN_EXCEPTIONS);
59 super.start();
60 } catch (Exception e) {
61 addError(
62 "Could not start evaluator with expression [" + expression + "]", e);
63 }
64 }
65
66 public boolean evaluate(E event) throws EvaluationException {
67 if (!isStarted()) {
68 throw new IllegalStateException("Evaluator [" + name
69 + "] was called in stopped state");
70 }
71 try {
72 Boolean result = (Boolean) scriptEvaluator.evaluate(getParameterValues(event));
73 return result.booleanValue();
74 } catch (Exception ex) {
75 errorCount++;
76 if (errorCount >= ERROR_THRESHOLD) {
77 stop();
78 }
79 throw new EvaluationException("Evaluator [" + name
80 + "] caused an exception", ex);
81 }
82 }
83
84 public String getExpression() {
85 return expression;
86 }
87
88 public void setExpression(String expression) {
89 this.expression = expression;
90 }
91
92 public void addMatcher(Matcher matcher) {
93 matcherList.add(matcher);
94 }
95
96 public List getMatcherList() {
97 return matcherList;
98 }
99 }