View Javadoc

1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2011, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package ch.qos.logback.core.joran.action;
15  
16  import ch.qos.logback.core.spi.ContextAware;
17  import org.xml.sax.Attributes;
18  
19  import ch.qos.logback.core.joran.spi.ActionException;
20  import ch.qos.logback.core.joran.spi.InterpretationContext;
21  import ch.qos.logback.core.spi.LifeCycle;
22  import ch.qos.logback.core.status.StatusListener;
23  import ch.qos.logback.core.util.OptionHelper;
24  
25  
26  public class StatusListenerAction extends Action {
27  
28  
29    boolean inError = false;
30    StatusListener statusListener = null;
31  
32    public void begin(InterpretationContext ec, String name, Attributes attributes) throws ActionException {
33      inError = false;
34      String className = attributes.getValue(CLASS_ATTRIBUTE);
35      if (OptionHelper.isEmpty(className)) {
36        addError("Missing class name for statusListener. Near ["
37                + name + "] line " + getLineNumber(ec));
38        inError = true;
39        return;
40      }
41  
42      try {
43        statusListener = (StatusListener) OptionHelper.instantiateByClassName(
44                className, StatusListener.class, context);
45        ec.getContext().getStatusManager().add(statusListener);
46        if (statusListener instanceof ContextAware) {
47          ((ContextAware) statusListener).setContext(context);
48        }
49        addInfo("Added status listener of type [" + className + "]");
50        ec.pushObject(statusListener);
51      } catch (Exception e) {
52        inError = true;
53        addError(
54                "Could not create an StatusListener of type [" + className + "].", e);
55        throw new ActionException(e);
56      }
57  
58    }
59  
60    public void finish(InterpretationContext ec) {
61    }
62  
63    public void end(InterpretationContext ec, String e) {
64      if (inError) {
65        return;
66      }
67      if (statusListener instanceof LifeCycle) {
68        ((LifeCycle) statusListener).start();
69      }
70      Object o = ec.peekObject();
71      if (o != statusListener) {
72        addWarn("The object at the of the stack is not the statusListener pushed earlier.");
73      } else {
74        ec.popObject();
75      }
76    }
77  }