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.filter;
015
016import ch.qos.logback.core.boolex.EvaluationException;
017import ch.qos.logback.core.boolex.EventEvaluator;
018import ch.qos.logback.core.spi.FilterReply;
019
020/**
021 * The value of the {@link #onMatch} and {@link #onMismatch} attributes is set
022 * to {@link FilterReply#NEUTRAL}, so that a badly configured evaluator filter does
023 * not disturb the functioning of the filter chain. 
024 * 
025 * <p>It is expected that one of the two attributes will have its value changed
026 * to {@link FilterReply#ACCEPT} or {@link FilterReply#DENY}. That way, it is possible to
027 * decide if a given result must be returned after the evaluation either failed
028 * or succeeded.
029 * 
030 * 
031 * <p> For more information about filters, please refer to the online manual at
032 * http://logback.qos.ch/manual/filters.html
033 * 
034 * @author Ceki G&uuml;lc&uuml;
035 * @author S&eacute;bastien Pennec
036 */
037public class EvaluatorFilter<E> extends AbstractMatcherFilter<E> {
038
039    EventEvaluator<E> evaluator;
040
041    @Override
042    public void start() {
043        if (evaluator != null) {
044            super.start();
045        } else {
046            addError("No evaluator set for filter " + this.getName());
047        }
048    }
049
050    public EventEvaluator<E> getEvaluator() {
051        return evaluator;
052    }
053
054    public void setEvaluator(EventEvaluator<E> evaluator) {
055        this.evaluator = evaluator;
056    }
057
058    public FilterReply decide(E event) {
059        // let us not throw an exception
060        // see also bug #17.
061        if (!isStarted() || !evaluator.isStarted()) {
062            return FilterReply.NEUTRAL;
063        }
064        try {
065            if (evaluator.evaluate(event)) {
066                return onMatch;
067            } else {
068                return onMismatch;
069            }
070        } catch (EvaluationException e) {
071            addError("Evaluator " + evaluator.getName() + " threw an exception", e);
072            return FilterReply.NEUTRAL;
073        }
074    }
075
076}