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.

AntClassLoader.java 60 kB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595
  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. */
  18. package org.apache.tools.ant;
  19. import java.io.ByteArrayOutputStream;
  20. import java.io.Closeable;
  21. import java.io.File;
  22. import java.io.FileInputStream;
  23. import java.io.IOException;
  24. import java.io.InputStream;
  25. import java.lang.reflect.Constructor;
  26. import java.net.MalformedURLException;
  27. import java.net.URL;
  28. import java.security.CodeSource;
  29. import java.security.ProtectionDomain;
  30. import java.security.cert.Certificate;
  31. import java.util.Collections;
  32. import java.util.Enumeration;
  33. import java.util.HashMap;
  34. import java.util.Hashtable;
  35. import java.util.Map;
  36. import java.util.NoSuchElementException;
  37. import java.util.StringTokenizer;
  38. import java.util.Vector;
  39. import java.util.jar.Attributes;
  40. import java.util.jar.Attributes.Name;
  41. import java.util.jar.JarEntry;
  42. import java.util.jar.JarFile;
  43. import java.util.jar.Manifest;
  44. import org.apache.tools.ant.launch.Locator;
  45. import org.apache.tools.ant.types.Path;
  46. import org.apache.tools.ant.util.CollectionUtils;
  47. import org.apache.tools.ant.util.FileUtils;
  48. import org.apache.tools.ant.util.JavaEnvUtils;
  49. import org.apache.tools.ant.util.LoaderUtils;
  50. import org.apache.tools.ant.util.VectorSet;
  51. import org.apache.tools.zip.ZipLong;
  52. /**
  53. * Used to load classes within ant with a different classpath from
  54. * that used to start ant. Note that it is possible to force a class
  55. * into this loader even when that class is on the system classpath by
  56. * using the forceLoadClass method. Any subsequent classes loaded by that
  57. * class will then use this loader rather than the system class loader.
  58. *
  59. * <p>
  60. * Note that this classloader has a feature to allow loading
  61. * in reverse order and for "isolation".
  62. * Due to the fact that a number of
  63. * methods in java.lang.ClassLoader are final (at least
  64. * in java 1.4 getResources) this means that the
  65. * class has to fake the given parent.
  66. * </p>
  67. *
  68. */
  69. public class AntClassLoader extends ClassLoader implements SubBuildListener, Closeable {
  70. private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
  71. static {
  72. registerAsParallelCapable();
  73. }
  74. /**
  75. * An enumeration of all resources of a given name found within the
  76. * classpath of this class loader. This enumeration is used by the
  77. * ClassLoader.findResources method, which is in
  78. * turn used by the ClassLoader.getResources method.
  79. *
  80. * @see AntClassLoader#findResources(String)
  81. * @see java.lang.ClassLoader#getResources(String)
  82. */
  83. private class ResourceEnumeration implements Enumeration<URL> {
  84. /**
  85. * The name of the resource being searched for.
  86. */
  87. private final String resourceName;
  88. /**
  89. * The index of the next classpath element to search.
  90. */
  91. private int pathElementsIndex;
  92. /**
  93. * The URL of the next resource to return in the enumeration. If this
  94. * field is <code>null</code> then the enumeration has been completed,
  95. * i.e., there are no more elements to return.
  96. */
  97. private URL nextResource;
  98. /**
  99. * Constructs a new enumeration of resources of the given name found
  100. * within this class loader's classpath.
  101. *
  102. * @param name the name of the resource to search for.
  103. */
  104. ResourceEnumeration(final String name) {
  105. this.resourceName = name;
  106. this.pathElementsIndex = 0;
  107. findNextResource();
  108. }
  109. /**
  110. * Indicates whether there are more elements in the enumeration to
  111. * return.
  112. *
  113. * @return <code>true</code> if there are more elements in the
  114. * enumeration; <code>false</code> otherwise.
  115. */
  116. public boolean hasMoreElements() {
  117. return (this.nextResource != null);
  118. }
  119. /**
  120. * Returns the next resource in the enumeration.
  121. *
  122. * @return the next resource in the enumeration
  123. */
  124. public URL nextElement() {
  125. final URL ret = this.nextResource;
  126. if (ret == null) {
  127. throw new NoSuchElementException();
  128. }
  129. findNextResource();
  130. return ret;
  131. }
  132. /**
  133. * Locates the next resource of the correct name in the classpath and
  134. * sets <code>nextResource</code> to the URL of that resource. If no
  135. * more resources can be found, <code>nextResource</code> is set to
  136. * <code>null</code>.
  137. */
  138. private void findNextResource() {
  139. URL url = null;
  140. while ((pathElementsIndex < pathComponents.size()) && (url == null)) {
  141. try {
  142. final File pathComponent = pathComponents.elementAt(pathElementsIndex);
  143. url = getResourceURL(pathComponent, this.resourceName);
  144. pathElementsIndex++;
  145. } catch (final BuildException e) {
  146. // ignore path elements which are not valid relative to the
  147. // project
  148. }
  149. }
  150. this.nextResource = url;
  151. }
  152. }
  153. /**
  154. * The size of buffers to be used in this classloader.
  155. */
  156. private static final int BUFFER_SIZE = 8192;
  157. /**
  158. * Number of array elements in a test array of strings
  159. */
  160. private static final int NUMBER_OF_STRINGS = 256;
  161. /**
  162. * The components of the classpath that the classloader searches
  163. * for classes.
  164. */
  165. private final Vector<File> pathComponents = new VectorSet<File>();
  166. /**
  167. * The project to which this class loader belongs.
  168. */
  169. private Project project;
  170. /**
  171. * Indicates whether the parent class loader should be
  172. * consulted before trying to load with this class loader.
  173. */
  174. private boolean parentFirst = true;
  175. /**
  176. * These are the package roots that are to be loaded by the parent class
  177. * loader regardless of whether the parent class loader is being searched
  178. * first or not.
  179. */
  180. private final Vector<String> systemPackages = new Vector<String>();
  181. /**
  182. * These are the package roots that are to be loaded by this class loader
  183. * regardless of whether the parent class loader is being searched first
  184. * or not.
  185. */
  186. private final Vector<String> loaderPackages = new Vector<String>();
  187. /**
  188. * Whether or not this classloader will ignore the base
  189. * classloader if it can't find a class.
  190. *
  191. * @see #setIsolated(boolean)
  192. */
  193. private boolean ignoreBase = false;
  194. /**
  195. * The parent class loader, if one is given or can be determined.
  196. */
  197. private ClassLoader parent = null;
  198. /**
  199. * A hashtable of zip files opened by the classloader (File to JarFile).
  200. */
  201. private Hashtable<File, JarFile> jarFiles = new Hashtable<File, JarFile>();
  202. /** Static map of jar file/time to manifest class-path entries */
  203. private static Map<String, String> pathMap =
  204. Collections.synchronizedMap(new HashMap<String, String>());
  205. /**
  206. * The context loader saved when setting the thread's current
  207. * context loader.
  208. */
  209. private ClassLoader savedContextLoader = null;
  210. /**
  211. * Whether or not the context loader is currently saved.
  212. */
  213. private boolean isContextLoaderSaved = false;
  214. /**
  215. * Create an Ant ClassLoader for a given project, with
  216. * a parent classloader and an initial classpath.
  217. * @since Ant 1.7.
  218. * @param parent the parent for this classloader.
  219. * @param project The project to which this classloader is to
  220. * belong.
  221. * @param classpath The classpath to use to load classes.
  222. */
  223. public AntClassLoader(final ClassLoader parent, final Project project, final Path classpath) {
  224. setParent(parent);
  225. setClassPath(classpath);
  226. setProject(project);
  227. }
  228. /**
  229. * Create an Ant Class Loader
  230. */
  231. public AntClassLoader() {
  232. setParent(null);
  233. }
  234. /**
  235. * Creates a classloader for the given project using the classpath given.
  236. *
  237. * @param project The project to which this classloader is to belong.
  238. * Must not be <code>null</code>.
  239. * @param classpath The classpath to use to load the classes. This
  240. * is combined with the system classpath in a manner
  241. * determined by the value of ${build.sysclasspath}.
  242. * May be <code>null</code>, in which case no path
  243. * elements are set up to start with.
  244. */
  245. public AntClassLoader(final Project project, final Path classpath) {
  246. setParent(null);
  247. setProject(project);
  248. setClassPath(classpath);
  249. }
  250. /**
  251. * Creates a classloader for the given project using the classpath given.
  252. *
  253. * @param parent The parent classloader to which unsatisfied loading
  254. * attempts are delegated. May be <code>null</code>,
  255. * in which case the classloader which loaded this
  256. * class is used as the parent.
  257. * @param project The project to which this classloader is to belong.
  258. * Must not be <code>null</code>.
  259. * @param classpath the classpath to use to load the classes.
  260. * May be <code>null</code>, in which case no path
  261. * elements are set up to start with.
  262. * @param parentFirst If <code>true</code>, indicates that the parent
  263. * classloader should be consulted before trying to
  264. * load the a class through this loader.
  265. */
  266. public AntClassLoader(
  267. final ClassLoader parent, final Project project, final Path classpath, final boolean parentFirst) {
  268. this(project, classpath);
  269. if (parent != null) {
  270. setParent(parent);
  271. }
  272. setParentFirst(parentFirst);
  273. addJavaLibraries();
  274. }
  275. /**
  276. * Creates a classloader for the given project using the classpath given.
  277. *
  278. * @param project The project to which this classloader is to belong.
  279. * Must not be <code>null</code>.
  280. * @param classpath The classpath to use to load the classes. May be
  281. * <code>null</code>, in which case no path
  282. * elements are set up to start with.
  283. * @param parentFirst If <code>true</code>, indicates that the parent
  284. * classloader should be consulted before trying to
  285. * load the a class through this loader.
  286. */
  287. public AntClassLoader(final Project project, final Path classpath, final boolean parentFirst) {
  288. this(null, project, classpath, parentFirst);
  289. }
  290. /**
  291. * Creates an empty class loader. The classloader should be configured
  292. * with path elements to specify where the loader is to look for
  293. * classes.
  294. *
  295. * @param parent The parent classloader to which unsatisfied loading
  296. * attempts are delegated. May be <code>null</code>,
  297. * in which case the classloader which loaded this
  298. * class is used as the parent.
  299. * @param parentFirst If <code>true</code>, indicates that the parent
  300. * classloader should be consulted before trying to
  301. * load the a class through this loader.
  302. */
  303. public AntClassLoader(final ClassLoader parent, final boolean parentFirst) {
  304. setParent(parent);
  305. project = null;
  306. this.parentFirst = parentFirst;
  307. }
  308. /**
  309. * Set the project associated with this class loader
  310. *
  311. * @param project the project instance
  312. */
  313. public void setProject(final Project project) {
  314. this.project = project;
  315. if (project != null) {
  316. project.addBuildListener(this);
  317. }
  318. }
  319. /**
  320. * Set the classpath to search for classes to load. This should not be
  321. * changed once the classloader starts to server classes
  322. *
  323. * @param classpath the search classpath consisting of directories and
  324. * jar/zip files.
  325. */
  326. public void setClassPath(final Path classpath) {
  327. pathComponents.removeAllElements();
  328. if (classpath != null) {
  329. final Path actualClasspath = classpath.concatSystemClasspath("ignore");
  330. final String[] pathElements = actualClasspath.list();
  331. for (int i = 0; i < pathElements.length; ++i) {
  332. try {
  333. addPathElement(pathElements[i]);
  334. } catch (final BuildException e) {
  335. // ignore path elements which are invalid
  336. // relative to the project
  337. }
  338. }
  339. }
  340. }
  341. /**
  342. * Set the parent for this class loader. This is the class loader to which
  343. * this class loader will delegate to load classes
  344. *
  345. * @param parent the parent class loader.
  346. */
  347. public void setParent(final ClassLoader parent) {
  348. this.parent = parent == null ? AntClassLoader.class.getClassLoader() : parent;
  349. }
  350. /**
  351. * Control whether class lookup is delegated to the parent loader first
  352. * or after this loader. Use with extreme caution. Setting this to
  353. * false violates the class loader hierarchy and can lead to Linkage errors
  354. *
  355. * @param parentFirst if true, delegate initial class search to the parent
  356. * classloader.
  357. */
  358. public void setParentFirst(final boolean parentFirst) {
  359. this.parentFirst = parentFirst;
  360. }
  361. /**
  362. * Logs a message through the project object if one has been provided.
  363. *
  364. * @param message The message to log.
  365. * Should not be <code>null</code>.
  366. *
  367. * @param priority The logging priority of the message.
  368. */
  369. protected void log(final String message, final int priority) {
  370. if (project != null) {
  371. project.log(message, priority);
  372. }
  373. }
  374. /**
  375. * Sets the current thread's context loader to this classloader, storing
  376. * the current loader value for later resetting.
  377. */
  378. public void setThreadContextLoader() {
  379. if (isContextLoaderSaved) {
  380. throw new BuildException("Context loader has not been reset");
  381. }
  382. if (LoaderUtils.isContextLoaderAvailable()) {
  383. savedContextLoader = LoaderUtils.getContextClassLoader();
  384. ClassLoader loader = this;
  385. if (project != null && "only".equals(project.getProperty("build.sysclasspath"))) {
  386. loader = this.getClass().getClassLoader();
  387. }
  388. LoaderUtils.setContextClassLoader(loader);
  389. isContextLoaderSaved = true;
  390. }
  391. }
  392. /**
  393. * Resets the current thread's context loader to its original value.
  394. */
  395. public void resetThreadContextLoader() {
  396. if (LoaderUtils.isContextLoaderAvailable() && isContextLoaderSaved) {
  397. LoaderUtils.setContextClassLoader(savedContextLoader);
  398. savedContextLoader = null;
  399. isContextLoaderSaved = false;
  400. }
  401. }
  402. /**
  403. * Adds an element to the classpath to be searched.
  404. *
  405. * @param pathElement The path element to add. Must not be
  406. * <code>null</code>.
  407. *
  408. * @exception BuildException if the given path element cannot be resolved
  409. * against the project.
  410. */
  411. public void addPathElement(final String pathElement) throws BuildException {
  412. final File pathComponent = project != null ? project.resolveFile(pathElement) : new File(
  413. pathElement);
  414. try {
  415. addPathFile(pathComponent);
  416. } catch (final IOException e) {
  417. throw new BuildException(e);
  418. }
  419. }
  420. /**
  421. * Add a path component.
  422. * This simply adds the file, unlike addPathElement
  423. * it does not open jar files and load files from
  424. * their CLASSPATH entry in the manifest file.
  425. * @param file the jar file or directory to add.
  426. */
  427. public void addPathComponent(final File file) {
  428. if (pathComponents.contains(file)) {
  429. return;
  430. }
  431. pathComponents.addElement(file);
  432. }
  433. /**
  434. * Add a file to the path.
  435. * Reads the manifest, if available, and adds any additional class path jars
  436. * specified in the manifest.
  437. *
  438. * @param pathComponent the file which is to be added to the path for
  439. * this class loader
  440. *
  441. * @throws IOException if data needed from the file cannot be read.
  442. */
  443. protected void addPathFile(final File pathComponent) throws IOException {
  444. if (!pathComponents.contains(pathComponent)) {
  445. pathComponents.addElement(pathComponent);
  446. }
  447. if (pathComponent.isDirectory()) {
  448. return;
  449. }
  450. final String absPathPlusTimeAndLength = pathComponent.getAbsolutePath()
  451. + pathComponent.lastModified() + "-" + pathComponent.length();
  452. String classpath = pathMap.get(absPathPlusTimeAndLength);
  453. if (classpath == null) {
  454. try (JarFile jarFile = new JarFile(pathComponent)) {
  455. final Manifest manifest = jarFile.getManifest();
  456. if (manifest == null) {
  457. return;
  458. }
  459. classpath = manifest.getMainAttributes()
  460. .getValue(Attributes.Name.CLASS_PATH);
  461. }
  462. if (classpath == null) {
  463. classpath = "";
  464. }
  465. pathMap.put(absPathPlusTimeAndLength, classpath);
  466. }
  467. if (!"".equals(classpath)) {
  468. final URL baseURL = FILE_UTILS.getFileURL(pathComponent);
  469. final StringTokenizer st = new StringTokenizer(classpath);
  470. while (st.hasMoreTokens()) {
  471. final String classpathElement = st.nextToken();
  472. final URL libraryURL = new URL(baseURL, classpathElement);
  473. if (!libraryURL.getProtocol().equals("file")) {
  474. log("Skipping jar library " + classpathElement
  475. + " since only relative URLs are supported by this" + " loader",
  476. Project.MSG_VERBOSE);
  477. continue;
  478. }
  479. final String decodedPath = Locator.decodeUri(libraryURL.getFile());
  480. final File libraryFile = new File(decodedPath);
  481. if (libraryFile.exists() && !isInPath(libraryFile)) {
  482. addPathFile(libraryFile);
  483. }
  484. }
  485. }
  486. }
  487. /**
  488. * Returns the classpath this classloader will consult.
  489. *
  490. * @return the classpath used for this classloader, with elements
  491. * separated by the path separator for the system.
  492. */
  493. public String getClasspath() {
  494. final StringBuilder sb = new StringBuilder();
  495. boolean firstPass = true;
  496. final Enumeration<File> componentEnum = pathComponents.elements();
  497. while (componentEnum.hasMoreElements()) {
  498. if (!firstPass) {
  499. sb.append(System.getProperty("path.separator"));
  500. } else {
  501. firstPass = false;
  502. }
  503. sb.append(componentEnum.nextElement().getAbsolutePath());
  504. }
  505. return sb.toString();
  506. }
  507. /**
  508. * Sets whether this classloader should run in isolated mode. In
  509. * isolated mode, classes not found on the given classpath will
  510. * not be referred to the parent class loader but will cause a
  511. * ClassNotFoundException.
  512. *
  513. * @param isolated Whether or not this classloader should run in
  514. * isolated mode.
  515. */
  516. public synchronized void setIsolated(final boolean isolated) {
  517. ignoreBase = isolated;
  518. }
  519. /**
  520. * Forces initialization of a class in a JDK 1.1 compatible, albeit hacky
  521. * way.
  522. *
  523. * @param theClass The class to initialize.
  524. * Must not be <code>null</code>.
  525. *
  526. * @deprecated since 1.6.x.
  527. * Use Class.forName with initialize=true instead.
  528. */
  529. @Deprecated
  530. public static void initializeClass(final Class<?> theClass) {
  531. // ***HACK*** We ask the VM to create an instance
  532. // by voluntarily providing illegal arguments to force
  533. // the VM to run the class' static initializer, while
  534. // at the same time not running a valid constructor.
  535. final Constructor<?>[] cons = theClass.getDeclaredConstructors();
  536. //At least one constructor is guaranteed to be there, but check anyway.
  537. if (cons != null) {
  538. if (cons.length > 0 && cons[0] != null) {
  539. final String[] strs = new String[NUMBER_OF_STRINGS];
  540. try {
  541. cons[0].newInstance((Object[]) strs);
  542. // Expecting an exception to be thrown by this call:
  543. // IllegalArgumentException: wrong number of Arguments
  544. } catch (final Exception e) {
  545. // Ignore - we are interested only in the side
  546. // effect - that of getting the static initializers
  547. // invoked. As we do not want to call a valid
  548. // constructor to get this side effect, an
  549. // attempt is made to call a hopefully
  550. // invalid constructor - come on, nobody
  551. // would have a constructor that takes in
  552. // 256 String arguments ;-)
  553. // (In fact, they can't - according to JVM spec
  554. // section 4.10, the number of method parameters is limited
  555. // to 255 by the definition of a method descriptor.
  556. // Constructors count as methods here.)
  557. }
  558. }
  559. }
  560. }
  561. /**
  562. * Adds a package root to the list of packages which must be loaded on the
  563. * parent loader.
  564. *
  565. * All subpackages are also included.
  566. *
  567. * @param packageRoot The root of all packages to be included.
  568. * Should not be <code>null</code>.
  569. */
  570. public void addSystemPackageRoot(final String packageRoot) {
  571. systemPackages.addElement(packageRoot + (packageRoot.endsWith(".") ? "" : "."));
  572. }
  573. /**
  574. * Adds a package root to the list of packages which must be loaded using
  575. * this loader.
  576. *
  577. * All subpackages are also included.
  578. *
  579. * @param packageRoot The root of all packages to be included.
  580. * Should not be <code>null</code>.
  581. */
  582. public void addLoaderPackageRoot(final String packageRoot) {
  583. loaderPackages.addElement(packageRoot + (packageRoot.endsWith(".") ? "" : "."));
  584. }
  585. /**
  586. * Loads a class through this class loader even if that class is available
  587. * on the parent classpath.
  588. *
  589. * This ensures that any classes which are loaded by the returned class
  590. * will use this classloader.
  591. *
  592. * @param classname The name of the class to be loaded.
  593. * Must not be <code>null</code>.
  594. *
  595. * @return the required Class object
  596. *
  597. * @exception ClassNotFoundException if the requested class does not exist
  598. * on this loader's classpath.
  599. */
  600. public Class<?> forceLoadClass(final String classname) throws ClassNotFoundException {
  601. log("force loading " + classname, Project.MSG_DEBUG);
  602. Class<?> theClass = findLoadedClass(classname);
  603. if (theClass == null) {
  604. theClass = findClass(classname);
  605. }
  606. return theClass;
  607. }
  608. /**
  609. * Loads a class through this class loader but defer to the parent class
  610. * loader.
  611. *
  612. * This ensures that instances of the returned class will be compatible
  613. * with instances which have already been loaded on the parent
  614. * loader.
  615. *
  616. * @param classname The name of the class to be loaded.
  617. * Must not be <code>null</code>.
  618. *
  619. * @return the required Class object
  620. *
  621. * @exception ClassNotFoundException if the requested class does not exist
  622. * on this loader's classpath.
  623. */
  624. public Class<?> forceLoadSystemClass(final String classname) throws ClassNotFoundException {
  625. log("force system loading " + classname, Project.MSG_DEBUG);
  626. Class<?> theClass = findLoadedClass(classname);
  627. if (theClass == null) {
  628. theClass = findBaseClass(classname);
  629. }
  630. return theClass;
  631. }
  632. /**
  633. * Returns a stream to read the requested resource name.
  634. *
  635. * @param name The name of the resource for which a stream is required.
  636. * Must not be <code>null</code>.
  637. *
  638. * @return a stream to the required resource or <code>null</code> if the
  639. * resource cannot be found on the loader's classpath.
  640. */
  641. @Override
  642. public InputStream getResourceAsStream(final String name) {
  643. InputStream resourceStream = null;
  644. if (isParentFirst(name)) {
  645. resourceStream = loadBaseResource(name);
  646. }
  647. if (resourceStream != null) {
  648. log("ResourceStream for " + name
  649. + " loaded from parent loader", Project.MSG_DEBUG);
  650. } else {
  651. resourceStream = loadResource(name);
  652. if (resourceStream != null) {
  653. log("ResourceStream for " + name
  654. + " loaded from ant loader", Project.MSG_DEBUG);
  655. }
  656. }
  657. if (resourceStream == null && !isParentFirst(name)) {
  658. if (ignoreBase) {
  659. resourceStream = getRootLoader() == null
  660. ? null
  661. : getRootLoader().getResourceAsStream(name);
  662. } else {
  663. resourceStream = loadBaseResource(name);
  664. }
  665. if (resourceStream != null) {
  666. log("ResourceStream for " + name + " loaded from parent loader",
  667. Project.MSG_DEBUG);
  668. }
  669. }
  670. if (resourceStream == null) {
  671. log("Couldn't load ResourceStream for " + name, Project.MSG_DEBUG);
  672. }
  673. return resourceStream;
  674. }
  675. /**
  676. * Returns a stream to read the requested resource name from this loader.
  677. *
  678. * @param name The name of the resource for which a stream is required.
  679. * Must not be <code>null</code>.
  680. *
  681. * @return a stream to the required resource or <code>null</code> if
  682. * the resource cannot be found on the loader's classpath.
  683. */
  684. private InputStream loadResource(final String name) {
  685. // we need to search the components of the path to see if we can
  686. // find the class we want.
  687. InputStream stream = null;
  688. final Enumeration<File> e = pathComponents.elements();
  689. while (e.hasMoreElements() && stream == null) {
  690. final File pathComponent = e.nextElement();
  691. stream = getResourceStream(pathComponent, name);
  692. }
  693. return stream;
  694. }
  695. /**
  696. * Finds a system resource (which should be loaded from the parent
  697. * classloader).
  698. *
  699. * @param name The name of the system resource to load.
  700. * Must not be <code>null</code>.
  701. *
  702. * @return a stream to the named resource, or <code>null</code> if
  703. * the resource cannot be found.
  704. */
  705. private InputStream loadBaseResource(final String name) {
  706. return parent == null ? super.getResourceAsStream(name) : parent.getResourceAsStream(name);
  707. }
  708. /**
  709. * Returns an inputstream to a given resource in the given file which may
  710. * either be a directory or a zip file.
  711. *
  712. * @param file the file (directory or jar) in which to search for the
  713. * resource. Must not be <code>null</code>.
  714. * @param resourceName The name of the resource for which a stream is
  715. * required. Must not be <code>null</code>.
  716. *
  717. * @return a stream to the required resource or <code>null</code> if
  718. * the resource cannot be found in the given file.
  719. */
  720. private InputStream getResourceStream(final File file, final String resourceName) {
  721. try {
  722. JarFile jarFile = jarFiles.get(file);
  723. if (jarFile == null && file.isDirectory()) {
  724. final File resource = new File(file, resourceName);
  725. if (resource.exists()) {
  726. return new FileInputStream(resource);
  727. }
  728. } else {
  729. if (jarFile == null) {
  730. if (file.exists()) {
  731. jarFile = new JarFile(file);
  732. jarFiles.put(file, jarFile);
  733. } else {
  734. return null;
  735. }
  736. //to eliminate a race condition, retrieve the entry
  737. //that is in the hash table under that filename
  738. jarFile = jarFiles.get(file);
  739. }
  740. final JarEntry entry = jarFile.getJarEntry(resourceName);
  741. if (entry != null) {
  742. return jarFile.getInputStream(entry);
  743. }
  744. }
  745. } catch (final Exception e) {
  746. log("Ignoring Exception " + e.getClass().getName() + ": " + e.getMessage()
  747. + " reading resource " + resourceName + " from " + file, Project.MSG_VERBOSE);
  748. }
  749. return null;
  750. }
  751. /**
  752. * Tests whether or not the parent classloader should be checked for a
  753. * resource before this one. If the resource matches both the "use parent
  754. * classloader first" and the "use this classloader first" lists, the latter
  755. * takes priority.
  756. *
  757. * @param resourceName
  758. * The name of the resource to check. Must not be
  759. * <code>null</code>.
  760. *
  761. * @return whether or not the parent classloader should be checked for a
  762. * resource before this one is.
  763. */
  764. private boolean isParentFirst(final String resourceName) {
  765. // default to the global setting and then see
  766. // if this class belongs to a package which has been
  767. // designated to use a specific loader first
  768. // (this one or the parent one)
  769. // TODO - shouldn't this always return false in isolated mode?
  770. boolean useParentFirst = parentFirst;
  771. for (final Enumeration<String> e = systemPackages.elements(); e.hasMoreElements();) {
  772. final String packageName = e.nextElement();
  773. if (resourceName.startsWith(packageName)) {
  774. useParentFirst = true;
  775. break;
  776. }
  777. }
  778. for (final Enumeration<String> e = loaderPackages.elements(); e.hasMoreElements();) {
  779. final String packageName = e.nextElement();
  780. if (resourceName.startsWith(packageName)) {
  781. useParentFirst = false;
  782. break;
  783. }
  784. }
  785. return useParentFirst;
  786. }
  787. /**
  788. * Used for isolated resource seaching.
  789. * @return the root classloader of AntClassLoader.
  790. */
  791. private ClassLoader getRootLoader() {
  792. ClassLoader ret = getClass().getClassLoader();
  793. while (ret != null && ret.getParent() != null) {
  794. ret = ret.getParent();
  795. }
  796. return ret;
  797. }
  798. /**
  799. * Finds the resource with the given name. A resource is
  800. * some data (images, audio, text, etc) that can be accessed by class
  801. * code in a way that is independent of the location of the code.
  802. *
  803. * @param name The name of the resource for which a stream is required.
  804. * Must not be <code>null</code>.
  805. *
  806. * @return a URL for reading the resource, or <code>null</code> if the
  807. * resource could not be found or the caller doesn't have
  808. * adequate privileges to get the resource.
  809. */
  810. @Override
  811. public URL getResource(final String name) {
  812. // we need to search the components of the path to see if
  813. // we can find the class we want.
  814. URL url = null;
  815. if (isParentFirst(name)) {
  816. url = parent == null ? super.getResource(name) : parent.getResource(name);
  817. }
  818. if (url != null) {
  819. log("Resource " + name + " loaded from parent loader", Project.MSG_DEBUG);
  820. } else {
  821. // try and load from this loader if the parent either didn't find
  822. // it or wasn't consulted.
  823. final Enumeration<File> e = pathComponents.elements();
  824. while (e.hasMoreElements() && url == null) {
  825. final File pathComponent = e.nextElement();
  826. url = getResourceURL(pathComponent, name);
  827. if (url != null) {
  828. log("Resource " + name + " loaded from ant loader", Project.MSG_DEBUG);
  829. }
  830. }
  831. }
  832. if (url == null && !isParentFirst(name)) {
  833. // this loader was first but it didn't find it - try the parent
  834. if (ignoreBase) {
  835. url = getRootLoader() == null ? null : getRootLoader().getResource(name);
  836. } else {
  837. url = parent == null ? super.getResource(name) : parent.getResource(name);
  838. }
  839. if (url != null) {
  840. log("Resource " + name + " loaded from parent loader", Project.MSG_DEBUG);
  841. }
  842. }
  843. if (url == null) {
  844. log("Couldn't load Resource " + name, Project.MSG_DEBUG);
  845. }
  846. return url;
  847. }
  848. /**
  849. * Finds all the resources with the given name. A resource is some
  850. * data (images, audio, text, etc) that can be accessed by class
  851. * code in a way that is independent of the location of the code.
  852. *
  853. * <p>Would override getResources if that wasn't final in Java
  854. * 1.4.</p>
  855. *
  856. * @param name name of the resource
  857. * @return possible URLs as enumeration
  858. * @throws IOException
  859. * @see {@link #findResources(String, boolean)}
  860. * @since Ant 1.8.0
  861. */
  862. public Enumeration<URL> getNamedResources(final String name)
  863. throws IOException {
  864. return findResources(name, false);
  865. }
  866. /**
  867. * Returns an enumeration of URLs representing all the resources with the
  868. * given name by searching the class loader's classpath.
  869. *
  870. * @param name The resource name to search for.
  871. * Must not be <code>null</code>.
  872. * @return an enumeration of URLs for the resources
  873. * @exception IOException if I/O errors occurs (can't happen)
  874. */
  875. @Override
  876. protected Enumeration<URL> findResources(final String name) throws IOException {
  877. return findResources(name, true);
  878. }
  879. /**
  880. * Returns an enumeration of URLs representing all the resources with the
  881. * given name by searching the class loader's classpath.
  882. *
  883. * @param name The resource name to search for.
  884. * Must not be <code>null</code>.
  885. * @param parentHasBeenSearched whether ClassLoader.this.parent
  886. * has been searched - will be true if the method is (indirectly)
  887. * called from ClassLoader.getResources
  888. * @return an enumeration of URLs for the resources
  889. * @exception IOException if I/O errors occurs (can't happen)
  890. */
  891. protected Enumeration<URL> findResources(final String name,
  892. final boolean parentHasBeenSearched)
  893. throws IOException {
  894. final Enumeration<URL> mine = new ResourceEnumeration(name);
  895. Enumeration<URL> base;
  896. if (parent != null && (!parentHasBeenSearched || parent != getParent())) {
  897. // Delegate to the parent:
  898. base = parent.getResources(name);
  899. // Note: could cause overlaps in case
  900. // ClassLoader.this.parent has matches and
  901. // parentHasBeenSearched is true
  902. } else {
  903. // ClassLoader.this.parent is already delegated to for example from
  904. // ClassLoader.getResources, no need:
  905. base = new CollectionUtils.EmptyEnumeration<URL>();
  906. }
  907. if (isParentFirst(name)) {
  908. // Normal case.
  909. return CollectionUtils.append(base, mine);
  910. }
  911. if (ignoreBase) {
  912. return getRootLoader() == null ? mine : CollectionUtils.append(mine, getRootLoader()
  913. .getResources(name));
  914. }
  915. // parent last:
  916. return CollectionUtils.append(mine, base);
  917. }
  918. /**
  919. * Returns the URL of a given resource in the given file which may
  920. * either be a directory or a zip file.
  921. *
  922. * @param file The file (directory or jar) in which to search for
  923. * the resource. Must not be <code>null</code>.
  924. * @param resourceName The name of the resource for which a stream
  925. * is required. Must not be <code>null</code>.
  926. *
  927. * @return a stream to the required resource or <code>null</code> if the
  928. * resource cannot be found in the given file object.
  929. */
  930. protected URL getResourceURL(final File file, final String resourceName) {
  931. try {
  932. JarFile jarFile = jarFiles.get(file);
  933. if (jarFile == null && file.isDirectory()) {
  934. final File resource = new File(file, resourceName);
  935. if (resource.exists()) {
  936. try {
  937. return FILE_UTILS.getFileURL(resource);
  938. } catch (final MalformedURLException ex) {
  939. return null;
  940. }
  941. }
  942. } else {
  943. if (jarFile == null) {
  944. if (file.exists()) {
  945. if (!isZip(file)) {
  946. final String msg = "CLASSPATH element " + file
  947. + " is not a JAR.";
  948. log(msg, Project.MSG_WARN);
  949. System.err.println(msg);
  950. return null;
  951. }
  952. jarFile = new JarFile(file);
  953. jarFiles.put(file, jarFile);
  954. } else {
  955. return null;
  956. }
  957. // potential race-condition
  958. jarFile = jarFiles.get(file);
  959. }
  960. final JarEntry entry = jarFile.getJarEntry(resourceName);
  961. if (entry != null) {
  962. try {
  963. return new URL("jar:" + FILE_UTILS.getFileURL(file) + "!/" + entry);
  964. } catch (final MalformedURLException ex) {
  965. return null;
  966. }
  967. }
  968. }
  969. } catch (final Exception e) {
  970. final String msg = "Unable to obtain resource from " + file + ": ";
  971. log(msg + e, Project.MSG_WARN);
  972. System.err.println(msg);
  973. e.printStackTrace();
  974. }
  975. return null;
  976. }
  977. /**
  978. * Loads a class with this class loader.
  979. *
  980. * This class attempts to load the class in an order determined by whether
  981. * or not the class matches the system/loader package lists, with the
  982. * loader package list taking priority. If the classloader is in isolated
  983. * mode, failure to load the class in this loader will result in a
  984. * ClassNotFoundException.
  985. *
  986. * @param classname The name of the class to be loaded.
  987. * Must not be <code>null</code>.
  988. * @param resolve <code>true</code> if all classes upon which this class
  989. * depends are to be loaded.
  990. *
  991. * @return the required Class object
  992. *
  993. * @exception ClassNotFoundException if the requested class does not exist
  994. * on the system classpath (when not in isolated mode) or this loader's
  995. * classpath.
  996. */
  997. @Override
  998. protected synchronized Class<?> loadClass(final String classname, final boolean resolve)
  999. throws ClassNotFoundException {
  1000. // 'sync' is needed - otherwise 2 threads can load the same class
  1001. // twice, resulting in LinkageError: duplicated class definition.
  1002. // findLoadedClass avoids that, but without sync it won't work.
  1003. Class<?> theClass = findLoadedClass(classname);
  1004. if (theClass != null) {
  1005. return theClass;
  1006. }
  1007. if (isParentFirst(classname)) {
  1008. try {
  1009. theClass = findBaseClass(classname);
  1010. log("Class " + classname + " loaded from parent loader " + "(parentFirst)",
  1011. Project.MSG_DEBUG);
  1012. } catch (final ClassNotFoundException cnfe) {
  1013. theClass = findClass(classname);
  1014. log("Class " + classname + " loaded from ant loader " + "(parentFirst)",
  1015. Project.MSG_DEBUG);
  1016. }
  1017. } else {
  1018. try {
  1019. theClass = findClass(classname);
  1020. log("Class " + classname + " loaded from ant loader", Project.MSG_DEBUG);
  1021. } catch (final ClassNotFoundException cnfe) {
  1022. if (ignoreBase) {
  1023. throw cnfe;
  1024. }
  1025. theClass = findBaseClass(classname);
  1026. log("Class " + classname + " loaded from parent loader", Project.MSG_DEBUG);
  1027. }
  1028. }
  1029. if (resolve) {
  1030. resolveClass(theClass);
  1031. }
  1032. return theClass;
  1033. }
  1034. /**
  1035. * Converts the class dot notation to a filesystem equivalent for
  1036. * searching purposes.
  1037. *
  1038. * @param classname The class name in dot format (eg java.lang.Integer).
  1039. * Must not be <code>null</code>.
  1040. *
  1041. * @return the classname in filesystem format (eg java/lang/Integer.class)
  1042. */
  1043. private String getClassFilename(final String classname) {
  1044. return classname.replace('.', '/') + ".class";
  1045. }
  1046. /**
  1047. * Define a class given its bytes
  1048. *
  1049. * @param container the container from which the class data has been read
  1050. * may be a directory or a jar/zip file.
  1051. *
  1052. * @param classData the bytecode data for the class
  1053. * @param classname the name of the class
  1054. *
  1055. * @return the Class instance created from the given data
  1056. *
  1057. * @throws IOException if the class data cannot be read.
  1058. */
  1059. protected Class<?> defineClassFromData(final File container, final byte[] classData, final String classname)
  1060. throws IOException {
  1061. definePackage(container, classname);
  1062. final ProtectionDomain currentPd = Project.class.getProtectionDomain();
  1063. final String classResource = getClassFilename(classname);
  1064. final CodeSource src = new CodeSource(FILE_UTILS.getFileURL(container),
  1065. getCertificates(container,
  1066. classResource));
  1067. final ProtectionDomain classesPd =
  1068. new ProtectionDomain(src, currentPd.getPermissions(),
  1069. this,
  1070. currentPd.getPrincipals());
  1071. return defineClass(classname, classData, 0, classData.length,
  1072. classesPd);
  1073. }
  1074. /**
  1075. * Define the package information associated with a class.
  1076. *
  1077. * @param container the file containing the class definition.
  1078. * @param className the class name of for which the package information
  1079. * is to be determined.
  1080. *
  1081. * @exception IOException if the package information cannot be read from the
  1082. * container.
  1083. */
  1084. protected void definePackage(final File container, final String className) throws IOException {
  1085. final int classIndex = className.lastIndexOf('.');
  1086. if (classIndex == -1) {
  1087. return;
  1088. }
  1089. final String packageName = className.substring(0, classIndex);
  1090. if (getPackage(packageName) != null) {
  1091. // already defined
  1092. return;
  1093. }
  1094. // define the package now
  1095. final Manifest manifest = getJarManifest(container);
  1096. if (manifest == null) {
  1097. definePackage(packageName, null, null, null, null, null, null, null);
  1098. } else {
  1099. definePackage(container, packageName, manifest);
  1100. }
  1101. }
  1102. /**
  1103. * Get the manifest from the given jar, if it is indeed a jar and it has a
  1104. * manifest
  1105. *
  1106. * @param container the File from which a manifest is required.
  1107. *
  1108. * @return the jar's manifest or null is the container is not a jar or it
  1109. * has no manifest.
  1110. *
  1111. * @exception IOException if the manifest cannot be read.
  1112. */
  1113. private Manifest getJarManifest(final File container) throws IOException {
  1114. if (container.isDirectory()) {
  1115. return null;
  1116. }
  1117. final JarFile jarFile = jarFiles.get(container);
  1118. if (jarFile == null) {
  1119. return null;
  1120. }
  1121. return jarFile.getManifest();
  1122. }
  1123. /**
  1124. * Get the certificates for a given jar entry, if it is indeed a jar.
  1125. *
  1126. * @param container the File from which to read the entry
  1127. * @param entry the entry of which the certificates are requested
  1128. *
  1129. * @return the entry's certificates or null is the container is
  1130. * not a jar or it has no certificates.
  1131. */
  1132. private Certificate[] getCertificates(final File container, final String entry) {
  1133. if (container.isDirectory()) {
  1134. return null;
  1135. }
  1136. final JarFile jarFile = jarFiles.get(container);
  1137. if (jarFile == null) {
  1138. return null;
  1139. }
  1140. final JarEntry ent = jarFile.getJarEntry(entry);
  1141. return ent == null ? null : ent.getCertificates();
  1142. }
  1143. /**
  1144. * Define the package information when the class comes from a
  1145. * jar with a manifest
  1146. *
  1147. * @param container the jar file containing the manifest
  1148. * @param packageName the name of the package being defined.
  1149. * @param manifest the jar's manifest
  1150. */
  1151. protected void definePackage(final File container, final String packageName, final Manifest manifest) {
  1152. final String sectionName = packageName.replace('.', '/') + "/";
  1153. String specificationTitle = null;
  1154. String specificationVendor = null;
  1155. String specificationVersion = null;
  1156. String implementationTitle = null;
  1157. String implementationVendor = null;
  1158. String implementationVersion = null;
  1159. String sealedString = null;
  1160. URL sealBase = null;
  1161. final Attributes sectionAttributes = manifest.getAttributes(sectionName);
  1162. if (sectionAttributes != null) {
  1163. specificationTitle = sectionAttributes.getValue(Name.SPECIFICATION_TITLE);
  1164. specificationVendor = sectionAttributes.getValue(Name.SPECIFICATION_VENDOR);
  1165. specificationVersion = sectionAttributes.getValue(Name.SPECIFICATION_VERSION);
  1166. implementationTitle = sectionAttributes.getValue(Name.IMPLEMENTATION_TITLE);
  1167. implementationVendor = sectionAttributes.getValue(Name.IMPLEMENTATION_VENDOR);
  1168. implementationVersion = sectionAttributes.getValue(Name.IMPLEMENTATION_VERSION);
  1169. sealedString = sectionAttributes.getValue(Name.SEALED);
  1170. }
  1171. final Attributes mainAttributes = manifest.getMainAttributes();
  1172. if (mainAttributes != null) {
  1173. if (specificationTitle == null) {
  1174. specificationTitle = mainAttributes.getValue(Name.SPECIFICATION_TITLE);
  1175. }
  1176. if (specificationVendor == null) {
  1177. specificationVendor = mainAttributes.getValue(Name.SPECIFICATION_VENDOR);
  1178. }
  1179. if (specificationVersion == null) {
  1180. specificationVersion = mainAttributes.getValue(Name.SPECIFICATION_VERSION);
  1181. }
  1182. if (implementationTitle == null) {
  1183. implementationTitle = mainAttributes.getValue(Name.IMPLEMENTATION_TITLE);
  1184. }
  1185. if (implementationVendor == null) {
  1186. implementationVendor = mainAttributes.getValue(Name.IMPLEMENTATION_VENDOR);
  1187. }
  1188. if (implementationVersion == null) {
  1189. implementationVersion = mainAttributes.getValue(Name.IMPLEMENTATION_VERSION);
  1190. }
  1191. if (sealedString == null) {
  1192. sealedString = mainAttributes.getValue(Name.SEALED);
  1193. }
  1194. }
  1195. if (sealedString != null && sealedString.equalsIgnoreCase("true")) {
  1196. try {
  1197. sealBase = new URL(FileUtils.getFileUtils().toURI(container.getAbsolutePath()));
  1198. } catch (final MalformedURLException e) {
  1199. // ignore
  1200. }
  1201. }
  1202. definePackage(packageName, specificationTitle, specificationVersion, specificationVendor,
  1203. implementationTitle, implementationVersion, implementationVendor, sealBase);
  1204. }
  1205. /**
  1206. * Reads a class definition from a stream.
  1207. *
  1208. * @param stream The stream from which the class is to be read.
  1209. * Must not be <code>null</code>.
  1210. * @param classname The name of the class in the stream.
  1211. * Must not be <code>null</code>.
  1212. * @param container the file or directory containing the class.
  1213. *
  1214. * @return the Class object read from the stream.
  1215. *
  1216. * @exception IOException if there is a problem reading the class from the
  1217. * stream.
  1218. * @exception SecurityException if there is a security problem while
  1219. * reading the class from the stream.
  1220. */
  1221. private Class<?> getClassFromStream(final InputStream stream, final String classname, final File container)
  1222. throws IOException, SecurityException {
  1223. final ByteArrayOutputStream baos = new ByteArrayOutputStream();
  1224. int bytesRead = -1;
  1225. final byte[] buffer = new byte[BUFFER_SIZE];
  1226. while ((bytesRead = stream.read(buffer, 0, BUFFER_SIZE)) != -1) {
  1227. baos.write(buffer, 0, bytesRead);
  1228. }
  1229. final byte[] classData = baos.toByteArray();
  1230. return defineClassFromData(container, classData, classname);
  1231. }
  1232. /**
  1233. * Searches for and load a class on the classpath of this class loader.
  1234. *
  1235. * @param name The name of the class to be loaded. Must not be
  1236. * <code>null</code>.
  1237. *
  1238. * @return the required Class object
  1239. *
  1240. * @exception ClassNotFoundException if the requested class does not exist
  1241. * on this loader's classpath.
  1242. */
  1243. @Override
  1244. public Class<?> findClass(final String name) throws ClassNotFoundException {
  1245. log("Finding class " + name, Project.MSG_DEBUG);
  1246. return findClassInComponents(name);
  1247. }
  1248. /**
  1249. * Indicate if the given file is in this loader's path
  1250. *
  1251. * @param component the file which is to be checked
  1252. *
  1253. * @return true if the file is in the class path
  1254. */
  1255. protected boolean isInPath(final File component) {
  1256. return pathComponents.contains(component);
  1257. }
  1258. /**
  1259. * Finds a class on the given classpath.
  1260. *
  1261. * @param name The name of the class to be loaded. Must not be
  1262. * <code>null</code>.
  1263. *
  1264. * @return the required Class object
  1265. *
  1266. * @exception ClassNotFoundException if the requested class does not exist
  1267. * on this loader's classpath.
  1268. */
  1269. private Class<?> findClassInComponents(final String name)
  1270. throws ClassNotFoundException {
  1271. // we need to search the components of the path to see if
  1272. // we can find the class we want.
  1273. final String classFilename = getClassFilename(name);
  1274. final Enumeration<File> e = pathComponents.elements();
  1275. while (e.hasMoreElements()) {
  1276. final File pathComponent = e.nextElement();
  1277. InputStream stream = null;
  1278. try {
  1279. stream = getResourceStream(pathComponent, classFilename);
  1280. if (stream != null) {
  1281. log("Loaded from " + pathComponent + " "
  1282. + classFilename, Project.MSG_DEBUG);
  1283. return getClassFromStream(stream, name, pathComponent);
  1284. }
  1285. } catch (final SecurityException se) {
  1286. throw se;
  1287. } catch (final IOException ioe) {
  1288. // ioe.printStackTrace();
  1289. log("Exception reading component " + pathComponent + " (reason: "
  1290. + ioe.getMessage() + ")", Project.MSG_VERBOSE);
  1291. } finally {
  1292. FileUtils.close(stream);
  1293. }
  1294. }
  1295. throw new ClassNotFoundException(name);
  1296. }
  1297. /**
  1298. * Finds a system class (which should be loaded from the same classloader
  1299. * as the Ant core).
  1300. *
  1301. * For JDK 1.1 compatibility, this uses the findSystemClass method if
  1302. * no parent classloader has been specified.
  1303. *
  1304. * @param name The name of the class to be loaded.
  1305. * Must not be <code>null</code>.
  1306. *
  1307. * @return the required Class object
  1308. *
  1309. * @exception ClassNotFoundException if the requested class does not exist
  1310. * on this loader's classpath.
  1311. */
  1312. private Class<?> findBaseClass(final String name) throws ClassNotFoundException {
  1313. return parent == null ? findSystemClass(name) : parent.loadClass(name);
  1314. }
  1315. /**
  1316. * Cleans up any resources held by this classloader. Any open archive
  1317. * files are closed.
  1318. */
  1319. public synchronized void cleanup() {
  1320. for (final Enumeration<JarFile> e = jarFiles.elements(); e.hasMoreElements();) {
  1321. FileUtils.close(e.nextElement());
  1322. }
  1323. jarFiles = new Hashtable<File, JarFile>();
  1324. if (project != null) {
  1325. project.removeBuildListener(this);
  1326. }
  1327. project = null;
  1328. }
  1329. /**
  1330. * Gets the parent as has been specified in the constructor or via
  1331. * setParent.
  1332. *
  1333. * @return classloader
  1334. * @since Ant 1.8.0
  1335. */
  1336. public ClassLoader getConfiguredParent() {
  1337. return parent;
  1338. }
  1339. /**
  1340. * Empty implementation to satisfy the BuildListener interface.
  1341. *
  1342. * @param event the buildStarted event
  1343. */
  1344. public void buildStarted(final BuildEvent event) {
  1345. // Not significant for the class loader.
  1346. }
  1347. /**
  1348. * Cleans up any resources held by this classloader at the end
  1349. * of a build.
  1350. *
  1351. * @param event the buildFinished event
  1352. */
  1353. public void buildFinished(final BuildEvent event) {
  1354. cleanup();
  1355. }
  1356. /**
  1357. * Cleans up any resources held by this classloader at the end of
  1358. * a subbuild if it has been created for the subbuild's project
  1359. * instance.
  1360. *
  1361. * @param event the buildFinished event
  1362. *
  1363. * @since Ant 1.6.2
  1364. */
  1365. public void subBuildFinished(final BuildEvent event) {
  1366. if (event.getProject() == project) {
  1367. cleanup();
  1368. }
  1369. }
  1370. /**
  1371. * Empty implementation to satisfy the BuildListener interface.
  1372. *
  1373. * @param event the buildStarted event
  1374. *
  1375. * @since Ant 1.6.2
  1376. */
  1377. public void subBuildStarted(final BuildEvent event) {
  1378. // Not significant for the class loader.
  1379. }
  1380. /**
  1381. * Empty implementation to satisfy the BuildListener interface.
  1382. *
  1383. * @param event the targetStarted event
  1384. */
  1385. public void targetStarted(final BuildEvent event) {
  1386. // Not significant for the class loader.
  1387. }
  1388. /**
  1389. * Empty implementation to satisfy the BuildListener interface.
  1390. *
  1391. * @param event the targetFinished event
  1392. */
  1393. public void targetFinished(final BuildEvent event) {
  1394. // Not significant for the class loader.
  1395. }
  1396. /**
  1397. * Empty implementation to satisfy the BuildListener interface.
  1398. *
  1399. * @param event the taskStarted event
  1400. */
  1401. public void taskStarted(final BuildEvent event) {
  1402. // Not significant for the class loader.
  1403. }
  1404. /**
  1405. * Empty implementation to satisfy the BuildListener interface.
  1406. *
  1407. * @param event the taskFinished event
  1408. */
  1409. public void taskFinished(final BuildEvent event) {
  1410. // Not significant for the class loader.
  1411. }
  1412. /**
  1413. * Empty implementation to satisfy the BuildListener interface.
  1414. *
  1415. * @param event the messageLogged event
  1416. */
  1417. public void messageLogged(final BuildEvent event) {
  1418. // Not significant for the class loader.
  1419. }
  1420. /**
  1421. * add any libraries that come with different java versions
  1422. * here
  1423. */
  1424. public void addJavaLibraries() {
  1425. final Vector<String> packages = JavaEnvUtils.getJrePackages();
  1426. final Enumeration<String> e = packages.elements();
  1427. while (e.hasMoreElements()) {
  1428. final String packageName = e.nextElement();
  1429. addSystemPackageRoot(packageName);
  1430. }
  1431. }
  1432. /**
  1433. * Returns a <code>String</code> representing this loader.
  1434. * @return the path that this classloader has.
  1435. */
  1436. @Override
  1437. public String toString() {
  1438. return "AntClassLoader[" + getClasspath() + "]";
  1439. }
  1440. /** {@inheritDoc} */
  1441. @Override
  1442. public Enumeration<URL> getResources(String name) throws IOException {
  1443. return getNamedResources(name);
  1444. }
  1445. /** {@inheritDoc} */
  1446. public void close() {
  1447. cleanup();
  1448. }
  1449. /**
  1450. * Factory method
  1451. */
  1452. public static AntClassLoader newAntClassLoader(final ClassLoader parent,
  1453. final Project project,
  1454. final Path path,
  1455. final boolean parentFirst) {
  1456. return new AntClassLoader(parent, project, path, parentFirst);
  1457. }
  1458. private static final ZipLong EOCD_SIG = new ZipLong(0X06054B50L);
  1459. private static final ZipLong SINGLE_SEGMENT_SPLIT_MARKER =
  1460. new ZipLong(0X30304B50L);
  1461. private static boolean isZip(final File file) throws IOException {
  1462. final byte[] sig = new byte[4];
  1463. if (readFully(file, sig)) {
  1464. final ZipLong start = new ZipLong(sig);
  1465. return ZipLong.LFH_SIG.equals(start) // normal file
  1466. || EOCD_SIG.equals(start) // empty zip
  1467. || ZipLong.DD_SIG.equals(start) // split zip
  1468. || SINGLE_SEGMENT_SPLIT_MARKER.equals(start);
  1469. }
  1470. return false;
  1471. }
  1472. private static boolean readFully(final File f, final byte[] b) throws IOException {
  1473. try (FileInputStream fis = new FileInputStream(f)) {
  1474. final int len = b.length;
  1475. int count = 0, x = 0;
  1476. while (count != len) {
  1477. x = fis.read(b, count, len - count);
  1478. if (x == -1) {
  1479. break;
  1480. }
  1481. count += x;
  1482. }
  1483. return count == len;
  1484. }
  1485. }
  1486. }