View Javadoc
1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2015, 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 chapters.onJoran.calculator;
15  
16  import java.util.EmptyStackException;
17  
18  import org.xml.sax.Attributes;
19  
20  import ch.qos.logback.core.joran.action.Action;
21  import ch.qos.logback.core.joran.spi.InterpretationContext;
22  
23  /**
24   * This action adds the two integers at the top of the stack (they are removed)
25   * and pushes the result to the top the stack.  
26   * 
27   * @author Ceki Gülcü
28   */
29  public class AddAction extends Action {
30  
31      public void begin(InterpretationContext ic, String name, Attributes attributes) {
32          int first = fetchInteger(ic);
33          int second = fetchInteger(ic);
34          // Push the result of the addition for the following actions.
35          ic.pushObject(first + second);
36      }
37  
38      /**
39       * Pop the Integer object at the top of the stack.
40       * This code also  illustrates usage of Joran's error handling paradigm. 
41       */
42      int fetchInteger(InterpretationContext ic) {
43          int result = 0;
44  
45          try {
46              // Pop the object at the top of the interpretation context's stack.
47              Object o1 = ic.popObject();
48  
49              if (o1 instanceof Integer) {
50                  result = ((Integer) o1).intValue();
51              } else {
52                  String errMsg = "Object [" + o1 + "] currently at the top of the stack is not an integer.";
53                  ic.addError(errMsg);
54                  throw new IllegalArgumentException(errMsg);
55              }
56          } catch (EmptyStackException ese) {
57              ic.addError(("Expecting an integer on the execution stack."));
58              throw ese;
59          }
60          return result;
61      }
62  
63      public void end(InterpretationContext ic, String name) {
64          // Nothing to do here.
65      }
66  }