You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

ClasspathUtils.java 17 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. /*
  2. * The Apache Software License, Version 1.1
  3. *
  4. * Copyright (c) 2003 The Apache Software Foundation. All rights
  5. * reserved.
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions
  9. * are met:
  10. *
  11. * 1. Redistributions of source code must retain the above copyright
  12. * notice, this list of conditions and the following disclaimer.
  13. *
  14. * 2. Redistributions in binary form must reproduce the above copyright
  15. * notice, this list of conditions and the following disclaimer in
  16. * the documentation and/or other materials provided with the
  17. * distribution.
  18. *
  19. * 3. The end-user documentation included with the redistribution, if
  20. * any, must include the following acknowlegement:
  21. * "This product includes software developed by the
  22. * Apache Software Foundation (http://www.apache.org/)."
  23. * Alternately, this acknowlegement may appear in the software itself,
  24. * if and wherever such third-party acknowlegements normally appear.
  25. *
  26. * 4. The names "Ant" and "Apache Software
  27. * Foundation" must not be used to endorse or promote products derived
  28. * from this software without prior written permission. For written
  29. * permission, please contact apache@apache.org.
  30. *
  31. * 5. Products derived from this software may not be called "Apache"
  32. * nor may "Apache" appear in their names without prior written
  33. * permission of the Apache Group.
  34. *
  35. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
  36. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  37. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  38. * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
  39. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  40. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  41. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  42. * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  43. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  44. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  45. * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  46. * SUCH DAMAGE.
  47. * ====================================================================
  48. *
  49. * This software consists of voluntary contributions made by many
  50. * individuals on behalf of the Apache Software Foundation. For more
  51. * information on the Apache Software Foundation, please see
  52. * <http://www.apache.org/>.
  53. */
  54. package org.apache.tools.ant.util;
  55. import org.apache.tools.ant.AntClassLoader;
  56. import org.apache.tools.ant.BuildException;
  57. import org.apache.tools.ant.Project;
  58. import org.apache.tools.ant.ProjectComponent;
  59. import org.apache.tools.ant.types.Path;
  60. import org.apache.tools.ant.types.Reference;
  61. /**
  62. * Offers some helper methods on the Path structure in ant.
  63. *
  64. * <p>Basic idea behind this utility class is to use it from inside the
  65. * different ant objects (and user defined objects) that need classLoading
  66. * for their operation.
  67. * Normally those would have a setClasspathRef() {for the @classpathref}
  68. * and/or a createClasspath() {for the nested &lt;classpath&gt;}
  69. * Typically one would have in your Ant Task or DataType</p>
  70. *
  71. * <pre><code>
  72. * ClasspathUtils.Delegate cpDelegate;
  73. *
  74. * public void init() {
  75. * this.cpDelegate = ClasspathUtils.getDelegate(this);
  76. * super.init();
  77. * }
  78. *
  79. * public void setClasspathRef(Reference r) {
  80. * this.cpDelegate.setClasspathRef(r);
  81. * }
  82. *
  83. * public Path createClasspath() {
  84. * return this.cpDelegate.createClasspath();
  85. * }
  86. *
  87. * public void setClassname(String fqcn) {
  88. * this.cpDelegate.setClassname(fqcn);
  89. * }
  90. * </code></pre>
  91. *
  92. * <p>At execution time, when you actually need the classloading
  93. * you can just:</p>
  94. *
  95. * <pre><code>
  96. * Object o = this.cpDelegate.newInstance();
  97. * </code></pre>
  98. *
  99. * @since Ant 1.6
  100. */
  101. public class ClasspathUtils {
  102. private static final String LOADER_ID_PREFIX = "ant.loader.";
  103. /**
  104. * Name of the magic property that controls classloader reuse in Ant 1.4.
  105. */
  106. public static final String REUSE_LOADER_REF = "ant.reuse.loader";
  107. /**
  108. * Convenience overloaded version of {@link
  109. * #getClassLoaderForPath(Project, Reference, boolean)}.
  110. *
  111. * <p>Assumes the logical 'false' for the reverseLoader.</p>
  112. *
  113. * @param path
  114. * @param pathId
  115. * @return
  116. */
  117. public static ClassLoader getClassLoaderForPath(
  118. Project p, Reference ref) {
  119. return getClassLoaderForPath(p, ref, false);
  120. }
  121. /**
  122. * Convenience overloaded version of {@link #geClassLoader(Project, Path,
  123. * String, boolean)}.
  124. *
  125. * <p>Delegates to the other one after extracting the referenced
  126. * Path from the Project This checks also that the passed
  127. * Reference is pointing to a Path all right.</p>
  128. * @param p current ant project
  129. * @param ref Reference to Path structure
  130. * @param reverseLoader if set to true this new loader will take
  131. * precedence over it's parent (which is contra the regular
  132. * classloader behaviour)
  133. * @return
  134. */
  135. public static ClassLoader getClassLoaderForPath(
  136. Project p, Reference ref, boolean reverseLoader) {
  137. String pathId = ref.getRefId();
  138. Object path = p.getReference(pathId);
  139. if (!(path instanceof Path)) {
  140. throw new BuildException(
  141. "The specified classpathref "
  142. + pathId
  143. + " does not reference a Path.");
  144. }
  145. String loaderId = LOADER_ID_PREFIX + pathId;
  146. return getClassLoaderForPath(p, (Path) path, loaderId, reverseLoader);
  147. }
  148. /**
  149. * Convenience overloaded version of {@link
  150. * #getClassLoaderForPath(Project, Path, String, boolean)}.
  151. *
  152. * <p>Assumes the logical 'false' for the reverseLoader.</p>
  153. *
  154. * @param path
  155. * @param loaderId
  156. * @return
  157. */
  158. public static ClassLoader getClassLoaderForPath(
  159. Project p, Path path, String loaderId) {
  160. return getClassLoaderForPath(p, path, loaderId, false);
  161. }
  162. /**
  163. * Convenience overloaded version of {@link
  164. * #getClassLoaderForPath(Project, Path, String, boolean, boolean)}.
  165. *
  166. * <p>Sets value for 'reuseLoader' to true if the magic property
  167. * has been set.</p>
  168. *
  169. * @param path
  170. * @param loaderId
  171. * @return
  172. */
  173. public static ClassLoader getClassLoaderForPath(
  174. Project p, Path path, String loaderId, boolean reverseLoader) {
  175. return getClassLoaderForPath(p, path, loaderId, reverseLoader,
  176. isMagicPropertySet(p));
  177. }
  178. /**
  179. * Gets a classloader that loads classes from the classpath
  180. * defined in the path argument.
  181. *
  182. * <p>Based on the setting of the magic property
  183. * 'ant.reuse.loader' this will try to reuse the perviously
  184. * created loader with that id, and of course store it there upon
  185. * creation.</p>
  186. * @param path Path object to be used as classpath for this classloader
  187. * @param loaderId identification for this Loader,
  188. * @param reverseLoader if set to true this new loader will take
  189. * precedence over it's parent (which is contra the regular
  190. * @param p Ant Project where the handled components are living in.
  191. * classloader behaviour)
  192. * @return ClassLoader that uses the Path as its classpath.
  193. */
  194. public static ClassLoader getClassLoaderForPath(
  195. Project p, Path path, String loaderId, boolean reverseLoader,
  196. boolean reuseLoader) {
  197. ClassLoader cl = null;
  198. // magic property
  199. if (loaderId != null && reuseLoader) {
  200. Object reusedLoader = p.getReference(loaderId);
  201. if (reusedLoader != null
  202. && !(reusedLoader instanceof ClassLoader)) {
  203. throw new BuildException("The specified loader id " + loaderId
  204. + " does not reference a class loader");
  205. }
  206. cl = (ClassLoader) reusedLoader;
  207. }
  208. if (cl == null) {
  209. cl = getUniqueClassLoaderForPath(p, path, reverseLoader);
  210. if (loaderId != null && reuseLoader) {
  211. p.addReference(loaderId, cl);
  212. }
  213. }
  214. return cl;
  215. }
  216. /**
  217. * Gets a fresh, different, not used before classloader that uses the
  218. * passed path as it's classpath.
  219. *
  220. * <p>This method completely ignores the ant.reuse.loader magic
  221. * property and should be used with caution.</p>
  222. * @param path the classpath for this loader
  223. * @param reverseLoader
  224. * @return
  225. */
  226. public static ClassLoader getUniqueClassLoaderForPath(
  227. Project p,
  228. Path path,
  229. boolean reverseLoader) {
  230. AntClassLoader acl = p.createClassLoader(path != null
  231. ? path : Path.systemClasspath);
  232. if (reverseLoader) {
  233. acl.setParentFirst(false);
  234. acl.addJavaLibraries();
  235. }
  236. return acl;
  237. }
  238. /**
  239. * Creates a fresh object instance of the specified classname.
  240. *
  241. * <p> This uses the userDefinedLoader to load the specified class,
  242. * and then makes an instance using the default no-argument constructor
  243. * </p>
  244. *
  245. * @param className the full qualified class name to load.
  246. * @param userDefinedLoader the classloader to use.
  247. * @return
  248. * @throws BuildException when loading or instantiation failed.
  249. */
  250. public static Object newInstance(
  251. String className,
  252. ClassLoader userDefinedLoader) {
  253. try {
  254. Class clazz = userDefinedLoader.loadClass(className);
  255. Object o = clazz.newInstance();
  256. return o;
  257. } catch (ClassNotFoundException e) {
  258. throw new BuildException(
  259. "Class "
  260. + className
  261. + " not found by the specific classLoader.",
  262. e);
  263. } catch (InstantiationException e) {
  264. throw new BuildException(
  265. "Could not instantiate "
  266. + className
  267. + ". Specified class should have a no "
  268. + "argument constructor.",
  269. e);
  270. } catch (IllegalAccessException e) {
  271. throw new BuildException(
  272. "Could not instantiate "
  273. + className
  274. + ". Specified class should have a "
  275. + "public constructor.",
  276. e);
  277. }
  278. }
  279. /**
  280. * Obtains a delegate that helps out with classic classpath configuration.
  281. *
  282. * @param component your projectComponent that needs the assistence
  283. * @return the helper, delegate.
  284. * @see ClasspathUtils.Delegate
  285. */
  286. public static Delegate getDelegate(ProjectComponent component) {
  287. return new Delegate(component);
  288. }
  289. /**
  290. * Checks for the magic property that enables class loader reuse
  291. * for <taskdef> and <typedef> in Ant 1.5 and earlier.
  292. */
  293. private static boolean isMagicPropertySet(Project p) {
  294. return p.getProperty(REUSE_LOADER_REF) != null;
  295. }
  296. /**
  297. * Delegate that helps out any specific ProjectComponent that needs
  298. * dynamic classloading.
  299. *
  300. * <p>Ant ProjectComponents that need a to be able to dynamically load
  301. * Classes and instantiate them often expose the following ant syntax
  302. * sugar: </p>
  303. *
  304. * <ul><li> nested &lt;classpath&gt; </li>
  305. * <li> attribute @classpathref </li>
  306. * <li> attribute @classname </li></ul>
  307. *
  308. * <p> This class functions as a delegate handling the configuration
  309. * issues for this recuring pattern. Its usage pattern, as the name
  310. * suggests is delegation, not inheritance. </p>
  311. *
  312. * @since Ant 1.6
  313. */
  314. public static class Delegate {
  315. private final ProjectComponent component;
  316. private Path classpath;
  317. private String classpathId;
  318. private String className;
  319. private String loaderId;
  320. private boolean reverseLoader = false;
  321. /**
  322. * Constructs Delegate
  323. * @param component
  324. */
  325. Delegate(ProjectComponent component) {
  326. this.component = component;
  327. }
  328. /**
  329. * Delegate method handling the @classpath attribute
  330. *
  331. * <p>This attribute can set a path to add to the classpath</p>
  332. *
  333. * @param classpath
  334. */
  335. public void setClasspath(Path classpath) {
  336. if (this.classpath == null) {
  337. this.classpath = classpath;
  338. } else {
  339. this.classpath.append(classpath);
  340. }
  341. }
  342. /**
  343. * Delegate method handling the &lt;classpath&gt; tag.
  344. *
  345. * <p>This nested path-like structure can set a path to add to the
  346. * classpath</p>
  347. *
  348. * @return
  349. */
  350. public Path createClasspath() {
  351. if (this.classpath == null) {
  352. this.classpath = new Path(component.getProject());
  353. }
  354. return this.classpath.createPath();
  355. }
  356. /**
  357. * Delegate method handling the @classname attribute.
  358. *
  359. * <p>This attribute sets the full qualified class name of the class
  360. * to lad and instantiate</p>
  361. *
  362. * @param fcqn
  363. */
  364. public void setClassname(String fcqn) {
  365. this.className = fcqn;
  366. }
  367. /**
  368. * Delegate method handling the @classpathref attribute.
  369. *
  370. * <p>This attribute can add a referenced path-like structure to the
  371. * classpath</p>
  372. *
  373. * @param r
  374. */
  375. public void setClasspathref(Reference r) {
  376. this.classpathId = r.getRefId();
  377. createClasspath().setRefid(r);
  378. }
  379. /**
  380. * Delegate method handling the @reverseLoader attribute.
  381. *
  382. * <p>This attribute can set a boolean indicating that the used
  383. * classloader should NOT follow the classical parent-first scheme.
  384. * </p>
  385. *
  386. * <p>By default this is supposed to be false</p>
  387. *
  388. * <p>Caution: this behaviour is contradictory to the normal way
  389. * classloaders work. Do not let your ProjectComponent use it if
  390. * you are not really sure</p>
  391. *
  392. * @param reverseLoader
  393. */
  394. public void setReverseLoader(boolean reverseLoader) {
  395. this.reverseLoader = reverseLoader;
  396. }
  397. /**
  398. * Sets the loaderRef
  399. * @param r
  400. */
  401. public void setLoaderRef(Reference r) {
  402. this.loaderId = r.getRefId();
  403. }
  404. /**
  405. * Finds or creates the classloader for this
  406. * @return
  407. */
  408. public ClassLoader getClassLoader() {
  409. ClassLoader cl;
  410. cl = ClasspathUtils.getClassLoaderForPath(
  411. getContextProject(),
  412. this.classpath,
  413. getClassLoadId(),
  414. this.reverseLoader,
  415. loaderId != null || isMagicPropertySet(getContextProject()));
  416. return cl;
  417. }
  418. /**
  419. * The project of the ProjectComponent we are working for.
  420. */
  421. private Project getContextProject() {
  422. return this.component.getProject();
  423. }
  424. /**
  425. * Computes the loaderId based on the configuration of the component.
  426. */
  427. public String getClassLoadId() {
  428. if (this.loaderId == null && this.classpathId != null) {
  429. return ClasspathUtils.LOADER_ID_PREFIX + this.classpathId;
  430. } else {
  431. return this.loaderId;
  432. }
  433. }
  434. /**
  435. * Helper method obtaining a fresh instance of the class specified
  436. * in the @classname and using the specified classpath.
  437. *
  438. * @return the fresh instantiated object.
  439. */
  440. public Object newInstance() {
  441. ClassLoader cl = getClassLoader();
  442. return ClasspathUtils.newInstance(this.className, cl);
  443. }
  444. /**
  445. * The classpath.
  446. */
  447. public Path getClasspath() {
  448. return classpath;
  449. }
  450. public boolean isReverseLoader() {
  451. return reverseLoader;
  452. }
  453. //TODO no methods yet for getClassname
  454. //TODO no method for newInstance using a reverse-classloader
  455. }
  456. }