View Javadoc

1   /**
2    * Logback: the generic, reliable, fast and flexible logging framework.
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  import org.xml.sax.Attributes;
15  
16  import ch.qos.logback.core.joran.action.Action;
17  import ch.qos.logback.core.joran.spi.InterpretationContext;
18  
19  import java.util.EmptyStackException;
20  
21  
22  /**
23   *
24   * This action multiplies the two integers at the top of the stack (they are removed)
25   * and pushes the result on top the stack.
26   *
27   * @author Ceki Gülcü
28   */
29  public class MultiplyAction extends Action {
30    
31    
32    public void begin(InterpretationContext ec, String name, Attributes attributes) {
33      int first = fetchInteger(ec);
34      int second = fetchInteger(ec);
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        Object o1 = ec.popObject();
47  
48        if (o1 instanceof Integer) {
49          result = ((Integer) o1).intValue();
50        } else {
51          String errMsg =
52            "Object [" + o1
53            + "] currently at the top of the stack is not an integer.";
54          ec.addError(errMsg);
55          throw new IllegalArgumentException(errMsg);
56        }
57      } catch (EmptyStackException ese) {
58        ec.addError("Expecting an integer on the execution stack.");
59        throw ese;
60      }
61      return result;
62    }
63  
64    public void end(InterpretationContext ec, String name) {
65      // Nothing to do here.
66      // In general, the end() method of actions associated with elements
67      // having no children do not need to perform any processing in their
68      // end() method.
69    }
70  }