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