KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > tools > ant > taskdefs > Exec


1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements. See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License. You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */

18
19 package org.apache.tools.ant.taskdefs;
20
21 import java.io.BufferedReader JavaDoc;
22 import java.io.File JavaDoc;
23 import java.io.FileWriter JavaDoc;
24 import java.io.IOException JavaDoc;
25 import java.io.InputStream JavaDoc;
26 import java.io.InputStreamReader JavaDoc;
27 import java.io.PrintWriter JavaDoc;
28
29 import org.apache.tools.ant.BuildException;
30 import org.apache.tools.ant.MagicNames;
31 import org.apache.tools.ant.Project;
32 import org.apache.tools.ant.Task;
33
34 /**
35  * Executes a given command if the os platform is appropriate.
36  *
37  * <p><strong>As of Ant 1.2, this class is no longer the
38  * implementation of Ant's &lt;exec&gt; task - it is considered to be
39  * dead code by the Ant developers and is unmaintained. Don't use
40  * it.</strong></p>
41  *
42  * @deprecated since 1.2.
43  * delegate to {@link org.apache.tools.ant.taskdefs.Execute Execute}
44  * instead.
45  */

46 public class Exec extends Task {
47     private String JavaDoc os;
48     private String JavaDoc out;
49     private File JavaDoc dir;
50     private String JavaDoc command;
51     // CheckStyle:VisibilityModifier OFF - bc
52
protected PrintWriter JavaDoc fos = null;
53     // CheckStyle:VisibilityModifier ON
54
private boolean failOnError = false;
55
56     /**
57      * Constructor for Exec.
58      * Prints a warning message to std error.
59      */

60     public Exec() {
61         System.err.println("As of Ant 1.2 released in October 2000, "
62             + "the Exec class");
63         System.err.println("is considered to be dead code by the Ant "
64             + "developers and is unmaintained.");
65         System.err.println("Don\'t use it!");
66     }
67
68     /**
69      * Execute the task.
70      * @throws BuildException on error
71      */

72     public void execute() throws BuildException {
73         run(command);
74     }
75
76     /**
77      * Execute the command.
78      * @param command the command to exec
79      * @return the exit value of the command
80      * @throws BuildException on error
81      */

82     protected int run(String JavaDoc command) throws BuildException {
83
84         int err = -1; // assume the worst
85

86         // test if os match
87
String JavaDoc myos = System.getProperty("os.name");
88         log("Myos = " + myos, Project.MSG_VERBOSE);
89         if ((os != null) && (os.indexOf(myos) < 0)) {
90             // this command will be executed only on the specified OS
91
log("Not found in " + os, Project.MSG_VERBOSE);
92             return 0;
93         }
94
95         // default directory to the project's base directory
96
if (dir == null) {
97           dir = getProject().getBaseDir();
98         }
99
100         if (myos.toLowerCase().indexOf("windows") >= 0) {
101             if (!dir.equals(getProject().resolveFile("."))) {
102                 if (myos.toLowerCase().indexOf("nt") >= 0) {
103                     command = "cmd /c cd " + dir + " && " + command;
104                 } else {
105                     String JavaDoc ant = getProject().getProperty(MagicNames.ANT_HOME);
106                     if (ant == null) {
107                         throw new BuildException("Property '" + MagicNames.ANT_HOME + "' not "
108                             + "found", getLocation());
109                     }
110
111                     String JavaDoc antRun = getProject().resolveFile(ant + "/bin/antRun.bat").toString();
112                     command = antRun + " " + dir + " " + command;
113                 }
114             }
115         } else {
116             String JavaDoc ant = getProject().getProperty(MagicNames.ANT_HOME);
117             if (ant == null) {
118               throw new BuildException("Property '" + MagicNames.ANT_HOME + "' not found",
119                                        getLocation());
120             }
121             String JavaDoc antRun = getProject().resolveFile(ant + "/bin/antRun").toString();
122
123             command = antRun + " " + dir + " " + command;
124         }
125
126         try {
127             // show the command
128
log(command, Project.MSG_VERBOSE);
129
130             // exec command on system runtime
131
Process JavaDoc proc = Runtime.getRuntime().exec(command);
132
133             if (out != null) {
134                 fos = new PrintWriter JavaDoc(new FileWriter JavaDoc(out));
135                 log("Output redirected to " + out, Project.MSG_VERBOSE);
136             }
137
138             // copy input and error to the output stream
139
StreamPumper inputPumper =
140                 new StreamPumper(proc.getInputStream(), Project.MSG_INFO);
141             StreamPumper errorPumper =
142                 new StreamPumper(proc.getErrorStream(), Project.MSG_WARN);
143
144             // starts pumping away the generated output/error
145
inputPumper.start();
146             errorPumper.start();
147
148             // Wait for everything to finish
149
proc.waitFor();
150             inputPumper.join();
151             errorPumper.join();
152             proc.destroy();
153
154             // close the output file if required
155
logFlush();
156
157             // check its exit value
158
err = proc.exitValue();
159             if (err != 0) {
160                 if (failOnError) {
161                     throw new BuildException("Exec returned: " + err, getLocation());
162                 } else {
163                     log("Result: " + err, Project.MSG_ERR);
164                 }
165             }
166         } catch (IOException JavaDoc ioe) {
167             throw new BuildException("Error exec: " + command, ioe, getLocation());
168         } catch (InterruptedException JavaDoc ex) {
169             //ignore
170
}
171
172         return err;
173     }
174
175     /**
176      * Set the directory.
177      * @param d a <code>String</code> value
178      */

179     public void setDir(String JavaDoc d) {
180         this.dir = getProject().resolveFile(d);
181     }
182
183     /**
184      * Set the Operating System that this exec is to run in.
185      * @param os a <code>String</code> value
186      */

187     public void setOs(String JavaDoc os) {
188         this.os = os;
189     }
190
191     /**
192      * Set the command to exec.
193      * @param command a <code>String</code> value
194      */

195     public void setCommand(String JavaDoc command) {
196         this.command = command;
197     }
198
199     /**
200      * Set the output filename.
201      * @param out a <code>String</code> value
202      */

203     public void setOutput(String JavaDoc out) {
204         this.out = out;
205     }
206
207     /**
208      * Set the failOnError attribute.
209      * Default is false.
210      * @param fail a <code>boolean</code> value
211      */

212     public void setFailonerror(boolean fail) {
213         failOnError = fail;
214     }
215
216     /**
217      * Log an output message.
218      * @param line the line to putput
219      * @param messageLevel the level of logging - ignored
220      * if output is going to a file
221      */

222     protected void outputLog(String JavaDoc line, int messageLevel) {
223         if (fos == null) {
224             log(line, messageLevel);
225         } else {
226             fos.println(line);
227         }
228     }
229
230     /**
231      * Close output.
232      */

233     protected void logFlush() {
234         if (fos != null) {
235           fos.close();
236         }
237     }
238
239     // Inner class for continually pumping the input stream during
240
// Process's runtime.
241
class StreamPumper extends Thread JavaDoc {
242         private BufferedReader JavaDoc din;
243         private int messageLevel;
244         private boolean endOfStream = false;
245         private static final int SLEEP_TIME = 5;
246
247         public StreamPumper(InputStream JavaDoc is, int messageLevel) {
248             this.din = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(is));
249             this.messageLevel = messageLevel;
250         }
251
252         public void pumpStream() throws IOException JavaDoc {
253             if (!endOfStream) {
254                 String JavaDoc line = din.readLine();
255
256                 if (line != null) {
257                     outputLog(line, messageLevel);
258                 } else {
259                     endOfStream = true;
260                 }
261             }
262         }
263
264         public void run() {
265             try {
266                 try {
267                     while (!endOfStream) {
268                         pumpStream();
269                         sleep(SLEEP_TIME);
270                     }
271                 } catch (InterruptedException JavaDoc ie) {
272                     //ignore
273
}
274                 din.close();
275             } catch (IOException JavaDoc ioe) {
276                 // ignore
277
}
278         }
279     }
280 }
281
Popular Tags