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 10 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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 java.io.File;
  58. import java.io.IOException;
  59. import java.io.InputStream;
  60. import java.io.OutputStream;
  61. import java.lang.reflect.InvocationTargetException;
  62. import java.lang.reflect.Method;
  63. /**
  64. * Runs an external program.
  65. *
  66. * @author thomas.haas@softwired-inc.com
  67. */
  68. public class Execute {
  69. /** Invalid exit code. **/
  70. public final static int INVALID = Integer.MAX_VALUE;
  71. private String[] cmdl = null;
  72. private String[] env = null;
  73. private int exitValue = INVALID;
  74. private ExecuteStreamHandler streamHandler;
  75. private ExecuteWatchdog watchdog;
  76. private File workingDirectory = null;
  77. private String antRun;
  78. private static String antWorkingDirectory = System.getProperty("user.dir");
  79. private static String myos = System.getProperty("os.name");
  80. private static Method execWithCWD = null;
  81. static {
  82. try {
  83. // JDK 1.3 API extension:
  84. // Runtime.exec(String[] cmdarray, String[] envp, File dir)
  85. execWithCWD = Runtime.class.getMethod("exec", new Class[] {String[].class, String[].class, File.class});
  86. } catch (NoSuchMethodException nsme) {
  87. // OK.
  88. }
  89. }
  90. /**
  91. * Creates a new execute object using <code>PumpStreamHandler</code> for
  92. * stream handling.
  93. */
  94. public Execute() {
  95. this(new PumpStreamHandler(), null);
  96. }
  97. /**
  98. * Creates a new execute object.
  99. *
  100. * @param streamHandler the stream handler used to handle the input and
  101. * output streams of the subprocess.
  102. */
  103. public Execute(ExecuteStreamHandler streamHandler) {
  104. this(streamHandler, null);
  105. }
  106. /**
  107. * Creates a new execute object.
  108. *
  109. * @param streamHandler the stream handler used to handle the input and
  110. * output streams of the subprocess.
  111. * @param watchdog a watchdog for the subprocess or <code>null</code> to
  112. * to disable a timeout for the subprocess.
  113. */
  114. public Execute(ExecuteStreamHandler streamHandler, ExecuteWatchdog watchdog) {
  115. this.streamHandler = streamHandler;
  116. this.watchdog = watchdog;
  117. }
  118. /**
  119. * Returns the commandline used to create a subprocess.
  120. *
  121. * @return the commandline used to create a subprocess
  122. */
  123. public String[] getCommandline() {
  124. return cmdl;
  125. }
  126. /**
  127. * Sets the commandline of the subprocess to launch.
  128. *
  129. * @param commandline the commandline of the subprocess to launch
  130. */
  131. public void setCommandline(String[] commandline) {
  132. cmdl = commandline;
  133. }
  134. /**
  135. * Returns the commandline used to create a subprocess.
  136. *
  137. * @return the commandline used to create a subprocess
  138. */
  139. public String[] getEnvironment() {
  140. return env;
  141. }
  142. /**
  143. * Sets the environment variables for the subprocess to launch.
  144. *
  145. * @param commandline array of Strings, each element of which has
  146. * an environment variable settings in format <em>key=value</em>
  147. */
  148. public void setEnvironment(String[] env) {
  149. this.env = env;
  150. }
  151. /**
  152. * Sets the working directory of the process to execute.
  153. *
  154. * <p>This is emulated using the antRun scripts unless the OS is
  155. * Windows NT in which case a cmd.exe is spawned,
  156. * or MRJ and setting user.dir works, or JDK 1.3 and there is
  157. * official support in java.lang.Runtime.
  158. *
  159. * @param wd the working directory of the process.
  160. */
  161. public void setWorkingDirectory(File wd) {
  162. if (wd == null || wd.getAbsolutePath().equals(antWorkingDirectory))
  163. workingDirectory = null;
  164. else
  165. workingDirectory = wd;
  166. }
  167. /**
  168. * Set the name of the antRun script using the project's value.
  169. *
  170. * @param project the current project.
  171. */
  172. public void setAntRun(Project project) throws BuildException {
  173. if (myos.equals("Mac OS") || execWithCWD != null)
  174. return;
  175. String ant = project.getProperty("ant.home");
  176. if (ant == null) {
  177. throw new BuildException("Property 'ant.home' not found");
  178. }
  179. if (myos.toLowerCase().indexOf("windows") >= 0) {
  180. antRun = project.resolveFile(ant + "/bin/antRun.bat").toString();
  181. } else {
  182. antRun = project.resolveFile(ant + "/bin/antRun").toString();
  183. }
  184. }
  185. /**
  186. * Runs a process defined by the command line and returns its exit status.
  187. *
  188. * @return the exit status of the subprocess or <code>INVALID</code>
  189. * @exception java.io.IOExcpetion The exception is thrown, if launching
  190. * of the subprocess failed
  191. */
  192. public int execute() throws IOException {
  193. final Process process = exec();
  194. try {
  195. streamHandler.setProcessInputStream(process.getOutputStream());
  196. streamHandler.setProcessOutputStream(process.getInputStream());
  197. streamHandler.setProcessErrorStream(process.getErrorStream());
  198. } catch (IOException e) {
  199. process.destroy();
  200. throw e;
  201. }
  202. streamHandler.start();
  203. if (watchdog != null) watchdog.start(process);
  204. waitFor(process);
  205. if (watchdog != null) watchdog.stop();
  206. streamHandler.stop();
  207. if (watchdog != null) watchdog.checkException();
  208. return getExitValue();
  209. }
  210. protected Process exec() throws IOException {
  211. if (workingDirectory == null) {
  212. // Easy.
  213. return Runtime.getRuntime().exec(cmdl, getEnvironment());
  214. } else if (execWithCWD != null) {
  215. // The best way to set cwd, if you have JDK 1.3.
  216. try {
  217. Object[] arguments = new Object[] {getCommandline(), getEnvironment(), workingDirectory};
  218. return (Process)execWithCWD.invoke(Runtime.getRuntime(), arguments);
  219. } catch (InvocationTargetException ite) {
  220. Throwable t = ite.getTargetException();
  221. if (t instanceof ThreadDeath) {
  222. throw (ThreadDeath)t;
  223. } else if (t instanceof IOException) {
  224. throw (IOException)t;
  225. } else {
  226. throw new IOException(t.toString());
  227. }
  228. } catch (Exception e) {
  229. // IllegalAccess, IllegalArgument, ClassCast
  230. throw new IOException(e.toString());
  231. }
  232. } else if (myos.equals("Mac OS")) {
  233. // Dubious Mac hack.
  234. System.getProperties().put("user.dir",
  235. workingDirectory.getAbsolutePath());
  236. try {
  237. return Runtime.getRuntime().exec(cmdl, getEnvironment());
  238. } finally {
  239. System.getProperties().put("user.dir", antWorkingDirectory);
  240. }
  241. } else if (myos.toLowerCase().indexOf("windows") >= 0 &&
  242. (myos.toLowerCase().indexOf("nt") >= 0 ||
  243. myos.indexOf("2000") >= 0)) {
  244. // cmd /c cd works OK on Windows NT & friends.
  245. String[] commandLine = new String[cmdl.length+5];
  246. commandLine[0] = "cmd";
  247. commandLine[1] = "/c";
  248. commandLine[2] = "cd";
  249. commandLine[3] = workingDirectory.getAbsolutePath();
  250. commandLine[4] = "&&";
  251. System.arraycopy(cmdl, 0, commandLine, 5, cmdl.length);
  252. return Runtime.getRuntime().exec(commandLine, getEnvironment());
  253. } else {
  254. // Fallback to the antRun wrapper script (POSIX, Win95/98, etc.):
  255. String[] commandLine = new String[cmdl.length+2];
  256. commandLine[0] = antRun;
  257. commandLine[1] = workingDirectory.getAbsolutePath();
  258. System.arraycopy(cmdl, 0, commandLine, 2, cmdl.length);
  259. return Runtime.getRuntime().exec(commandLine, getEnvironment());
  260. }
  261. }
  262. protected void waitFor(Process process) {
  263. try {
  264. process.waitFor();
  265. setExitValue(process.exitValue());
  266. } catch (InterruptedException e) {}
  267. }
  268. protected void setExitValue(int value) {
  269. exitValue = value;
  270. }
  271. protected int getExitValue() {
  272. return exitValue;
  273. }
  274. }