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.joran.action;
015
016import org.xml.sax.Attributes;
017
018import ch.qos.logback.core.Appender;
019import ch.qos.logback.core.CoreConstants;
020import ch.qos.logback.core.joran.spi.InterpretationContext;
021import ch.qos.logback.core.spi.AppenderAttachable;
022import ch.qos.logback.core.util.OptionHelper;
023
024import java.util.HashMap;
025
026public class AppenderRefAction<E> extends Action {
027    boolean inError = false;
028
029    @SuppressWarnings("unchecked")
030    public void begin(InterpretationContext ec, String tagName, Attributes attributes) {
031        // Let us forget about previous errors (in this object)
032        inError = false;
033
034        // logger.debug("begin called");
035
036        Object o = ec.peekObject();
037
038        if (!(o instanceof AppenderAttachable)) {
039            String errMsg = "Could not find an AppenderAttachable at the top of execution stack. Near [" + tagName + "] line " + getLineNumber(ec);
040            inError = true;
041            addError(errMsg);
042            return;
043        }
044
045        AppenderAttachable<E> appenderAttachable = (AppenderAttachable<E>) o;
046
047        String appenderName = ec.subst(attributes.getValue(ActionConst.REF_ATTRIBUTE));
048
049        if (OptionHelper.isEmpty(appenderName)) {
050            // print a meaningful error message and return
051            String errMsg = "Missing appender ref attribute in <appender-ref> tag.";
052            inError = true;
053            addError(errMsg);
054
055            return;
056        }
057
058        HashMap<String, Appender<E>> appenderBag = (HashMap<String, Appender<E>>) ec.getObjectMap().get(ActionConst.APPENDER_BAG);
059        Appender<E> appender = (Appender<E>) appenderBag.get(appenderName);
060
061        if (appender == null) {
062            String msg = "Could not find an appender named [" + appenderName + "]. Did you define it below instead of above in the configuration file?";
063            inError = true;
064            addError(msg);
065            addError("See " + CoreConstants.CODES_URL + "#appender_order for more details.");
066            return;
067        }
068
069        addInfo("Attaching appender named [" + appenderName + "] to " + appenderAttachable);
070        appenderAttachable.addAppender(appender);
071    }
072
073    public void end(InterpretationContext ec, String n) {
074    }
075
076}