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.

Java.java 15 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. /*
  2. * The Apache Software License, Version 1.1
  3. *
  4. * Copyright (c) 2000-2002 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.BuildException;
  56. import org.apache.tools.ant.ExitException;
  57. import org.apache.tools.ant.Project;
  58. import org.apache.tools.ant.Task;
  59. import org.apache.tools.ant.types.Commandline;
  60. import org.apache.tools.ant.types.Path;
  61. import org.apache.tools.ant.types.CommandlineJava;
  62. import org.apache.tools.ant.types.Reference;
  63. import org.apache.tools.ant.types.Environment;
  64. import java.io.File;
  65. import java.io.PrintStream;
  66. import java.io.FileOutputStream;
  67. import java.io.IOException;
  68. import java.util.Vector;
  69. /**
  70. * This task acts as a loader for java applications but allows to use
  71. * the same JVM for the called application thus resulting in much
  72. * faster operation.
  73. *
  74. * @author Stefano Mazzocchi
  75. * <a href="mailto:stefano@apache.org">stefano@apache.org</a>
  76. * @author <a href="mailto:stefan.bodewig@epost.de">Stefan Bodewig</a>
  77. *
  78. * @since Ant 1.1
  79. *
  80. * @ant.task category="java"
  81. */
  82. public class Java extends Task {
  83. private CommandlineJava cmdl = new CommandlineJava();
  84. private Environment env = new Environment();
  85. private boolean fork = false;
  86. private boolean newEnvironment = false;
  87. private File dir = null;
  88. private File out;
  89. private PrintStream outStream = null;
  90. private boolean failOnError = false;
  91. private boolean append = false;
  92. private Long timeout = null;
  93. /**
  94. * Do the execution.
  95. */
  96. public void execute() throws BuildException {
  97. File savedDir = dir;
  98. int err = -1;
  99. try {
  100. if ((err = executeJava()) != 0) {
  101. if (failOnError) {
  102. throw new BuildException("Java returned: " + err, location);
  103. } else {
  104. log("Java Result: " + err, Project.MSG_ERR);
  105. }
  106. }
  107. } finally {
  108. dir = savedDir;
  109. }
  110. }
  111. /**
  112. * Do the execution and return a return code.
  113. *
  114. * @return the return code from the execute java class if it was
  115. * executed in a separate VM (fork = "yes").
  116. */
  117. public int executeJava() throws BuildException {
  118. String classname = cmdl.getClassname();
  119. if (classname == null && cmdl.getJar() == null) {
  120. throw new BuildException("Classname must not be null.");
  121. }
  122. if (!fork && cmdl.getJar() != null){
  123. throw new BuildException("Cannot execute a jar in non-forked mode."
  124. + " Please set fork='true'. ");
  125. }
  126. if (fork) {
  127. log("Forking " + cmdl.toString(), Project.MSG_VERBOSE);
  128. } else {
  129. if (cmdl.getVmCommand().size() > 1) {
  130. log("JVM args ignored when same JVM is used.",
  131. Project.MSG_WARN);
  132. }
  133. if (dir != null) {
  134. log("Working directory ignored when same JVM is used.",
  135. Project.MSG_WARN);
  136. }
  137. if (newEnvironment || null != env.getVariables()) {
  138. log("Changes to environment variables are ignored when same "
  139. + "JVM is used.", Project.MSG_WARN);
  140. }
  141. log("Running in same VM " + cmdl.getJavaCommand().toString(),
  142. Project.MSG_VERBOSE);
  143. }
  144. try {
  145. if (fork) {
  146. return run(cmdl.getCommandline());
  147. } else {
  148. try {
  149. run(cmdl);
  150. return 0;
  151. } catch (ExitException ex) {
  152. return ex.getStatus();
  153. }
  154. }
  155. } catch (BuildException e) {
  156. if (failOnError) {
  157. throw e;
  158. } else {
  159. log(e.getMessage(), Project.MSG_ERR);
  160. return 0;
  161. }
  162. } catch (Throwable t) {
  163. if (failOnError) {
  164. throw new BuildException(t);
  165. } else {
  166. log(t.getMessage(), Project.MSG_ERR);
  167. return 0;
  168. }
  169. }
  170. }
  171. /**
  172. * Set the classpath to be used when running the Java class
  173. *
  174. * @param s an Ant Path object containing the classpath.
  175. */
  176. public void setClasspath(Path s) {
  177. createClasspath().append(s);
  178. }
  179. /**
  180. * Creates a nested classpath element
  181. */
  182. public Path createClasspath() {
  183. return cmdl.createClasspath(project).createPath();
  184. }
  185. /**
  186. * Adds a reference to a CLASSPATH defined elsewhere.
  187. */
  188. public void setClasspathRef(Reference r) {
  189. createClasspath().setRefid(r);
  190. }
  191. /**
  192. * set the jar name...
  193. */
  194. public void setJar(File jarfile) throws BuildException {
  195. if (cmdl.getClassname() != null){
  196. throw new BuildException("Cannot use 'jar' and 'classname' "
  197. + "attributes in same command.");
  198. }
  199. cmdl.setJar(jarfile.getAbsolutePath());
  200. }
  201. /**
  202. * Set the class name.
  203. */
  204. public void setClassname(String s) throws BuildException {
  205. if (cmdl.getJar() != null){
  206. throw new BuildException("Cannot use 'jar' and 'classname' "
  207. + "attributes in same command");
  208. }
  209. cmdl.setClassname(s);
  210. }
  211. /**
  212. * Set the command line arguments for the class.
  213. */
  214. public void setArgs(String s) {
  215. log("The args attribute is deprecated. " +
  216. "Please use nested arg elements.",
  217. Project.MSG_WARN);
  218. cmdl.createArgument().setLine(s);
  219. }
  220. /**
  221. * Creates a nested arg element.
  222. */
  223. public Commandline.Argument createArg() {
  224. return cmdl.createArgument();
  225. }
  226. /**
  227. * Set the forking flag.
  228. */
  229. public void setFork(boolean s) {
  230. this.fork = s;
  231. }
  232. /**
  233. * Set the command line arguments for the JVM.
  234. */
  235. public void setJvmargs(String s) {
  236. log("The jvmargs attribute is deprecated. " +
  237. "Please use nested jvmarg elements.",
  238. Project.MSG_WARN);
  239. cmdl.createVmArgument().setLine(s);
  240. }
  241. /**
  242. * Creates a nested jvmarg element.
  243. */
  244. public Commandline.Argument createJvmarg() {
  245. return cmdl.createVmArgument();
  246. }
  247. /**
  248. * Set the command used to start the VM (only if fork==false).
  249. */
  250. public void setJvm(String s) {
  251. cmdl.setVm(s);
  252. }
  253. /**
  254. * Add a nested sysproperty element.
  255. */
  256. public void addSysproperty(Environment.Variable sysp) {
  257. cmdl.addSysproperty(sysp);
  258. }
  259. /**
  260. * Throw a BuildException if process returns non 0.
  261. */
  262. public void setFailonerror(boolean fail) {
  263. failOnError = fail;
  264. }
  265. /**
  266. * The working directory of the process
  267. */
  268. public void setDir(File d) {
  269. this.dir = d;
  270. }
  271. /**
  272. * File the output of the process is redirected to.
  273. */
  274. public void setOutput(File out) {
  275. this.out = out;
  276. }
  277. /**
  278. * -mx or -Xmx depending on VM version
  279. */
  280. public void setMaxmemory(String max){
  281. cmdl.setMaxmemory(max);
  282. }
  283. public void setJVMVersion(String value) {
  284. cmdl.setVmversion(value);
  285. }
  286. /**
  287. * Add a nested env element - an environment variable.
  288. *
  289. * <p>Will be ignored if we are not forking a new VM.
  290. *
  291. * @since Ant 1.5
  292. */
  293. public void addEnv(Environment.Variable var) {
  294. env.addVariable(var);
  295. }
  296. /**
  297. * Use a completely new environment.
  298. *
  299. * <p>Will be ignored if we are not forking a new VM.
  300. *
  301. * @since Ant 1.5
  302. */
  303. public void setNewenvironment(boolean newenv) {
  304. newEnvironment = newenv;
  305. }
  306. /**
  307. * Shall we append to an existing file?
  308. *
  309. * @since Ant 1.5
  310. */
  311. public void setAppend(boolean append) {
  312. this.append = append;
  313. }
  314. /**
  315. * Timeout in milliseconds after which the process will be killed.
  316. *
  317. * @since Ant 1.5
  318. */
  319. public void setTimeout(Long value) {
  320. timeout = value;
  321. }
  322. /**
  323. * Pass output sent to System.out to specified output file.
  324. *
  325. * @since Ant 1.5
  326. */
  327. protected void handleOutput(String line) {
  328. if (outStream != null) {
  329. outStream.println(line);
  330. } else {
  331. super.handleOutput(line);
  332. }
  333. }
  334. /**
  335. * Pass output sent to System.err to specified output file.
  336. *
  337. * @since Ant 1.5
  338. */
  339. protected void handleErrorOutput(String line) {
  340. if (outStream != null) {
  341. outStream.println(line);
  342. } else {
  343. super.handleErrorOutput(line);
  344. }
  345. }
  346. /**
  347. * Executes the given classname with the given arguments as it
  348. * was a command line application.
  349. */
  350. private void run(CommandlineJava command) throws BuildException {
  351. ExecuteJava exe = new ExecuteJava();
  352. exe.setJavaCommand(command.getJavaCommand());
  353. exe.setClasspath(command.getClasspath());
  354. exe.setSystemProperties(command.getSystemProperties());
  355. exe.setTimeout(timeout);
  356. if (out != null) {
  357. try {
  358. outStream =
  359. new PrintStream(new FileOutputStream(out.getAbsolutePath(),
  360. append));
  361. exe.execute(project);
  362. } catch (IOException io) {
  363. throw new BuildException(io, location);
  364. } finally {
  365. if (outStream != null) {
  366. outStream.close();
  367. }
  368. }
  369. } else {
  370. exe.execute(project);
  371. }
  372. }
  373. /**
  374. * Executes the given classname with the given arguments in a separate VM.
  375. */
  376. private int run(String[] command) throws BuildException {
  377. FileOutputStream fos = null;
  378. try {
  379. Execute exe = null;
  380. if (out == null) {
  381. exe = new Execute(new LogStreamHandler(this, Project.MSG_INFO,
  382. Project.MSG_WARN),
  383. createWatchdog());
  384. } else {
  385. fos = new FileOutputStream(out.getAbsolutePath(), append);
  386. exe = new Execute(new PumpStreamHandler(fos),
  387. createWatchdog());
  388. }
  389. exe.setAntRun(project);
  390. if (dir == null) {
  391. dir = project.getBaseDir();
  392. } else if (!dir.exists() || !dir.isDirectory()) {
  393. throw new BuildException(dir.getAbsolutePath()
  394. + " is not a valid directory",
  395. location);
  396. }
  397. exe.setWorkingDirectory(dir);
  398. String[] environment = env.getVariables();
  399. if (environment != null) {
  400. for (int i = 0; i < environment.length; i++) {
  401. log("Setting environment variable: " + environment[i],
  402. Project.MSG_VERBOSE);
  403. }
  404. }
  405. exe.setNewenvironment(newEnvironment);
  406. exe.setEnvironment(environment);
  407. exe.setCommandline(command);
  408. try {
  409. int rc = exe.execute();
  410. if (exe.killedProcess()) {
  411. log("Timeout: killed the sub-process", Project.MSG_WARN);
  412. }
  413. return rc;
  414. } catch (IOException e) {
  415. throw new BuildException(e, location);
  416. }
  417. } catch (IOException io) {
  418. throw new BuildException(io, location);
  419. } finally {
  420. if (fos != null) {
  421. try {fos.close();} catch (IOException io) {}
  422. }
  423. }
  424. }
  425. /**
  426. * Executes the given classname with the given arguments as it
  427. * was a command line application.
  428. */
  429. protected void run(String classname, Vector args) throws BuildException {
  430. CommandlineJava cmdj = new CommandlineJava();
  431. cmdj.setClassname(classname);
  432. for (int i = 0; i < args.size(); i++) {
  433. cmdj.createArgument().setValue((String) args.elementAt(i));
  434. }
  435. run(cmdj);
  436. }
  437. /**
  438. * Clear out the arguments to this java task.
  439. */
  440. public void clearArgs() {
  441. cmdl.clearJavaArgs();
  442. }
  443. /**
  444. * Create the Watchdog to kill a runaway process.
  445. *
  446. * @since Ant 1.5
  447. */
  448. protected ExecuteWatchdog createWatchdog() throws BuildException {
  449. if (timeout == null) {
  450. return null;
  451. }
  452. return new ExecuteWatchdog(timeout.longValue());
  453. }
  454. }