PageRenderTime 4082ms CodeModel.GetById 12ms RepoModel.GetById 1ms app.codeStats 0ms

/projects/tomcat-7.0.2/test/org/apache/catalina/tribes/demos/IntrospectionUtils.java

https://gitlab.com/essere.lab.public/qualitas.class-corpus
Java | 905 lines | 679 code | 92 blank | 134 comment | 226 complexity | 04f76e083ef938909cf9cfbabcb33695 MD5 | raw file
  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. package org.apache.catalina.tribes.demos;
  18. import java.io.File;
  19. import java.io.FilenameFilter;
  20. import java.io.IOException;
  21. import java.lang.reflect.InvocationTargetException;
  22. import java.lang.reflect.Method;
  23. import java.net.InetAddress;
  24. import java.net.MalformedURLException;
  25. import java.net.URL;
  26. import java.net.UnknownHostException;
  27. import java.util.Hashtable;
  28. import java.util.StringTokenizer;
  29. import java.util.Vector;
  30. // Depends: JDK1.1
  31. /**
  32. * Utils for introspection and reflection
  33. */
  34. public final class IntrospectionUtils {
  35. private static final org.apache.juli.logging.Log log=
  36. org.apache.juli.logging.LogFactory.getLog( IntrospectionUtils.class );
  37. /**
  38. * Call execute() - any ant-like task should work
  39. */
  40. public static void execute(Object proxy, String method) throws Exception {
  41. Method executeM = null;
  42. Class<?> c = proxy.getClass();
  43. Class<?> params[] = new Class[0];
  44. // params[0]=args.getClass();
  45. executeM = findMethod(c, method, params);
  46. if (executeM == null) {
  47. throw new RuntimeException("No execute in " + proxy.getClass());
  48. }
  49. executeM.invoke(proxy, (Object[]) null);//new Object[] { args });
  50. }
  51. /**
  52. * Call void setAttribute( String ,Object )
  53. */
  54. public static void setAttribute(Object proxy, String n, Object v)
  55. throws Exception {
  56. if (proxy instanceof AttributeHolder) {
  57. ((AttributeHolder) proxy).setAttribute(n, v);
  58. return;
  59. }
  60. Method executeM = null;
  61. Class<?> c = proxy.getClass();
  62. Class<?> params[] = new Class[2];
  63. params[0] = String.class;
  64. params[1] = Object.class;
  65. executeM = findMethod(c, "setAttribute", params);
  66. if (executeM == null) {
  67. if (log.isDebugEnabled())
  68. log.debug("No setAttribute in " + proxy.getClass());
  69. return;
  70. }
  71. if (log.isDebugEnabled())
  72. log.debug("Setting " + n + "=" + v + " in " + proxy);
  73. executeM.invoke(proxy, new Object[] { n, v });
  74. return;
  75. }
  76. /**
  77. * Call void getAttribute( String )
  78. */
  79. public static Object getAttribute(Object proxy, String n) throws Exception {
  80. Method executeM = null;
  81. Class<?> c = proxy.getClass();
  82. Class<?> params[] = new Class[1];
  83. params[0] = String.class;
  84. executeM = findMethod(c, "getAttribute", params);
  85. if (executeM == null) {
  86. if (log.isDebugEnabled())
  87. log.debug("No getAttribute in " + proxy.getClass());
  88. return null;
  89. }
  90. return executeM.invoke(proxy, new Object[] { n });
  91. }
  92. /**
  93. * Construct a URLClassLoader. Will compile and work in JDK1.1 too.
  94. */
  95. public static ClassLoader getURLClassLoader(URL urls[], ClassLoader parent) {
  96. try {
  97. Class<?> urlCL = Class.forName("java.net.URLClassLoader");
  98. Class<?> paramT[] = new Class[2];
  99. paramT[0] = urls.getClass();
  100. paramT[1] = ClassLoader.class;
  101. Method m = findMethod(urlCL, "newInstance", paramT);
  102. if (m == null)
  103. return null;
  104. ClassLoader cl = (ClassLoader) m.invoke(urlCL, new Object[] { urls,
  105. parent });
  106. return cl;
  107. } catch (ClassNotFoundException ex) {
  108. // jdk1.1
  109. return null;
  110. } catch (Exception ex) {
  111. ex.printStackTrace();
  112. return null;
  113. }
  114. }
  115. public static String guessInstall(String installSysProp,
  116. String homeSysProp, String jarName) {
  117. return guessInstall(installSysProp, homeSysProp, jarName, null);
  118. }
  119. /**
  120. * Guess a product install/home by analyzing the class path. It works for
  121. * product using the pattern: lib/executable.jar or if executable.jar is
  122. * included in classpath by a shell script. ( java -jar also works )
  123. *
  124. * Insures both "install" and "home" System properties are set. If either or
  125. * both System properties are unset, "install" and "home" will be set to the
  126. * same value. This value will be the other System property that is set, or
  127. * the guessed value if neither is set.
  128. */
  129. public static String guessInstall(String installSysProp,
  130. String homeSysProp, String jarName, String classFile) {
  131. String install = null;
  132. String home = null;
  133. if (installSysProp != null)
  134. install = System.getProperty(installSysProp);
  135. if (homeSysProp != null)
  136. home = System.getProperty(homeSysProp);
  137. if (install != null) {
  138. if (home == null)
  139. System.getProperties().put(homeSysProp, install);
  140. return install;
  141. }
  142. // Find the directory where jarName.jar is located
  143. String cpath = System.getProperty("java.class.path");
  144. String pathSep = System.getProperty("path.separator");
  145. StringTokenizer st = new StringTokenizer(cpath, pathSep);
  146. while (st.hasMoreTokens()) {
  147. String path = st.nextToken();
  148. // log( "path " + path );
  149. if (path.endsWith(jarName)) {
  150. home = path.substring(0, path.length() - jarName.length());
  151. try {
  152. if ("".equals(home)) {
  153. home = new File("./").getCanonicalPath();
  154. } else if (home.endsWith(File.separator)) {
  155. home = home.substring(0, home.length() - 1);
  156. }
  157. File f = new File(home);
  158. String parentDir = f.getParent();
  159. if (parentDir == null)
  160. parentDir = home; // unix style
  161. File f1 = new File(parentDir);
  162. install = f1.getCanonicalPath();
  163. if (installSysProp != null)
  164. System.getProperties().put(installSysProp, install);
  165. if (home == null && homeSysProp != null)
  166. System.getProperties().put(homeSysProp, install);
  167. return install;
  168. } catch (Exception ex) {
  169. ex.printStackTrace();
  170. }
  171. } else {
  172. String fname = path + (path.endsWith("/") ? "" : "/")
  173. + classFile;
  174. if (new File(fname).exists()) {
  175. try {
  176. File f = new File(path);
  177. String parentDir = f.getParent();
  178. if (parentDir == null)
  179. parentDir = path; // unix style
  180. File f1 = new File(parentDir);
  181. install = f1.getCanonicalPath();
  182. if (installSysProp != null)
  183. System.getProperties().put(installSysProp, install);
  184. if (home == null && homeSysProp != null)
  185. System.getProperties().put(homeSysProp, install);
  186. return install;
  187. } catch (Exception ex) {
  188. ex.printStackTrace();
  189. }
  190. }
  191. }
  192. }
  193. // if install directory can't be found, use home as the default
  194. if (home != null) {
  195. System.getProperties().put(installSysProp, home);
  196. return home;
  197. }
  198. return null;
  199. }
  200. /**
  201. * Debug method, display the classpath
  202. */
  203. public static void displayClassPath(String msg, URL[] cp) {
  204. if (log.isDebugEnabled()) {
  205. log.debug(msg);
  206. for (int i = 0; i < cp.length; i++) {
  207. log.debug(cp[i].getFile());
  208. }
  209. }
  210. }
  211. public static final String PATH_SEPARATOR =
  212. System.getProperty("path.separator");
  213. /**
  214. * Adds classpath entries from a vector of URL's to the "tc_path_add" System
  215. * property. This System property lists the classpath entries common to web
  216. * applications. This System property is currently used by Jasper when its
  217. * JSP servlet compiles the Java file for a JSP.
  218. */
  219. public static String classPathAdd(URL urls[], String cp) {
  220. if (urls == null)
  221. return cp;
  222. for (int i = 0; i < urls.length; i++) {
  223. if (cp != null)
  224. cp += PATH_SEPARATOR + urls[i].getFile();
  225. else
  226. cp = urls[i].getFile();
  227. }
  228. return cp;
  229. }
  230. /**
  231. * Find a method with the right name If found, call the method ( if param is
  232. * int or boolean we'll convert value to the right type before) - that means
  233. * you can have setDebug(1).
  234. */
  235. public static boolean setProperty(Object o, String name, String value) {
  236. if (log.isDebugEnabled())
  237. log.debug("IntrospectionUtils: setProperty(" +
  238. o.getClass() + " " + name + "=" + value + ")");
  239. String setter = "set" + capitalize(name);
  240. try {
  241. Method methods[] = findMethods(o.getClass());
  242. Method setPropertyMethodVoid = null;
  243. Method setPropertyMethodBool = null;
  244. // First, the ideal case - a setFoo( String ) method
  245. for (int i = 0; i < methods.length; i++) {
  246. Class<?> paramT[] = methods[i].getParameterTypes();
  247. if (setter.equals(methods[i].getName()) && paramT.length == 1
  248. && "java.lang.String".equals(paramT[0].getName())) {
  249. methods[i].invoke(o, new Object[] { value });
  250. return true;
  251. }
  252. }
  253. // Try a setFoo ( int ) or ( boolean )
  254. for (int i = 0; i < methods.length; i++) {
  255. boolean ok = true;
  256. if (setter.equals(methods[i].getName())
  257. && methods[i].getParameterTypes().length == 1) {
  258. // match - find the type and invoke it
  259. Class<?> paramType = methods[i].getParameterTypes()[0];
  260. Object params[] = new Object[1];
  261. // Try a setFoo ( int )
  262. if ("java.lang.Integer".equals(paramType.getName())
  263. || "int".equals(paramType.getName())) {
  264. try {
  265. params[0] = new Integer(value);
  266. } catch (NumberFormatException ex) {
  267. ok = false;
  268. }
  269. // Try a setFoo ( long )
  270. }else if ("java.lang.Long".equals(paramType.getName())
  271. || "long".equals(paramType.getName())) {
  272. try {
  273. params[0] = new Long(value);
  274. } catch (NumberFormatException ex) {
  275. ok = false;
  276. }
  277. // Try a setFoo ( boolean )
  278. } else if ("java.lang.Boolean".equals(paramType.getName())
  279. || "boolean".equals(paramType.getName())) {
  280. params[0] = new Boolean(value);
  281. // Try a setFoo ( InetAddress )
  282. } else if ("java.net.InetAddress".equals(paramType
  283. .getName())) {
  284. try {
  285. params[0] = InetAddress.getByName(value);
  286. } catch (UnknownHostException exc) {
  287. if (log.isDebugEnabled())
  288. log.debug("IntrospectionUtils: Unable to resolve host name:" + value);
  289. ok = false;
  290. }
  291. // Unknown type
  292. } else {
  293. if (log.isDebugEnabled())
  294. log.debug("IntrospectionUtils: Unknown type " +
  295. paramType.getName());
  296. }
  297. if (ok) {
  298. methods[i].invoke(o, params);
  299. return true;
  300. }
  301. }
  302. // save "setProperty" for later
  303. if ("setProperty".equals(methods[i].getName())) {
  304. if (methods[i].getReturnType()==Boolean.TYPE){
  305. setPropertyMethodBool = methods[i];
  306. }else {
  307. setPropertyMethodVoid = methods[i];
  308. }
  309. }
  310. }
  311. // Ok, no setXXX found, try a setProperty("name", "value")
  312. if (setPropertyMethodBool != null || setPropertyMethodVoid != null) {
  313. Object params[] = new Object[2];
  314. params[0] = name;
  315. params[1] = value;
  316. if (setPropertyMethodBool != null) {
  317. try {
  318. return (Boolean) setPropertyMethodBool.invoke(o, params);
  319. }catch (IllegalArgumentException biae) {
  320. //the boolean method had the wrong
  321. //parameter types. lets try the other
  322. if (setPropertyMethodVoid!=null) {
  323. setPropertyMethodVoid.invoke(o, params);
  324. return true;
  325. }else {
  326. throw biae;
  327. }
  328. }
  329. } else {
  330. setPropertyMethodVoid.invoke(o, params);
  331. return true;
  332. }
  333. }
  334. } catch (IllegalArgumentException ex2) {
  335. log.warn("IAE " + o + " " + name + " " + value, ex2);
  336. } catch (SecurityException ex1) {
  337. if (log.isDebugEnabled())
  338. log.debug("IntrospectionUtils: SecurityException for " +
  339. o.getClass() + " " + name + "=" + value + ")", ex1);
  340. } catch (IllegalAccessException iae) {
  341. if (log.isDebugEnabled())
  342. log.debug("IntrospectionUtils: IllegalAccessException for " +
  343. o.getClass() + " " + name + "=" + value + ")", iae);
  344. } catch (InvocationTargetException ie) {
  345. if (log.isDebugEnabled())
  346. log.debug("IntrospectionUtils: InvocationTargetException for " +
  347. o.getClass() + " " + name + "=" + value + ")", ie);
  348. }
  349. return false;
  350. }
  351. public static Object getProperty(Object o, String name) {
  352. String getter = "get" + capitalize(name);
  353. String isGetter = "is" + capitalize(name);
  354. try {
  355. Method methods[] = findMethods(o.getClass());
  356. Method getPropertyMethod = null;
  357. // First, the ideal case - a getFoo() method
  358. for (int i = 0; i < methods.length; i++) {
  359. Class<?> paramT[] = methods[i].getParameterTypes();
  360. if (getter.equals(methods[i].getName()) && paramT.length == 0) {
  361. return methods[i].invoke(o, (Object[]) null);
  362. }
  363. if (isGetter.equals(methods[i].getName()) && paramT.length == 0) {
  364. return methods[i].invoke(o, (Object[]) null);
  365. }
  366. if ("getProperty".equals(methods[i].getName())) {
  367. getPropertyMethod = methods[i];
  368. }
  369. }
  370. // Ok, no setXXX found, try a getProperty("name")
  371. if (getPropertyMethod != null) {
  372. Object params[] = new Object[1];
  373. params[0] = name;
  374. return getPropertyMethod.invoke(o, params);
  375. }
  376. } catch (IllegalArgumentException ex2) {
  377. log.warn("IAE " + o + " " + name, ex2);
  378. } catch (SecurityException ex1) {
  379. if (log.isDebugEnabled())
  380. log.debug("IntrospectionUtils: SecurityException for " +
  381. o.getClass() + " " + name + ")", ex1);
  382. } catch (IllegalAccessException iae) {
  383. if (log.isDebugEnabled())
  384. log.debug("IntrospectionUtils: IllegalAccessException for " +
  385. o.getClass() + " " + name + ")", iae);
  386. } catch (InvocationTargetException ie) {
  387. if (log.isDebugEnabled())
  388. log.debug("IntrospectionUtils: InvocationTargetException for " +
  389. o.getClass() + " " + name + ")");
  390. }
  391. return null;
  392. }
  393. /**
  394. */
  395. public static void setProperty(Object o, String name) {
  396. String setter = "set" + capitalize(name);
  397. try {
  398. Method methods[] = findMethods(o.getClass());
  399. // find setFoo() method
  400. for (int i = 0; i < methods.length; i++) {
  401. Class<?> paramT[] = methods[i].getParameterTypes();
  402. if (setter.equals(methods[i].getName()) && paramT.length == 0) {
  403. methods[i].invoke(o, new Object[] {});
  404. return;
  405. }
  406. }
  407. } catch (Exception ex1) {
  408. if (log.isDebugEnabled())
  409. log.debug("IntrospectionUtils: Exception for " +
  410. o.getClass() + " " + name, ex1);
  411. }
  412. }
  413. /**
  414. * Replace ${NAME} with the property value
  415. */
  416. public static String replaceProperties(String value,
  417. Hashtable<Object,Object> staticProp, PropertySource dynamicProp[]) {
  418. if (value.indexOf("$") < 0) {
  419. return value;
  420. }
  421. StringBuilder sb = new StringBuilder();
  422. int prev = 0;
  423. // assert value!=nil
  424. int pos;
  425. while ((pos = value.indexOf("$", prev)) >= 0) {
  426. if (pos > 0) {
  427. sb.append(value.substring(prev, pos));
  428. }
  429. if (pos == (value.length() - 1)) {
  430. sb.append('$');
  431. prev = pos + 1;
  432. } else if (value.charAt(pos + 1) != '{') {
  433. sb.append('$');
  434. prev = pos + 1; // XXX
  435. } else {
  436. int endName = value.indexOf('}', pos);
  437. if (endName < 0) {
  438. sb.append(value.substring(pos));
  439. prev = value.length();
  440. continue;
  441. }
  442. String n = value.substring(pos + 2, endName);
  443. String v = null;
  444. if (staticProp != null) {
  445. v = (String) staticProp.get(n);
  446. }
  447. if (v == null && dynamicProp != null) {
  448. for (int i = 0; i < dynamicProp.length; i++) {
  449. v = dynamicProp[i].getProperty(n);
  450. if (v != null) {
  451. break;
  452. }
  453. }
  454. }
  455. if (v == null)
  456. v = "${" + n + "}";
  457. sb.append(v);
  458. prev = endName + 1;
  459. }
  460. }
  461. if (prev < value.length())
  462. sb.append(value.substring(prev));
  463. return sb.toString();
  464. }
  465. /**
  466. * Reverse of Introspector.decapitalize
  467. */
  468. public static String capitalize(String name) {
  469. if (name == null || name.length() == 0) {
  470. return name;
  471. }
  472. char chars[] = name.toCharArray();
  473. chars[0] = Character.toUpperCase(chars[0]);
  474. return new String(chars);
  475. }
  476. public static String unCapitalize(String name) {
  477. if (name == null || name.length() == 0) {
  478. return name;
  479. }
  480. char chars[] = name.toCharArray();
  481. chars[0] = Character.toLowerCase(chars[0]);
  482. return new String(chars);
  483. }
  484. // -------------------- Class path tools --------------------
  485. /**
  486. * Add all the jar files in a dir to the classpath, represented as a Vector
  487. * of URLs.
  488. */
  489. public static void addToClassPath(Vector<URL> cpV, String dir) {
  490. try {
  491. String cpComp[] = getFilesByExt(dir, ".jar");
  492. if (cpComp != null) {
  493. int jarCount = cpComp.length;
  494. for (int i = 0; i < jarCount; i++) {
  495. URL url = getURL(dir, cpComp[i]);
  496. if (url != null)
  497. cpV.addElement(url);
  498. }
  499. }
  500. } catch (Exception ex) {
  501. ex.printStackTrace();
  502. }
  503. }
  504. public static void addToolsJar(Vector<URL> v) {
  505. try {
  506. // Add tools.jar in any case
  507. File f = new File(System.getProperty("java.home")
  508. + "/../lib/tools.jar");
  509. if (!f.exists()) {
  510. // On some systems java.home gets set to the root of jdk.
  511. // That's a bug, but we can work around and be nice.
  512. f = new File(System.getProperty("java.home") + "/lib/tools.jar");
  513. if (f.exists()) {
  514. if (log.isDebugEnabled())
  515. log.debug("Detected strange java.home value "
  516. + System.getProperty("java.home")
  517. + ", it should point to jre");
  518. }
  519. }
  520. URL url = new URL("file", "", f.getAbsolutePath());
  521. v.addElement(url);
  522. } catch (MalformedURLException ex) {
  523. ex.printStackTrace();
  524. }
  525. }
  526. /**
  527. * Return all files with a given extension in a dir
  528. */
  529. public static String[] getFilesByExt(String ld, String ext) {
  530. File dir = new File(ld);
  531. String[] names = null;
  532. final String lext = ext;
  533. if (dir.isDirectory()) {
  534. names = dir.list(new FilenameFilter() {
  535. public boolean accept(File d, String name) {
  536. if (name.endsWith(lext)) {
  537. return true;
  538. }
  539. return false;
  540. }
  541. });
  542. }
  543. return names;
  544. }
  545. /**
  546. * Construct a file url from a file, using a base dir
  547. */
  548. public static URL getURL(String base, String file) {
  549. try {
  550. File baseF = new File(base);
  551. File f = new File(baseF, file);
  552. String path = f.getCanonicalPath();
  553. if (f.isDirectory()) {
  554. path += "/";
  555. }
  556. if (!f.exists())
  557. return null;
  558. return new URL("file", "", path);
  559. } catch (Exception ex) {
  560. ex.printStackTrace();
  561. return null;
  562. }
  563. }
  564. /**
  565. * Add elements from the classpath <i>cp </i> to a Vector <i>jars </i> as
  566. * file URLs (We use Vector for JDK 1.1 compat).
  567. * <p>
  568. *
  569. * @param jars The jar list
  570. * @param cp a String classpath of directory or jar file elements
  571. * separated by path.separator delimiters.
  572. * @throws IOException If an I/O error occurs
  573. * @throws MalformedURLException Doh ;)
  574. */
  575. public static void addJarsFromClassPath(Vector<URL> jars, String cp)
  576. throws IOException, MalformedURLException {
  577. String sep = System.getProperty("path.separator");
  578. StringTokenizer st;
  579. if (cp != null) {
  580. st = new StringTokenizer(cp, sep);
  581. while (st.hasMoreTokens()) {
  582. File f = new File(st.nextToken());
  583. String path = f.getCanonicalPath();
  584. if (f.isDirectory()) {
  585. path += "/";
  586. }
  587. URL url = new URL("file", "", path);
  588. if (!jars.contains(url)) {
  589. jars.addElement(url);
  590. }
  591. }
  592. }
  593. }
  594. /**
  595. * Return a URL[] that can be used to construct a class loader
  596. */
  597. public static URL[] getClassPath(Vector<URL> v) {
  598. URL[] urls = new URL[v.size()];
  599. for (int i = 0; i < v.size(); i++) {
  600. urls[i] = v.elementAt(i);
  601. }
  602. return urls;
  603. }
  604. /**
  605. * Construct a URL classpath from files in a directory, a cpath property,
  606. * and tools.jar.
  607. */
  608. public static URL[] getClassPath(String dir, String cpath,
  609. String cpathProp, boolean addTools) throws IOException,
  610. MalformedURLException {
  611. Vector<URL> jarsV = new Vector<URL>();
  612. if (dir != null) {
  613. // Add dir/classes first, if it exists
  614. URL url = getURL(dir, "classes");
  615. if (url != null)
  616. jarsV.addElement(url);
  617. addToClassPath(jarsV, dir);
  618. }
  619. if (cpath != null)
  620. addJarsFromClassPath(jarsV, cpath);
  621. if (cpathProp != null) {
  622. String cpath1 = System.getProperty(cpathProp);
  623. addJarsFromClassPath(jarsV, cpath1);
  624. }
  625. if (addTools)
  626. addToolsJar(jarsV);
  627. return getClassPath(jarsV);
  628. }
  629. // -------------------- other utils --------------------
  630. public static void clear() {
  631. objectMethods.clear();
  632. }
  633. static Hashtable<Class<?>,Method[]> objectMethods =
  634. new Hashtable<Class<?>,Method[]>();
  635. public static Method[] findMethods(Class<?> c) {
  636. Method methods[] = objectMethods.get(c);
  637. if (methods != null)
  638. return methods;
  639. methods = c.getMethods();
  640. objectMethods.put(c, methods);
  641. return methods;
  642. }
  643. public static Method findMethod(Class<?> c, String name,
  644. Class<?> params[]) {
  645. Method methods[] = findMethods(c);
  646. if (methods == null)
  647. return null;
  648. for (int i = 0; i < methods.length; i++) {
  649. if (methods[i].getName().equals(name)) {
  650. Class<?> methodParams[] = methods[i].getParameterTypes();
  651. if (methodParams == null)
  652. if (params == null || params.length == 0)
  653. return methods[i];
  654. if (params == null)
  655. if (methodParams == null || methodParams.length == 0)
  656. return methods[i];
  657. if (params.length != methodParams.length)
  658. continue;
  659. boolean found = true;
  660. for (int j = 0; j < params.length; j++) {
  661. if (params[j] != methodParams[j]) {
  662. found = false;
  663. break;
  664. }
  665. }
  666. if (found)
  667. return methods[i];
  668. }
  669. }
  670. return null;
  671. }
  672. /** Test if the object implements a particular
  673. * method
  674. */
  675. public static boolean hasHook(Object obj, String methodN) {
  676. try {
  677. Method myMethods[] = findMethods(obj.getClass());
  678. for (int i = 0; i < myMethods.length; i++) {
  679. if (methodN.equals(myMethods[i].getName())) {
  680. // check if it's overriden
  681. Class<?> declaring = myMethods[i].getDeclaringClass();
  682. Class<?> parentOfDeclaring = declaring.getSuperclass();
  683. // this works only if the base class doesn't extend
  684. // another class.
  685. // if the method is declared in a top level class
  686. // like BaseInterceptor parent is Object, otherwise
  687. // parent is BaseInterceptor or an intermediate class
  688. if (!"java.lang.Object".equals(parentOfDeclaring.getName())) {
  689. return true;
  690. }
  691. }
  692. }
  693. } catch (Exception ex) {
  694. ex.printStackTrace();
  695. }
  696. return false;
  697. }
  698. public static void callMain(Class<?> c, String args[]) throws Exception {
  699. Class<?> p[] = new Class[1];
  700. p[0] = args.getClass();
  701. Method m = c.getMethod("main", p);
  702. m.invoke(c, new Object[] { args });
  703. }
  704. public static Object callMethod1(Object target, String methodN,
  705. Object param1, String typeParam1, ClassLoader cl) throws Exception {
  706. if (target == null || param1 == null) {
  707. if (log.isDebugEnabled())
  708. log.debug("IntrospectionUtils: Assert: Illegal params " +
  709. target + " " + param1);
  710. }
  711. if (log.isDebugEnabled())
  712. log.debug("IntrospectionUtils: callMethod1 " +
  713. target.getClass().getName() + " " +
  714. param1.getClass().getName() + " " + typeParam1);
  715. Class<?> params[] = new Class[1];
  716. if (typeParam1 == null)
  717. params[0] = param1.getClass();
  718. else
  719. params[0] = cl.loadClass(typeParam1);
  720. Method m = findMethod(target.getClass(), methodN, params);
  721. if (m == null)
  722. throw new NoSuchMethodException(target.getClass().getName() + " "
  723. + methodN);
  724. return m.invoke(target, new Object[] { param1 });
  725. }
  726. public static Object callMethod0(Object target, String methodN)
  727. throws Exception {
  728. if (target == null) {
  729. if (log.isDebugEnabled())
  730. log.debug("IntrospectionUtils: Assert: Illegal params " +
  731. target);
  732. return null;
  733. }
  734. if (log.isDebugEnabled())
  735. log.debug("IntrospectionUtils: callMethod0 " +
  736. target.getClass().getName() + "." + methodN);
  737. Class<?> params[] = new Class[0];
  738. Method m = findMethod(target.getClass(), methodN, params);
  739. if (m == null)
  740. throw new NoSuchMethodException(target.getClass().getName() + " "
  741. + methodN);
  742. return m.invoke(target, emptyArray);
  743. }
  744. static Object[] emptyArray = new Object[] {};
  745. public static Object callMethodN(Object target, String methodN,
  746. Object params[], Class<?> typeParams[]) throws Exception {
  747. Method m = null;
  748. m = findMethod(target.getClass(), methodN, typeParams);
  749. if (m == null) {
  750. if (log.isDebugEnabled())
  751. log.debug("IntrospectionUtils: Can't find method " + methodN +
  752. " in " + target + " CLASS " + target.getClass());
  753. return null;
  754. }
  755. Object o = m.invoke(target, params);
  756. if (log.isDebugEnabled()) {
  757. // debug
  758. StringBuilder sb = new StringBuilder();
  759. sb.append("" + target.getClass().getName() + "." + methodN + "( ");
  760. for (int i = 0; i < params.length; i++) {
  761. if (i > 0)
  762. sb.append(", ");
  763. sb.append(params[i]);
  764. }
  765. sb.append(")");
  766. log.debug("IntrospectionUtils:" + sb.toString());
  767. }
  768. return o;
  769. }
  770. public static Object convert(String object, Class<?> paramType) {
  771. Object result = null;
  772. if ("java.lang.String".equals(paramType.getName())) {
  773. result = object;
  774. } else if ("java.lang.Integer".equals(paramType.getName())
  775. || "int".equals(paramType.getName())) {
  776. try {
  777. result = new Integer(object);
  778. } catch (NumberFormatException ex) {
  779. }
  780. // Try a setFoo ( boolean )
  781. } else if ("java.lang.Boolean".equals(paramType.getName())
  782. || "boolean".equals(paramType.getName())) {
  783. result = new Boolean(object);
  784. // Try a setFoo ( InetAddress )
  785. } else if ("java.net.InetAddress".equals(paramType
  786. .getName())) {
  787. try {
  788. result = InetAddress.getByName(object);
  789. } catch (UnknownHostException exc) {
  790. if (log.isDebugEnabled())
  791. log.debug("IntrospectionUtils: Unable to resolve host name:" +
  792. object);
  793. }
  794. // Unknown type
  795. } else {
  796. if (log.isDebugEnabled())
  797. log.debug("IntrospectionUtils: Unknown type " +
  798. paramType.getName());
  799. }
  800. if (result == null) {
  801. throw new IllegalArgumentException("Can't convert argument: " + object);
  802. }
  803. return result;
  804. }
  805. // -------------------- Get property --------------------
  806. // This provides a layer of abstraction
  807. public static interface PropertySource {
  808. public String getProperty(String key);
  809. }
  810. public static interface AttributeHolder {
  811. public void setAttribute(String key, Object o);
  812. }
  813. }