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.

Execute.java 19 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. /*
  2. * The Apache Software License, Version 1.1
  3. *
  4. * Copyright (c) 2000 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 "The Jakarta Project", "Tomcat", 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.taskdefs;
  55. import org.apache.tools.ant.BuildException;
  56. import org.apache.tools.ant.Project;
  57. import org.apache.tools.ant.Task;
  58. import org.apache.tools.ant.types.Commandline;
  59. import java.io.File;
  60. import java.io.IOException;
  61. import java.io.InputStream;
  62. import java.io.OutputStream;
  63. import java.lang.reflect.InvocationTargetException;
  64. import java.lang.reflect.Method;
  65. /**
  66. * Runs an external program.
  67. *
  68. * @author thomas.haas@softwired-inc.com
  69. */
  70. public class Execute {
  71. /** Invalid exit code. **/
  72. public final static int INVALID = Integer.MAX_VALUE;
  73. private String[] cmdl = null;
  74. private String[] env = null;
  75. private int exitValue = INVALID;
  76. private ExecuteStreamHandler streamHandler;
  77. private ExecuteWatchdog watchdog;
  78. private File workingDirectory = null;
  79. private Project project = null;
  80. private static String antWorkingDirectory = System.getProperty("user.dir");
  81. private static CommandLauncher launcher = createCommandLauncher();
  82. /**
  83. * Builds a command launcher for the OS and JVM we are running under
  84. */
  85. private static CommandLauncher createCommandLauncher()
  86. {
  87. // Try using a JDK 1.3 launcher
  88. try {
  89. return new Java13CommandLauncher();
  90. }
  91. catch ( NoSuchMethodException exc ) {
  92. // Ignore and keep try
  93. }
  94. String osname = System.getProperty("os.name").toLowerCase();
  95. if ( osname.indexOf("mac os") >= 0 ) {
  96. // Mac
  97. return new MacCommandLauncher(new CommandLauncher());
  98. }
  99. else if ( osname.indexOf("os/2") >= 0 ) {
  100. // OS/2 - use same mechanism as Windows 2000
  101. return new WinNTCommandLauncher(new CommandLauncher());
  102. }
  103. else if ( osname.indexOf("windows") >= 0 ) {
  104. // Windows. Need to determine which JDK we're running in
  105. CommandLauncher baseLauncher;
  106. if ( System.getProperty("java.version").startsWith("1.1") ) {
  107. // JDK 1.1
  108. baseLauncher = new Java11CommandLauncher();
  109. }
  110. else {
  111. // JDK 1.2
  112. baseLauncher = new CommandLauncher();
  113. }
  114. // Determine if we're running under 2000/NT or 98/95
  115. if ( osname.indexOf("nt") >= 0 || osname.indexOf("2000") >= 0 ) {
  116. // Windows 2000/NT
  117. return new WinNTCommandLauncher(baseLauncher);
  118. }
  119. else {
  120. // Windows 98/95 - need to use an auxiliary script
  121. return new ScriptCommandLauncher("bin/antRun.bat", baseLauncher);
  122. }
  123. }
  124. else {
  125. // Generic
  126. return new ScriptCommandLauncher("bin/antRun", new CommandLauncher());
  127. }
  128. }
  129. /**
  130. * Creates a new execute object using <code>PumpStreamHandler</code> for
  131. * stream handling.
  132. */
  133. public Execute() {
  134. this(new PumpStreamHandler(), null);
  135. }
  136. /**
  137. * Creates a new execute object.
  138. *
  139. * @param streamHandler the stream handler used to handle the input and
  140. * output streams of the subprocess.
  141. */
  142. public Execute(ExecuteStreamHandler streamHandler) {
  143. this(streamHandler, null);
  144. }
  145. /**
  146. * Creates a new execute object.
  147. *
  148. * @param streamHandler the stream handler used to handle the input and
  149. * output streams of the subprocess.
  150. * @param watchdog a watchdog for the subprocess or <code>null</code> to
  151. * to disable a timeout for the subprocess.
  152. */
  153. public Execute(ExecuteStreamHandler streamHandler, ExecuteWatchdog watchdog) {
  154. this.streamHandler = streamHandler;
  155. this.watchdog = watchdog;
  156. }
  157. /**
  158. * Returns the commandline used to create a subprocess.
  159. *
  160. * @return the commandline used to create a subprocess
  161. */
  162. public String[] getCommandline() {
  163. return cmdl;
  164. }
  165. /**
  166. * Sets the commandline of the subprocess to launch.
  167. *
  168. * @param commandline the commandline of the subprocess to launch
  169. */
  170. public void setCommandline(String[] commandline) {
  171. cmdl = commandline;
  172. }
  173. /**
  174. * Returns the commandline used to create a subprocess.
  175. *
  176. * @return the commandline used to create a subprocess
  177. */
  178. public String[] getEnvironment() {
  179. return env;
  180. }
  181. /**
  182. * Sets the environment variables for the subprocess to launch.
  183. *
  184. * @param commandline array of Strings, each element of which has
  185. * an environment variable settings in format <em>key=value</em>
  186. */
  187. public void setEnvironment(String[] env) {
  188. this.env = env;
  189. }
  190. /**
  191. * Sets the working directory of the process to execute.
  192. *
  193. * <p>This is emulated using the antRun scripts unless the OS is
  194. * Windows NT in which case a cmd.exe is spawned,
  195. * or MRJ and setting user.dir works, or JDK 1.3 and there is
  196. * official support in java.lang.Runtime.
  197. *
  198. * @param wd the working directory of the process.
  199. */
  200. public void setWorkingDirectory(File wd) {
  201. if (wd == null || wd.getAbsolutePath().equals(antWorkingDirectory))
  202. workingDirectory = null;
  203. else
  204. workingDirectory = wd;
  205. }
  206. /**
  207. * Set the name of the antRun script using the project's value.
  208. *
  209. * @param project the current project.
  210. */
  211. public void setAntRun(Project project) throws BuildException {
  212. this.project = project;
  213. }
  214. /**
  215. * Runs a process defined by the command line and returns its exit status.
  216. *
  217. * @return the exit status of the subprocess or <code>INVALID</code>
  218. * @exception java.io.IOExcpetion The exception is thrown, if launching
  219. * of the subprocess failed
  220. */
  221. public int execute() throws IOException {
  222. final Process process = launcher.exec(project, getCommandline(), getEnvironment(), workingDirectory);
  223. try {
  224. streamHandler.setProcessInputStream(process.getOutputStream());
  225. streamHandler.setProcessOutputStream(process.getInputStream());
  226. streamHandler.setProcessErrorStream(process.getErrorStream());
  227. } catch (IOException e) {
  228. process.destroy();
  229. throw e;
  230. }
  231. streamHandler.start();
  232. if (watchdog != null) watchdog.start(process);
  233. waitFor(process);
  234. if (watchdog != null) watchdog.stop();
  235. streamHandler.stop();
  236. if (watchdog != null) watchdog.checkException();
  237. return getExitValue();
  238. }
  239. protected void waitFor(Process process) {
  240. try {
  241. process.waitFor();
  242. setExitValue(process.exitValue());
  243. } catch (InterruptedException e) {}
  244. }
  245. protected void setExitValue(int value) {
  246. exitValue = value;
  247. }
  248. protected int getExitValue() {
  249. return exitValue;
  250. }
  251. /**
  252. * A utility method that runs an external command. Writes the output and
  253. * error streams of the command to the project log.
  254. *
  255. * @param task The task that the command is part of. Used for logging
  256. * @param cmdline The command to execute.
  257. *
  258. * @throws BuildException if the command does not return 0.
  259. */
  260. public static void runCommand(Task task, String[] cmdline) throws BuildException
  261. {
  262. try {
  263. task.log(Commandline.toString(cmdline), Project.MSG_VERBOSE);
  264. Execute exe = new Execute(new LogStreamHandler(task,
  265. Project.MSG_INFO,
  266. Project.MSG_ERR));
  267. exe.setAntRun(task.getProject());
  268. exe.setCommandline(cmdline);
  269. int retval = exe.execute();
  270. if ( retval != 0 ) {
  271. throw new BuildException(cmdline[0] + " failed with return code " + retval, task.getLocation());
  272. }
  273. }
  274. catch (java.io.IOException exc) {
  275. throw new BuildException("Could not launch " + cmdline[0] + ": " + exc, task.getLocation());
  276. }
  277. }
  278. /**
  279. * A command launcher for a particular JVM/OS platform. This class is
  280. * a general purpose command launcher which can only launch commands in
  281. * the current working directory.
  282. */
  283. private static class CommandLauncher
  284. {
  285. /**
  286. * Launches the given command in a new process.
  287. *
  288. * @param project The project that the command is part of
  289. * @param cmd The command to execute
  290. * @param env The environment for the new process. If null,
  291. * the environment of the current proccess is used.
  292. */
  293. public Process exec(Project project, String[] cmd, String[] env) throws IOException
  294. {
  295. return Runtime.getRuntime().exec(cmd, env);
  296. }
  297. /**
  298. * Launches the given command in a new process, in the given working
  299. * directory.
  300. *
  301. * @param project The project that the command is part of
  302. * @param cmd The command to execute
  303. * @param env The environment for the new process. If null,
  304. * the environment of the current proccess is used.
  305. * @param workingDir The directory to start the command in. If null,
  306. * the current directory is used
  307. */
  308. public Process exec(Project project, String[] cmd, String[] env, File workingDir) throws IOException
  309. {
  310. if ( workingDir == null ) {
  311. return exec(project, cmd, env);
  312. }
  313. throw new IOException("Cannot execute a process in different directory under this JVM");
  314. }
  315. }
  316. /**
  317. * A command launcher for JDK/JRE 1.1 under Windows. Fixes quoting problems
  318. * in Runtime.exec(). Can only launch commands in the current working
  319. * directory
  320. */
  321. private static class Java11CommandLauncher extends CommandLauncher
  322. {
  323. /**
  324. * Launches the given command in a new process. Needs to quote
  325. * arguments
  326. */
  327. public Process exec(Project project, String[] cmd, String[] env) throws IOException
  328. {
  329. // Need to quote arguments with spaces, and to escape quote characters
  330. String[] newcmd = new String[cmd.length];
  331. for ( int i = 0; i < cmd.length; i++ ) {
  332. newcmd[i] = Commandline.quoteArgument(cmd[i]);
  333. }
  334. return Runtime.getRuntime().exec(newcmd, env);
  335. }
  336. }
  337. /**
  338. * A command launcher for JDK/JRE 1.3 (and higher). Uses the built-in
  339. * Runtime.exec() command
  340. */
  341. private static class Java13CommandLauncher extends CommandLauncher
  342. {
  343. public Java13CommandLauncher() throws NoSuchMethodException
  344. {
  345. // Locate method Runtime.exec(String[] cmdarray, String[] envp, File dir)
  346. _execWithCWD = Runtime.class.getMethod("exec", new Class[] {String[].class, String[].class, File.class});
  347. }
  348. /**
  349. * Launches the given command in a new process, in the given working
  350. * directory
  351. */
  352. public Process exec(Project project, String[] cmd, String[] env, File workingDir) throws IOException
  353. {
  354. try {
  355. Object[] arguments = { cmd, env, workingDir };
  356. return (Process)_execWithCWD.invoke(Runtime.getRuntime(), arguments);
  357. }
  358. catch ( InvocationTargetException exc ) {
  359. Throwable realexc = exc.getTargetException();
  360. if ( realexc instanceof ThreadDeath ) {
  361. throw (ThreadDeath)realexc;
  362. }
  363. else if ( realexc instanceof IOException ) {
  364. throw (IOException)realexc;
  365. }
  366. else {
  367. throw new IOException(realexc.getMessage());
  368. }
  369. }
  370. catch ( Exception exc ) {
  371. // IllegalAccess, IllegalArgument, ClassCast
  372. throw new IOException(exc.getMessage());
  373. }
  374. }
  375. private Method _execWithCWD;
  376. }
  377. /**
  378. * A command launcher that proxies another command launcher.
  379. *
  380. * Sub-classes override exec(args, env, workdir)
  381. */
  382. private static class CommandLauncherProxy extends CommandLauncher
  383. {
  384. CommandLauncherProxy(CommandLauncher launcher)
  385. {
  386. _launcher = launcher;
  387. }
  388. /**
  389. * Launches the given command in a new process. Delegates this
  390. * method to the proxied launcher
  391. */
  392. public Process exec(Project project, String[] cmd, String[] env) throws IOException
  393. {
  394. return _launcher.exec(project, cmd, env);
  395. }
  396. private CommandLauncher _launcher;
  397. }
  398. /**
  399. * A command launcher for Windows 2000/NT that uses 'cmd.exe' when
  400. * launching commands in directories other than the current working
  401. * directory.
  402. */
  403. private static class WinNTCommandLauncher extends CommandLauncherProxy
  404. {
  405. WinNTCommandLauncher(CommandLauncher launcher)
  406. {
  407. super(launcher);
  408. }
  409. /**
  410. * Launches the given command in a new process, in the given working
  411. * directory.
  412. */
  413. public Process exec(Project project, String[] cmd, String[] env, File workingDir) throws IOException
  414. {
  415. if ( workingDir == null ) {
  416. return exec(project, cmd, env);
  417. }
  418. // Use cmd.exe to change to the specified directory before running
  419. // the command
  420. String[] newcmd = new String[cmd.length+5];
  421. newcmd[0] = "cmd";
  422. newcmd[1] = "/c";
  423. newcmd[2] = "cd";
  424. newcmd[3] = workingDir.getAbsolutePath();
  425. newcmd[4] = "&&";
  426. System.arraycopy(cmd, 0, newcmd, 5, cmd.length);
  427. return exec(project, newcmd, env);
  428. }
  429. }
  430. /**
  431. * A command launcher for Mac that uses a dodgy mechanism to change
  432. * working directory before launching commands.
  433. */
  434. private static class MacCommandLauncher extends CommandLauncherProxy
  435. {
  436. MacCommandLauncher(CommandLauncher launcher)
  437. {
  438. super(launcher);
  439. }
  440. /**
  441. * Launches the given command in a new process, in the given working
  442. * directory
  443. */
  444. public Process exec(Project project, String[] cmd, String[] env, File workingDir) throws IOException
  445. {
  446. if ( workingDir == null ) {
  447. return exec(project, cmd, env);
  448. }
  449. System.getProperties().put("user.dir", workingDir.getAbsolutePath());
  450. try {
  451. return exec(project, cmd, env);
  452. }
  453. finally {
  454. System.getProperties().put("user.dir", antWorkingDirectory);
  455. }
  456. }
  457. }
  458. /**
  459. * A command launcher that uses an auxiliary script to launch commands
  460. * in directories other than the current working directory.
  461. */
  462. private static class ScriptCommandLauncher extends CommandLauncherProxy
  463. {
  464. ScriptCommandLauncher(String script, CommandLauncher launcher)
  465. {
  466. super(launcher);
  467. _script = script;
  468. }
  469. /**
  470. * Launches the given command in a new process, in the given working
  471. * directory
  472. */
  473. public Process exec(Project project, String[] cmd, String[] env, File workingDir) throws IOException
  474. {
  475. if ( workingDir == null ) {
  476. return exec(project, cmd, env);
  477. }
  478. // Locate the auxiliary script
  479. if ( project == null ) {
  480. throw new IOException("Cannot locate antRun script: No project provided");
  481. }
  482. String antHome = project.getProperty("ant.home");
  483. if ( antHome == null ) {
  484. throw new IOException("Cannot locate antRun script: Property 'ant.home' not found");
  485. }
  486. String antRun = project.resolveFile(antHome + File.separator + _script).toString();
  487. // Build the command
  488. String[] newcmd = new String[cmd.length + 2];
  489. newcmd[0] = antRun;
  490. newcmd[1] = workingDir.getAbsolutePath();
  491. System.arraycopy(cmd, 0, newcmd, 2, cmd.length);
  492. return exec(project, newcmd, env);
  493. }
  494. private String _script;
  495. }
  496. }