KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jfun > yan > xml > NutsUtils


1 package jfun.yan.xml;
2
3 import java.beans.IntrospectionException JavaDoc;
4 import java.beans.PropertyDescriptor JavaDoc;
5 import java.beans.PropertyEditor JavaDoc;
6 import java.beans.PropertyEditorManager JavaDoc;
7 import java.io.File JavaDoc;
8 import java.lang.reflect.Method JavaDoc;
9 import java.math.BigDecimal JavaDoc;
10 import java.math.BigInteger JavaDoc;
11 import java.net.MalformedURLException JavaDoc;
12 import java.net.URI JavaDoc;
13 import java.net.URISyntaxException JavaDoc;
14 import java.net.URL JavaDoc;
15 import java.net.URLClassLoader JavaDoc;
16 import java.text.DateFormat JavaDoc;
17 import java.text.ParseException JavaDoc;
18 import java.util.ArrayList JavaDoc;
19 import java.util.Date JavaDoc;
20 import java.util.HashMap JavaDoc;
21 import java.util.List JavaDoc;
22 import java.util.Locale JavaDoc;
23 import java.util.Map JavaDoc;
24 import java.util.StringTokenizer JavaDoc;
25 import java.util.TimeZone JavaDoc;
26
27 import jfun.util.DateUtil;
28 import jfun.util.Misc;
29 import jfun.util.beans.BeanType;
30 import jfun.util.os.PathTokenizer;
31 import jfun.yan.Binder;
32 import jfun.yan.Component;
33 import jfun.yan.Components;
34 import jfun.yan.Creator;
35 import jfun.yan.Monad;
36 import jfun.yan.Mutation;
37 import jfun.yan.util.ReflectionUtil;
38 import jfun.yan.util.Utils;
39 import jfun.yan.util.deserializer.Deserializer;
40
41 /**
42  * A common utility class for various Nuts helper functions.
43  * <p>
44  * @author Ben Yu
45  *
46  */

47 public class NutsUtils {
48
49   /**
50    * To split a string into an array of sub-strings.
51    * @param str the string to split.
52    * @param sep the separator characters.
53    * @return an array of sub-strings who are seperated by
54    * one or many of the characters in the sep string.
55    */

56   public static String JavaDoc[] split(String JavaDoc str, String JavaDoc sep){
57     final StringTokenizer JavaDoc tok = new StringTokenizer JavaDoc(str, sep);
58     final ArrayList JavaDoc buf = new ArrayList JavaDoc();
59     while(tok.hasMoreTokens()){
60       buf.add(tok.nextToken().trim());
61     }
62     final String JavaDoc[] result = new String JavaDoc[buf.size()];
63     buf.toArray(result);
64     return result;
65   }
66   private static final HashMap JavaDoc booleans = getBooleanMap();
67   private static HashMap JavaDoc getBooleanMap(){
68     final HashMap JavaDoc r = new HashMap JavaDoc();
69     r.put("on", Boolean.valueOf(true));
70     r.put("yes", Boolean.valueOf(true));
71     r.put("true", Boolean.valueOf(true));
72     r.put("off", Boolean.valueOf(false));
73     r.put("no", Boolean.valueOf(false));
74     r.put("false", Boolean.valueOf(false));
75     return r;
76   }
77   /**
78    * To convert a string literal to boolean.
79    * @param str the string literal
80    * @return Boolean object. null if the string is not recognized.
81    */

82   public static Boolean JavaDoc toBoolean(String JavaDoc str){
83     return (Boolean JavaDoc)booleans.get(str);
84   }
85   /**
86    * Convert a string to a File. if the string represents
87    * a relative path, it is treated as relative to the basedir.
88    * @param basedir the base directory.
89    * @param path the string.
90    * @return the File object.
91    */

92   public static File JavaDoc toFile(File JavaDoc basedir, String JavaDoc path){
93     final File JavaDoc f = new File JavaDoc(path);
94     if(f.isAbsolute() || f.getPath().startsWith("/")){
95       return f;
96     }
97     else{
98       return new File JavaDoc(basedir, path);
99     }
100   }
101   /**
102    * Convert a string to a URL. if the string represents
103    * a relative path, it is treated as relative to the basedir.
104    * @param basedir the base directory.
105    * @param str the string.
106    * @return the URL object.
107    * @throws MalformedURLException if the string represents neither a file nor a URL.
108    */

109   public static URL JavaDoc toUrl(File JavaDoc basedir, String JavaDoc str)
110   throws MalformedURLException JavaDoc{
111     try{
112       return new URL JavaDoc(str);
113     }
114     catch(MalformedURLException JavaDoc e){
115       return toFile(basedir, str).toURL();
116     }
117   }
118   /**
119    * To convert a string literal to a URI object.
120    * @param str the string literal.
121    * @return the URI object.
122    * @throws URISyntaxException if the uri syntax is wrong.
123    */

124   public static URI JavaDoc toUri(String JavaDoc str)
125   throws URISyntaxException JavaDoc{
126     return new URI JavaDoc(str);
127   }
128   private static void populate(Map JavaDoc m, Class JavaDoc t, Deserializer des){
129     m.put(t, des);
130     m.put(ReflectionUtil.toObjectType(t), des);
131   }
132
133
134   //private static HashMap deserializers = getDeserializers();
135

136   static HashMap JavaDoc getDeserializers(){
137     final HashMap JavaDoc hmap = new HashMap JavaDoc();
138     populate(hmap, boolean.class, new Deserializer(){
139       public Object JavaDoc deserialize(String JavaDoc str){
140         return toBoolean(str);
141       }
142     });
143     populate(hmap, char.class, new Deserializer(){
144       public Object JavaDoc deserialize(String JavaDoc str){
145         if(str.length()!=1){
146           throw new IllegalArgumentException JavaDoc("cannot convert string to character");
147         }
148         return new Character JavaDoc(str.charAt(0));
149       }
150     });
151     populate(hmap, byte.class, new Deserializer(){
152       public Object JavaDoc deserialize(String JavaDoc str){
153         return Byte.valueOf(str);
154       }
155     });
156     populate(hmap, short.class, new Deserializer(){
157       public Object JavaDoc deserialize(String JavaDoc str){
158         return Short.valueOf(str);
159       }
160     });
161     final Deserializer int_des = new Deserializer(){
162       public Object JavaDoc deserialize(String JavaDoc str){
163         return Integer.valueOf(str);
164       }
165     };
166     populate(hmap, int.class, int_des);
167     populate(hmap, Number JavaDoc.class, int_des);
168     populate(hmap, long.class, new Deserializer(){
169       public Object JavaDoc deserialize(String JavaDoc str){
170         return Long.valueOf(str);
171       }
172     });
173     populate(hmap, float.class, new Deserializer(){
174       public Object JavaDoc deserialize(String JavaDoc str){
175         return Float.valueOf(str);
176       }
177     });
178     populate(hmap, double.class, new Deserializer(){
179       public Object JavaDoc deserialize(String JavaDoc str){
180         return Double.valueOf(str);
181       }
182     });
183     populate(hmap, BigInteger JavaDoc.class, new Deserializer(){
184       public Object JavaDoc deserialize(String JavaDoc str){
185         return new BigInteger JavaDoc(str);
186       }
187     });
188     populate(hmap, BigDecimal JavaDoc.class, new Deserializer(){
189       public Object JavaDoc deserialize(String JavaDoc str){
190         return new BigDecimal JavaDoc(str);
191       }
192     });
193     final Deserializer component_des = new Deserializer(){
194       public Object JavaDoc deserialize(String JavaDoc str){
195         return asComponent(str);
196       }
197     };
198     populate(hmap, Creator.class, component_des);
199     populate(hmap, Component.class, component_des);
200     populate(hmap, URL JavaDoc.class, new Deserializer(){
201       public Object JavaDoc deserialize(String JavaDoc str)
202       throws MalformedURLException JavaDoc{
203         return new URL JavaDoc(str);
204       }
205     });
206     populate(hmap, URI JavaDoc.class, new Deserializer(){
207       public Object JavaDoc deserialize(String JavaDoc str)
208       throws URISyntaxException JavaDoc{
209         return toUri(str);
210       }
211     });
212     populate(hmap, Date JavaDoc.class, new Deserializer(){
213       public Object JavaDoc deserialize(String JavaDoc str)
214       throws ParseException JavaDoc{
215         return DateFormat.getInstance().parseObject(str);
216       }
217     });
218     populate(hmap, Locale JavaDoc.class, new Deserializer(){
219       public Object JavaDoc deserialize(String JavaDoc str){
220         return DateUtil.parseLocale(str);
221       }
222     });
223     populate(hmap, TimeZone JavaDoc.class, new Deserializer(){
224       public Object JavaDoc deserialize(String JavaDoc str){
225         return TimeZone.getTimeZone(str);
226       }
227     });
228     populate(hmap, Class JavaDoc.class, new Deserializer(){
229       public Object JavaDoc deserialize(String JavaDoc str)
230       throws ClassNotFoundException JavaDoc{
231         return Class.forName(str);
232       }
233     });
234     populate(hmap, File JavaDoc.class, new Deserializer(){
235       public Object JavaDoc deserialize(String JavaDoc str){
236         return new File JavaDoc(str);
237       }
238     });
239     return hmap;
240   }
241   /**
242    * Convert a string to an array of URL. The
243    * string contains a series of sub-string seperated by whitespaces
244    * or "," or ";"
245    * @param basedir the base directory to resolve relative path.
246    * @param str the string.
247    * @return the array of URL
248    * @throws MalformedURLException if any sub-string is not convertible to URL.
249    */

250   public static URL JavaDoc[] toUrls(File JavaDoc basedir, String JavaDoc str)
251   throws MalformedURLException JavaDoc{
252     final List JavaDoc result = new ArrayList JavaDoc();
253     PathTokenizer tok = new PathTokenizer(str);
254     while (tok.hasMoreTokens()) {
255       final String JavaDoc element = tok.nextToken();
256       result.add(toUrl(basedir, element));
257     }
258     final URL JavaDoc[] ret = new URL JavaDoc[result.size()];
259     result.toArray(ret);
260     return ret;
261   }
262   private static boolean isIdentifierStart(char c){
263     return c=='/' || c!='$' && Character.isJavaIdentifierStart(c);
264   }
265   private static boolean isIdentifierPart(char c){
266     return c=='_' || c=='.' || c==' ' || c=='-' || c=='/' ||
267     Character.isLetter(c)||Character.isDigit(c);
268   }
269   /**
270    * To determine if a string is a valid id in yan xml config file.
271    * @param str the string.
272    * @return true if valid.
273    */

274   public static boolean isValidId(String JavaDoc str){
275     final int len = str.length();
276     if(str==null || len==0) return false;
277     if(!isIdentifierStart(str.charAt(0)))
278       return false;
279     int i=1;
280     for(; i<len; i++){
281       final char c = str.charAt(i);
282       if(c=='\'')break;
283       if(!isIdentifierPart(c))
284         return false;
285     }
286     for(++i;i<len;i++){
287       final char c = str.charAt(i);
288       if(c!='\''){
289         return false;
290       }
291     }
292     return true;
293   }
294   
295   static String JavaDoc getTypeName(Object JavaDoc v){
296     if(v==null) return null;
297     else return Misc.getTypeName(v.getClass());
298   }
299   /**
300    * Call a NutsFunction object with an array of arguments.
301    * @param nfun the NutsFunction object.
302    * @param args the arguments.
303    * @return the result.
304    */

305   public static Object JavaDoc callFunction(NutsFunction nfun, Object JavaDoc[] args) {
306     final int params = nfun.getParameterCount();
307     if(params!=args.length){
308       throw new IllegalArgumentException JavaDoc(""+params+" parameter expected by function "+nfun.getName()
309           + ", while "+args.length+" arguments provided.");
310     }
311     return nfun.call(args);
312   }
313   /**
314    * Call a NutsFunction object with a map of parameter name to argument value.
315    * @param nfun the function.
316    * @param arg_map the map of the argument values.
317    * @return the result.
318    */

319   public static Object JavaDoc callFunction(NutsFunction nfun,
320       final Map JavaDoc arg_map){
321     final String JavaDoc[] params = nfun.getParameterNames();
322     if(params.length!=arg_map.size()){
323       throw new IllegalArgumentException JavaDoc(""+params.length
324           +" parameter expected by function "+nfun.getName()
325           + ", while "+arg_map.size()+" arguments provided.");
326     }
327     final Object JavaDoc[] args = new Object JavaDoc[params.length];
328     for(int i=0; i<params.length; i++){
329       final String JavaDoc name = params[i];
330       if(!arg_map.containsKey(name)){
331         throw new IllegalArgumentException JavaDoc("missing parameter "
332             + name + " for function "+nfun.getName());
333       }
334       args[i] = arg_map.get(name);
335     }
336     return nfun.call(args);
337   }
338   /**
339    * Convert an object to Component.
340    * Conversion is automatically done if necessary.
341    * @param val the value to be converted to Component.
342    * @return the Component.
343    */

344   public static Component asComponent(Object JavaDoc val){
345     if(val==null) return Components.value(null);
346     else if(val instanceof Creator)
347       return Components.adapt((Creator)val);
348     else if(val instanceof NutsFunction){
349       return Components.fun(new NutsFunction2Function((NutsFunction)val))
350         .bind(Monad.instantiator());
351     }
352     else if(val instanceof Binder){
353       return Utils.asComponent((Binder)val);
354     }
355     else{
356       return Components.value(val);
357     }
358   }
359   /**
360    * Canonicalize an attribute name by replacing "-" with "_".
361    * @param name the attribute name.
362    * @return the new attribute name, or null if the attribute name is null.
363    */

364   public static String JavaDoc canonicalizeAttributeName(String JavaDoc name){
365     if(name==null) return name;
366     return name.replace('-', '_');
367   }
368   /**
369    * To get a ClassLoader object that uses a base ClassLoader object
370    * as parent and alternatively searches a classpath if the class
371    * or resource is not found in parent.
372    * @param baseloader the base class loader.
373    * @param classpath the alternative classpath.
374    * @param basedir the base directory used in the classpath.
375    * @return the ClassLoader object.
376    * @throws MalformedURLException if the classpath is invalid.
377    */

378   public static ClassLoader JavaDoc getClassLoader(ClassLoader JavaDoc baseloader,
379       String JavaDoc classpath, File JavaDoc basedir)
380   throws MalformedURLException JavaDoc{
381     if(classpath != null){
382       return new URLClassLoader JavaDoc(
383           NutsUtils.toUrls(basedir, classpath)
384           , baseloader);
385     }
386     else return baseloader;
387   }
388   
389   /**
390    * Add named state to a Component object.
391    * @param c the Component object.
392    * @param key the key of the state.
393    * @param val the value of the state.
394    * @return the new Component object with this state.
395    */

396   public static Component setState(Component c, Object JavaDoc key, Object JavaDoc val){
397     java.util.Map JavaDoc carrier = (java.util.Map JavaDoc)c.getState();
398     if(carrier==null){
399       //to save space, we don't leave a lot of empty space in the map.
400
carrier = new HashMap JavaDoc(4);
401       c = c.withState(carrier);
402     }
403     carrier.put(key, val);
404     return c;
405   }
406   /**
407    * Get a state value by name.
408    * @param c the Component object to get state from.
409    * @param key the state key.
410    * @return the state value.
411    */

412   public static Object JavaDoc getState(Component c, Object JavaDoc key){
413     final java.util.Map JavaDoc carrier = (java.util.Map JavaDoc)c.getState();
414     if(carrier==null) return null;
415     else return carrier.get(key);
416   }
417   
418   /**
419    * If a property of the component type exists and the property type is
420    * compatible with the property value, the property is set when
421    * the component is instantiated.
422    * @param c the component.
423    * @param name the property name.
424    * @param val the property value.
425    * @return the result Component.
426    * @throws IntrospectionException
427    */

428   public static Component setPossiblePropertyValue(Component c, String JavaDoc name, Object JavaDoc val)
429   throws IntrospectionException JavaDoc{
430     final Method JavaDoc mtd = getPossiblePropertySetter(c, name);
431     if(mtd==null) return c;
432     final Class JavaDoc[] param_types = mtd.getParameterTypes();
433     if(param_types.length!=1){
434       return c;
435     }
436     final Class JavaDoc param_type = param_types[0];
437     if(ReflectionUtil.isInstance(param_type, val)){
438       final Object JavaDoc[] args = {val};
439       return c.mutate(new Mutation(){
440         public void mutate(Object JavaDoc obj)
441         throws Exception JavaDoc{
442           mtd.invoke(obj, args);
443         }
444       });
445     }
446     return c;
447   }
448   public static Component setPossibleProperty(Component c, String JavaDoc name,
449       final Component valc)
450   throws IntrospectionException JavaDoc{
451     final Method JavaDoc mtd = getPossiblePropertySetter(c, name);
452     if(mtd==null) return c;
453     final Class JavaDoc[] param_types = mtd.getParameterTypes();
454     if(param_types.length!=1){
455       return c;
456     }
457     final Class JavaDoc param_type = param_types[0];
458     final Class JavaDoc argtype = valc.getType();
459     if(argtype!=null && !ReflectionUtil.isAssignableFrom(param_type, argtype)){
460       return c;
461     }
462     return c.followedBy(new Binder(){
463       public Creator bind(final Object JavaDoc obj){
464         return valc.mutate(new Mutation(){
465           public void mutate(Object JavaDoc arg) throws Exception JavaDoc {
466             if(ReflectionUtil.isInstance(param_type, arg)){
467               mtd.invoke(obj, new Object JavaDoc[]{arg});
468             }
469           }
470         });
471       }
472     });
473   }
474   private static Method JavaDoc getPossiblePropertySetter(Component c, String JavaDoc name)
475   throws IntrospectionException JavaDoc{
476     if(name==null||name.length()==0) return null;
477     final Class JavaDoc type = c.getType();
478     if(type==null){
479       //unknown type, do not set property.
480
return null;
481     }
482     final BeanType beantype = BeanType.instance(type);
483     final PropertyDescriptor JavaDoc prop = beantype.getPropertyDescriptor(name);
484     if(prop == null) return null;
485     final Method JavaDoc mtd = prop.getWriteMethod();
486     return mtd;
487   }
488 }
489
Popular Tags