View Javadoc

1   /**
2    * Logback: the reliable, fast and flexible logging library for Java.
3    * 
4    * Copyright (C) 1999-2006, 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 chapter3.calculator;
12  
13  
14  
15  import java.util.EmptyStackException;
16  
17  import org.xml.sax.Attributes;
18  
19  import ch.qos.logback.core.joran.action.Action;
20  import ch.qos.logback.core.joran.spi.InterpretationContext;
21  
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 ec, String name, Attributes attributes) {
32      int first = fetchInteger(ec);
33      int second = fetchInteger(ec);
34      // Push the result of the addition for the following actions.
35      ec.pushObject(new Integer(first + second));
36    }
37  
38    /**
39     * Pop the Integer object at the top of the stack.
40     * This code illustrates usage of Joran's error handling paradigm. 
41     */
42    int fetchInteger(InterpretationContext ec) {
43      int result = 0;
44  
45      try {
46        // Pop the object at the top of the exection context stack.
47        Object o1 = ec.popObject();
48  
49        if (o1 instanceof Integer) {
50          result = ((Integer) o1).intValue();
51        } else {
52          String errMsg =
53            "Object [" + o1
54            + "] currently at the top of the stack is not an integer.";
55          ec.addError(errMsg);
56          throw new IllegalArgumentException(errMsg);
57        }
58      } catch (EmptyStackException ese) {
59        ec.addError(("Expecting an integer on the execution stack."));
60        throw ese;
61      }
62      return result;
63    }
64  
65    public void end(InterpretationContext ec, String name) {
66      // Nothing to do here.
67      // In general, the end() method of actions associated with elements
68      // having no children do not need to perform any processing in their
69      // end() method.
70    }
71  }