PageRenderTime 70ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/projects/tomcat-7.0.2/java/org/apache/tomcat/util/IntrospectionUtils.java

https://gitlab.com/essere.lab.public/qualitas.class-corpus
Java | 909 lines | 683 code | 92 blank | 134 comment | 226 complexity | 95371f42b62052aeca4f49874d537013 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.tomcat.util;
  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 final static String PATH_SEPARATOR = System.getProperty("path.separator");
  212. /**
  213. * Adds classpath entries from a vector of URL's to the "tc_path_add" System
  214. * property. This System property lists the classpath entries common to web
  215. * applications. This System property is currently used by Jasper when its
  216. * JSP servlet compiles the Java file for a JSP.
  217. */
  218. public static String classPathAdd(URL urls[], String cp) {
  219. if (urls == null)
  220. return cp;
  221. for (int i = 0; i < urls.length; i++) {
  222. if (cp != null)
  223. cp += PATH_SEPARATOR + urls[i].getFile();
  224. else
  225. cp = urls[i].getFile();
  226. }
  227. return cp;
  228. }
  229. /**
  230. * Find a method with the right name If found, call the method ( if param is
  231. * int or boolean we'll convert value to the right type before) - that means
  232. * you can have setDebug(1).
  233. */
  234. public static boolean setProperty(Object o, String name, String value) {
  235. return setProperty(o,name,value,true);
  236. }
  237. public static boolean setProperty(Object o, String name, String value,
  238. boolean invokeSetProperty) {
  239. if (log.isDebugEnabled())
  240. log.debug("IntrospectionUtils: setProperty(" +
  241. o.getClass() + " " + name + "=" + value + ")");
  242. String setter = "set" + capitalize(name);
  243. try {
  244. Method methods[] = findMethods(o.getClass());
  245. Method setPropertyMethodVoid = null;
  246. Method setPropertyMethodBool = null;
  247. // First, the ideal case - a setFoo( String ) method
  248. for (int i = 0; i < methods.length; i++) {
  249. Class<?> paramT[] = methods[i].getParameterTypes();
  250. if (setter.equals(methods[i].getName()) && paramT.length == 1
  251. && "java.lang.String".equals(paramT[0].getName())) {
  252. methods[i].invoke(o, new Object[] { value });
  253. return true;
  254. }
  255. }
  256. // Try a setFoo ( int ) or ( boolean )
  257. for (int i = 0; i < methods.length; i++) {
  258. boolean ok = true;
  259. if (setter.equals(methods[i].getName())
  260. && methods[i].getParameterTypes().length == 1) {
  261. // match - find the type and invoke it
  262. Class<?> paramType = methods[i].getParameterTypes()[0];
  263. Object params[] = new Object[1];
  264. // Try a setFoo ( int )
  265. if ("java.lang.Integer".equals(paramType.getName())
  266. || "int".equals(paramType.getName())) {
  267. try {
  268. params[0] = new Integer(value);
  269. } catch (NumberFormatException ex) {
  270. ok = false;
  271. }
  272. // Try a setFoo ( long )
  273. }else if ("java.lang.Long".equals(paramType.getName())
  274. || "long".equals(paramType.getName())) {
  275. try {
  276. params[0] = new Long(value);
  277. } catch (NumberFormatException ex) {
  278. ok = false;
  279. }
  280. // Try a setFoo ( boolean )
  281. } else if ("java.lang.Boolean".equals(paramType.getName())
  282. || "boolean".equals(paramType.getName())) {
  283. params[0] = new Boolean(value);
  284. // Try a setFoo ( InetAddress )
  285. } else if ("java.net.InetAddress".equals(paramType
  286. .getName())) {
  287. try {
  288. params[0] = InetAddress.getByName(value);
  289. } catch (UnknownHostException exc) {
  290. if (log.isDebugEnabled())
  291. log.debug("IntrospectionUtils: Unable to resolve host name:" + value);
  292. ok = false;
  293. }
  294. // Unknown type
  295. } else {
  296. if (log.isDebugEnabled())
  297. log.debug("IntrospectionUtils: Unknown type " +
  298. paramType.getName());
  299. }
  300. if (ok) {
  301. methods[i].invoke(o, params);
  302. return true;
  303. }
  304. }
  305. // save "setProperty" for later
  306. if ("setProperty".equals(methods[i].getName())) {
  307. if (methods[i].getReturnType()==Boolean.TYPE){
  308. setPropertyMethodBool = methods[i];
  309. }else {
  310. setPropertyMethodVoid = methods[i];
  311. }
  312. }
  313. }
  314. // Ok, no setXXX found, try a setProperty("name", "value")
  315. if (invokeSetProperty && (setPropertyMethodBool != null ||
  316. setPropertyMethodVoid != null)) {
  317. Object params[] = new Object[2];
  318. params[0] = name;
  319. params[1] = value;
  320. if (setPropertyMethodBool != null) {
  321. try {
  322. return (Boolean) setPropertyMethodBool.invoke(o, params);
  323. }catch (IllegalArgumentException biae) {
  324. //the boolean method had the wrong
  325. //parameter types. lets try the other
  326. if (setPropertyMethodVoid!=null) {
  327. setPropertyMethodVoid.invoke(o, params);
  328. return true;
  329. }else {
  330. throw biae;
  331. }
  332. }
  333. } else {
  334. setPropertyMethodVoid.invoke(o, params);
  335. return true;
  336. }
  337. }
  338. } catch (IllegalArgumentException ex2) {
  339. log.warn("IAE " + o + " " + name + " " + value, ex2);
  340. } catch (SecurityException ex1) {
  341. if (log.isDebugEnabled())
  342. log.debug("IntrospectionUtils: SecurityException for " +
  343. o.getClass() + " " + name + "=" + value + ")", ex1);
  344. } catch (IllegalAccessException iae) {
  345. if (log.isDebugEnabled())
  346. log.debug("IntrospectionUtils: IllegalAccessException for " +
  347. o.getClass() + " " + name + "=" + value + ")", iae);
  348. } catch (InvocationTargetException ie) {
  349. if (log.isDebugEnabled())
  350. log.debug("IntrospectionUtils: InvocationTargetException for " +
  351. o.getClass() + " " + name + "=" + value + ")", ie);
  352. }
  353. return false;
  354. }
  355. public static Object getProperty(Object o, String name) {
  356. String getter = "get" + capitalize(name);
  357. String isGetter = "is" + capitalize(name);
  358. try {
  359. Method methods[] = findMethods(o.getClass());
  360. Method getPropertyMethod = null;
  361. // First, the ideal case - a getFoo() method
  362. for (int i = 0; i < methods.length; i++) {
  363. Class<?> paramT[] = methods[i].getParameterTypes();
  364. if (getter.equals(methods[i].getName()) && paramT.length == 0) {
  365. return methods[i].invoke(o, (Object[]) null);
  366. }
  367. if (isGetter.equals(methods[i].getName()) && paramT.length == 0) {
  368. return methods[i].invoke(o, (Object[]) null);
  369. }
  370. if ("getProperty".equals(methods[i].getName())) {
  371. getPropertyMethod = methods[i];
  372. }
  373. }
  374. // Ok, no setXXX found, try a getProperty("name")
  375. if (getPropertyMethod != null) {
  376. Object params[] = new Object[1];
  377. params[0] = name;
  378. return getPropertyMethod.invoke(o, params);
  379. }
  380. } catch (IllegalArgumentException ex2) {
  381. log.warn("IAE " + o + " " + name, ex2);
  382. } catch (SecurityException ex1) {
  383. if (log.isDebugEnabled())
  384. log.debug("IntrospectionUtils: SecurityException for " +
  385. o.getClass() + " " + name + ")", ex1);
  386. } catch (IllegalAccessException iae) {
  387. if (log.isDebugEnabled())
  388. log.debug("IntrospectionUtils: IllegalAccessException for " +
  389. o.getClass() + " " + name + ")", iae);
  390. } catch (InvocationTargetException ie) {
  391. if (log.isDebugEnabled())
  392. log.debug("IntrospectionUtils: InvocationTargetException for " +
  393. o.getClass() + " " + name + ")");
  394. }
  395. return null;
  396. }
  397. /**
  398. */
  399. public static void setProperty(Object o, String name) {
  400. String setter = "set" + capitalize(name);
  401. try {
  402. Method methods[] = findMethods(o.getClass());
  403. // find setFoo() method
  404. for (int i = 0; i < methods.length; i++) {
  405. Class<?> paramT[] = methods[i].getParameterTypes();
  406. if (setter.equals(methods[i].getName()) && paramT.length == 0) {
  407. methods[i].invoke(o, new Object[] {});
  408. return;
  409. }
  410. }
  411. } catch (Exception ex1) {
  412. if (log.isDebugEnabled())
  413. log.debug("IntrospectionUtils: Exception for " +
  414. o.getClass() + " " + name, ex1);
  415. }
  416. }
  417. /**
  418. * Replace ${NAME} with the property value
  419. */
  420. public static String replaceProperties(String value,
  421. Hashtable<Object,Object> staticProp, PropertySource dynamicProp[]) {
  422. if (value.indexOf("$") < 0) {
  423. return value;
  424. }
  425. StringBuilder sb = new StringBuilder();
  426. int prev = 0;
  427. // assert value!=nil
  428. int pos;
  429. while ((pos = value.indexOf("$", prev)) >= 0) {
  430. if (pos > 0) {
  431. sb.append(value.substring(prev, pos));
  432. }
  433. if (pos == (value.length() - 1)) {
  434. sb.append('$');
  435. prev = pos + 1;
  436. } else if (value.charAt(pos + 1) != '{') {
  437. sb.append('$');
  438. prev = pos + 1; // XXX
  439. } else {
  440. int endName = value.indexOf('}', pos);
  441. if (endName < 0) {
  442. sb.append(value.substring(pos));
  443. prev = value.length();
  444. continue;
  445. }
  446. String n = value.substring(pos + 2, endName);
  447. String v = null;
  448. if (staticProp != null) {
  449. v = (String) staticProp.get(n);
  450. }
  451. if (v == null && dynamicProp != null) {
  452. for (int i = 0; i < dynamicProp.length; i++) {
  453. v = dynamicProp[i].getProperty(n);
  454. if (v != null) {
  455. break;
  456. }
  457. }
  458. }
  459. if (v == null)
  460. v = "${" + n + "}";
  461. sb.append(v);
  462. prev = endName + 1;
  463. }
  464. }
  465. if (prev < value.length())
  466. sb.append(value.substring(prev));
  467. return sb.toString();
  468. }
  469. /**
  470. * Reverse of Introspector.decapitalize
  471. */
  472. public static String capitalize(String name) {
  473. if (name == null || name.length() == 0) {
  474. return name;
  475. }
  476. char chars[] = name.toCharArray();
  477. chars[0] = Character.toUpperCase(chars[0]);
  478. return new String(chars);
  479. }
  480. public static String unCapitalize(String name) {
  481. if (name == null || name.length() == 0) {
  482. return name;
  483. }
  484. char chars[] = name.toCharArray();
  485. chars[0] = Character.toLowerCase(chars[0]);
  486. return new String(chars);
  487. }
  488. // -------------------- Class path tools --------------------
  489. /**
  490. * Add all the jar files in a dir to the classpath, represented as a Vector
  491. * of URLs.
  492. */
  493. public static void addToClassPath(Vector<URL> cpV, String dir) {
  494. try {
  495. String cpComp[] = getFilesByExt(dir, ".jar");
  496. if (cpComp != null) {
  497. int jarCount = cpComp.length;
  498. for (int i = 0; i < jarCount; i++) {
  499. URL url = getURL(dir, cpComp[i]);
  500. if (url != null)
  501. cpV.addElement(url);
  502. }
  503. }
  504. } catch (Exception ex) {
  505. ex.printStackTrace();
  506. }
  507. }
  508. public static void addToolsJar(Vector<URL> v) {
  509. try {
  510. // Add tools.jar in any case
  511. File f = new File(System.getProperty("java.home")
  512. + "/../lib/tools.jar");
  513. if (!f.exists()) {
  514. // On some systems java.home gets set to the root of jdk.
  515. // That's a bug, but we can work around and be nice.
  516. f = new File(System.getProperty("java.home") + "/lib/tools.jar");
  517. if (f.exists()) {
  518. if (log.isDebugEnabled())
  519. log.debug("Detected strange java.home value "
  520. + System.getProperty("java.home")
  521. + ", it should point to jre");
  522. }
  523. }
  524. URL url = new URL("file", "", f.getAbsolutePath());
  525. v.addElement(url);
  526. } catch (MalformedURLException ex) {
  527. ex.printStackTrace();
  528. }
  529. }
  530. /**
  531. * Return all files with a given extension in a dir
  532. */
  533. public static String[] getFilesByExt(String ld, String ext) {
  534. File dir = new File(ld);
  535. String[] names = null;
  536. final String lext = ext;
  537. if (dir.isDirectory()) {
  538. names = dir.list(new FilenameFilter() {
  539. public boolean accept(File d, String name) {
  540. if (name.endsWith(lext)) {
  541. return true;
  542. }
  543. return false;
  544. }
  545. });
  546. }
  547. return names;
  548. }
  549. /**
  550. * Construct a file url from a file, using a base dir
  551. */
  552. public static URL getURL(String base, String file) {
  553. try {
  554. File baseF = new File(base);
  555. File f = new File(baseF, file);
  556. String path = f.getCanonicalPath();
  557. if (f.isDirectory()) {
  558. path += "/";
  559. }
  560. if (!f.exists())
  561. return null;
  562. return new URL("file", "", path);
  563. } catch (Exception ex) {
  564. ex.printStackTrace();
  565. return null;
  566. }
  567. }
  568. /**
  569. * Add elements from the classpath <i>cp </i> to a Vector <i>jars </i> as
  570. * file URLs (We use Vector for JDK 1.1 compat).
  571. * <p>
  572. *
  573. * @param jars The jar list
  574. * @param cp a String classpath of directory or jar file elements
  575. * separated by path.separator delimiters.
  576. * @throws IOException If an I/O error occurs
  577. * @throws MalformedURLException Doh ;)
  578. */
  579. public static void addJarsFromClassPath(Vector<URL> jars, String cp)
  580. throws IOException, MalformedURLException {
  581. String sep = System.getProperty("path.separator");
  582. StringTokenizer st;
  583. if (cp != null) {
  584. st = new StringTokenizer(cp, sep);
  585. while (st.hasMoreTokens()) {
  586. File f = new File(st.nextToken());
  587. String path = f.getCanonicalPath();
  588. if (f.isDirectory()) {
  589. path += "/";
  590. }
  591. URL url = new URL("file", "", path);
  592. if (!jars.contains(url)) {
  593. jars.addElement(url);
  594. }
  595. }
  596. }
  597. }
  598. /**
  599. * Return a URL[] that can be used to construct a class loader
  600. */
  601. public static URL[] getClassPath(Vector<URL> v) {
  602. URL[] urls = new URL[v.size()];
  603. for (int i = 0; i < v.size(); i++) {
  604. urls[i] = v.elementAt(i);
  605. }
  606. return urls;
  607. }
  608. /**
  609. * Construct a URL classpath from files in a directory, a cpath property,
  610. * and tools.jar.
  611. */
  612. public static URL[] getClassPath(String dir, String cpath,
  613. String cpathProp, boolean addTools) throws IOException,
  614. MalformedURLException {
  615. Vector<URL> jarsV = new Vector<URL>();
  616. if (dir != null) {
  617. // Add dir/classes first, if it exists
  618. URL url = getURL(dir, "classes");
  619. if (url != null)
  620. jarsV.addElement(url);
  621. addToClassPath(jarsV, dir);
  622. }
  623. if (cpath != null)
  624. addJarsFromClassPath(jarsV, cpath);
  625. if (cpathProp != null) {
  626. String cpath1 = System.getProperty(cpathProp);
  627. addJarsFromClassPath(jarsV, cpath1);
  628. }
  629. if (addTools)
  630. addToolsJar(jarsV);
  631. return getClassPath(jarsV);
  632. }
  633. // -------------------- other utils --------------------
  634. public static void clear() {
  635. objectMethods.clear();
  636. }
  637. static Hashtable<Class<?>,Method[]> objectMethods =
  638. new Hashtable<Class<?>,Method[]>();
  639. public static Method[] findMethods(Class<?> c) {
  640. Method methods[] = objectMethods.get(c);
  641. if (methods != null)
  642. return methods;
  643. methods = c.getMethods();
  644. objectMethods.put(c, methods);
  645. return methods;
  646. }
  647. public static Method findMethod(Class<?> c, String name,
  648. Class<?> params[]) {
  649. Method methods[] = findMethods(c);
  650. if (methods == null)
  651. return null;
  652. for (int i = 0; i < methods.length; i++) {
  653. if (methods[i].getName().equals(name)) {
  654. Class<?> methodParams[] = methods[i].getParameterTypes();
  655. if (methodParams == null)
  656. if (params == null || params.length == 0)
  657. return methods[i];
  658. if (params == null)
  659. if (methodParams == null || methodParams.length == 0)
  660. return methods[i];
  661. if (params.length != methodParams.length)
  662. continue;
  663. boolean found = true;
  664. for (int j = 0; j < params.length; j++) {
  665. if (params[j] != methodParams[j]) {
  666. found = false;
  667. break;
  668. }
  669. }
  670. if (found)
  671. return methods[i];
  672. }
  673. }
  674. return null;
  675. }
  676. /** Test if the object implements a particular
  677. * method
  678. */
  679. public static boolean hasHook(Object obj, String methodN) {
  680. try {
  681. Method myMethods[] = findMethods(obj.getClass());
  682. for (int i = 0; i < myMethods.length; i++) {
  683. if (methodN.equals(myMethods[i].getName())) {
  684. // check if it's overridden
  685. Class<?> declaring = myMethods[i].getDeclaringClass();
  686. Class<?> parentOfDeclaring = declaring.getSuperclass();
  687. // this works only if the base class doesn't extend
  688. // another class.
  689. // if the method is declared in a top level class
  690. // like BaseInterceptor parent is Object, otherwise
  691. // parent is BaseInterceptor or an intermediate class
  692. if (!"java.lang.Object".equals(parentOfDeclaring.getName())) {
  693. return true;
  694. }
  695. }
  696. }
  697. } catch (Exception ex) {
  698. ex.printStackTrace();
  699. }
  700. return false;
  701. }
  702. public static void callMain(Class<?> c, String args[]) throws Exception {
  703. Class<?> p[] = new Class[1];
  704. p[0] = args.getClass();
  705. Method m = c.getMethod("main", p);
  706. m.invoke(c, new Object[] { args });
  707. }
  708. public static Object callMethod1(Object target, String methodN,
  709. Object param1, String typeParam1, ClassLoader cl) throws Exception {
  710. if (target == null || param1 == null) {
  711. if (log.isDebugEnabled())
  712. log.debug("IntrospectionUtils: Assert: Illegal params " +
  713. target + " " + param1);
  714. }
  715. if (log.isDebugEnabled())
  716. log.debug("IntrospectionUtils: callMethod1 " +
  717. target.getClass().getName() + " " +
  718. param1.getClass().getName() + " " + typeParam1);
  719. Class<?> params[] = new Class[1];
  720. if (typeParam1 == null)
  721. params[0] = param1.getClass();
  722. else
  723. params[0] = cl.loadClass(typeParam1);
  724. Method m = findMethod(target.getClass(), methodN, params);
  725. if (m == null)
  726. throw new NoSuchMethodException(target.getClass().getName() + " "
  727. + methodN);
  728. return m.invoke(target, new Object[] { param1 });
  729. }
  730. public static Object callMethod0(Object target, String methodN)
  731. throws Exception {
  732. if (target == null) {
  733. if (log.isDebugEnabled())
  734. log.debug("IntrospectionUtils: Assert: Illegal params " +
  735. target);
  736. return null;
  737. }
  738. if (log.isDebugEnabled())
  739. log.debug("IntrospectionUtils: callMethod0 " +
  740. target.getClass().getName() + "." + methodN);
  741. Class<?> params[] = new Class[0];
  742. Method m = findMethod(target.getClass(), methodN, params);
  743. if (m == null)
  744. throw new NoSuchMethodException(target.getClass().getName() + " "
  745. + methodN);
  746. return m.invoke(target, emptyArray);
  747. }
  748. static Object[] emptyArray = new Object[] {};
  749. public static Object callMethodN(Object target, String methodN,
  750. Object params[], Class<?> typeParams[]) throws Exception {
  751. Method m = null;
  752. m = findMethod(target.getClass(), methodN, typeParams);
  753. if (m == null) {
  754. if (log.isDebugEnabled())
  755. log.debug("IntrospectionUtils: Can't find method " + methodN +
  756. " in " + target + " CLASS " + target.getClass());
  757. return null;
  758. }
  759. Object o = m.invoke(target, params);
  760. if (log.isDebugEnabled()) {
  761. // debug
  762. StringBuilder sb = new StringBuilder();
  763. sb.append("" + target.getClass().getName() + "." + methodN + "( ");
  764. for (int i = 0; i < params.length; i++) {
  765. if (i > 0)
  766. sb.append(", ");
  767. sb.append(params[i]);
  768. }
  769. sb.append(")");
  770. log.debug("IntrospectionUtils:" + sb.toString());
  771. }
  772. return o;
  773. }
  774. public static Object convert(String object, Class<?> paramType) {
  775. Object result = null;
  776. if ("java.lang.String".equals(paramType.getName())) {
  777. result = object;
  778. } else if ("java.lang.Integer".equals(paramType.getName())
  779. || "int".equals(paramType.getName())) {
  780. try {
  781. result = new Integer(object);
  782. } catch (NumberFormatException ex) {
  783. }
  784. // Try a setFoo ( boolean )
  785. } else if ("java.lang.Boolean".equals(paramType.getName())
  786. || "boolean".equals(paramType.getName())) {
  787. result = new Boolean(object);
  788. // Try a setFoo ( InetAddress )
  789. } else if ("java.net.InetAddress".equals(paramType
  790. .getName())) {
  791. try {
  792. result = InetAddress.getByName(object);
  793. } catch (UnknownHostException exc) {
  794. if (log.isDebugEnabled())
  795. log.debug("IntrospectionUtils: Unable to resolve host name:" +
  796. object);
  797. }
  798. // Unknown type
  799. } else {
  800. if (log.isDebugEnabled())
  801. log.debug("IntrospectionUtils: Unknown type " +
  802. paramType.getName());
  803. }
  804. if (result == null) {
  805. throw new IllegalArgumentException("Can't convert argument: " + object);
  806. }
  807. return result;
  808. }
  809. // -------------------- Get property --------------------
  810. // This provides a layer of abstraction
  811. public static interface PropertySource {
  812. public String getProperty(String key);
  813. }
  814. public static interface AttributeHolder {
  815. public void setAttribute(String key, Object o);
  816. }
  817. }