package jfun.yan.xml.nuts.optional;
import java.util.HashMap;
import java.util.Iterator;
import jfun.util.Misc;
import jfun.yan.Binder;
import jfun.yan.Component;
import jfun.yan.Creator;
import jfun.yan.xml.NutsUtils;
import jfun.yan.xml.nuts.DelegatingNut;
/**
* This Nut class enables setting properties for a bean with
* property key-value map created dynamically, rather than through the
* <code>prop</code> sub-elements literally.
* <p>
* @author Ben Yu
* Nov 10, 2005 12:10:12 AM
*/
public class WithPropertiesNut extends DelegatingNut {
private Component props;
public Component getProps() {
checkMandatory("props", props);
return props;
}
public void setProps(Component props) {
this.props = props;
}
public Component eval(){
final Component p = getProps();
final Component cc = getMandatory();
Component result = p.bind(new Binder(){
public Creator bind(Object v) throws Throwable {
if(v==null) return cc;
if(v instanceof java.util.Map){
final java.util.Map m = (java.util.Map)v;
final int sz = m.size();
final HashMap cmap = new HashMap(sz);
for(Iterator it=m.keySet().iterator(); it.hasNext();){
final Object key = it.next();
cmap.put(key, NutsUtils.asComponent(m.get(key)));
}
return cc.withProperties(cmap);
}
else{
throw raise(Misc.getTypeName(v.getClass())+
" cannot be used as property map");
}
}
});
final Class type = cc.getType();
if(type!=null)
result = cast(type, result);
return result;
}
}