001/** 002 * Logback: the reliable, generic, fast and flexible logging framework. 003 * Copyright (C) 1999-2015, QOS.ch. All rights reserved. 004 * 005 * This program and the accompanying materials are dual-licensed under 006 * either the terms of the Eclipse Public License v1.0 as published by 007 * the Eclipse Foundation 008 * 009 * or (per the licensee's choosing) 010 * 011 * under the terms of the GNU Lesser General Public License version 2.1 012 * as published by the Free Software Foundation. 013 */ 014package ch.qos.logback.core.boolex; 015 016import java.util.ArrayList; 017import java.util.List; 018 019import org.codehaus.janino.ScriptEvaluator; 020 021/** 022 * Abstract class which sets the groundwork for janino based evaluations. 023 * 024 * @author Ceki Gülcü 025 * 026 * @param <E> event type 027 */ 028abstract public class JaninoEventEvaluatorBase<E> extends EventEvaluatorBase<E> { 029 030 static Class<?> EXPRESSION_TYPE = boolean.class; 031 static Class<?>[] THROWN_EXCEPTIONS = new Class[1]; 032 033 static public final int ERROR_THRESHOLD = 4; 034 static { 035 THROWN_EXCEPTIONS[0] = EvaluationException.class; 036 } 037 038 private String expression; 039 040 ScriptEvaluator scriptEvaluator; 041 private int errorCount = 0; 042 043 abstract protected String getDecoratedExpression(); 044 045 abstract protected String[] getParameterNames(); 046 047 abstract protected Class<?>[] getParameterTypes(); 048 049 abstract protected Object[] getParameterValues(E event); 050 051 protected List<Matcher> matcherList = new ArrayList<>(); 052 053 @Override 054 public void start() { 055 try { 056 assert context != null; 057 scriptEvaluator = new ScriptEvaluator(getDecoratedExpression(), EXPRESSION_TYPE, getParameterNames(), 058 getParameterTypes(), THROWN_EXCEPTIONS); 059 super.start(); 060 } catch (Exception e) { 061 addError("Could not start evaluator with expression [" + expression + "]", e); 062 } 063 } 064 065 public boolean evaluate(E event) throws EvaluationException { 066 if (!isStarted()) { 067 throw new IllegalStateException("Evaluator [" + name + "] was called in stopped state"); 068 } 069 try { 070 Boolean result = (Boolean) scriptEvaluator.evaluate(getParameterValues(event)); 071 return result; 072 } catch (Exception ex) { 073 errorCount++; 074 if (errorCount >= ERROR_THRESHOLD) { 075 stop(); 076 } 077 throw new EvaluationException("Evaluator [" + name + "] caused an exception", ex); 078 } 079 } 080 081 public String getExpression() { 082 return expression; 083 } 084 085 public void setExpression(String expression) { 086 this.expression = expression; 087 } 088 089 public void addMatcher(Matcher matcher) { 090 matcherList.add(matcher); 091 } 092 093 public List<Matcher> getMatcherList() { 094 return matcherList; 095 } 096}