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