Source Code Cross Referenced for IntrospectionUtils.java in  » Sevlet-Container » apache-tomcat-6.0.14 » org » apache » catalina » tribes » demos » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Sevlet Container » apache tomcat 6.0.14 » org.apache.catalina.tribes.demos 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


0001:        /*
0002:         *  Licensed to the Apache Software Foundation (ASF) under one or more
0003:         *  contributor license agreements.  See the NOTICE file distributed with
0004:         *  this work for additional information regarding copyright ownership.
0005:         *  The ASF licenses this file to You under the Apache License, Version 2.0
0006:         *  (the "License"); you may not use this file except in compliance with
0007:         *  the License.  You may obtain a copy of the License at
0008:         *
0009:         *      http://www.apache.org/licenses/LICENSE-2.0
0010:         *
0011:         *  Unless required by applicable law or agreed to in writing, software
0012:         *  distributed under the License is distributed on an "AS IS" BASIS,
0013:         *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
0014:         *  See the License for the specific language governing permissions and
0015:         *  limitations under the License.
0016:         */
0017:
0018:        package org.apache.catalina.tribes.demos;
0019:
0020:        import java.io.File;
0021:        import java.io.FilenameFilter;
0022:        import java.io.IOException;
0023:        import java.lang.reflect.InvocationTargetException;
0024:        import java.lang.reflect.Method;
0025:        import java.net.InetAddress;
0026:        import java.net.MalformedURLException;
0027:        import java.net.URL;
0028:        import java.net.UnknownHostException;
0029:        import java.util.Hashtable;
0030:        import java.util.StringTokenizer;
0031:        import java.util.Vector;
0032:        import org.apache.juli.logging.LogFactory;
0033:        import org.apache.juli.logging.Log;
0034:
0035:        // Depends: JDK1.1
0036:
0037:        /**
0038:         * Utils for introspection and reflection
0039:         */
0040:        public final class IntrospectionUtils {
0041:
0042:            private static Log log = LogFactory
0043:                    .getLog(IntrospectionUtils.class);
0044:
0045:            /**
0046:             * Call execute() - any ant-like task should work
0047:             */
0048:            public static void execute(Object proxy, String method)
0049:                    throws Exception {
0050:                Method executeM = null;
0051:                Class c = proxy.getClass();
0052:                Class params[] = new Class[0];
0053:                //	params[0]=args.getClass();
0054:                executeM = findMethod(c, method, params);
0055:                if (executeM == null) {
0056:                    throw new RuntimeException("No execute in "
0057:                            + proxy.getClass());
0058:                }
0059:                executeM.invoke(proxy, (Object[]) null);//new Object[] { args });
0060:            }
0061:
0062:            /**
0063:             * Call void setAttribute( String ,Object )
0064:             */
0065:            public static void setAttribute(Object proxy, String n, Object v)
0066:                    throws Exception {
0067:                if (proxy instanceof  AttributeHolder) {
0068:                    ((AttributeHolder) proxy).setAttribute(n, v);
0069:                    return;
0070:                }
0071:
0072:                Method executeM = null;
0073:                Class c = proxy.getClass();
0074:                Class params[] = new Class[2];
0075:                params[0] = String.class;
0076:                params[1] = Object.class;
0077:                executeM = findMethod(c, "setAttribute", params);
0078:                if (executeM == null) {
0079:                    if (log.isDebugEnabled())
0080:                        log.debug("No setAttribute in " + proxy.getClass());
0081:                    return;
0082:                }
0083:                if (false)
0084:                    if (log.isDebugEnabled())
0085:                        log.debug("Setting " + n + "=" + v + "  in " + proxy);
0086:                executeM.invoke(proxy, new Object[] { n, v });
0087:                return;
0088:            }
0089:
0090:            /**
0091:             * Call void getAttribute( String )
0092:             */
0093:            public static Object getAttribute(Object proxy, String n)
0094:                    throws Exception {
0095:                Method executeM = null;
0096:                Class c = proxy.getClass();
0097:                Class params[] = new Class[1];
0098:                params[0] = String.class;
0099:                executeM = findMethod(c, "getAttribute", params);
0100:                if (executeM == null) {
0101:                    if (log.isDebugEnabled())
0102:                        log.debug("No getAttribute in " + proxy.getClass());
0103:                    return null;
0104:                }
0105:                return executeM.invoke(proxy, new Object[] { n });
0106:            }
0107:
0108:            /**
0109:             * Construct a URLClassLoader. Will compile and work in JDK1.1 too.
0110:             */
0111:            public static ClassLoader getURLClassLoader(URL urls[],
0112:                    ClassLoader parent) {
0113:                try {
0114:                    Class urlCL = Class.forName("java.net.URLClassLoader");
0115:                    Class paramT[] = new Class[2];
0116:                    paramT[0] = urls.getClass();
0117:                    paramT[1] = ClassLoader.class;
0118:                    Method m = findMethod(urlCL, "newInstance", paramT);
0119:                    if (m == null)
0120:                        return null;
0121:
0122:                    ClassLoader cl = (ClassLoader) m.invoke(urlCL,
0123:                            new Object[] { urls, parent });
0124:                    return cl;
0125:                } catch (ClassNotFoundException ex) {
0126:                    // jdk1.1
0127:                    return null;
0128:                } catch (Exception ex) {
0129:                    ex.printStackTrace();
0130:                    return null;
0131:                }
0132:            }
0133:
0134:            public static String guessInstall(String installSysProp,
0135:                    String homeSysProp, String jarName) {
0136:                return guessInstall(installSysProp, homeSysProp, jarName, null);
0137:            }
0138:
0139:            /**
0140:             * Guess a product install/home by analyzing the class path. It works for
0141:             * product using the pattern: lib/executable.jar or if executable.jar is
0142:             * included in classpath by a shell script. ( java -jar also works )
0143:             *
0144:             * Insures both "install" and "home" System properties are set. If either or
0145:             * both System properties are unset, "install" and "home" will be set to the
0146:             * same value. This value will be the other System property that is set, or
0147:             * the guessed value if neither is set.
0148:             */
0149:            public static String guessInstall(String installSysProp,
0150:                    String homeSysProp, String jarName, String classFile) {
0151:                String install = null;
0152:                String home = null;
0153:
0154:                if (installSysProp != null)
0155:                    install = System.getProperty(installSysProp);
0156:
0157:                if (homeSysProp != null)
0158:                    home = System.getProperty(homeSysProp);
0159:
0160:                if (install != null) {
0161:                    if (home == null)
0162:                        System.getProperties().put(homeSysProp, install);
0163:                    return install;
0164:                }
0165:
0166:                // Find the directory where jarName.jar is located
0167:
0168:                String cpath = System.getProperty("java.class.path");
0169:                String pathSep = System.getProperty("path.separator");
0170:                StringTokenizer st = new StringTokenizer(cpath, pathSep);
0171:                while (st.hasMoreTokens()) {
0172:                    String path = st.nextToken();
0173:                    //	    log( "path " + path );
0174:                    if (path.endsWith(jarName)) {
0175:                        home = path.substring(0, path.length()
0176:                                - jarName.length());
0177:                        try {
0178:                            if ("".equals(home)) {
0179:                                home = new File("./").getCanonicalPath();
0180:                            } else if (home.endsWith(File.separator)) {
0181:                                home = home.substring(0, home.length() - 1);
0182:                            }
0183:                            File f = new File(home);
0184:                            String parentDir = f.getParent();
0185:                            if (parentDir == null)
0186:                                parentDir = home; // unix style
0187:                            File f1 = new File(parentDir);
0188:                            install = f1.getCanonicalPath();
0189:                            if (installSysProp != null)
0190:                                System.getProperties().put(installSysProp,
0191:                                        install);
0192:                            if (home == null && homeSysProp != null)
0193:                                System.getProperties()
0194:                                        .put(homeSysProp, install);
0195:                            return install;
0196:                        } catch (Exception ex) {
0197:                            ex.printStackTrace();
0198:                        }
0199:                    } else {
0200:                        String fname = path + (path.endsWith("/") ? "" : "/")
0201:                                + classFile;
0202:                        if (new File(fname).exists()) {
0203:                            try {
0204:                                File f = new File(path);
0205:                                String parentDir = f.getParent();
0206:                                if (parentDir == null)
0207:                                    parentDir = path; // unix style
0208:                                File f1 = new File(parentDir);
0209:                                install = f1.getCanonicalPath();
0210:                                if (installSysProp != null)
0211:                                    System.getProperties().put(installSysProp,
0212:                                            install);
0213:                                if (home == null && homeSysProp != null)
0214:                                    System.getProperties().put(homeSysProp,
0215:                                            install);
0216:                                return install;
0217:                            } catch (Exception ex) {
0218:                                ex.printStackTrace();
0219:                            }
0220:                        }
0221:                    }
0222:                }
0223:
0224:                // if install directory can't be found, use home as the default
0225:                if (home != null) {
0226:                    System.getProperties().put(installSysProp, home);
0227:                    return home;
0228:                }
0229:
0230:                return null;
0231:            }
0232:
0233:            /**
0234:             * Debug method, display the classpath
0235:             */
0236:            public static void displayClassPath(String msg, URL[] cp) {
0237:                if (log.isDebugEnabled()) {
0238:                    log.debug(msg);
0239:                    for (int i = 0; i < cp.length; i++) {
0240:                        log.debug(cp[i].getFile());
0241:                    }
0242:                }
0243:            }
0244:
0245:            public static String PATH_SEPARATOR = System
0246:                    .getProperty("path.separator");
0247:
0248:            /**
0249:             * Adds classpath entries from a vector of URL's to the "tc_path_add" System
0250:             * property. This System property lists the classpath entries common to web
0251:             * applications. This System property is currently used by Jasper when its
0252:             * JSP servlet compiles the Java file for a JSP.
0253:             */
0254:            public static String classPathAdd(URL urls[], String cp) {
0255:                if (urls == null)
0256:                    return cp;
0257:
0258:                for (int i = 0; i < urls.length; i++) {
0259:                    if (cp != null)
0260:                        cp += PATH_SEPARATOR + urls[i].getFile();
0261:                    else
0262:                        cp = urls[i].getFile();
0263:                }
0264:                return cp;
0265:            }
0266:
0267:            /**
0268:             * Find a method with the right name If found, call the method ( if param is
0269:             * int or boolean we'll convert value to the right type before) - that means
0270:             * you can have setDebug(1).
0271:             */
0272:            public static void setProperty(Object o, String name, String value) {
0273:                if (dbg > 1)
0274:                    d("setProperty(" + o.getClass() + " " + name + "=" + value
0275:                            + ")");
0276:
0277:                String setter = "set" + capitalize(name);
0278:
0279:                try {
0280:                    Method methods[] = findMethods(o.getClass());
0281:                    Method setPropertyMethod = null;
0282:
0283:                    // First, the ideal case - a setFoo( String ) method
0284:                    for (int i = 0; i < methods.length; i++) {
0285:                        Class paramT[] = methods[i].getParameterTypes();
0286:                        if (setter.equals(methods[i].getName())
0287:                                && paramT.length == 1
0288:                                && "java.lang.String".equals(paramT[0]
0289:                                        .getName())) {
0290:
0291:                            methods[i].invoke(o, new Object[] { value });
0292:                            return;
0293:                        }
0294:                    }
0295:
0296:                    // Try a setFoo ( int ) or ( boolean )
0297:                    for (int i = 0; i < methods.length; i++) {
0298:                        boolean ok = true;
0299:                        if (setter.equals(methods[i].getName())
0300:                                && methods[i].getParameterTypes().length == 1) {
0301:
0302:                            // match - find the type and invoke it
0303:                            Class paramType = methods[i].getParameterTypes()[0];
0304:                            Object params[] = new Object[1];
0305:
0306:                            // Try a setFoo ( int )
0307:                            if ("java.lang.Integer".equals(paramType.getName())
0308:                                    || "int".equals(paramType.getName())) {
0309:                                try {
0310:                                    params[0] = new Integer(value);
0311:                                } catch (NumberFormatException ex) {
0312:                                    ok = false;
0313:                                }
0314:                                // Try a setFoo ( long )
0315:                            } else if ("java.lang.Long".equals(paramType
0316:                                    .getName())
0317:                                    || "long".equals(paramType.getName())) {
0318:                                try {
0319:                                    params[0] = new Long(value);
0320:                                } catch (NumberFormatException ex) {
0321:                                    ok = false;
0322:                                }
0323:
0324:                                // Try a setFoo ( boolean )
0325:                            } else if ("java.lang.Boolean".equals(paramType
0326:                                    .getName())
0327:                                    || "boolean".equals(paramType.getName())) {
0328:                                params[0] = new Boolean(value);
0329:
0330:                                // Try a setFoo ( InetAddress )
0331:                            } else if ("java.net.InetAddress".equals(paramType
0332:                                    .getName())) {
0333:                                try {
0334:                                    params[0] = InetAddress.getByName(value);
0335:                                } catch (UnknownHostException exc) {
0336:                                    d("Unable to resolve host name:" + value);
0337:                                    ok = false;
0338:                                }
0339:
0340:                                // Unknown type
0341:                            } else {
0342:                                d("Unknown type " + paramType.getName());
0343:                            }
0344:
0345:                            if (ok) {
0346:                                methods[i].invoke(o, params);
0347:                                return;
0348:                            }
0349:                        }
0350:
0351:                        // save "setProperty" for later
0352:                        if ("setProperty".equals(methods[i].getName())) {
0353:                            setPropertyMethod = methods[i];
0354:                        }
0355:                    }
0356:
0357:                    // Ok, no setXXX found, try a setProperty("name", "value")
0358:                    if (setPropertyMethod != null) {
0359:                        Object params[] = new Object[2];
0360:                        params[0] = name;
0361:                        params[1] = value;
0362:                        setPropertyMethod.invoke(o, params);
0363:                    }
0364:
0365:                } catch (IllegalArgumentException ex2) {
0366:                    log.warn("IAE " + o + " " + name + " " + value, ex2);
0367:                } catch (SecurityException ex1) {
0368:                    if (dbg > 0)
0369:                        d("SecurityException for " + o.getClass() + " " + name
0370:                                + "=" + value + ")");
0371:                    if (dbg > 1)
0372:                        ex1.printStackTrace();
0373:                } catch (IllegalAccessException iae) {
0374:                    if (dbg > 0)
0375:                        d("IllegalAccessException for " + o.getClass() + " "
0376:                                + name + "=" + value + ")");
0377:                    if (dbg > 1)
0378:                        iae.printStackTrace();
0379:                } catch (InvocationTargetException ie) {
0380:                    if (dbg > 0)
0381:                        d("InvocationTargetException for " + o.getClass() + " "
0382:                                + name + "=" + value + ")");
0383:                    if (dbg > 1)
0384:                        ie.printStackTrace();
0385:                }
0386:            }
0387:
0388:            public static Object getProperty(Object o, String name) {
0389:                String getter = "get" + capitalize(name);
0390:                String isGetter = "is" + capitalize(name);
0391:
0392:                try {
0393:                    Method methods[] = findMethods(o.getClass());
0394:                    Method getPropertyMethod = null;
0395:
0396:                    // First, the ideal case - a getFoo() method
0397:                    for (int i = 0; i < methods.length; i++) {
0398:                        Class paramT[] = methods[i].getParameterTypes();
0399:                        if (getter.equals(methods[i].getName())
0400:                                && paramT.length == 0) {
0401:                            return methods[i].invoke(o, (Object[]) null);
0402:                        }
0403:                        if (isGetter.equals(methods[i].getName())
0404:                                && paramT.length == 0) {
0405:                            return methods[i].invoke(o, (Object[]) null);
0406:                        }
0407:
0408:                        if ("getProperty".equals(methods[i].getName())) {
0409:                            getPropertyMethod = methods[i];
0410:                        }
0411:                    }
0412:
0413:                    // Ok, no setXXX found, try a getProperty("name")
0414:                    if (getPropertyMethod != null) {
0415:                        Object params[] = new Object[1];
0416:                        params[0] = name;
0417:                        return getPropertyMethod.invoke(o, params);
0418:                    }
0419:
0420:                } catch (IllegalArgumentException ex2) {
0421:                    log.warn("IAE " + o + " " + name, ex2);
0422:                } catch (SecurityException ex1) {
0423:                    if (dbg > 0)
0424:                        d("SecurityException for " + o.getClass() + " " + name
0425:                                + ")");
0426:                    if (dbg > 1)
0427:                        ex1.printStackTrace();
0428:                } catch (IllegalAccessException iae) {
0429:                    if (dbg > 0)
0430:                        d("IllegalAccessException for " + o.getClass() + " "
0431:                                + name + ")");
0432:                    if (dbg > 1)
0433:                        iae.printStackTrace();
0434:                } catch (InvocationTargetException ie) {
0435:                    if (dbg > 0)
0436:                        d("InvocationTargetException for " + o.getClass() + " "
0437:                                + name + ")");
0438:                    if (dbg > 1)
0439:                        ie.printStackTrace();
0440:                }
0441:                return null;
0442:            }
0443:
0444:            /**
0445:             */
0446:            public static void setProperty(Object o, String name) {
0447:                String setter = "set" + capitalize(name);
0448:                try {
0449:                    Method methods[] = findMethods(o.getClass());
0450:                    Method setPropertyMethod = null;
0451:                    // find setFoo() method
0452:                    for (int i = 0; i < methods.length; i++) {
0453:                        Class paramT[] = methods[i].getParameterTypes();
0454:                        if (setter.equals(methods[i].getName())
0455:                                && paramT.length == 0) {
0456:                            methods[i].invoke(o, new Object[] {});
0457:                            return;
0458:                        }
0459:                    }
0460:                } catch (Exception ex1) {
0461:                    if (dbg > 0)
0462:                        d("Exception for " + o.getClass() + " " + name);
0463:                    if (dbg > 1)
0464:                        ex1.printStackTrace();
0465:                }
0466:            }
0467:
0468:            /**
0469:             * Replace ${NAME} with the property value
0470:             *
0471:             * @deprecated Use the explicit method
0472:             */
0473:            public static String replaceProperties(String value, Object getter) {
0474:                if (getter instanceof  Hashtable)
0475:                    return replaceProperties(value, (Hashtable) getter, null);
0476:
0477:                if (getter instanceof  PropertySource) {
0478:                    PropertySource src[] = new PropertySource[] { (PropertySource) getter };
0479:                    return replaceProperties(value, null, src);
0480:                }
0481:                return value;
0482:            }
0483:
0484:            /**
0485:             * Replace ${NAME} with the property value
0486:             */
0487:            public static String replaceProperties(String value,
0488:                    Hashtable staticProp, PropertySource dynamicProp[]) {
0489:                StringBuffer sb = new StringBuffer();
0490:                int prev = 0;
0491:                // assert value!=nil
0492:                int pos;
0493:                while ((pos = value.indexOf("$", prev)) >= 0) {
0494:                    if (pos > 0) {
0495:                        sb.append(value.substring(prev, pos));
0496:                    }
0497:                    if (pos == (value.length() - 1)) {
0498:                        sb.append('$');
0499:                        prev = pos + 1;
0500:                    } else if (value.charAt(pos + 1) != '{') {
0501:                        sb.append('$');
0502:                        prev = pos + 1; // XXX
0503:                    } else {
0504:                        int endName = value.indexOf('}', pos);
0505:                        if (endName < 0) {
0506:                            sb.append(value.substring(pos));
0507:                            prev = value.length();
0508:                            continue;
0509:                        }
0510:                        String n = value.substring(pos + 2, endName);
0511:                        String v = null;
0512:                        if (staticProp != null) {
0513:                            v = (String) ((Hashtable) staticProp).get(n);
0514:                        }
0515:                        if (v == null && dynamicProp != null) {
0516:                            for (int i = 0; i < dynamicProp.length; i++) {
0517:                                v = dynamicProp[i].getProperty(n);
0518:                                if (v != null) {
0519:                                    break;
0520:                                }
0521:                            }
0522:                        }
0523:                        if (v == null)
0524:                            v = "${" + n + "}";
0525:
0526:                        sb.append(v);
0527:                        prev = endName + 1;
0528:                    }
0529:                }
0530:                if (prev < value.length())
0531:                    sb.append(value.substring(prev));
0532:                return sb.toString();
0533:            }
0534:
0535:            /**
0536:             * Reverse of Introspector.decapitalize
0537:             */
0538:            public static String capitalize(String name) {
0539:                if (name == null || name.length() == 0) {
0540:                    return name;
0541:                }
0542:                char chars[] = name.toCharArray();
0543:                chars[0] = Character.toUpperCase(chars[0]);
0544:                return new String(chars);
0545:            }
0546:
0547:            public static String unCapitalize(String name) {
0548:                if (name == null || name.length() == 0) {
0549:                    return name;
0550:                }
0551:                char chars[] = name.toCharArray();
0552:                chars[0] = Character.toLowerCase(chars[0]);
0553:                return new String(chars);
0554:            }
0555:
0556:            // -------------------- Class path tools --------------------
0557:
0558:            /**
0559:             * Add all the jar files in a dir to the classpath, represented as a Vector
0560:             * of URLs.
0561:             */
0562:            public static void addToClassPath(Vector cpV, String dir) {
0563:                try {
0564:                    String cpComp[] = getFilesByExt(dir, ".jar");
0565:                    if (cpComp != null) {
0566:                        int jarCount = cpComp.length;
0567:                        for (int i = 0; i < jarCount; i++) {
0568:                            URL url = getURL(dir, cpComp[i]);
0569:                            if (url != null)
0570:                                cpV.addElement(url);
0571:                        }
0572:                    }
0573:                } catch (Exception ex) {
0574:                    ex.printStackTrace();
0575:                }
0576:            }
0577:
0578:            public static void addToolsJar(Vector v) {
0579:                try {
0580:                    // Add tools.jar in any case
0581:                    File f = new File(System.getProperty("java.home")
0582:                            + "/../lib/tools.jar");
0583:
0584:                    if (!f.exists()) {
0585:                        // On some systems java.home gets set to the root of jdk.
0586:                        // That's a bug, but we can work around and be nice.
0587:                        f = new File(System.getProperty("java.home")
0588:                                + "/lib/tools.jar");
0589:                        if (f.exists()) {
0590:                            if (log.isDebugEnabled())
0591:                                log.debug("Detected strange java.home value "
0592:                                        + System.getProperty("java.home")
0593:                                        + ", it should point to jre");
0594:                        }
0595:                    }
0596:                    URL url = new URL("file", "", f.getAbsolutePath());
0597:
0598:                    v.addElement(url);
0599:                } catch (MalformedURLException ex) {
0600:                    ex.printStackTrace();
0601:                }
0602:            }
0603:
0604:            /**
0605:             * Return all files with a given extension in a dir
0606:             */
0607:            public static String[] getFilesByExt(String ld, String ext) {
0608:                File dir = new File(ld);
0609:                String[] names = null;
0610:                final String lext = ext;
0611:                if (dir.isDirectory()) {
0612:                    names = dir.list(new FilenameFilter() {
0613:                        public boolean accept(File d, String name) {
0614:                            if (name.endsWith(lext)) {
0615:                                return true;
0616:                            }
0617:                            return false;
0618:                        }
0619:                    });
0620:                }
0621:                return names;
0622:            }
0623:
0624:            /**
0625:             * Construct a file url from a file, using a base dir
0626:             */
0627:            public static URL getURL(String base, String file) {
0628:                try {
0629:                    File baseF = new File(base);
0630:                    File f = new File(baseF, file);
0631:                    String path = f.getCanonicalPath();
0632:                    if (f.isDirectory()) {
0633:                        path += "/";
0634:                    }
0635:                    if (!f.exists())
0636:                        return null;
0637:                    return new URL("file", "", path);
0638:                } catch (Exception ex) {
0639:                    ex.printStackTrace();
0640:                    return null;
0641:                }
0642:            }
0643:
0644:            /**
0645:             * Add elements from the classpath <i>cp </i> to a Vector <i>jars </i> as
0646:             * file URLs (We use Vector for JDK 1.1 compat).
0647:             * <p>
0648:             *
0649:             * @param jars The jar list
0650:             * @param cp a String classpath of directory or jar file elements
0651:             *   separated by path.separator delimiters.
0652:             * @throws IOException If an I/O error occurs
0653:             * @throws MalformedURLException Doh ;)
0654:             */
0655:            public static void addJarsFromClassPath(Vector jars, String cp)
0656:                    throws IOException, MalformedURLException {
0657:                String sep = System.getProperty("path.separator");
0658:                String token;
0659:                StringTokenizer st;
0660:                if (cp != null) {
0661:                    st = new StringTokenizer(cp, sep);
0662:                    while (st.hasMoreTokens()) {
0663:                        File f = new File(st.nextToken());
0664:                        String path = f.getCanonicalPath();
0665:                        if (f.isDirectory()) {
0666:                            path += "/";
0667:                        }
0668:                        URL url = new URL("file", "", path);
0669:                        if (!jars.contains(url)) {
0670:                            jars.addElement(url);
0671:                        }
0672:                    }
0673:                }
0674:            }
0675:
0676:            /**
0677:             * Return a URL[] that can be used to construct a class loader
0678:             */
0679:            public static URL[] getClassPath(Vector v) {
0680:                URL[] urls = new URL[v.size()];
0681:                for (int i = 0; i < v.size(); i++) {
0682:                    urls[i] = (URL) v.elementAt(i);
0683:                }
0684:                return urls;
0685:            }
0686:
0687:            /**
0688:             * Construct a URL classpath from files in a directory, a cpath property,
0689:             * and tools.jar.
0690:             */
0691:            public static URL[] getClassPath(String dir, String cpath,
0692:                    String cpathProp, boolean addTools) throws IOException,
0693:                    MalformedURLException {
0694:                Vector jarsV = new Vector();
0695:                if (dir != null) {
0696:                    // Add dir/classes first, if it exists
0697:                    URL url = getURL(dir, "classes");
0698:                    if (url != null)
0699:                        jarsV.addElement(url);
0700:                    addToClassPath(jarsV, dir);
0701:                }
0702:
0703:                if (cpath != null)
0704:                    addJarsFromClassPath(jarsV, cpath);
0705:
0706:                if (cpathProp != null) {
0707:                    String cpath1 = System.getProperty(cpathProp);
0708:                    addJarsFromClassPath(jarsV, cpath1);
0709:                }
0710:
0711:                if (addTools)
0712:                    addToolsJar(jarsV);
0713:
0714:                return getClassPath(jarsV);
0715:            }
0716:
0717:            // -------------------- Mapping command line params to setters
0718:
0719:            public static boolean processArgs(Object proxy, String args[])
0720:                    throws Exception {
0721:                String args0[] = null;
0722:                if (null != findMethod(proxy.getClass(), "getOptions1",
0723:                        new Class[] {})) {
0724:                    args0 = (String[]) callMethod0(proxy, "getOptions1");
0725:                }
0726:
0727:                if (args0 == null) {
0728:                    //args0=findVoidSetters(proxy.getClass());
0729:                    args0 = findBooleanSetters(proxy.getClass());
0730:                }
0731:                Hashtable h = null;
0732:                if (null != findMethod(proxy.getClass(), "getOptionAliases",
0733:                        new Class[] {})) {
0734:                    h = (Hashtable) callMethod0(proxy, "getOptionAliases");
0735:                }
0736:                return processArgs(proxy, args, args0, null, h);
0737:            }
0738:
0739:            public static boolean processArgs(Object proxy, String args[],
0740:                    String args0[], String args1[], Hashtable aliases)
0741:                    throws Exception {
0742:                for (int i = 0; i < args.length; i++) {
0743:                    String arg = args[i];
0744:                    if (arg.startsWith("-"))
0745:                        arg = arg.substring(1);
0746:                    if (aliases != null && aliases.get(arg) != null)
0747:                        arg = (String) aliases.get(arg);
0748:
0749:                    if (args0 != null) {
0750:                        boolean set = false;
0751:                        for (int j = 0; j < args0.length; j++) {
0752:                            if (args0[j].equalsIgnoreCase(arg)) {
0753:                                setProperty(proxy, args0[j], "true");
0754:                                set = true;
0755:                                break;
0756:                            }
0757:                        }
0758:                        if (set)
0759:                            continue;
0760:                    }
0761:                    if (args1 != null) {
0762:                        for (int j = 0; j < args1.length; j++) {
0763:                            if (args1[j].equalsIgnoreCase(arg)) {
0764:                                i++;
0765:                                if (i >= args.length)
0766:                                    return false;
0767:                                setProperty(proxy, arg, args[i]);
0768:                                break;
0769:                            }
0770:                        }
0771:                    } else {
0772:                        // if args1 is not specified,assume all other options have param
0773:                        i++;
0774:                        if (i >= args.length)
0775:                            return false;
0776:                        setProperty(proxy, arg, args[i]);
0777:                    }
0778:
0779:                }
0780:                return true;
0781:            }
0782:
0783:            // -------------------- other utils --------------------
0784:            public static void clear() {
0785:                objectMethods.clear();
0786:            }
0787:
0788:            public static String[] findVoidSetters(Class c) {
0789:                Method m[] = findMethods(c);
0790:                if (m == null)
0791:                    return null;
0792:                Vector v = new Vector();
0793:                for (int i = 0; i < m.length; i++) {
0794:                    if (m[i].getName().startsWith("set")
0795:                            && m[i].getParameterTypes().length == 0) {
0796:                        String arg = m[i].getName().substring(3);
0797:                        v.addElement(unCapitalize(arg));
0798:                    }
0799:                }
0800:                String s[] = new String[v.size()];
0801:                for (int i = 0; i < s.length; i++) {
0802:                    s[i] = (String) v.elementAt(i);
0803:                }
0804:                return s;
0805:            }
0806:
0807:            public static String[] findBooleanSetters(Class c) {
0808:                Method m[] = findMethods(c);
0809:                if (m == null)
0810:                    return null;
0811:                Vector v = new Vector();
0812:                for (int i = 0; i < m.length; i++) {
0813:                    if (m[i].getName().startsWith("set")
0814:                            && m[i].getParameterTypes().length == 1
0815:                            && "boolean".equalsIgnoreCase(m[i]
0816:                                    .getParameterTypes()[0].getName())) {
0817:                        String arg = m[i].getName().substring(3);
0818:                        v.addElement(unCapitalize(arg));
0819:                    }
0820:                }
0821:                String s[] = new String[v.size()];
0822:                for (int i = 0; i < s.length; i++) {
0823:                    s[i] = (String) v.elementAt(i);
0824:                }
0825:                return s;
0826:            }
0827:
0828:            static Hashtable objectMethods = new Hashtable();
0829:
0830:            public static Method[] findMethods(Class c) {
0831:                Method methods[] = (Method[]) objectMethods.get(c);
0832:                if (methods != null)
0833:                    return methods;
0834:
0835:                methods = c.getMethods();
0836:                objectMethods.put(c, methods);
0837:                return methods;
0838:            }
0839:
0840:            public static Method findMethod(Class c, String name,
0841:                    Class params[]) {
0842:                Method methods[] = findMethods(c);
0843:                if (methods == null)
0844:                    return null;
0845:                for (int i = 0; i < methods.length; i++) {
0846:                    if (methods[i].getName().equals(name)) {
0847:                        Class methodParams[] = methods[i].getParameterTypes();
0848:                        if (methodParams == null)
0849:                            if (params == null || params.length == 0)
0850:                                return methods[i];
0851:                        if (params == null)
0852:                            if (methodParams == null
0853:                                    || methodParams.length == 0)
0854:                                return methods[i];
0855:                        if (params.length != methodParams.length)
0856:                            continue;
0857:                        boolean found = true;
0858:                        for (int j = 0; j < params.length; j++) {
0859:                            if (params[j] != methodParams[j]) {
0860:                                found = false;
0861:                                break;
0862:                            }
0863:                        }
0864:                        if (found)
0865:                            return methods[i];
0866:                    }
0867:                }
0868:                return null;
0869:            }
0870:
0871:            /** Test if the object implements a particular
0872:             *  method
0873:             */
0874:            public static boolean hasHook(Object obj, String methodN) {
0875:                try {
0876:                    Method myMethods[] = findMethods(obj.getClass());
0877:                    for (int i = 0; i < myMethods.length; i++) {
0878:                        if (methodN.equals(myMethods[i].getName())) {
0879:                            // check if it's overriden
0880:                            Class declaring = myMethods[i].getDeclaringClass();
0881:                            Class parentOfDeclaring = declaring.getSuperclass();
0882:                            // this works only if the base class doesn't extend
0883:                            // another class.
0884:
0885:                            // if the method is declared in a top level class
0886:                            // like BaseInterceptor parent is Object, otherwise
0887:                            // parent is BaseInterceptor or an intermediate class
0888:                            if (!"java.lang.Object".equals(parentOfDeclaring
0889:                                    .getName())) {
0890:                                return true;
0891:                            }
0892:                        }
0893:                    }
0894:                } catch (Exception ex) {
0895:                    ex.printStackTrace();
0896:                }
0897:                return false;
0898:            }
0899:
0900:            public static void callMain(Class c, String args[])
0901:                    throws Exception {
0902:                Class p[] = new Class[1];
0903:                p[0] = args.getClass();
0904:                Method m = c.getMethod("main", p);
0905:                m.invoke(c, new Object[] { args });
0906:            }
0907:
0908:            public static Object callMethod1(Object target, String methodN,
0909:                    Object param1, String typeParam1, ClassLoader cl)
0910:                    throws Exception {
0911:                if (target == null || param1 == null) {
0912:                    d("Assert: Illegal params " + target + " " + param1);
0913:                }
0914:                if (dbg > 0)
0915:                    d("callMethod1 " + target.getClass().getName() + " "
0916:                            + param1.getClass().getName() + " " + typeParam1);
0917:
0918:                Class params[] = new Class[1];
0919:                if (typeParam1 == null)
0920:                    params[0] = param1.getClass();
0921:                else
0922:                    params[0] = cl.loadClass(typeParam1);
0923:                Method m = findMethod(target.getClass(), methodN, params);
0924:                if (m == null)
0925:                    throw new NoSuchMethodException(target.getClass().getName()
0926:                            + " " + methodN);
0927:                return m.invoke(target, new Object[] { param1 });
0928:            }
0929:
0930:            public static Object callMethod0(Object target, String methodN)
0931:                    throws Exception {
0932:                if (target == null) {
0933:                    d("Assert: Illegal params " + target);
0934:                    return null;
0935:                }
0936:                if (dbg > 0)
0937:                    d("callMethod0 " + target.getClass().getName() + "."
0938:                            + methodN);
0939:
0940:                Class params[] = new Class[0];
0941:                Method m = findMethod(target.getClass(), methodN, params);
0942:                if (m == null)
0943:                    throw new NoSuchMethodException(target.getClass().getName()
0944:                            + " " + methodN);
0945:                return m.invoke(target, emptyArray);
0946:            }
0947:
0948:            static Object[] emptyArray = new Object[] {};
0949:
0950:            public static Object callMethodN(Object target, String methodN,
0951:                    Object params[], Class typeParams[]) throws Exception {
0952:                Method m = null;
0953:                m = findMethod(target.getClass(), methodN, typeParams);
0954:                if (m == null) {
0955:                    d("Can't find method " + methodN + " in " + target
0956:                            + " CLASS " + target.getClass());
0957:                    return null;
0958:                }
0959:                Object o = m.invoke(target, params);
0960:
0961:                if (dbg > 0) {
0962:                    // debug
0963:                    StringBuffer sb = new StringBuffer();
0964:                    sb.append("" + target.getClass().getName() + "." + methodN
0965:                            + "( ");
0966:                    for (int i = 0; i < params.length; i++) {
0967:                        if (i > 0)
0968:                            sb.append(", ");
0969:                        sb.append(params[i]);
0970:                    }
0971:                    sb.append(")");
0972:                    d(sb.toString());
0973:                }
0974:                return o;
0975:            }
0976:
0977:            public static Object convert(String object, Class paramType) {
0978:                Object result = null;
0979:                if ("java.lang.String".equals(paramType.getName())) {
0980:                    result = object;
0981:                } else if ("java.lang.Integer".equals(paramType.getName())
0982:                        || "int".equals(paramType.getName())) {
0983:                    try {
0984:                        result = new Integer(object);
0985:                    } catch (NumberFormatException ex) {
0986:                    }
0987:                    // Try a setFoo ( boolean )
0988:                } else if ("java.lang.Boolean".equals(paramType.getName())
0989:                        || "boolean".equals(paramType.getName())) {
0990:                    result = new Boolean(object);
0991:
0992:                    // Try a setFoo ( InetAddress )
0993:                } else if ("java.net.InetAddress".equals(paramType.getName())) {
0994:                    try {
0995:                        result = InetAddress.getByName(object);
0996:                    } catch (UnknownHostException exc) {
0997:                        d("Unable to resolve host name:" + object);
0998:                    }
0999:
1000:                    // Unknown type
1001:                } else {
1002:                    d("Unknown type " + paramType.getName());
1003:                }
1004:                if (result == null) {
1005:                    throw new IllegalArgumentException(
1006:                            "Can't convert argument: " + object);
1007:                }
1008:                return result;
1009:            }
1010:
1011:            // -------------------- Get property --------------------
1012:            // This provides a layer of abstraction
1013:
1014:            public static interface PropertySource {
1015:
1016:                public String getProperty(String key);
1017:
1018:            }
1019:
1020:            public static interface AttributeHolder {
1021:
1022:                public void setAttribute(String key, Object o);
1023:
1024:            }
1025:
1026:            // debug --------------------
1027:            static final int dbg = 0;
1028:
1029:            static void d(String s) {
1030:                if (log.isDebugEnabled())
1031:                    log.debug("IntrospectionUtils: " + s);
1032:            }
1033:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.