1. /*
  2. * ====================================================================
  3. *
  4. * The Apache Software License, Version 1.1
  5. *
  6. * Copyright (c) 1999-2003 The Apache Software Foundation. All rights
  7. * reserved.
  8. *
  9. * Redistribution and use in source and binary forms, with or without
  10. * modification, are permitted provided that the following conditions
  11. * are met:
  12. *
  13. * 1. Redistributions of source code must retain the above copyright
  14. * notice, this list of conditions and the following disclaimer.
  15. *
  16. * 2. Redistributions in binary form must reproduce the above copyright
  17. * notice, this list of conditions and the following disclaimer in
  18. * the documentation and/or other materials provided with the
  19. * distribution.
  20. *
  21. * 3. The end-user documentation included with the redistribution, if
  22. * any, must include the following acknowlegement:
  23. * "This product includes software developed by the
  24. * Apache Software Foundation (http://www.apache.org/)."
  25. * Alternately, this acknowlegement may appear in the software itself,
  26. * if and wherever such third-party acknowlegements normally appear.
  27. *
  28. * 4. The names "The Jakarta Project", "Commons", and "Apache Software
  29. * Foundation" must not be used to endorse or promote products derived
  30. * from this software without prior written permission. For written
  31. * permission, please contact apache@apache.org.
  32. *
  33. * 5. Products derived from this software may not be called "Apache"
  34. * nor may "Apache" appear in their names without prior written
  35. * permission of the Apache Group.
  36. *
  37. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
  38. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  39. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  40. * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
  41. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  42. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  43. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  44. * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  45. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  46. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  47. * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  48. * SUCH DAMAGE.
  49. * ====================================================================
  50. *
  51. * This software consists of voluntary contributions made by many
  52. * individuals on behalf of the Apache Software Foundation. For more
  53. * information on the Apache Software Foundation, please see
  54. * <http://www.apache.org/>.
  55. *
  56. * [Additional notices, if required by prior licensing conditions]
  57. *
  58. */
  59. package org.apache.commons.modeler.util;
  60. import java.io.File;
  61. import java.io.FilenameFilter;
  62. import java.io.IOException;
  63. import java.lang.reflect.InvocationTargetException;
  64. import java.lang.reflect.Method;
  65. import java.net.InetAddress;
  66. import java.net.MalformedURLException;
  67. import java.net.URL;
  68. import java.net.UnknownHostException;
  69. import java.util.Hashtable;
  70. import java.util.StringTokenizer;
  71. import java.util.Vector;
  72. // Depends:
  73. // JDK1.1
  74. /**
  75. * Utils for introspection and reflection
  76. *
  77. * Source: jakarta-tomcat-connector/util
  78. */
  79. public final class IntrospectionUtils {
  80. static final Class NO_PARAMS[]=new Class[0];
  81. static final Class STRING_OBJ_PARAM[]=new Class[] {
  82. String.class, Object.class };
  83. static final Class STRING_PARAM[]=new Class[] {
  84. String.class };
  85. /** Execute a no-param method.
  86. */
  87. public static void execute( Object proxy, String method )
  88. throws Exception
  89. {
  90. Method executeM=null;
  91. Class c=proxy.getClass();
  92. executeM=findMethod( c, method, NO_PARAMS );
  93. if( executeM == null ) {
  94. throw new RuntimeException("No method " + method + " in " +
  95. proxy.getClass() );
  96. }
  97. executeM.invoke(proxy, null );
  98. }
  99. /**
  100. * Call void setAttribute( String ,Object )
  101. */
  102. public static void setAttribute( Object proxy, String n, Object v)
  103. throws Exception
  104. {
  105. if( proxy instanceof AttributeHolder ) {
  106. ((AttributeHolder)proxy).setAttribute( n, v );
  107. return;
  108. }
  109. Method executeM=null;
  110. Class c=proxy.getClass();
  111. executeM=findMethod( c, "setAttribute", STRING_OBJ_PARAM );
  112. if( executeM == null ) {
  113. System.out.println("No setAttribute in " + proxy.getClass() );
  114. return;
  115. }
  116. executeM.invoke(proxy, new Object[] { n, v });
  117. return;
  118. }
  119. /**
  120. * Call void getAttribute( String )
  121. */
  122. public static Object getAttribute( Object proxy, String n)
  123. throws Exception
  124. {
  125. Method executeM=null;
  126. Class c=proxy.getClass();
  127. executeM=findMethod( c, "getAttribute", STRING_PARAM);
  128. if( executeM == null ) {
  129. System.out.println("No getAttribute in " + proxy.getClass() );
  130. return null;
  131. }
  132. return executeM.invoke(proxy, new Object[] { n });
  133. }
  134. /** Construct a URLClassLoader. Will compile and work in JDK1.1 too.
  135. */
  136. public static ClassLoader getURLClassLoader( URL urls[],
  137. ClassLoader parent )
  138. {
  139. try {
  140. Class urlCL=Class.forName( "java.net.URLClassLoader");
  141. Class paramT[]=new Class[2];
  142. paramT[0]= urls.getClass();
  143. paramT[1]=ClassLoader.class;
  144. Method m=findMethod( urlCL, "newInstance", paramT);
  145. if( m==null ) return null;
  146. ClassLoader cl=(ClassLoader)m.invoke( urlCL,
  147. new Object[] { urls,
  148. parent } );
  149. return cl;
  150. } catch(ClassNotFoundException ex ) {
  151. // jdk1.1
  152. return null;
  153. } catch(Exception ex ) {
  154. ex.printStackTrace();
  155. return null;
  156. }
  157. }
  158. public static String guessInstall(String installSysProp,
  159. String homeSysProp, String jarName) {
  160. return guessInstall( installSysProp, homeSysProp, jarName, null);
  161. }
  162. /** Guess a product install/home by analyzing the class path.
  163. * It works for product using the pattern: lib/executable.jar
  164. * or if executable.jar is included in classpath by a shell
  165. * script. ( java -jar also works )
  166. *
  167. * Insures both "install" and "home" System properties are set.
  168. * If either or both System properties are unset, "install" and
  169. * "home" will be set to the same value. This value will be
  170. * the other System property that is set, or the guessed value
  171. * if neither is set.
  172. */
  173. public static String guessInstall(String installSysProp, String homeSysProp,
  174. String jarName, String classFile) {
  175. String install=null;
  176. String home=null;
  177. if ( installSysProp != null )
  178. install=System.getProperty( installSysProp );
  179. if( homeSysProp != null )
  180. home=System.getProperty( homeSysProp );
  181. if ( install != null ) {
  182. if ( home == null )
  183. System.getProperties().put( homeSysProp, install );
  184. return install;
  185. }
  186. // Find the directory where jarName.jar is located
  187. String cpath=System.getProperty( "java.class.path");
  188. String pathSep=System.getProperty( "path.separator");
  189. StringTokenizer st=new StringTokenizer( cpath, pathSep );
  190. while( st.hasMoreTokens() ) {
  191. String path=st.nextToken();
  192. // log( "path " + path );
  193. if( path.endsWith( jarName ) ) {
  194. home=path.substring( 0, path.length() - jarName.length() );
  195. try {
  196. if( "".equals(home) ) {
  197. home=new File("./").getCanonicalPath();
  198. } else if( home.endsWith(File.separator) ) {
  199. home = home.substring(0,home.length()-1);
  200. }
  201. File f=new File( home );
  202. String parentDir = f.getParent();
  203. if(parentDir == null)
  204. parentDir = home; // unix style
  205. File f1=new File ( parentDir );
  206. install = f1.getCanonicalPath();
  207. if( installSysProp != null )
  208. System.getProperties().put( installSysProp, install );
  209. if( home == null && homeSysProp != null )
  210. System.getProperties().put( homeSysProp, install );
  211. return install;
  212. } catch( Exception ex ) {
  213. ex.printStackTrace();
  214. }
  215. } else {
  216. String fname=path + ( path.endsWith("/") ?"":"/" ) + classFile;
  217. if( new File( fname ).exists()) {
  218. try {
  219. File f=new File( path );
  220. String parentDir = f.getParent();
  221. if( parentDir == null )
  222. parentDir = path; // unix style
  223. File f1=new File ( parentDir );
  224. install = f1.getCanonicalPath();
  225. if( installSysProp != null )
  226. System.getProperties().put( installSysProp,
  227. install );
  228. if( home == null && homeSysProp != null )
  229. System.getProperties().put( homeSysProp, install );
  230. return install;
  231. } catch( Exception ex ) {
  232. ex.printStackTrace();
  233. }
  234. }
  235. }
  236. }
  237. // if install directory can't be found, use home as the default
  238. if ( home != null ) {
  239. System.getProperties().put( installSysProp, home );
  240. return home;
  241. }
  242. return null;
  243. }
  244. /** Debug method, display the classpath
  245. */
  246. public static void displayClassPath( String msg, URL[] cp ) {
  247. System.out.println(msg);
  248. for( int i=0; i<cp.length; i++ ) {
  249. System.out.println( cp[i].getFile() );
  250. }
  251. }
  252. public static String PATH_SEPARATOR = System.getProperty("path.separator");
  253. /**
  254. * Adds classpath entries from a vector of URL's to the
  255. * "tc_path_add" System property. This System property lists
  256. * the classpath entries common to web applications. This System
  257. * property is currently used by Jasper when its JSP servlet
  258. * compiles the Java file for a JSP.
  259. */
  260. public static String classPathAdd(URL urls[], String cp )
  261. {
  262. if( urls==null ) return cp;
  263. for( int i=0; i<urls.length; i++ ) {
  264. if( cp != null)
  265. cp += PATH_SEPARATOR + urls[i].getFile();
  266. else
  267. cp = urls[i].getFile();
  268. }
  269. return cp;
  270. }
  271. /** Find a method with the right name
  272. If found, call the method ( if param is int or boolean we'll convert
  273. value to the right type before) - that means you can have setDebug(1).
  274. */
  275. public static void setProperty( Object o, String name, String value ) {
  276. if( dbg > 1 ) d("setProperty(" +
  277. o.getClass() + " " + name + "=" +
  278. value +")" );
  279. String setter= "set" +capitalize(name);
  280. try {
  281. Method methods[]=findMethods( o.getClass() );
  282. Method setPropertyMethod=null;
  283. // First, the ideal case - a setFoo( String ) method
  284. for( int i=0; i< methods.length; i++ ) {
  285. Class paramT[]=methods[i].getParameterTypes();
  286. if( setter.equals( methods[i].getName() ) &&
  287. paramT.length == 1 &&
  288. "java.lang.String".equals( paramT[0].getName())) {
  289. methods[i].invoke( o, new Object[] { value } );
  290. return;
  291. }
  292. }
  293. // Try a setFoo ( int ) or ( boolean )
  294. for( int i=0; i< methods.length; i++ ) {
  295. boolean ok=true;
  296. if( setter.equals( methods[i].getName() ) &&
  297. methods[i].getParameterTypes().length == 1) {
  298. // match - find the type and invoke it
  299. Class paramType=methods[i].getParameterTypes()[0];
  300. Object params[]=new Object[1];
  301. // Try a setFoo ( int )
  302. if ("java.lang.Integer".equals( paramType.getName()) ||
  303. "int".equals( paramType.getName())) {
  304. try {
  305. params[0]=new Integer(value);
  306. } catch( NumberFormatException ex ) {ok=false;}
  307. // Try a setFoo ( boolean )
  308. } else if ("java.lang.Boolean".
  309. equals( paramType.getName()) ||
  310. "boolean".equals( paramType.getName())) {
  311. params[0]=new Boolean(value);
  312. // Try a setFoo ( InetAddress )
  313. } else if ("java.net.InetAddress".
  314. equals( paramType.getName())){
  315. try{
  316. params[0]= InetAddress.getByName(value);
  317. }catch(UnknownHostException exc) {
  318. d("Unable to resolve host name:" + value);
  319. ok=false;
  320. }
  321. // Try a setFoo ( Object )
  322. } else if ("java.lang.Object".
  323. equals( paramType.getName())) {
  324. params[0] = value;
  325. // Unknown type
  326. } else {
  327. d("Unknown type " + paramType.getName() );
  328. }
  329. if( ok ) {
  330. methods[i].invoke( o, params );
  331. return;
  332. }
  333. }
  334. // save "setProperty" for later
  335. if( "setProperty".equals( methods[i].getName())) {
  336. setPropertyMethod=methods[i];
  337. }
  338. }
  339. // Ok, no setXXX found, try a setProperty("name", "value")
  340. if( setPropertyMethod != null ) {
  341. Object params[]=new Object[2];
  342. params[0]=name;
  343. params[1]=value;
  344. setPropertyMethod.invoke( o, params );
  345. }
  346. } catch( IllegalArgumentException ex2 ) {
  347. System.err.println("IAE " + o + " " + name + " " + value);
  348. ex2.printStackTrace();
  349. } catch( SecurityException ex1 ) {
  350. if( dbg > 0 )
  351. d("SecurityException for " + o.getClass() + " " +
  352. name + "=" + value +")" );
  353. if( dbg > 1 ) ex1.printStackTrace();
  354. } catch (IllegalAccessException iae) {
  355. if( dbg > 0 )
  356. d("IllegalAccessException for " +
  357. o.getClass() + " " + name + "=" + value +")" );
  358. if( dbg > 1 ) iae.printStackTrace();
  359. } catch (InvocationTargetException ie) {
  360. if( dbg > 0 )
  361. d("InvocationTargetException for " + o.getClass() +
  362. " " + name + "=" + value +")" );
  363. if( dbg > 1 ) ie.printStackTrace();
  364. }
  365. }
  366. public static Object getProperty( Object o, String name ) {
  367. String getter= "get" +capitalize(name);
  368. try {
  369. Method methods[]=findMethods( o.getClass() );
  370. Method getPropertyMethod=null;
  371. // First, the ideal case - a getFoo() method
  372. for( int i=0; i< methods.length; i++ ) {
  373. Class paramT[]=methods[i].getParameterTypes();
  374. if( getter.equals( methods[i].getName() ) &&
  375. paramT.length == 0 ) {
  376. return methods[i].invoke( o, null );
  377. }
  378. if( "getProperty".equals( methods[i].getName())) {
  379. getPropertyMethod=methods[i];
  380. }
  381. if( "getAttribute".equals( methods[i].getName())) {
  382. getPropertyMethod=methods[i];
  383. }
  384. }
  385. // Ok, no setXXX found, try a getProperty("name")
  386. if( getPropertyMethod != null ) {
  387. Object params[]=new Object[1];
  388. params[0]=name;
  389. getPropertyMethod.invoke( o, params );
  390. }
  391. } catch( IllegalArgumentException ex2 ) {
  392. System.err.println("IAE " + o + " " + name );
  393. ex2.printStackTrace();
  394. } catch( SecurityException ex1 ) {
  395. if( dbg > 0 )
  396. d("SecurityException for " + o.getClass() + " " +
  397. name + ")" );
  398. if( dbg > 1 ) ex1.printStackTrace();
  399. } catch (IllegalAccessException iae) {
  400. if( dbg > 0 )
  401. d("IllegalAccessException for " +
  402. o.getClass() + " " + name +")" );
  403. if( dbg > 1 ) iae.printStackTrace();
  404. } catch (InvocationTargetException ie) {
  405. if( dbg > 0 )
  406. d("InvocationTargetException for " + o.getClass() +
  407. " " + name +")" );
  408. if( dbg > 1 ) ie.printStackTrace();
  409. }
  410. return null;
  411. }
  412. /**
  413. */
  414. public static void setProperty( Object o, String name ) {
  415. String setter= "set" +capitalize(name);
  416. try {
  417. Method methods[]=findMethods( o.getClass() );
  418. Method setPropertyMethod=null;
  419. // find setFoo() method
  420. for( int i=0; i< methods.length; i++ ) {
  421. Class paramT[]=methods[i].getParameterTypes();
  422. if( setter.equals( methods[i].getName() ) &&
  423. paramT.length == 0 ) {
  424. methods[i].invoke( o, new Object[] {} );
  425. return;
  426. }
  427. }
  428. } catch( Exception ex1 ) {
  429. if( dbg > 0 )
  430. d("Exception for " + o.getClass() + " " + name);
  431. if( dbg > 1 ) ex1.printStackTrace();
  432. }
  433. }
  434. /** Replace ${NAME} with the property value
  435. * @deprecated Use the explicit method
  436. */
  437. public static String replaceProperties(String value,
  438. Object getter )
  439. {
  440. if( getter instanceof Hashtable )
  441. return replaceProperties( value, (Hashtable)getter, null );
  442. if( getter instanceof PropertySource ) {
  443. PropertySource src[]=new PropertySource[] {(PropertySource)getter};
  444. return replaceProperties( value, null, src);
  445. }
  446. return value;
  447. }
  448. /** Replace ${NAME} with the property value
  449. */
  450. public static String replaceProperties(String value,
  451. Hashtable staticProp, PropertySource dynamicProp[] )
  452. {
  453. StringBuffer sb=new StringBuffer();
  454. int prev=0;
  455. // assert value!=nil
  456. int pos;
  457. while( (pos=value.indexOf( "$", prev )) >= 0 ) {
  458. if(pos>0) {
  459. sb.append( value.substring( prev, pos ) );
  460. }
  461. if( pos == (value.length() - 1)) {
  462. sb.append('$');
  463. prev = pos + 1;
  464. }
  465. else if (value.charAt( pos + 1 ) != '{' ) {
  466. sb.append( value.charAt( pos + 1 ) );
  467. prev=pos+2; // XXX
  468. } else {
  469. int endName=value.indexOf( '}', pos );
  470. if( endName < 0 ) {
  471. sb.append( value.substring( pos ));
  472. prev=value.length();
  473. continue;
  474. }
  475. String n=value.substring( pos+2, endName );
  476. String v= null;
  477. if( staticProp != null ) {
  478. v=(String)((Hashtable)staticProp).get(n);
  479. }
  480. if( v==null && dynamicProp != null) {
  481. for( int i=0; i<dynamicProp.length; i++ ) {
  482. v=dynamicProp[i].getProperty( n );
  483. if( v!=null ) {
  484. break;
  485. }
  486. }
  487. }
  488. if( v== null )
  489. v = "${"+n+"}";
  490. sb.append( v );
  491. prev=endName+1;
  492. }
  493. }
  494. if( prev < value.length() ) sb.append( value.substring( prev ) );
  495. return sb.toString();
  496. }
  497. /** Reverse of Introspector.decapitalize
  498. */
  499. public static String capitalize(String name) {
  500. if (name == null || name.length() == 0) {
  501. return name;
  502. }
  503. char chars[] = name.toCharArray();
  504. chars[0] = Character.toUpperCase(chars[0]);
  505. return new String(chars);
  506. }
  507. public static String unCapitalize(String name) {
  508. if (name == null || name.length() == 0) {
  509. return name;
  510. }
  511. char chars[] = name.toCharArray();
  512. chars[0] = Character.toLowerCase(chars[0]);
  513. return new String(chars);
  514. }
  515. // -------------------- Class path tools --------------------
  516. /** Add all the jar files in a dir to the classpath,
  517. * represented as a Vector of URLs.
  518. */
  519. public static void addToClassPath( Vector cpV, String dir ) {
  520. try{
  521. String cpComp[]=getFilesByExt(dir, ".jar");
  522. if (cpComp != null){
  523. int jarCount=cpComp.length;
  524. for( int i=0; i< jarCount ; i++ ) {
  525. URL url=getURL( dir , cpComp[i] );
  526. if( url!=null )
  527. cpV.addElement( url );
  528. }
  529. }
  530. }catch(Exception ex){
  531. ex.printStackTrace();
  532. }
  533. }
  534. public static void addToolsJar( Vector v )
  535. {
  536. try {
  537. // Add tools.jar in any case
  538. File f=new File( System.getProperty( "java.home" ) +
  539. "/../lib/tools.jar");
  540. if( ! f.exists() ) {
  541. // On some systems java.home gets set to the root of jdk.
  542. // That's a bug, but we can work around and be nice.
  543. f=new File( System.getProperty( "java.home" ) +
  544. "/lib/tools.jar");
  545. if( f.exists() ) {
  546. System.out.println("Detected strange java.home value " +
  547. System.getProperty( "java.home" ) +
  548. ", it should point to jre");
  549. }
  550. }
  551. URL url=new URL( "file", "" , f.getAbsolutePath() );
  552. v.addElement( url );
  553. } catch ( MalformedURLException ex ) {
  554. ex.printStackTrace();
  555. }
  556. }
  557. /** Return all files with a given extension in a dir
  558. */
  559. public static String[] getFilesByExt( String ld, String ext ) {
  560. File dir = new File(ld);
  561. String[] names=null;
  562. final String lext=ext;
  563. if (dir.isDirectory()){
  564. names = dir.list( new FilenameFilter(){
  565. public boolean accept(File d, String name) {
  566. if (name.endsWith(lext)){
  567. return true;
  568. }
  569. return false;
  570. }
  571. });
  572. }
  573. return names;
  574. }
  575. /** Construct a file url from a file, using a base dir
  576. */
  577. public static URL getURL( String base, String file ) {
  578. try {
  579. File baseF = new File(base);
  580. File f = new File(baseF,file);
  581. String path = f.getCanonicalPath();
  582. if( f.isDirectory() ){
  583. path +="/";
  584. }
  585. if( ! f.exists() ) return null;
  586. return new URL( "file", "", path );
  587. } catch (Exception ex) {
  588. ex.printStackTrace();
  589. return null;
  590. }
  591. }
  592. /**
  593. * add elements from the classpath <i>cp</i> to a Vector
  594. * <i>jars</i> as file URLs (We use Vector for JDK 1.1 compat).
  595. *
  596. * @param jars A vector of URLs
  597. * @param cp a String classpath of directory or jar file
  598. * elements separated by path.separator delimiters.
  599. */
  600. public static void addJarsFromClassPath(Vector jars, String cp)
  601. throws IOException,MalformedURLException
  602. {
  603. String sep = System.getProperty("path.separator");
  604. String token;
  605. StringTokenizer st;
  606. if(cp!=null){
  607. st = new StringTokenizer(cp,sep);
  608. while(st.hasMoreTokens()){
  609. File f = new File(st.nextToken());
  610. String path = f.getCanonicalPath();
  611. if(f.isDirectory()){
  612. path += "/";
  613. }
  614. URL url = new URL("file","",path);
  615. if(!jars.contains(url)){
  616. jars.addElement(url);
  617. }
  618. }
  619. }
  620. }
  621. /** Return a URL[] that can be used to construct a class loader
  622. */
  623. public static URL[] getClassPath(Vector v){
  624. URL[] urls=new URL[ v.size() ];
  625. for( int i=0; i<v.size(); i++ ) {
  626. urls[i]=(URL)v.elementAt( i );
  627. }
  628. return urls;
  629. }
  630. /** Construct a URL classpath from files in a directory,
  631. * a cpath property, and tools.jar.
  632. */
  633. public static URL[] getClassPath( String dir, String cpath,
  634. String cpathProp, boolean addTools )
  635. throws IOException, MalformedURLException
  636. {
  637. Vector jarsV = new Vector();
  638. if( dir!=null ) {
  639. // Add dir/classes first, if it exists
  640. URL url=getURL( dir, "classes");
  641. if( url!=null )
  642. jarsV.addElement(url);
  643. addToClassPath( jarsV, dir );
  644. }
  645. if( cpath != null )
  646. addJarsFromClassPath(jarsV,cpath);
  647. if( cpathProp!=null ) {
  648. String cpath1=System.getProperty( cpathProp );
  649. addJarsFromClassPath(jarsV,cpath1);
  650. }
  651. if(addTools)
  652. addToolsJar( jarsV );
  653. return getClassPath(jarsV);
  654. }
  655. // -------------------- Mapping command line params to setters
  656. public static boolean processArgs(Object proxy, String args[] )
  657. throws Exception
  658. {
  659. String args0[]=null;
  660. if( null != findMethod( proxy.getClass(),
  661. "getOptions1", new Class[] {} )) {
  662. args0=(String[])callMethod0( proxy, "getOptions1");
  663. }
  664. if( args0==null ) {
  665. //args0=findVoidSetters(proxy.getClass());
  666. args0=findBooleanSetters(proxy.getClass());
  667. }
  668. Hashtable h=null;
  669. if( null != findMethod( proxy.getClass(),
  670. "getOptionAliases", new Class[] {} )) {
  671. h=(Hashtable)callMethod0( proxy, "getOptionAliases");
  672. }
  673. return processArgs( proxy, args, args0, null, h );
  674. }
  675. public static boolean processArgs(Object proxy, String args[],
  676. String args0[], String args1[],
  677. Hashtable aliases )
  678. throws Exception
  679. {
  680. for( int i=0; i< args.length; i++ ) {
  681. String arg=args[i];
  682. if( arg.startsWith("-"))
  683. arg=arg.substring(1);
  684. if( aliases != null && aliases.get( arg ) != null)
  685. arg=(String)aliases.get(arg);
  686. if( args0!=null ) {
  687. boolean set=false;
  688. for( int j=0; j< args0.length ; j++ ) {
  689. if( args0[j].equalsIgnoreCase( arg )) {
  690. setProperty( proxy, args0[j], "true");
  691. set=true;
  692. break;
  693. }
  694. }
  695. if( set ) continue;
  696. }
  697. if( args1!=null ) {
  698. for( int j=0; j< args1.length ; j++ ) {
  699. if( args1[j].equalsIgnoreCase( arg )) {
  700. i++;
  701. if( i >= args.length )
  702. return false;
  703. setProperty( proxy, arg, args[i]);
  704. break;
  705. }
  706. }
  707. } else {
  708. // if args1 is not specified,assume all other options have param
  709. i++;
  710. if( i >= args.length )
  711. return false;
  712. setProperty( proxy,arg, args[i]);
  713. }
  714. }
  715. return true;
  716. }
  717. // -------------------- other utils --------------------
  718. public static String[] findVoidSetters( Class c ) {
  719. Method m[]=findMethods( c );
  720. if( m==null ) return null;
  721. Vector v=new Vector();
  722. for( int i=0; i<m.length; i++ ) {
  723. if( m[i].getName().startsWith("set") &&
  724. m[i].getParameterTypes().length == 0 ) {
  725. String arg=m[i].getName().substring( 3 );
  726. v.addElement( unCapitalize( arg ));
  727. }
  728. }
  729. String s[]=new String[v.size()];
  730. for( int i=0; i<s.length; i++ ) {
  731. s[i]=(String)v.elementAt( i );
  732. }
  733. return s;
  734. }
  735. public static String[] findBooleanSetters( Class c ) {
  736. Method m[]=findMethods( c );
  737. if( m==null ) return null;
  738. Vector v=new Vector();
  739. for( int i=0; i<m.length; i++ ) {
  740. if( m[i].getName().startsWith("set") &&
  741. m[i].getParameterTypes().length == 1 &&
  742. "boolean".equalsIgnoreCase( m[i].getParameterTypes()[0].getName()) ) {
  743. String arg=m[i].getName().substring( 3 );
  744. v.addElement( unCapitalize( arg ));
  745. }
  746. }
  747. String s[]=new String[v.size()];
  748. for( int i=0; i<s.length; i++ ) {
  749. s[i]=(String)v.elementAt( i );
  750. }
  751. return s;
  752. }
  753. static Hashtable objectMethods=new Hashtable();
  754. public static Method[] findMethods( Class c ) {
  755. Method methods[]= (Method [])objectMethods.get( c );
  756. if( methods != null ) return methods;
  757. methods=c.getMethods();
  758. objectMethods.put( c, methods );
  759. return methods;
  760. }
  761. public static Method findMethod( Class c, String name, Class params[] ) {
  762. Method methods[] = findMethods( c );
  763. if( methods==null ) return null;
  764. for (int i = 0; i < methods.length; i++) {
  765. if (methods[i].getName().equals(name) ) {
  766. Class methodParams[]=methods[i].getParameterTypes();
  767. if( methodParams==null )
  768. if( params==null || params.length==0 )
  769. return methods[i];
  770. if( params==null )
  771. if( methodParams==null || methodParams.length==0 )
  772. return methods[i];
  773. if( params.length != methodParams.length )
  774. continue;
  775. boolean found=true;
  776. for( int j=0; j< params.length; j++ ) {
  777. if( params[j] != methodParams[j] ) {
  778. found=false;
  779. break;
  780. }
  781. }
  782. if( found ) return methods[i];
  783. }
  784. }
  785. return null;
  786. }
  787. /** Test if the object implements a particular
  788. * method
  789. */
  790. public static boolean hasHook( Object obj, String methodN ) {
  791. try {
  792. Method myMethods[]=findMethods( obj.getClass() );
  793. for( int i=0; i< myMethods.length; i++ ) {
  794. if( methodN.equals ( myMethods[i].getName() )) {
  795. // check if it's overriden
  796. Class declaring=myMethods[i].getDeclaringClass();
  797. Class parentOfDeclaring=declaring.getSuperclass();
  798. // this works only if the base class doesn't extend
  799. // another class.
  800. // if the method is declared in a top level class
  801. // like BaseInterceptor parent is Object, otherwise
  802. // parent is BaseInterceptor or an intermediate class
  803. if( ! "java.lang.Object".
  804. equals(parentOfDeclaring.getName() )) {
  805. return true;
  806. }
  807. }
  808. }
  809. } catch ( Exception ex ) {
  810. ex.printStackTrace();
  811. }
  812. return false;
  813. }
  814. public static void callMain( Class c, String args[] )
  815. throws Exception
  816. {
  817. Class p[]=new Class[1];
  818. p[0]=args.getClass();
  819. Method m=c.getMethod( "main", p);
  820. m.invoke( c, new Object[] {args} );
  821. }
  822. public static Object callMethod1( Object target,
  823. String methodN,
  824. Object param1,
  825. String typeParam1,
  826. ClassLoader cl)
  827. throws Exception
  828. {
  829. if( target==null || param1==null ) {
  830. d("Assert: Illegal params " + target + " " + param1 );
  831. }
  832. if( dbg > 0 ) d("callMethod1 " + target.getClass().getName() +
  833. " " + param1.getClass().getName() +
  834. " " + typeParam1 );
  835. Class params[]=new Class[1];
  836. if( typeParam1==null )
  837. params[0]=param1.getClass();
  838. else
  839. params[0]=cl.loadClass( typeParam1 );
  840. Method m=findMethod( target.getClass(), methodN, params);
  841. if( m==null )
  842. throw new NoSuchMethodException(target.getClass().getName() +
  843. " " + methodN);
  844. return m.invoke(target, new Object[] {param1 } );
  845. }
  846. public static Object callMethod0( Object target,
  847. String methodN)
  848. throws Exception
  849. {
  850. if( target==null ) {
  851. d("Assert: Illegal params " + target );
  852. return null;
  853. }
  854. if( dbg > 0 )
  855. d("callMethod0 " + target.getClass().getName() + "." + methodN);
  856. Class params[]=new Class[0];
  857. Method m=findMethod( target.getClass(), methodN, params);
  858. if( m==null )
  859. throw new NoSuchMethodException(target.getClass().getName() +
  860. " " + methodN);
  861. return m.invoke(target, emptyArray );
  862. }
  863. static Object[] emptyArray=new Object[] {};
  864. public static Object callMethodN( Object target, String methodN,
  865. Object params[], Class typeParams[] )
  866. throws Exception
  867. {
  868. Method m=null;
  869. m=findMethod( target.getClass(), methodN, typeParams );
  870. if( m== null ) {
  871. d("Can't find method " + methodN + " in " +
  872. target + " CLASS " + target.getClass());
  873. return null;
  874. }
  875. Object o=m.invoke( target, params );
  876. if(dbg > 0 ) {
  877. // debug
  878. StringBuffer sb=new StringBuffer();
  879. sb.append("" + target.getClass().getName() + "." + methodN + "( " );
  880. for(int i=0; i<params.length; i++ ) {
  881. if(i>0) sb.append( ", ");
  882. sb.append(params[i]);
  883. }
  884. sb.append(")");
  885. d(sb.toString());
  886. }
  887. return o;
  888. }
  889. // -------------------- Get property --------------------
  890. // This provides a layer of abstraction
  891. public static interface PropertySource {
  892. public String getProperty( String key );
  893. }
  894. public static interface AttributeHolder {
  895. public void setAttribute( String key, Object o );
  896. }
  897. // debug --------------------
  898. static final int dbg=0;
  899. static void d(String s ) {
  900. System.out.println("IntrospectionUtils: " + s );
  901. }
  902. }