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

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