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.

ExecTask.java 11 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. /*
  2. * The Apache Software License, Version 1.1
  3. *
  4. * Copyright (c) 1999 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", "Ant", and "Apache Software
  27. * Foundation" must not be used to endorse or promote products derived
  28. * from this software without prior written permission. For written
  29. * permission, please contact apache@apache.org.
  30. *
  31. * 5. Products derived from this software may not be called "Apache"
  32. * nor may "Apache" appear in their names without prior written
  33. * permission of the Apache Group.
  34. *
  35. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
  36. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  37. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  38. * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
  39. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  40. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  41. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  42. * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  43. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  44. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  45. * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  46. * SUCH DAMAGE.
  47. * ====================================================================
  48. *
  49. * This software consists of voluntary contributions made by many
  50. * individuals on behalf of the Apache Software Foundation. For more
  51. * information on the Apache Software Foundation, please see
  52. * <http://www.apache.org/>.
  53. */
  54. package org.apache.tools.ant.taskdefs;
  55. import org.apache.tools.ant.Task;
  56. import org.apache.tools.ant.BuildException;
  57. import org.apache.tools.ant.Project;
  58. import org.apache.tools.ant.types.Commandline;
  59. import org.apache.tools.ant.types.Environment;
  60. import java.io.File;
  61. import java.io.FileOutputStream;
  62. import java.io.ByteArrayOutputStream;
  63. import java.io.IOException;
  64. import java.io.BufferedReader;
  65. import java.io.StringReader;
  66. import java.io.FileNotFoundException;
  67. /**
  68. * Executes a given command if the os platform is appropriate.
  69. *
  70. * @author duncan@x180.com
  71. * @author rubys@us.ibm.com
  72. * @author thomas.haas@softwired-inc.com
  73. * @author <a href="mailto:stefan.bodewig@epost.de">Stefan Bodewig</a>
  74. * @author <a href="mailto:mariusz@rakiura.org">Mariusz Nowostawski</a>
  75. */
  76. public class ExecTask extends Task {
  77. private static String lSep = System.getProperty("line.separator");
  78. private String os;
  79. private File out;
  80. private File dir;
  81. protected boolean failOnError = false;
  82. protected boolean newEnvironment = false;
  83. private Integer timeout = null;
  84. private Environment env = new Environment();
  85. protected Commandline cmdl = new Commandline();
  86. private FileOutputStream fos = null;
  87. private ByteArrayOutputStream baos = null;
  88. private String outputprop;
  89. /** Controls whether the VM (1.3 and above) is used to execute the command */
  90. private boolean vmLauncher = true;
  91. /**
  92. * Timeout in milliseconds after which the process will be killed.
  93. */
  94. public void setTimeout(Integer value) {
  95. timeout = value;
  96. }
  97. /**
  98. * The command to execute.
  99. */
  100. public void setExecutable(String value) {
  101. cmdl.setExecutable(value);
  102. }
  103. /**
  104. * The working directory of the process
  105. */
  106. public void setDir(File d) {
  107. this.dir = d;
  108. }
  109. /**
  110. * Only execute the process if <code>os.name</code> is included in this string.
  111. */
  112. public void setOs(String os) {
  113. this.os = os;
  114. }
  115. /**
  116. * The full commandline to execute, executable + arguments.
  117. */
  118. public void setCommand(Commandline cmdl) {
  119. log("The command attribute is deprecated. " +
  120. "Please use the executable attribute and nested arg elements.",
  121. Project.MSG_WARN);
  122. this.cmdl = cmdl;
  123. }
  124. /**
  125. * File the output of the process is redirected to.
  126. */
  127. public void setOutput(File out) {
  128. this.out = out;
  129. }
  130. /**
  131. * Property name whose value should be set to the output of
  132. * the process
  133. */
  134. public void setOutputproperty(String outputprop) {
  135. this.outputprop = outputprop;
  136. }
  137. /**
  138. * Throw a BuildException if process returns non 0.
  139. */
  140. public void setFailonerror(boolean fail) {
  141. failOnError = fail;
  142. }
  143. /**
  144. * Use a completely new environment
  145. */
  146. public void setNewenvironment(boolean newenv) {
  147. newEnvironment = newenv;
  148. }
  149. /**
  150. * Add a nested env element - an environment variable.
  151. */
  152. public void addEnv(Environment.Variable var) {
  153. env.addVariable(var);
  154. }
  155. /**
  156. * Add a nested arg element - a command line argument.
  157. */
  158. public Commandline.Argument createArg() {
  159. return cmdl.createArgument();
  160. }
  161. /**
  162. * Do the work.
  163. */
  164. public void execute() throws BuildException {
  165. checkConfiguration();
  166. if (isValidOs()) {
  167. runExec(prepareExec());
  168. }
  169. }
  170. /**
  171. * Has the user set all necessary attributes?
  172. */
  173. protected void checkConfiguration() throws BuildException {
  174. if (cmdl.getExecutable() == null) {
  175. throw new BuildException("no executable specified", location);
  176. }
  177. if (dir != null && !dir.exists()) {
  178. throw new BuildException("The directory you specified does not exist");
  179. }
  180. if (dir != null && !dir.isDirectory()) {
  181. throw new BuildException("The directory you specified is not a directory");
  182. }
  183. }
  184. /**
  185. * Is this the OS the user wanted?
  186. */
  187. protected boolean isValidOs() {
  188. // test if os match
  189. String myos = System.getProperty("os.name");
  190. log("Current OS is " + myos, Project.MSG_VERBOSE);
  191. if ((os != null) && (os.indexOf(myos) < 0)){
  192. // this command will be executed only on the specified OS
  193. log("This OS, " + myos + " was not found in the specified list of valid OSes: " + os, Project.MSG_VERBOSE);
  194. return false;
  195. }
  196. return true;
  197. }
  198. /**
  199. * Control whether the VM is used to launch the new process or
  200. * whether the OS's shell is used.
  201. */
  202. public void setVMLauncher(boolean vmLauncher) {
  203. this.vmLauncher = vmLauncher;
  204. }
  205. /**
  206. * Create an Execute instance with the correct working directory set.
  207. */
  208. protected Execute prepareExec() throws BuildException {
  209. // default directory to the project's base directory
  210. if (dir == null) dir = project.getBaseDir();
  211. // show the command
  212. log(cmdl.toString(), Project.MSG_VERBOSE);
  213. Execute exe = new Execute(createHandler(), createWatchdog());
  214. exe.setAntRun(project);
  215. exe.setWorkingDirectory(dir);
  216. exe.setVMLauncher(vmLauncher);
  217. String[] environment = env.getVariables();
  218. if (environment != null) {
  219. for (int i=0; i<environment.length; i++) {
  220. log("Setting environment variable: "+environment[i],
  221. Project.MSG_VERBOSE);
  222. }
  223. }
  224. exe.setNewenvironment(newEnvironment);
  225. exe.setEnvironment(environment);
  226. return exe;
  227. }
  228. /**
  229. * A Utility method for this classes and subclasses to run an Execute instance (an external command).
  230. */
  231. protected final void runExecute(Execute exe) throws IOException {
  232. int err = -1; // assume the worst
  233. err = exe.execute();
  234. if (err != 0) {
  235. if (failOnError) {
  236. throw new BuildException(taskType + " returned: "+err, location);
  237. } else {
  238. log("Result: " + err, Project.MSG_ERR);
  239. }
  240. }
  241. if (baos != null) {
  242. BufferedReader in =
  243. new BufferedReader(new StringReader(baos.toString()));
  244. String line = null;
  245. StringBuffer val = new StringBuffer();
  246. while ((line = in.readLine()) != null) {
  247. if (val.length() != 0) {
  248. val.append(lSep);
  249. }
  250. val.append(line);
  251. }
  252. project.setProperty(outputprop, val.toString());
  253. }
  254. }
  255. /**
  256. * Run the command using the given Execute instance. This may be overidden by subclasses
  257. */
  258. protected void runExec(Execute exe) throws BuildException {
  259. exe.setCommandline(cmdl.getCommandline());
  260. try {
  261. runExecute(exe);
  262. } catch (IOException e) {
  263. throw new BuildException("Execute failed: " + e, e, location);
  264. } finally {
  265. // close the output file if required
  266. logFlush();
  267. }
  268. }
  269. /**
  270. * Create the StreamHandler to use with our Execute instance.
  271. */
  272. protected ExecuteStreamHandler createHandler() throws BuildException {
  273. if(out!=null) {
  274. try {
  275. fos = new FileOutputStream(out);
  276. log("Output redirected to " + out, Project.MSG_VERBOSE);
  277. return new PumpStreamHandler(fos);
  278. } catch (FileNotFoundException fne) {
  279. throw new BuildException("Cannot write to "+out, fne, location);
  280. } catch (IOException ioe) {
  281. throw new BuildException("Cannot write to "+out, ioe, location);
  282. }
  283. } else if (outputprop != null) {
  284. // try {
  285. baos = new ByteArrayOutputStream();
  286. log("Output redirected to ByteArray", Project.MSG_VERBOSE);
  287. return new PumpStreamHandler(baos);
  288. } else {
  289. return new LogStreamHandler(this,
  290. Project.MSG_INFO, Project.MSG_WARN);
  291. }
  292. }
  293. /**
  294. * Create the Watchdog to kill a runaway process.
  295. */
  296. protected ExecuteWatchdog createWatchdog() throws BuildException {
  297. if (timeout == null) return null;
  298. return new ExecuteWatchdog(timeout.intValue());
  299. }
  300. /**
  301. * Flush the output stream - if there is one.
  302. */
  303. protected void logFlush() {
  304. try {
  305. if (fos != null) fos.close();
  306. if (baos != null) baos.close();
  307. } catch (IOException io) {}
  308. }
  309. }