View Javadoc

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