View Javadoc

1   /**
2    * Logback: the generic, reliable, fast and flexible logging framework.
3    * 
4    * Copyright (C) 2000-2009, QOS.ch
5    * 
6    * This library is free software, you can redistribute it and/or modify it under
7    * the terms of the GNU Lesser General Public License as published by the Free
8    * Software Foundation.
9    */
10  
11  package chapter10.calculator;
12  
13  import java.util.EmptyStackException;
14  
15  import org.xml.sax.Attributes;
16  
17  import ch.qos.logback.core.joran.action.Action;
18  import ch.qos.logback.core.joran.spi.InterpretationContext;
19  
20  
21  /**
22   * This action adds the two integers at the top of the stack (they are removed)
23   * and pushes the result to the top the stack.  
24   * 
25   * @author Ceki Gülcü
26   */
27  public class AddAction extends Action {
28    
29    public void begin(InterpretationContext ic, String name, Attributes attributes) {
30      int first = fetchInteger(ic);
31      int second = fetchInteger(ic);
32      // Push the result of the addition for the following actions.
33      ic.pushObject(new Integer(first + second));
34    }
35  
36    /**
37     * Pop the Integer object at the top of the stack.
38     * This code also  illustrates usage of Joran's error handling paradigm. 
39     */
40    int fetchInteger(InterpretationContext ic) {
41      int result = 0;
42  
43      try {
44        // Pop the object at the top of the interpretation context's stack.
45        Object o1 = ic.popObject();
46  
47        if (o1 instanceof Integer) {
48          result = ((Integer) o1).intValue();
49        } else {
50          String errMsg =
51            "Object [" + o1
52            + "] 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  }