KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jfun > yan > xml > nuts > optional > SwitchNut


1 package jfun.yan.xml.nuts.optional;
2
3 import java.util.ArrayList JavaDoc;
4
5 import jfun.yan.Component;
6 import jfun.yan.Components;
7 import jfun.yan.xml.nut.ComponentNut;
8
9 /**
10  * The switch-case tag that supports <case> and <default> sub-tags.
11  * It takes similar syntax and semantics as Java switch-case statement. for example:
12  * <pre>
13  * &lt;switch val="1"&gt;
14  * &lt;case of="1"&gt;
15  * &lt;return val="one"/&gt;
16  * &lt;/case&gt;
17  * &lt;case of="2"&gt;
18  * &lt;fail msg="this is so wrong!"/&gt;
19  * &lt;/case&gt;
20  * &lt;default&gt;
21  * &lt;pring msg="did not find a match"/&gt;
22  * &lt;/default&gt;
23  * &lt;/switch&gt;
24  * </pre>
25  * Unlike Java, there's no fall-through behavior. And if default branch is not specified
26  * and no match is found, it silently returns.
27  * <p>
28  * @author Ben Yu
29  * Nov 11, 2005 3:46:03 PM
30  */

31 public class SwitchNut extends ComponentNut {
32   private Object JavaDoc val;
33   private final ArrayList JavaDoc cases = new ArrayList JavaDoc();
34   private Component def;
35   
36   public Object JavaDoc getVal() {
37     return val;
38   }
39   public void setVal(Object JavaDoc val) {
40     this.val = val;
41   }
42   public void addCase(Case cs){
43     cases.add(cs);
44   }
45   public void addDefault(Default def){
46     checkDuplicate("default", this.def);
47     this.def = def.getComponent();
48   }
49   private boolean match(Object JavaDoc v){
50     return val==null?v==null:val.equals(v);
51   }
52   public Component eval(){
53     final int sz = cases.size();
54     for(int i=0; i<sz; i++){
55       final Case cs = (Case)cases.get(i);
56       if(match(cs.getOf())){
57         return cs.getComponent();
58       }
59     }
60     return def==null?Components.value(null):def;
61   }
62
63 }
64
Popular Tags