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

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