KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > tomcat > util > IntrospectionUtils


1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements. See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License. You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */

17
18 package org.apache.tomcat.util;
19
20 import java.io.File JavaDoc;
21 import java.io.FilenameFilter JavaDoc;
22 import java.io.IOException JavaDoc;
23 import java.lang.reflect.InvocationTargetException JavaDoc;
24 import java.lang.reflect.Method JavaDoc;
25 import java.net.InetAddress JavaDoc;
26 import java.net.MalformedURLException JavaDoc;
27 import java.net.URL JavaDoc;
28 import java.net.UnknownHostException JavaDoc;
29 import java.util.Hashtable JavaDoc;
30 import java.util.StringTokenizer JavaDoc;
31 import java.util.Vector JavaDoc;
32
33 // Depends: JDK1.1
34

35 /**
36  * Utils for introspection and reflection
37  */

38 public final class IntrospectionUtils {
39
40     
41     private static org.apache.commons.logging.Log log=
42         org.apache.commons.logging.LogFactory.getLog( IntrospectionUtils.class );
43     
44     /**
45      * Call execute() - any ant-like task should work
46      */

47     public static void execute(Object JavaDoc proxy, String JavaDoc method) throws Exception JavaDoc {
48         Method JavaDoc executeM = null;
49         Class JavaDoc c = proxy.getClass();
50         Class JavaDoc params[] = new Class JavaDoc[0];
51         // params[0]=args.getClass();
52
executeM = findMethod(c, method, params);
53         if (executeM == null) {
54             throw new RuntimeException JavaDoc("No execute in " + proxy.getClass());
55         }
56         executeM.invoke(proxy, (Object JavaDoc[]) null);//new Object[] { args });
57
}
58
59     /**
60      * Call void setAttribute( String ,Object )
61      */

62     public static void setAttribute(Object JavaDoc proxy, String JavaDoc n, Object JavaDoc v)
63             throws Exception JavaDoc {
64         if (proxy instanceof AttributeHolder) {
65             ((AttributeHolder) proxy).setAttribute(n, v);
66             return;
67         }
68
69         Method JavaDoc executeM = null;
70         Class JavaDoc c = proxy.getClass();
71         Class JavaDoc params[] = new Class JavaDoc[2];
72         params[0] = String JavaDoc.class;
73         params[1] = Object JavaDoc.class;
74         executeM = findMethod(c, "setAttribute", params);
75         if (executeM == null) {
76             if (log.isDebugEnabled())
77                 log.debug("No setAttribute in " + proxy.getClass());
78             return;
79         }
80         if (false)
81             if (log.isDebugEnabled())
82                 log.debug("Setting " + n + "=" + v + " in " + proxy);
83         executeM.invoke(proxy, new Object JavaDoc[] { n, v });
84         return;
85     }
86
87     /**
88      * Call void getAttribute( String )
89      */

90     public static Object JavaDoc getAttribute(Object JavaDoc proxy, String JavaDoc n) throws Exception JavaDoc {
91         Method JavaDoc executeM = null;
92         Class JavaDoc c = proxy.getClass();
93         Class JavaDoc params[] = new Class JavaDoc[1];
94         params[0] = String JavaDoc.class;
95         executeM = findMethod(c, "getAttribute", params);
96         if (executeM == null) {
97             if (log.isDebugEnabled())
98                 log.debug("No getAttribute in " + proxy.getClass());
99             return null;
100         }
101         return executeM.invoke(proxy, new Object JavaDoc[] { n });
102     }
103
104     /**
105      * Construct a URLClassLoader. Will compile and work in JDK1.1 too.
106      */

107     public static ClassLoader JavaDoc getURLClassLoader(URL JavaDoc urls[], ClassLoader JavaDoc parent) {
108         try {
109             Class JavaDoc urlCL = Class.forName("java.net.URLClassLoader");
110             Class JavaDoc paramT[] = new Class JavaDoc[2];
111             paramT[0] = urls.getClass();
112             paramT[1] = ClassLoader JavaDoc.class;
113             Method JavaDoc m = findMethod(urlCL, "newInstance", paramT);
114             if (m == null)
115                 return null;
116
117             ClassLoader JavaDoc cl = (ClassLoader JavaDoc) m.invoke(urlCL, new Object JavaDoc[] { urls,
118                     parent });
119             return cl;
120         } catch (ClassNotFoundException JavaDoc ex) {
121             // jdk1.1
122
return null;
123         } catch (Exception JavaDoc ex) {
124             ex.printStackTrace();
125             return null;
126         }
127     }
128
129     public static String JavaDoc guessInstall(String JavaDoc installSysProp,
130             String JavaDoc homeSysProp, String JavaDoc jarName) {
131         return guessInstall(installSysProp, homeSysProp, jarName, null);
132     }
133
134     /**
135      * Guess a product install/home by analyzing the class path. It works for
136      * product using the pattern: lib/executable.jar or if executable.jar is
137      * included in classpath by a shell script. ( java -jar also works )
138      *
139      * Insures both "install" and "home" System properties are set. If either or
140      * both System properties are unset, "install" and "home" will be set to the
141      * same value. This value will be the other System property that is set, or
142      * the guessed value if neither is set.
143      */

144     public static String JavaDoc guessInstall(String JavaDoc installSysProp,
145             String JavaDoc homeSysProp, String JavaDoc jarName, String JavaDoc classFile) {
146         String JavaDoc install = null;
147         String JavaDoc home = null;
148
149         if (installSysProp != null)
150             install = System.getProperty(installSysProp);
151
152         if (homeSysProp != null)
153             home = System.getProperty(homeSysProp);
154
155         if (install != null) {
156             if (home == null)
157                 System.getProperties().put(homeSysProp, install);
158             return install;
159         }
160
161         // Find the directory where jarName.jar is located
162

163         String JavaDoc cpath = System.getProperty("java.class.path");
164         String JavaDoc pathSep = System.getProperty("path.separator");
165         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(cpath, pathSep);
166         while (st.hasMoreTokens()) {
167             String JavaDoc path = st.nextToken();
168             // log( "path " + path );
169
if (path.endsWith(jarName)) {
170                 home = path.substring(0, path.length() - jarName.length());
171                 try {
172                     if ("".equals(home)) {
173                         home = new File JavaDoc("./").getCanonicalPath();
174                     } else if (home.endsWith(File.separator)) {
175                         home = home.substring(0, home.length() - 1);
176                     }
177                     File JavaDoc f = new File JavaDoc(home);
178                     String JavaDoc parentDir = f.getParent();
179                     if (parentDir == null)
180                         parentDir = home; // unix style
181
File JavaDoc f1 = new File JavaDoc(parentDir);
182                     install = f1.getCanonicalPath();
183                     if (installSysProp != null)
184                         System.getProperties().put(installSysProp, install);
185                     if (home == null && homeSysProp != null)
186                         System.getProperties().put(homeSysProp, install);
187                     return install;
188                 } catch (Exception JavaDoc ex) {
189                     ex.printStackTrace();
190                 }
191             } else {
192                 String JavaDoc fname = path + (path.endsWith("/") ? "" : "/")
193                         + classFile;
194                 if (new File JavaDoc(fname).exists()) {
195                     try {
196                         File JavaDoc f = new File JavaDoc(path);
197                         String JavaDoc parentDir = f.getParent();
198                         if (parentDir == null)
199                             parentDir = path; // unix style
200
File JavaDoc f1 = new File JavaDoc(parentDir);
201                         install = f1.getCanonicalPath();
202                         if (installSysProp != null)
203                             System.getProperties().put(installSysProp, install);
204                         if (home == null && homeSysProp != null)
205                             System.getProperties().put(homeSysProp, install);
206                         return install;
207                     } catch (Exception JavaDoc ex) {
208                         ex.printStackTrace();
209                     }
210                 }
211             }
212         }
213
214         // if install directory can't be found, use home as the default
215
if (home != null) {
216             System.getProperties().put(installSysProp, home);
217             return home;
218         }
219
220         return null;
221     }
222
223     /**
224      * Debug method, display the classpath
225      */

226     public static void displayClassPath(String JavaDoc msg, URL JavaDoc[] cp) {
227         if (log.isDebugEnabled()) {
228             log.debug(msg);
229             for (int i = 0; i < cp.length; i++) {
230                 log.debug(cp[i].getFile());
231             }
232         }
233     }
234
235     public static String JavaDoc PATH_SEPARATOR = System.getProperty("path.separator");
236
237     /**
238      * Adds classpath entries from a vector of URL's to the "tc_path_add" System
239      * property. This System property lists the classpath entries common to web
240      * applications. This System property is currently used by Jasper when its
241      * JSP servlet compiles the Java file for a JSP.
242      */

243     public static String JavaDoc classPathAdd(URL JavaDoc urls[], String JavaDoc cp) {
244         if (urls == null)
245             return cp;
246
247         for (int i = 0; i < urls.length; i++) {
248             if (cp != null)
249                 cp += PATH_SEPARATOR + urls[i].getFile();
250             else
251                 cp = urls[i].getFile();
252         }
253         return cp;
254     }
255
256     /**
257      * Find a method with the right name If found, call the method ( if param is
258      * int or boolean we'll convert value to the right type before) - that means
259      * you can have setDebug(1).
260      */

261     public static void setProperty(Object JavaDoc o, String JavaDoc name, String JavaDoc value) {
262         if (dbg > 1)
263             d("setProperty(" + o.getClass() + " " + name + "=" + value + ")");
264
265         String JavaDoc setter = "set" + capitalize(name);
266
267         try {
268             Method JavaDoc methods[] = findMethods(o.getClass());
269             Method JavaDoc setPropertyMethod = null;
270
271             // First, the ideal case - a setFoo( String ) method
272
for (int i = 0; i < methods.length; i++) {
273                 Class JavaDoc paramT[] = methods[i].getParameterTypes();
274                 if (setter.equals(methods[i].getName()) && paramT.length == 1
275                         && "java.lang.String".equals(paramT[0].getName())) {
276
277                     methods[i].invoke(o, new Object JavaDoc[] { value });
278                     return;
279                 }
280             }
281
282             // Try a setFoo ( int ) or ( boolean )
283
for (int i = 0; i < methods.length; i++) {
284                 boolean ok = true;
285                 if (setter.equals(methods[i].getName())
286                         && methods[i].getParameterTypes().length == 1) {
287
288                     // match - find the type and invoke it
289
Class JavaDoc paramType = methods[i].getParameterTypes()[0];
290                     Object JavaDoc params[] = new Object JavaDoc[1];
291
292                     // Try a setFoo ( int )
293
if ("java.lang.Integer".equals(paramType.getName())
294                             || "int".equals(paramType.getName())) {
295                         try {
296                             params[0] = new Integer JavaDoc(value);
297                         } catch (NumberFormatException JavaDoc ex) {
298                             ok = false;
299                         }
300                     // Try a setFoo ( long )
301
}else if ("java.lang.Long".equals(paramType.getName())
302                                 || "long".equals(paramType.getName())) {
303                             try {
304                                 params[0] = new Long JavaDoc(value);
305                             } catch (NumberFormatException JavaDoc ex) {
306                                 ok = false;
307                             }
308
309                         // Try a setFoo ( boolean )
310
} else if ("java.lang.Boolean".equals(paramType.getName())
311                             || "boolean".equals(paramType.getName())) {
312                         params[0] = new Boolean JavaDoc(value);
313
314                         // Try a setFoo ( InetAddress )
315
} else if ("java.net.InetAddress".equals(paramType
316                             .getName())) {
317                         try {
318                             params[0] = InetAddress.getByName(value);
319                         } catch (UnknownHostException JavaDoc exc) {
320                             d("Unable to resolve host name:" + value);
321                             ok = false;
322                         }
323
324                         // Unknown type
325
} else {
326                         d("Unknown type " + paramType.getName());
327                     }
328
329                     if (ok) {
330                         methods[i].invoke(o, params);
331                         return;
332                     }
333                 }
334
335                 // save "setProperty" for later
336
if ("setProperty".equals(methods[i].getName())) {
337                     setPropertyMethod = methods[i];
338                 }
339             }
340
341             // Ok, no setXXX found, try a setProperty("name", "value")
342
if (setPropertyMethod != null) {
343                 Object JavaDoc params[] = new Object JavaDoc[2];
344                 params[0] = name;
345                 params[1] = value;
346                 setPropertyMethod.invoke(o, params);
347             }
348
349         } catch (IllegalArgumentException JavaDoc ex2) {
350             log.warn("IAE " + o + " " + name + " " + value, ex2);
351         } catch (SecurityException JavaDoc ex1) {
352             if (dbg > 0)
353                 d("SecurityException for " + o.getClass() + " " + name + "="
354                         + value + ")");
355             if (dbg > 1)
356                 ex1.printStackTrace();
357         } catch (IllegalAccessException JavaDoc iae) {
358             if (dbg > 0)
359                 d("IllegalAccessException for " + o.getClass() + " " + name
360                         + "=" + value + ")");
361             if (dbg > 1)
362                 iae.printStackTrace();
363         } catch (InvocationTargetException JavaDoc ie) {
364             if (dbg > 0)
365                 d("InvocationTargetException for " + o.getClass() + " " + name
366                         + "=" + value + ")");
367             if (dbg > 1)
368                 ie.printStackTrace();
369         }
370     }
371
372     public static Object JavaDoc getProperty(Object JavaDoc o, String JavaDoc name) {
373         String JavaDoc getter = "get" + capitalize(name);
374         String JavaDoc isGetter = "is" + capitalize(name);
375
376         try {
377             Method JavaDoc methods[] = findMethods(o.getClass());
378             Method JavaDoc getPropertyMethod = null;
379
380             // First, the ideal case - a getFoo() method
381
for (int i = 0; i < methods.length; i++) {
382                 Class JavaDoc paramT[] = methods[i].getParameterTypes();
383                 if (getter.equals(methods[i].getName()) && paramT.length == 0) {
384                     return methods[i].invoke(o, (Object JavaDoc[]) null);
385                 }
386                 if (isGetter.equals(methods[i].getName()) && paramT.length == 0) {
387                     return methods[i].invoke(o, (Object JavaDoc[]) null);
388                 }
389
390                 if ("getProperty".equals(methods[i].getName())) {
391                     getPropertyMethod = methods[i];
392                 }
393             }
394
395             // Ok, no setXXX found, try a getProperty("name")
396
if (getPropertyMethod != null) {
397                 Object JavaDoc params[] = new Object JavaDoc[1];
398                 params[0] = name;
399                 return getPropertyMethod.invoke(o, params);
400             }
401
402         } catch (IllegalArgumentException JavaDoc ex2) {
403             log.warn("IAE " + o + " " + name, ex2);
404         } catch (SecurityException JavaDoc ex1) {
405             if (dbg > 0)
406                 d("SecurityException for " + o.getClass() + " " + name + ")");
407             if (dbg > 1)
408                 ex1.printStackTrace();
409         } catch (IllegalAccessException JavaDoc iae) {
410             if (dbg > 0)
411                 d("IllegalAccessException for " + o.getClass() + " " + name
412                         + ")");
413             if (dbg > 1)
414                 iae.printStackTrace();
415         } catch (InvocationTargetException JavaDoc ie) {
416             if (dbg > 0)
417                 d("InvocationTargetException for " + o.getClass() + " " + name
418                         + ")");
419             if (dbg > 1)
420                 ie.printStackTrace();
421         }
422         return null;
423     }
424
425     /**
426      */

427     public static void setProperty(Object JavaDoc o, String JavaDoc name) {
428         String JavaDoc setter = "set" + capitalize(name);
429         try {
430             Method JavaDoc methods[] = findMethods(o.getClass());
431             Method JavaDoc setPropertyMethod = null;
432             // find setFoo() method
433
for (int i = 0; i < methods.length; i++) {
434                 Class JavaDoc paramT[] = methods[i].getParameterTypes();
435                 if (setter.equals(methods[i].getName()) && paramT.length == 0) {
436                     methods[i].invoke(o, new Object JavaDoc[] {});
437                     return;
438                 }
439             }
440         } catch (Exception JavaDoc ex1) {
441             if (dbg > 0)
442                 d("Exception for " + o.getClass() + " " + name);
443             if (dbg > 1)
444                 ex1.printStackTrace();
445         }
446     }
447
448     /**
449      * Replace ${NAME} with the property value
450      *
451      * @deprecated Use the explicit method
452      */

453     public static String JavaDoc replaceProperties(String JavaDoc value, Object JavaDoc getter) {
454         if (getter instanceof Hashtable JavaDoc)
455             return replaceProperties(value, (Hashtable JavaDoc) getter, null);
456
457         if (getter instanceof PropertySource) {
458             PropertySource src[] = new PropertySource[] { (PropertySource) getter };
459             return replaceProperties(value, null, src);
460         }
461         return value;
462     }
463
464     /**
465      * Replace ${NAME} with the property value
466      */

467     public static String JavaDoc replaceProperties(String JavaDoc value, Hashtable JavaDoc staticProp,
468             PropertySource dynamicProp[]) {
469         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
470         int prev = 0;
471         // assert value!=nil
472
int pos;
473         while ((pos = value.indexOf("$", prev)) >= 0) {
474             if (pos > 0) {
475                 sb.append(value.substring(prev, pos));
476             }
477             if (pos == (value.length() - 1)) {
478                 sb.append('$');
479                 prev = pos + 1;
480             } else if (value.charAt(pos + 1) != '{') {
481                 sb.append('$');
482                 prev = pos + 1; // XXX
483
} else {
484                 int endName = value.indexOf('}', pos);
485                 if (endName < 0) {
486                     sb.append(value.substring(pos));
487                     prev = value.length();
488                     continue;
489                 }
490                 String JavaDoc n = value.substring(pos + 2, endName);
491                 String JavaDoc v = null;
492                 if (staticProp != null) {
493                     v = (String JavaDoc) ((Hashtable JavaDoc) staticProp).get(n);
494                 }
495                 if (v == null && dynamicProp != null) {
496                     for (int i = 0; i < dynamicProp.length; i++) {
497                         v = dynamicProp[i].getProperty(n);
498                         if (v != null) {
499                             break;
500                         }
501                     }
502                 }
503                 if (v == null)
504                     v = "${" + n + "}";
505
506                 sb.append(v);
507                 prev = endName + 1;
508             }
509         }
510         if (prev < value.length())
511             sb.append(value.substring(prev));
512         return sb.toString();
513     }
514
515     /**
516      * Reverse of Introspector.decapitalize
517      */

518     public static String JavaDoc capitalize(String JavaDoc name) {
519         if (name == null || name.length() == 0) {
520             return name;
521         }
522         char chars[] = name.toCharArray();
523         chars[0] = Character.toUpperCase(chars[0]);
524         return new String JavaDoc(chars);
525     }
526
527     public static String JavaDoc unCapitalize(String JavaDoc name) {
528         if (name == null || name.length() == 0) {
529             return name;
530         }
531         char chars[] = name.toCharArray();
532         chars[0] = Character.toLowerCase(chars[0]);
533         return new String JavaDoc(chars);
534     }
535
536     // -------------------- Class path tools --------------------
537

538     /**
539      * Add all the jar files in a dir to the classpath, represented as a Vector
540      * of URLs.
541      */

542     public static void addToClassPath(Vector JavaDoc cpV, String JavaDoc dir) {
543         try {
544             String JavaDoc cpComp[] = getFilesByExt(dir, ".jar");
545             if (cpComp != null) {
546                 int jarCount = cpComp.length;
547                 for (int i = 0; i < jarCount; i++) {
548                     URL JavaDoc url = getURL(dir, cpComp[i]);
549                     if (url != null)
550                         cpV.addElement(url);
551                 }
552             }
553         } catch (Exception JavaDoc ex) {
554             ex.printStackTrace();
555         }
556     }
557
558     public static void addToolsJar(Vector JavaDoc v) {
559         try {
560             // Add tools.jar in any case
561
File JavaDoc f = new File JavaDoc(System.getProperty("java.home")
562                     + "/../lib/tools.jar");
563
564             if (!f.exists()) {
565                 // On some systems java.home gets set to the root of jdk.
566
// That's a bug, but we can work around and be nice.
567
f = new File JavaDoc(System.getProperty("java.home") + "/lib/tools.jar");
568                 if (f.exists()) {
569                     if (log.isDebugEnabled())
570                         log.debug("Detected strange java.home value "
571                             + System.getProperty("java.home")
572                             + ", it should point to jre");
573                 }
574             }
575             URL JavaDoc url = new URL JavaDoc("file", "", f.getAbsolutePath());
576
577             v.addElement(url);
578         } catch (MalformedURLException JavaDoc ex) {
579             ex.printStackTrace();
580         }
581     }
582
583     /**
584      * Return all files with a given extension in a dir
585      */

586     public static String JavaDoc[] getFilesByExt(String JavaDoc ld, String JavaDoc ext) {
587         File JavaDoc dir = new File JavaDoc(ld);
588         String JavaDoc[] names = null;
589         final String JavaDoc lext = ext;
590         if (dir.isDirectory()) {
591             names = dir.list(new FilenameFilter JavaDoc() {
592                 public boolean accept(File JavaDoc d, String JavaDoc name) {
593                     if (name.endsWith(lext)) {
594                         return true;
595                     }
596                     return false;
597                 }
598             });
599         }
600         return names;
601     }
602
603     /**
604      * Construct a file url from a file, using a base dir
605      */

606     public static URL JavaDoc getURL(String JavaDoc base, String JavaDoc file) {
607         try {
608             File JavaDoc baseF = new File JavaDoc(base);
609             File JavaDoc f = new File JavaDoc(baseF, file);
610             String JavaDoc path = f.getCanonicalPath();
611             if (f.isDirectory()) {
612                 path += "/";
613             }
614             if (!f.exists())
615                 return null;
616             return new URL JavaDoc("file", "", path);
617         } catch (Exception JavaDoc ex) {
618             ex.printStackTrace();
619             return null;
620         }
621     }
622
623     /**
624      * Add elements from the classpath <i>cp </i> to a Vector <i>jars </i> as
625      * file URLs (We use Vector for JDK 1.1 compat).
626      * <p>
627      *
628      * @param jars The jar list
629      * @param cp a String classpath of directory or jar file elements
630      * separated by path.separator delimiters.
631      * @throws IOException If an I/O error occurs
632      * @throws MalformedURLException Doh ;)
633      */

634     public static void addJarsFromClassPath(Vector JavaDoc jars, String JavaDoc cp)
635             throws IOException JavaDoc, MalformedURLException JavaDoc {
636         String JavaDoc sep = System.getProperty("path.separator");
637         String JavaDoc token;
638         StringTokenizer JavaDoc st;
639         if (cp != null) {
640             st = new StringTokenizer JavaDoc(cp, sep);
641             while (st.hasMoreTokens()) {
642                 File JavaDoc f = new File JavaDoc(st.nextToken());
643                 String JavaDoc path = f.getCanonicalPath();
644                 if (f.isDirectory()) {
645                     path += "/";
646                 }
647                 URL JavaDoc url = new URL JavaDoc("file", "", path);
648                 if (!jars.contains(url)) {
649                     jars.addElement(url);
650                 }
651             }
652         }
653     }
654
655     /**
656      * Return a URL[] that can be used to construct a class loader
657      */

658     public static URL JavaDoc[] getClassPath(Vector JavaDoc v) {
659         URL JavaDoc[] urls = new URL JavaDoc[v.size()];
660         for (int i = 0; i < v.size(); i++) {
661             urls[i] = (URL JavaDoc) v.elementAt(i);
662         }
663         return urls;
664     }
665
666     /**
667      * Construct a URL classpath from files in a directory, a cpath property,
668      * and tools.jar.
669      */

670     public static URL JavaDoc[] getClassPath(String JavaDoc dir, String JavaDoc cpath,
671             String JavaDoc cpathProp, boolean addTools) throws IOException JavaDoc,
672             MalformedURLException JavaDoc {
673         Vector JavaDoc jarsV = new Vector JavaDoc();
674         if (dir != null) {
675             // Add dir/classes first, if it exists
676
URL JavaDoc url = getURL(dir, "classes");
677             if (url != null)
678                 jarsV.addElement(url);
679             addToClassPath(jarsV, dir);
680         }
681
682         if (cpath != null)
683             addJarsFromClassPath(jarsV, cpath);
684
685         if (cpathProp != null) {
686             String JavaDoc cpath1 = System.getProperty(cpathProp);
687             addJarsFromClassPath(jarsV, cpath1);
688         }
689
690         if (addTools)
691             addToolsJar(jarsV);
692
693         return getClassPath(jarsV);
694     }
695
696     // -------------------- Mapping command line params to setters
697

698     public static boolean processArgs(Object JavaDoc proxy, String JavaDoc args[])
699             throws Exception JavaDoc {
700         String JavaDoc args0[] = null;
701         if (null != findMethod(proxy.getClass(), "getOptions1", new Class JavaDoc[] {})) {
702             args0 = (String JavaDoc[]) callMethod0(proxy, "getOptions1");
703         }
704
705         if (args0 == null) {
706             //args0=findVoidSetters(proxy.getClass());
707
args0 = findBooleanSetters(proxy.getClass());
708         }
709         Hashtable JavaDoc h = null;
710         if (null != findMethod(proxy.getClass(), "getOptionAliases",
711                 new Class JavaDoc[] {})) {
712             h = (Hashtable JavaDoc) callMethod0(proxy, "getOptionAliases");
713         }
714         return processArgs(proxy, args, args0, null, h);
715     }
716
717     public static boolean processArgs(Object JavaDoc proxy, String JavaDoc args[],
718             String JavaDoc args0[], String JavaDoc args1[], Hashtable JavaDoc aliases) throws Exception JavaDoc {
719         for (int i = 0; i < args.length; i++) {
720             String JavaDoc arg = args[i];
721             if (arg.startsWith("-"))
722                 arg = arg.substring(1);
723             if (aliases != null && aliases.get(arg) != null)
724                 arg = (String JavaDoc) aliases.get(arg);
725
726             if (args0 != null) {
727                 boolean set = false;
728                 for (int j = 0; j < args0.length; j++) {
729                     if (args0[j].equalsIgnoreCase(arg)) {
730                         setProperty(proxy, args0[j], "true");
731                         set = true;
732                         break;
733                     }
734                 }
735                 if (set)
736                     continue;
737             }
738             if (args1 != null) {
739                 for (int j = 0; j < args1.length; j++) {
740                     if (args1[j].equalsIgnoreCase(arg)) {
741                         i++;
742                         if (i >= args.length)
743                             return false;
744                         setProperty(proxy, arg, args[i]);
745                         break;
746                     }
747                 }
748             } else {
749                 // if args1 is not specified,assume all other options have param
750
i++;
751                 if (i >= args.length)
752                     return false;
753                 setProperty(proxy, arg, args[i]);
754             }
755
756         }
757         return true;
758     }
759
760     // -------------------- other utils --------------------
761
public static void clear() {
762         objectMethods.clear();
763     }
764     
765     public static String JavaDoc[] findVoidSetters(Class JavaDoc c) {
766         Method JavaDoc m[] = findMethods(c);
767         if (m == null)
768             return null;
769         Vector JavaDoc v = new Vector JavaDoc();
770         for (int i = 0; i < m.length; i++) {
771             if (m[i].getName().startsWith("set")
772                     && m[i].getParameterTypes().length == 0) {
773                 String JavaDoc arg = m[i].getName().substring(3);
774                 v.addElement(unCapitalize(arg));
775             }
776         }
777         String JavaDoc s[] = new String JavaDoc[v.size()];
778         for (int i = 0; i < s.length; i++) {
779             s[i] = (String JavaDoc) v.elementAt(i);
780         }
781         return s;
782     }
783
784     public static String JavaDoc[] findBooleanSetters(Class JavaDoc c) {
785         Method JavaDoc m[] = findMethods(c);
786         if (m == null)
787             return null;
788         Vector JavaDoc v = new Vector JavaDoc();
789         for (int i = 0; i < m.length; i++) {
790             if (m[i].getName().startsWith("set")
791                     && m[i].getParameterTypes().length == 1
792                     && "boolean".equalsIgnoreCase(m[i].getParameterTypes()[0]
793                             .getName())) {
794                 String JavaDoc arg = m[i].getName().substring(3);
795                 v.addElement(unCapitalize(arg));
796             }
797         }
798         String JavaDoc s[] = new String JavaDoc[v.size()];
799         for (int i = 0; i < s.length; i++) {
800             s[i] = (String JavaDoc) v.elementAt(i);
801         }
802         return s;
803     }
804
805     static Hashtable JavaDoc objectMethods = new Hashtable JavaDoc();
806
807     public static Method JavaDoc[] findMethods(Class JavaDoc c) {
808         Method JavaDoc methods[] = (Method JavaDoc[]) objectMethods.get(c);
809         if (methods != null)
810             return methods;
811
812         methods = c.getMethods();
813         objectMethods.put(c, methods);
814         return methods;
815     }
816
817     public static Method JavaDoc findMethod(Class JavaDoc c, String JavaDoc name, Class JavaDoc params[]) {
818         Method JavaDoc methods[] = findMethods(c);
819         if (methods == null)
820             return null;
821         for (int i = 0; i < methods.length; i++) {
822             if (methods[i].getName().equals(name)) {
823                 Class JavaDoc methodParams[] = methods[i].getParameterTypes();
824                 if (methodParams == null)
825                     if (params == null || params.length == 0)
826                         return methods[i];
827                 if (params == null)
828                     if (methodParams == null || methodParams.length == 0)
829                         return methods[i];
830                 if (params.length != methodParams.length)
831                     continue;
832                 boolean found = true;
833                 for (int j = 0; j < params.length; j++) {
834                     if (params[j] != methodParams[j]) {
835                         found = false;
836                         break;
837                     }
838                 }
839                 if (found)
840                     return methods[i];
841             }
842         }
843         return null;
844     }
845
846     /** Test if the object implements a particular
847      * method
848      */

849     public static boolean hasHook(Object JavaDoc obj, String JavaDoc methodN) {
850         try {
851             Method JavaDoc myMethods[] = findMethods(obj.getClass());
852             for (int i = 0; i < myMethods.length; i++) {
853                 if (methodN.equals(myMethods[i].getName())) {
854                     // check if it's overriden
855
Class JavaDoc declaring = myMethods[i].getDeclaringClass();
856                     Class JavaDoc parentOfDeclaring = declaring.getSuperclass();
857                     // this works only if the base class doesn't extend
858
// another class.
859

860                     // if the method is declared in a top level class
861
// like BaseInterceptor parent is Object, otherwise
862
// parent is BaseInterceptor or an intermediate class
863
if (!"java.lang.Object".equals(parentOfDeclaring.getName())) {
864                         return true;
865                     }
866                 }
867             }
868         } catch (Exception JavaDoc ex) {
869             ex.printStackTrace();
870         }
871         return false;
872     }
873
874     public static void callMain(Class JavaDoc c, String JavaDoc args[]) throws Exception JavaDoc {
875         Class JavaDoc p[] = new Class JavaDoc[1];
876         p[0] = args.getClass();
877         Method JavaDoc m = c.getMethod("main", p);
878         m.invoke(c, new Object JavaDoc[] { args });
879     }
880
881     public static Object JavaDoc callMethod1(Object JavaDoc target, String JavaDoc methodN,
882             Object JavaDoc param1, String JavaDoc typeParam1, ClassLoader JavaDoc cl) throws Exception JavaDoc {
883         if (target == null || param1 == null) {
884             d("Assert: Illegal params " + target + " " + param1);
885         }
886         if (dbg > 0)
887             d("callMethod1 " + target.getClass().getName() + " "
888                     + param1.getClass().getName() + " " + typeParam1);
889
890         Class JavaDoc params[] = new Class JavaDoc[1];
891         if (typeParam1 == null)
892             params[0] = param1.getClass();
893         else
894             params[0] = cl.loadClass(typeParam1);
895         Method JavaDoc m = findMethod(target.getClass(), methodN, params);
896         if (m == null)
897             throw new NoSuchMethodException JavaDoc(target.getClass().getName() + " "
898                     + methodN);
899         return m.invoke(target, new Object JavaDoc[] { param1 });
900     }
901
902     public static Object JavaDoc callMethod0(Object JavaDoc target, String JavaDoc methodN)
903             throws Exception JavaDoc {
904         if (target == null) {
905             d("Assert: Illegal params " + target);
906             return null;
907         }
908         if (dbg > 0)
909             d("callMethod0 " + target.getClass().getName() + "." + methodN);
910
911         Class JavaDoc params[] = new Class JavaDoc[0];
912         Method JavaDoc m = findMethod(target.getClass(), methodN, params);
913         if (m == null)
914             throw new NoSuchMethodException JavaDoc(target.getClass().getName() + " "
915                     + methodN);
916         return m.invoke(target, emptyArray);
917     }
918
919     static Object JavaDoc[] emptyArray = new Object JavaDoc[] {};
920
921     public static Object JavaDoc callMethodN(Object JavaDoc target, String JavaDoc methodN,
922             Object JavaDoc params[], Class JavaDoc typeParams[]) throws Exception JavaDoc {
923         Method JavaDoc m = null;
924         m = findMethod(target.getClass(), methodN, typeParams);
925         if (m == null) {
926             d("Can't find method " + methodN + " in " + target + " CLASS "
927                     + target.getClass());
928             return null;
929         }
930         Object JavaDoc o = m.invoke(target, params);
931
932         if (dbg > 0) {
933             // debug
934
StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
935             sb.append("" + target.getClass().getName() + "." + methodN + "( ");
936             for (int i = 0; i < params.length; i++) {
937                 if (i > 0)
938                     sb.append(", ");
939                 sb.append(params[i]);
940             }
941             sb.append(")");
942             d(sb.toString());
943         }
944         return o;
945     }
946
947     public static Object JavaDoc convert(String JavaDoc object, Class JavaDoc paramType) {
948         Object JavaDoc result = null;
949         if ("java.lang.String".equals(paramType.getName())) {
950             result = object;
951         } else if ("java.lang.Integer".equals(paramType.getName())
952                 || "int".equals(paramType.getName())) {
953             try {
954                 result = new Integer JavaDoc(object);
955             } catch (NumberFormatException JavaDoc ex) {
956             }
957             // Try a setFoo ( boolean )
958
} else if ("java.lang.Boolean".equals(paramType.getName())
959                 || "boolean".equals(paramType.getName())) {
960             result = new Boolean JavaDoc(object);
961
962             // Try a setFoo ( InetAddress )
963
} else if ("java.net.InetAddress".equals(paramType
964                 .getName())) {
965             try {
966                 result = InetAddress.getByName(object);
967             } catch (UnknownHostException JavaDoc exc) {
968                 d("Unable to resolve host name:" + object);
969             }
970
971             // Unknown type
972
} else {
973             d("Unknown type " + paramType.getName());
974         }
975         if (result == null) {
976             throw new IllegalArgumentException JavaDoc("Can't convert argument: " + object);
977         }
978         return result;
979     }
980     
981     // -------------------- Get property --------------------
982
// This provides a layer of abstraction
983

984     public static interface PropertySource {
985
986         public String JavaDoc getProperty(String JavaDoc key);
987
988     }
989
990     public static interface AttributeHolder {
991
992         public void setAttribute(String JavaDoc key, Object JavaDoc o);
993
994     }
995
996     // debug --------------------
997
static final int dbg = 0;
998
999     static void d(String JavaDoc s) {
1000        if (log.isDebugEnabled())
1001            log.debug("IntrospectionUtils: " + s);
1002    }
1003}
1004
Popular Tags