KickJava   Java API By Example, From Geeks To Geeks.

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


1 package jfun.yan.xml.nuts.optional;
2
3
4 import java.util.HashMap JavaDoc;
5 import java.util.Iterator JavaDoc;
6
7
8 import jfun.util.Misc;
9 import jfun.yan.Binder;
10 import jfun.yan.Component;
11 import jfun.yan.Creator;
12 import jfun.yan.xml.NutsUtils;
13 import jfun.yan.xml.nuts.DelegatingNut;
14
15 /**
16  * This Nut class enables setting properties for a bean with
17  * property key-value map created dynamically, rather than through the
18  * <code>prop</code> sub-elements literally.
19  * <p>
20  * @author Ben Yu
21  * Nov 10, 2005 12:10:12 AM
22  */

23 public class WithPropertiesNut extends DelegatingNut {
24   private Component props;
25   
26   public Component getProps() {
27     checkMandatory("props", props);
28     return props;
29   }
30
31   public void setProps(Component props) {
32     this.props = props;
33   }
34
35   public Component eval(){
36     final Component p = getProps();
37     final Component cc = getMandatory();
38     Component result = p.bind(new Binder(){
39       public Creator bind(Object JavaDoc v) throws Throwable JavaDoc {
40         if(v==null) return cc;
41         if(v instanceof java.util.Map JavaDoc){
42           final java.util.Map JavaDoc m = (java.util.Map JavaDoc)v;
43           final int sz = m.size();
44           final HashMap JavaDoc cmap = new HashMap JavaDoc(sz);
45           for(Iterator JavaDoc it=m.keySet().iterator(); it.hasNext();){
46             final Object JavaDoc key = it.next();
47             cmap.put(key, NutsUtils.asComponent(m.get(key)));
48           }
49           return cc.withProperties(cmap);
50         }
51         else{
52           throw raise(Misc.getTypeName(v.getClass())+
53               " cannot be used as property map");
54         }
55       }
56     });
57     final Class JavaDoc type = cc.getType();
58     if(type!=null)
59       result = cast(type, result);
60     return result;
61   }
62
63 }
64
Popular Tags