KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jfun > yan > util > Utils


1 package jfun.yan.util;
2
3
4 import java.beans.IntrospectionException JavaDoc;
5 import java.io.FileNotFoundException JavaDoc;
6 import java.io.IOException JavaDoc;
7 import java.io.InputStream JavaDoc;
8 import java.lang.reflect.AccessibleObject JavaDoc;
9 import java.lang.reflect.InvocationTargetException JavaDoc;
10 import java.lang.reflect.Method JavaDoc;
11 import java.util.ArrayList JavaDoc;
12 import java.util.Arrays JavaDoc;
13 import java.util.Collection JavaDoc;
14 import java.util.HashMap JavaDoc;
15 import java.util.HashSet JavaDoc;
16 import java.util.Hashtable JavaDoc;
17 import java.util.Iterator JavaDoc;
18 import java.util.LinkedList JavaDoc;
19 import java.util.List JavaDoc;
20 import java.util.Map JavaDoc;
21 import java.util.Properties JavaDoc;
22 import java.util.Set JavaDoc;
23 import java.util.Vector JavaDoc;
24
25 import jfun.util.ArrayAsList;
26 import jfun.util.Misc;
27 import jfun.util.beans.BeanType;
28 import jfun.yan.Binder;
29 import jfun.yan.Component;
30 import jfun.yan.ComponentInstantiationException;
31 import jfun.yan.Components;
32 import jfun.yan.DefaultingException;
33 import jfun.yan.Dependency;
34 import jfun.yan.Functions;
35 import jfun.yan.Monad;
36 import jfun.yan.PropertyEntry;
37 import jfun.yan.YanException;
38 import jfun.yan.util.resource.ResourceLoader;
39
40
41 /**
42  * Common utility class that provides some utility functions.
43  * <p>
44  * @author Ben Yu
45  * Nov 14, 2005 9:57:35 PM
46  */

47 public class Utils {
48   /**
49    * Convert an array of parameter types to a string in the form of
50    * "(type1, type2, type3)". Array types are printed in the human readable form.
51    * @param param_types the parameter types.
52    * @return the string representation.
53    */

54   public static String JavaDoc toString(Class JavaDoc[] param_types){
55     if(param_types==null) return "()";
56     StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
57     buf.append('(');
58     for(int i=0; i<param_types.length; i++){
59       buf.append(Misc.getTypeName(param_types[i]));
60       if(i<param_types.length-1){
61         buf.append(", ");
62       }
63     }
64     buf.append(')');
65     return buf.toString();
66   }
67   /**
68    * To suppress access check against a reflection object.
69    * SecurityException is silently ignored.
70    * @param acc the reflection object.
71    */

72   static void forceAccess(AccessibleObject JavaDoc acc){
73     try{
74       acc.setAccessible(true);
75     }
76     catch(SecurityException JavaDoc e){}
77   }
78   /**
79    * Checkes to see if a component may return a value that's an instance
80    * of a type.
81    * @param type the type.
82    * @param c the component.
83    * @return true if the component may return a value that's an instance of the type.
84    */

85   public static boolean isCompatible(Class JavaDoc type, jfun.yan.Component c){
86     final Class JavaDoc ctype = c.getType();
87     if(ctype==null)
88       return true;
89     if(c.isConcrete()){
90       return ReflectionUtil.isAssignableFrom(type,ctype);
91     }
92     else{
93       return ReflectionUtil.isCompatible(type, ctype);
94     }
95   }
96   /**
97    * Create a java.util.Set instance.
98    * @param impltype the actual implementation class.
99    * If it is null or java.util.Set, java.util.HashSet is used.
100    * @param capacity the initial capacity.
101    * @return the Set instance.
102    * @throws IllegalAccessException when the constructor is not public.
103    * @throws InstantiationException when the constructor fails.
104    */

105   public static Set JavaDoc createSet(Class JavaDoc impltype, int capacity)
106   throws IllegalAccessException JavaDoc, InstantiationException JavaDoc{
107     if(impltype==null || HashSet JavaDoc.class.equals(impltype)
108         || Set JavaDoc.class.equals(impltype)){
109       return new HashSet JavaDoc(capacity);
110     }
111     else{
112       return (Set JavaDoc)createPreallocatedCollection(impltype);
113     }
114   }
115   /**
116    * Create a java.util.Map instance.
117    * @param impltype the actual implementation class.
118    * If it is null or java.util.Map, java.util.HashMap is used.
119    * @param capacity the initial capacity.
120    * @return the Map instance.
121    * @throws IllegalAccessException when the constructor is not public.
122    * @throws InstantiationException when the constructor fails.
123    */

124   public static Map JavaDoc createMap(Class JavaDoc impltype, int capacity)
125   throws IllegalAccessException JavaDoc, InstantiationException JavaDoc{
126     if(impltype==null || HashMap JavaDoc.class.equals(impltype)
127         || Map JavaDoc.class.equals(impltype)){
128       return new HashMap JavaDoc(capacity);
129     }
130     else if(Hashtable JavaDoc.class.equals(impltype)){
131       return new Hashtable JavaDoc(capacity);
132     }
133     else{
134       return (Map JavaDoc)createPreallocatedCollection(impltype);
135     }
136   }
137   /**
138    * Create a java.util.List instance.
139    * @param impltype the implementation class.
140    * If it is null or java.util.List, java.util.ArrayList is used.
141    * @param capacity the initial capacity.
142    * @return the List instance.
143    * @throws IllegalAccessException when the constructor is not public.
144    * @throws InstantiationException when the constructor fails.
145    */

146   public static List JavaDoc createList(Class JavaDoc impltype, int capacity)
147   throws IllegalAccessException JavaDoc, InstantiationException JavaDoc{
148     if(impltype==null || ArrayList JavaDoc.class.equals(impltype)
149         || List JavaDoc.class.equals(impltype) || Collection JavaDoc.class.equals(impltype)){
150       return new ArrayList JavaDoc(capacity);
151     }
152     else if(LinkedList JavaDoc.class.equals(impltype)){
153       return new LinkedList JavaDoc();
154     }
155     else if(Vector JavaDoc.class.equals(impltype)){
156       return new Vector JavaDoc(capacity);
157     }
158     return (List JavaDoc)Utils.createPreallocatedCollection(impltype);
159   }
160   /**
161    * To instantiate a collection instance.
162    * <p>
163    * The default constructor of the type is called.
164    * </p>
165    * @param type the type of the collection.
166    * @return the instance.
167    * @throws IllegalAccessException when the constructor is not public.
168    * @throws InstantiationException when the constructor fails.
169    */

170   public static Object JavaDoc createPreallocatedCollection(Class JavaDoc type)
171   throws IllegalAccessException JavaDoc, InstantiationException JavaDoc{
172     return type.newInstance();
173   }
174   
175   private static final class HelperMethods{
176     static final Method JavaDoc binder_bind =
177       ReflectionUtil.getMethod(Binder.class, "bind", new Class JavaDoc[]{Object JavaDoc.class},
178         false);
179   }
180   /**
181    * Convert a Binder object's bind() method to a Component that expects
182    * one parameter and instantiates the component instance by calling
183    * the return value of the bind() method.
184    * @param binder the Binder object.
185    * @return the Component.
186    */

187   public static Component asComponent(Binder binder){
188     return Components.fun(Functions.method(binder, HelperMethods.binder_bind))
189     .bind(Monad.instantiator());
190   }
191   
192   /**
193    * Use an array as a list.
194    * @param arr the array object.
195    * @return the List object.
196    */

197   public static List JavaDoc asList(Object JavaDoc arr){
198     if(arr instanceof Object JavaDoc[]){
199       return Arrays.asList((Object JavaDoc[])arr);
200     }
201     else{
202       return new ArrayAsList(arr);
203     }
204   }
205   /**
206    * Wrap an exception thrown when instantiating components.
207    * Error is thrown out directly without being wrapped.
208    * @param e the exception.
209    * @return the wrapped exception.
210    */

211   public static YanException wrapInstantiationException(Throwable JavaDoc e){
212     if(e instanceof Error JavaDoc)
213       throw (Error JavaDoc)e;
214     if(e instanceof YanException){
215       final YanException ye = (YanException)e;
216       return ye;
217     }
218     if(e instanceof InvocationTargetException JavaDoc){
219       final Throwable JavaDoc cause =
220         ((InvocationTargetException JavaDoc)e).getTargetException();
221       if(cause != e){
222         return wrapInstantiationException(cause);
223       }
224     }
225     final YanException ye = new ComponentInstantiationException(e);
226     return ye;
227   }
228   /**
229    * Inject a property value.
230    * @param btype the BeanType.
231    * @param obj the object to inject property into.
232    * @param name the property name.
233    * @param dep the dependency to resolve property value.
234    */

235   public static void injectProperty(BeanType btype, Object JavaDoc obj, String JavaDoc name,
236       Dependency dep){
237     final Class JavaDoc objtype = obj.getClass();
238     final Class JavaDoc atype = btype.getPropertySetterType(name);
239     if(atype!=null){
240       final Object JavaDoc v = dep.getProperty(objtype, name, atype);
241       try{
242         btype.setProperty(obj, name, v);
243       }
244       catch(Throwable JavaDoc e){
245         throw wrapInstantiationException(e);
246       }
247     }
248   }
249   /**
250    * Get the BeanType for a class.
251    * @param type the class.
252    * @return the BeanType object. Or null if the type is null.
253    */

254   public static BeanType toBeanType(Class JavaDoc type){
255     if(type==null) return null;
256     try{
257       return BeanType.instance(type);
258     }
259     catch(IntrospectionException JavaDoc e){
260       throw new ComponentInstantiationException(e);
261     }
262   }
263   /**
264    * Inject property values into a bean.
265    * @param btype the BeanType.
266    * @param obj the bean object.
267    * @param props the property names.
268    * @param dep the dependency object to resolve property values.
269    */

270   public static void injectProperties(BeanType btype, Object JavaDoc obj,
271       Set JavaDoc props, Dependency dep){
272     for(Iterator JavaDoc it=props.iterator(); it.hasNext();){
273       final String JavaDoc name = it.next().toString();
274       try{
275         jfun.yan.util.Utils.injectProperty(btype, obj, name, dep);
276       }
277       catch(DefaultingException e){
278         //when default value is used, this property is ignored.
279
continue;
280       }
281       catch(YanException e){
282         e.push(new PropertyEntry(btype.getType(), name));
283         throw e;
284       }
285     }
286   }
287   private static Class JavaDoc getArgumentType(BeanType btype, String JavaDoc name){
288     return btype.getPropertySetterType(name);
289   }
290   /**
291    * Verify that a set of properties can be resolved.
292    * @param btype the BeanType object.
293    * @param props the set of property names.
294    * @param dep the dependency.
295    */

296   public static void verifyProperties(BeanType btype, Set JavaDoc props, Dependency dep){
297     for(Iterator JavaDoc it=props.iterator(); it.hasNext();){
298       final String JavaDoc name = it.next().toString();
299       final Class JavaDoc atype = getArgumentType(btype, name);
300       if(atype!=null){
301         try{
302           dep.verifyProperty(btype.getType(), name, atype);
303         }
304         catch(DefaultingException e){
305           continue;
306         }
307         catch(YanException e){
308           e.push(new PropertyEntry(btype.getType(), name));
309           throw e;
310         }
311       }
312     }
313
314   }
315   /**
316    * Convert an array of objects to a Set. No duplicate is allowed.
317    * @param keys the array of objects.
318    * @param item_name the item name in the error message when duplicate is found.
319    * @return the Set object.
320    */

321   public static java.util.HashSet JavaDoc toSet(Object JavaDoc[] keys, String JavaDoc item_name){
322     final HashSet JavaDoc hset = new HashSet JavaDoc();
323     for(int i=0; i<keys.length; i++){
324       final Object JavaDoc name = keys[i];
325       if(hset.contains(name)){
326         throw new IllegalArgumentException JavaDoc("duplicate " + item_name
327             +": " + name);
328       }
329       hset.add(name);
330     }
331     return hset;
332   }
333   /**
334    * To read a property file from a class loader
335    * into a Properties object.
336    * @param loader the ResourceLoader used to load resource.
337    * @param resource the resource name.
338    * @return the Properties object.
339    * @throws IOException when loading fails.
340    */

341   public static Properties JavaDoc loadResourceProperties(ResourceLoader loader, String JavaDoc resource)
342   throws IOException JavaDoc{
343     final Properties JavaDoc props = new Properties JavaDoc();
344     final InputStream JavaDoc in = loader.getResourceAsStream(resource);
345     if(in==null){
346       throw new FileNotFoundException JavaDoc(resource);
347     }
348     try{
349       props.load(in);
350     }
351     finally{
352       try{
353         in.close();
354       }
355       catch(Exception JavaDoc e){}
356     }
357     return props;
358   }
359   /**
360    * Get the type name of an object.
361    * @param arg the object.
362    * @param nullname the default name if the object is null.
363    * @return the name.
364    */

365   public static String JavaDoc getObjTypeName(Object JavaDoc arg, String JavaDoc nullname){
366     return (arg==null)?nullname:Misc.getTypeName(arg.getClass());
367   }
368   /**
369    * Get the type of an object.
370    * @param arg the object.
371    * @param nulltype the default type if the object is null.
372    * @return the type.
373    */

374   public static Class JavaDoc getObjType(Object JavaDoc arg, Class JavaDoc nulltype){
375     if(arg==null) return nulltype;
376     else return arg.getClass();
377   }
378 }
379
Popular Tags