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.

Launcher.java 15 kB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
9 years ago
11 years ago
11 years ago
11 years ago
8 years ago
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
9 years ago
11 years ago
9 years ago
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
9 years ago
11 years ago
9 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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. * https://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.launch;
  19. import java.io.File;
  20. import java.net.MalformedURLException;
  21. import java.net.URL;
  22. import java.net.URLClassLoader;
  23. import java.util.ArrayList;
  24. import java.util.List;
  25. import java.util.StringTokenizer;
  26. /**
  27. * This is a launcher for Ant.
  28. *
  29. * @since Ant 1.6
  30. */
  31. public class Launcher {
  32. /**
  33. * The Ant Home (installation) Directory property.
  34. * {@value}
  35. */
  36. public static final String ANTHOME_PROPERTY = "ant.home";
  37. /**
  38. * The Ant Library Directory property.
  39. * {@value}
  40. */
  41. public static final String ANTLIBDIR_PROPERTY = "ant.library.dir";
  42. /**
  43. * The directory name of the per-user ant directory.
  44. * {@value}
  45. */
  46. public static final String ANT_PRIVATEDIR = ".ant";
  47. /**
  48. * The name of a per-user library directory.
  49. * {@value}
  50. */
  51. public static final String ANT_PRIVATELIB = "lib";
  52. /**
  53. * The location of a per-user library directory.
  54. * <p>It's value is the concatenation of {@link #ANT_PRIVATEDIR}
  55. * with {@link #ANT_PRIVATELIB}, with an appropriate file separator
  56. * in between. For example, on Unix, it's <code>.ant/lib</code>.</p>
  57. */
  58. public static final String USER_LIBDIR =
  59. ANT_PRIVATEDIR + File.separatorChar + ANT_PRIVATELIB;
  60. /**
  61. * The startup class that is to be run.
  62. * {@value}
  63. */
  64. public static final String MAIN_CLASS = "org.apache.tools.ant.Main";
  65. /**
  66. * System property with user home directory.
  67. * {@value}
  68. */
  69. public static final String USER_HOMEDIR = "user.home";
  70. /**
  71. * System property with application classpath.
  72. * {@value}
  73. */
  74. private static final String JAVA_CLASS_PATH = "java.class.path";
  75. /**
  76. * Exit code on trouble
  77. */
  78. protected static final int EXIT_CODE_ERROR = 2;
  79. /**
  80. * Entry point for starting command line Ant.
  81. *
  82. * @param args commandline arguments
  83. */
  84. public static void main(final String[] args) {
  85. int exitCode;
  86. boolean launchDiag = false;
  87. try {
  88. final Launcher launcher = new Launcher();
  89. exitCode = launcher.run(args);
  90. launchDiag = launcher.launchDiag;
  91. } catch (final LaunchException e) {
  92. exitCode = EXIT_CODE_ERROR;
  93. System.err.println(e.getMessage());
  94. } catch (final Throwable t) {
  95. exitCode = EXIT_CODE_ERROR;
  96. t.printStackTrace(System.err); //NOSONAR
  97. }
  98. if (exitCode != 0) {
  99. if (launchDiag) {
  100. System.out.println("Exit code: " + exitCode);
  101. }
  102. System.exit(exitCode);
  103. }
  104. }
  105. /**
  106. * launch diagnostics flag; for debugging trouble at launch time.
  107. */
  108. public boolean launchDiag = false;
  109. private Launcher() {
  110. }
  111. /**
  112. * Add a CLASSPATH or -lib to lib path urls.
  113. * Only filesystem resources are supported.
  114. *
  115. * @param path the classpath or lib path to add to the libPathULRLs
  116. * @param getJars if true and a path is a directory, add the jars in
  117. * the directory to the path urls
  118. * @param libPathURLs the list of paths to add to
  119. * @throws MalformedURLException if we can't create a URL
  120. */
  121. private void addPath(final String path, final boolean getJars, final List<URL> libPathURLs)
  122. throws MalformedURLException {
  123. final StringTokenizer tokenizer = new StringTokenizer(path, File.pathSeparator);
  124. while (tokenizer.hasMoreElements()) {
  125. final String elementName = tokenizer.nextToken();
  126. final File element = new File(elementName);
  127. if (elementName.contains("%") && !element.exists()) {
  128. continue;
  129. }
  130. if (getJars && element.isDirectory()) {
  131. // add any jars in the directory
  132. for (URL dirURL : Locator.getLocationURLs(element)) {
  133. if (launchDiag) {
  134. System.out.println("adding library JAR: " + dirURL);
  135. }
  136. libPathURLs.add(dirURL);
  137. }
  138. }
  139. final URL url = new URL(element.toURI().toASCIIString());
  140. if (launchDiag) {
  141. System.out.println("adding library URL: " + url);
  142. }
  143. libPathURLs.add(url);
  144. }
  145. }
  146. /**
  147. * Run the launcher to launch Ant.
  148. *
  149. * @param args the command line arguments
  150. * @return an exit code. As the normal ant main calls exit when it ends,
  151. * this is for handling failures at bind-time
  152. * @throws MalformedURLException if the URLs required for the classloader
  153. * cannot be created.
  154. * @throws LaunchException for launching problems
  155. */
  156. private int run(final String[] args)
  157. throws LaunchException, MalformedURLException {
  158. final String antHomeProperty = System.getProperty(ANTHOME_PROPERTY);
  159. File antHome = null;
  160. final File sourceJar = Locator.getClassSource(getClass());
  161. final File jarDir = sourceJar.getParentFile();
  162. String mainClassname = MAIN_CLASS;
  163. if (antHomeProperty != null) {
  164. antHome = new File(antHomeProperty);
  165. }
  166. if (antHome == null || !antHome.exists()) {
  167. antHome = jarDir.getParentFile();
  168. setProperty(ANTHOME_PROPERTY, antHome.getAbsolutePath());
  169. }
  170. if (!antHome.exists()) {
  171. throw new LaunchException(
  172. "Ant home is set incorrectly or ant could not be located (estimated value="
  173. + antHome.getAbsolutePath() + ")");
  174. }
  175. final List<String> libPaths = new ArrayList<>();
  176. String cpString = null;
  177. final List<String> argList = new ArrayList<>();
  178. String[] newArgs;
  179. boolean noUserLib = false;
  180. boolean noClassPath = false;
  181. for (int i = 0; i < args.length; ++i) {
  182. if ("-lib".equals(args[i])) {
  183. if (i == args.length - 1) {
  184. throw new LaunchException(
  185. "The -lib argument must be followed by a library location");
  186. }
  187. libPaths.add(args[++i]);
  188. } else if ("-cp".equals(args[i])) {
  189. if (i == args.length - 1) {
  190. throw new LaunchException(
  191. "The -cp argument must be followed by a classpath expression");
  192. }
  193. if (cpString != null) {
  194. throw new LaunchException(
  195. "The -cp argument must not be repeated");
  196. }
  197. cpString = args[++i];
  198. } else if ("--nouserlib".equals(args[i]) || "-nouserlib".equals(args[i])) {
  199. noUserLib = true;
  200. } else if ("--launchdiag".equals(args[i])) {
  201. launchDiag = true;
  202. } else if ("--noclasspath".equals(args[i]) || "-noclasspath".equals(args[i])) {
  203. noClassPath = true;
  204. } else if ("-main".equals(args[i])) {
  205. if (i == args.length - 1) {
  206. throw new LaunchException(
  207. "The -main argument must be followed by a library location");
  208. }
  209. mainClassname = args[++i];
  210. } else {
  211. argList.add(args[i]);
  212. }
  213. }
  214. logPath("Launcher JAR", sourceJar);
  215. logPath("Launcher JAR directory", sourceJar.getParentFile());
  216. logPath("java.home", new File(System.getProperty("java.home")));
  217. //decide whether to copy the existing arg set, or
  218. //build a new one from the list of all args excluding the special
  219. //operations that only we handle
  220. if (argList.size() == args.length) {
  221. newArgs = args;
  222. } else {
  223. newArgs = argList.toArray(new String[0]);
  224. }
  225. final URL[] libURLs = getLibPathURLs(
  226. noClassPath ? null : cpString, libPaths);
  227. final URL[] systemURLs = getSystemURLs(jarDir);
  228. final URL[] userURLs = noUserLib ? new URL[0] : getUserURLs();
  229. final File toolsJAR = Locator.getToolsJar();
  230. logPath("tools.jar", toolsJAR);
  231. final URL[] jars = getJarArray(
  232. libURLs, userURLs, systemURLs, toolsJAR);
  233. // now update the class.path property
  234. final StringBuilder baseClassPath
  235. = new StringBuilder(System.getProperty(JAVA_CLASS_PATH));
  236. if (baseClassPath.charAt(baseClassPath.length() - 1)
  237. == File.pathSeparatorChar) {
  238. baseClassPath.setLength(baseClassPath.length() - 1);
  239. }
  240. for (URL jar : jars) {
  241. baseClassPath.append(File.pathSeparatorChar);
  242. baseClassPath.append(Locator.fromURI(jar.toString()));
  243. }
  244. setProperty(JAVA_CLASS_PATH, baseClassPath.toString());
  245. final URLClassLoader loader = new URLClassLoader(jars, Launcher.class.getClassLoader());
  246. Thread.currentThread().setContextClassLoader(loader);
  247. Class<? extends AntMain> mainClass = null;
  248. int exitCode = 0;
  249. Throwable thrown = null;
  250. try {
  251. mainClass = loader.loadClass(mainClassname).asSubclass(AntMain.class);
  252. final AntMain main = mainClass.getDeclaredConstructor().newInstance();
  253. main.startAnt(newArgs, null, null);
  254. } catch (final InstantiationException ex) {
  255. System.err.println(
  256. "Incompatible version of " + mainClassname + " detected");
  257. final File mainJar = Locator.getClassSource(mainClass);
  258. System.err.println(
  259. "Location of this class " + mainJar);
  260. thrown = ex;
  261. } catch (final ClassNotFoundException cnfe) {
  262. System.err.println(
  263. "Failed to locate" + mainClassname);
  264. thrown = cnfe;
  265. } catch (final Throwable t) {
  266. t.printStackTrace(System.err); //NOSONAR
  267. thrown = t;
  268. }
  269. if (thrown != null) {
  270. System.err.println(ANTHOME_PROPERTY + ": " + antHome.getAbsolutePath());
  271. System.err.println("Classpath: " + baseClassPath.toString());
  272. System.err.println("Launcher JAR: " + sourceJar.getAbsolutePath());
  273. System.err.println("Launcher Directory: " + jarDir.getAbsolutePath());
  274. exitCode = EXIT_CODE_ERROR;
  275. }
  276. return exitCode;
  277. }
  278. /**
  279. * Get the list of -lib entries and -cp entry into
  280. * a URL array.
  281. * @param cpString the classpath string
  282. * @param libPaths the list of -lib entries.
  283. * @return an array of URLs.
  284. * @throws MalformedURLException if the URLs cannot be created.
  285. */
  286. private URL[] getLibPathURLs(final String cpString, final List<String> libPaths)
  287. throws MalformedURLException {
  288. final List<URL> libPathURLs = new ArrayList<>();
  289. if (cpString != null) {
  290. addPath(cpString, false, libPathURLs);
  291. }
  292. for (final String libPath : libPaths) {
  293. addPath(libPath, true, libPathURLs);
  294. }
  295. return libPathURLs.toArray(new URL[0]);
  296. }
  297. /**
  298. * Get the jar files in ANT_HOME/lib.
  299. * determine ant library directory for system jars: use property
  300. * or default using location of ant-launcher.jar
  301. * @param antLauncherDir the dir that ant-launcher ran from
  302. * @return the URLs
  303. * @throws MalformedURLException if the URLs cannot be created.
  304. */
  305. private URL[] getSystemURLs(final File antLauncherDir) throws MalformedURLException {
  306. File antLibDir = null;
  307. final String antLibDirProperty = System.getProperty(ANTLIBDIR_PROPERTY);
  308. if (antLibDirProperty != null) {
  309. antLibDir = new File(antLibDirProperty);
  310. }
  311. if (antLibDir == null || !antLibDir.exists()) {
  312. antLibDir = antLauncherDir;
  313. setProperty(ANTLIBDIR_PROPERTY, antLibDir.getAbsolutePath());
  314. }
  315. return Locator.getLocationURLs(antLibDir);
  316. }
  317. /**
  318. * Get the jar files in user.home/.ant/lib
  319. * @return the URLS from the user's lib dir
  320. * @throws MalformedURLException if the URLs cannot be created.
  321. */
  322. private URL[] getUserURLs() throws MalformedURLException {
  323. final File userLibDir
  324. = new File(System.getProperty(USER_HOMEDIR), USER_LIBDIR);
  325. return Locator.getLocationURLs(userLibDir);
  326. }
  327. /**
  328. * Combine the various jar sources into a single array of jars.
  329. * @param libJars the jars specified in -lib command line options
  330. * @param userJars the jars in ~/.ant/lib
  331. * @param systemJars the jars in $ANT_HOME/lib
  332. * @param toolsJar the tools.jar file
  333. * @return a combined array
  334. * @throws MalformedURLException if there is a problem.
  335. */
  336. private URL[] getJarArray(final URL[] libJars, final URL[] userJars,
  337. final URL[] systemJars, final File toolsJar)
  338. throws MalformedURLException {
  339. int numJars = libJars.length + userJars.length + systemJars.length;
  340. if (toolsJar != null) {
  341. numJars++;
  342. }
  343. final URL[] jars = new URL[numJars];
  344. System.arraycopy(libJars, 0, jars, 0, libJars.length);
  345. System.arraycopy(userJars, 0, jars, libJars.length, userJars.length);
  346. System.arraycopy(systemJars, 0, jars, userJars.length + libJars.length,
  347. systemJars.length);
  348. if (toolsJar != null) {
  349. jars[jars.length - 1] = new URL(toolsJar.toURI().toASCIIString());
  350. }
  351. return jars;
  352. }
  353. /**
  354. * set a system property, optionally log what is going on
  355. * @param name property name
  356. * @param value value
  357. */
  358. private void setProperty(final String name, final String value) {
  359. if (launchDiag) {
  360. System.out.println("Setting \"" + name + "\" to \"" + value + "\"");
  361. }
  362. System.setProperty(name, value);
  363. }
  364. private void logPath(final String name, final File path) {
  365. if (launchDiag) {
  366. System.out.println(name + "= \"" + path + "\"");
  367. }
  368. }
  369. }