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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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. private String resultProperty;
  90. private boolean failIfExecFails=true;
  91. /** Controls whether the VM (1.3 and above) is used to execute the command */
  92. private boolean vmLauncher = true;
  93. /**
  94. * Timeout in milliseconds after which the process will be killed.
  95. */
  96. public void setTimeout(Integer value) {
  97. timeout = value;
  98. }
  99. /**
  100. * The command to execute.
  101. */
  102. public void setExecutable(String value) {
  103. cmdl.setExecutable(value);
  104. }
  105. /**
  106. * The working directory of the process
  107. */
  108. public void setDir(File d) {
  109. this.dir = d;
  110. }
  111. /**
  112. * Only execute the process if <code>os.name</code> is included in this string.
  113. */
  114. public void setOs(String os) {
  115. this.os = os;
  116. }
  117. /**
  118. * The full commandline to execute, executable + arguments.
  119. */
  120. public void setCommand(Commandline cmdl) {
  121. log("The command attribute is deprecated. " +
  122. "Please use the executable attribute and nested arg elements.",
  123. Project.MSG_WARN);
  124. this.cmdl = cmdl;
  125. }
  126. /**
  127. * File the output of the process is redirected to.
  128. */
  129. public void setOutput(File out) {
  130. this.out = out;
  131. }
  132. /**
  133. * Property name whose value should be set to the output of
  134. * the process
  135. */
  136. public void setOutputproperty(String outputprop) {
  137. this.outputprop = outputprop;
  138. }
  139. /**
  140. * Throw a BuildException if process returns non 0.
  141. */
  142. public void setFailonerror(boolean fail) {
  143. failOnError = fail;
  144. }
  145. /**
  146. * Use a completely new environment
  147. */
  148. public void setNewenvironment(boolean newenv) {
  149. newEnvironment = newenv;
  150. }
  151. /**
  152. * Add a nested env element - an environment variable.
  153. */
  154. public void addEnv(Environment.Variable var) {
  155. env.addVariable(var);
  156. }
  157. /**
  158. * Add a nested arg element - a command line argument.
  159. */
  160. public Commandline.Argument createArg() {
  161. return cmdl.createArgument();
  162. }
  163. /**
  164. * fill a property in with a result.
  165. * when no property is defined: failure to execute
  166. * @since 1.5
  167. */
  168. public void setResultProperty(String resultProperty) {
  169. this.resultProperty=resultProperty;
  170. }
  171. /**
  172. * helper method to set result property to the
  173. * passed in value if appropriate
  174. */
  175. protected void maybeSetResultPropertyValue(int result) {
  176. String res=Integer.toString(result);
  177. if(resultProperty!=null
  178. && project.getProperty(resultProperty) == null) {
  179. project.setNewProperty(resultProperty,res);
  180. }
  181. }
  182. /**
  183. * ant attribute
  184. */
  185. public void setFailIfExecutionFails(boolean flag) {
  186. failIfExecFails=flag;
  187. }
  188. /**
  189. * Do the work.
  190. */
  191. public void execute() throws BuildException {
  192. checkConfiguration();
  193. if (isValidOs()) {
  194. runExec(prepareExec());
  195. }
  196. }
  197. /**
  198. * Has the user set all necessary attributes?
  199. */
  200. protected void checkConfiguration() throws BuildException {
  201. if (cmdl.getExecutable() == null) {
  202. throw new BuildException("no executable specified", location);
  203. }
  204. if (dir != null && !dir.exists()) {
  205. throw new BuildException("The directory you specified does not exist");
  206. }
  207. if (dir != null && !dir.isDirectory()) {
  208. throw new BuildException("The directory you specified is not a directory");
  209. }
  210. }
  211. /**
  212. * Is this the OS the user wanted?
  213. */
  214. protected boolean isValidOs() {
  215. // test if os match
  216. String myos = System.getProperty("os.name");
  217. log("Current OS is " + myos, Project.MSG_VERBOSE);
  218. if ((os != null) && (os.indexOf(myos) < 0)){
  219. // this command will be executed only on the specified OS
  220. log("This OS, " + myos + " was not found in the specified list of valid OSes: " + os, Project.MSG_VERBOSE);
  221. return false;
  222. }
  223. return true;
  224. }
  225. /**
  226. * Control whether the VM is used to launch the new process or
  227. * whether the OS's shell is used.
  228. */
  229. public void setVMLauncher(boolean vmLauncher) {
  230. this.vmLauncher = vmLauncher;
  231. }
  232. /**
  233. * Create an Execute instance with the correct working directory set.
  234. */
  235. protected Execute prepareExec() throws BuildException {
  236. // default directory to the project's base directory
  237. if (dir == null) dir = project.getBaseDir();
  238. // show the command
  239. log(cmdl.toString(), Project.MSG_VERBOSE);
  240. Execute exe = new Execute(createHandler(), createWatchdog());
  241. exe.setAntRun(project);
  242. exe.setWorkingDirectory(dir);
  243. exe.setVMLauncher(vmLauncher);
  244. String[] environment = env.getVariables();
  245. if (environment != null) {
  246. for (int i=0; i<environment.length; i++) {
  247. log("Setting environment variable: "+environment[i],
  248. Project.MSG_VERBOSE);
  249. }
  250. }
  251. exe.setNewenvironment(newEnvironment);
  252. exe.setEnvironment(environment);
  253. return exe;
  254. }
  255. /**
  256. * A Utility method for this classes and subclasses to run an Execute instance (an external command).
  257. */
  258. protected final void runExecute(Execute exe) throws IOException {
  259. int err = -1; // assume the worst
  260. err = exe.execute();
  261. //test for and handle a forced process death
  262. if(exe.killedProcess()) {
  263. log("Timeout: killed the sub-process",Project.MSG_WARN);
  264. }
  265. maybeSetResultPropertyValue(err);
  266. if (err != 0) {
  267. if (failOnError) {
  268. throw new BuildException(taskType + " returned: "+err, location);
  269. } else {
  270. log("Result: " + err, Project.MSG_ERR);
  271. }
  272. }
  273. if (baos != null) {
  274. BufferedReader in =
  275. new BufferedReader(new StringReader(baos.toString()));
  276. String line = null;
  277. StringBuffer val = new StringBuffer();
  278. while ((line = in.readLine()) != null) {
  279. if (val.length() != 0) {
  280. val.append(lSep);
  281. }
  282. val.append(line);
  283. }
  284. project.setNewProperty(outputprop, val.toString());
  285. }
  286. }
  287. /**
  288. * Run the command using the given Execute instance. This may be overidden by subclasses
  289. */
  290. protected void runExec(Execute exe) throws BuildException {
  291. exe.setCommandline(cmdl.getCommandline());
  292. try {
  293. runExecute(exe);
  294. } catch (IOException e) {
  295. if (failIfExecFails) {
  296. throw new BuildException("Execute failed: "+e.toString(),e, location);
  297. } else {
  298. log("Execute failed: "+e.toString(), Project.MSG_ERR);
  299. }
  300. } finally {
  301. // close the output file if required
  302. logFlush();
  303. }
  304. }
  305. /**
  306. * Create the StreamHandler to use with our Execute instance.
  307. */
  308. protected ExecuteStreamHandler createHandler() throws BuildException {
  309. if(out!=null) {
  310. try {
  311. fos = new FileOutputStream(out);
  312. log("Output redirected to " + out, Project.MSG_VERBOSE);
  313. return new PumpStreamHandler(fos);
  314. } catch (FileNotFoundException fne) {
  315. throw new BuildException("Cannot write to "+out, fne, location);
  316. } catch (IOException ioe) {
  317. throw new BuildException("Cannot write to "+out, ioe, location);
  318. }
  319. } else if (outputprop != null) {
  320. baos = new ByteArrayOutputStream();
  321. log("Output redirected to ByteArray", Project.MSG_VERBOSE);
  322. return new PumpStreamHandler(baos);
  323. } else {
  324. return new LogStreamHandler(this,
  325. Project.MSG_INFO, Project.MSG_WARN);
  326. }
  327. }
  328. /**
  329. * Create the Watchdog to kill a runaway process.
  330. */
  331. protected ExecuteWatchdog createWatchdog() throws BuildException {
  332. if (timeout == null) return null;
  333. return new ExecuteWatchdog(timeout.intValue());
  334. }
  335. /**
  336. * Flush the output stream - if there is one.
  337. */
  338. protected void logFlush() {
  339. try {
  340. if (fos != null) fos.close();
  341. if (baos != null) baos.close();
  342. } catch (IOException io) {}
  343. }
  344. }