KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > tools > ant > taskdefs > optional > dotnet > NetCommand


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  * build notes
20  * The reference CD to listen to while editing this file is
21  * Underworld Everything, Everything
22  * variable naming policy from Fowler's refactoring book.
23  */

24 // place below the optional ant tasks package
25

26 package org.apache.tools.ant.taskdefs.optional.dotnet;
27
28 // imports
29

30 import java.io.File JavaDoc;
31 import java.io.IOException JavaDoc;
32 import java.io.FileOutputStream JavaDoc;
33 import java.io.PrintWriter JavaDoc;
34 import java.io.BufferedOutputStream JavaDoc;
35 import java.util.Hashtable JavaDoc;
36
37 import org.apache.tools.ant.BuildException;
38 import org.apache.tools.ant.Project;
39 import org.apache.tools.ant.Task;
40 import org.apache.tools.ant.DirectoryScanner;
41 import org.apache.tools.ant.util.FileUtils;
42 import org.apache.tools.ant.taskdefs.Execute;
43 import org.apache.tools.ant.taskdefs.ExecuteStreamHandler;
44 import org.apache.tools.ant.taskdefs.LogStreamHandler;
45 import org.apache.tools.ant.types.Commandline;
46
47 /**
48  * This is a helper class to spawn net commands out. In its initial form it
49  * contains no .net specifics, just contains all the command line/exe
50  * construction stuff. However, it may be handy in future to have a means of
51  * setting the path to point to the dotnet bin directory; in which case the
52  * shared code should go in here.
53  *
54  *@version 0.5
55  */

56
57 public class NetCommand {
58
59     private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
60     // CheckStyle:VisibilityModifier OFF - bc
61

62     /**
63      * owner project
64      */

65     protected Task owner;
66
67     /**
68      * executable
69      */

70     protected Execute executable;
71
72     /**
73      * what is the command line
74      */

75     protected Commandline commandLine;
76
77     /**
78      * title of the command
79      */

80     protected String JavaDoc title;
81
82     /**
83      * actual program to invoke
84      */

85     protected String JavaDoc program;
86
87     /**
88      * trace flag
89      */

90     protected boolean traceCommandLine = false;
91
92     /**
93      * flag to control action on execution trouble
94      */

95     protected boolean failOnError;
96
97     // CheckStyle:VisibilityModifier ON
98

99     /**
100      * the directory to execute the command in. When null, the current
101      * directory is used.
102      */

103     private File JavaDoc directory;
104
105     /**
106      * flag to set to to use @file based command cache
107      */

108     private boolean useResponseFile = false;
109
110     /**
111      * name of a temp file; may be null
112      */

113     private File JavaDoc temporaryCommandFile;
114
115     /**
116      * internal threshold for auto-switch
117      */

118     private int automaticResponseFileThreshold = 64;
119
120     /**
121      * constructor
122      *
123      *@param title (for logging/errors)
124      *@param owner owner task
125      *@param program app we are to run
126      */

127
128     public NetCommand(Task owner, String JavaDoc title, String JavaDoc program) {
129         this.owner = owner;
130         this.title = title;
131         this.program = program;
132         commandLine = new Commandline();
133         commandLine.setExecutable(program);
134     }
135
136
137     /**
138      * turn tracing on or off
139      *
140      *@param b trace flag
141      */

142     public void setTraceCommandLine(boolean b) {
143         traceCommandLine = b;
144     }
145
146
147     /**
148      * set fail on error flag
149      *
150      *@param b fail flag -set to true to cause an exception to be raised if
151      * the return value != 0
152      */

153     public void setFailOnError(boolean b) {
154         failOnError = b;
155     }
156
157
158     /**
159      * query fail on error flag
160      *
161      *@return The failFailOnError value
162      */

163     public boolean getFailFailOnError() {
164         return failOnError;
165     }
166
167
168     /**
169      * set the directory to run from, if the default is inadequate
170      * @param directory the directory to use.
171      */

172     public void setDirectory(File JavaDoc directory) {
173         this.directory = directory;
174     }
175
176     /**
177      * verbose text log
178      *
179      *@param msg string to add to log if verbose is defined for the build
180      */

181     protected void logVerbose(String JavaDoc msg) {
182         owner.getProject().log(msg, Project.MSG_VERBOSE);
183     }
184
185
186     /**
187      * error text log
188      *
189      *@param msg message to display as an error
190      */

191     protected void logError(String JavaDoc msg) {
192         owner.getProject().log(msg, Project.MSG_ERR);
193     }
194
195
196     /**
197      * add an argument to a command line; do nothing if the arg is null or
198      * empty string
199      *
200      *@param argument The feature to be added to the Argument attribute
201      */

202     public void addArgument(String JavaDoc argument) {
203         if (argument != null && argument.length() != 0) {
204             commandLine.createArgument().setValue(argument);
205         }
206     }
207
208     /**
209      * add an argument to a command line; do nothing if the arg is null or
210      * empty string
211      *
212      *@param arguments The features to be added to the Argument attribute
213      */

214     public void addArguments(String JavaDoc[] arguments) {
215         if (arguments != null && arguments.length != 0) {
216             for (int i = 0; i < arguments.length; i++) {
217                 addArgument(arguments[i]);
218             }
219         }
220     }
221
222     /**
223      * concatenate two strings together and add them as a single argument,
224      * but only if argument2 is non-null and non-zero length
225      *
226      *@param argument1 The first argument
227      *@param argument2 The second argument
228      */

229     public void addArgument(String JavaDoc argument1, String JavaDoc argument2) {
230         if (argument2 != null && argument2.length() != 0) {
231             commandLine.createArgument().setValue(argument1 + argument2);
232         }
233     }
234
235     /**
236      * getter
237      * @return response file state
238      */

239     public boolean isUseResponseFile() {
240         return useResponseFile;
241     }
242
243     /**
244      * set this to true to always use the response file
245      * @param useResponseFile a <code>boolean</code> value.
246      */

247     public void setUseResponseFile(boolean useResponseFile) {
248         this.useResponseFile = useResponseFile;
249     }
250
251     /**
252      * getter for threshold
253      * @return 0 for disabled, or a threshold for enabling response files
254      */

255     public int getAutomaticResponseFileThreshold() {
256         return automaticResponseFileThreshold;
257     }
258
259     /**
260      * set threshold for automatically using response files -use 0 for off
261      * @param automaticResponseFileThreshold the threshold value to use.
262      */

263     public void setAutomaticResponseFileThreshold(int automaticResponseFileThreshold) {
264         this.automaticResponseFileThreshold = automaticResponseFileThreshold;
265     }
266
267     /**
268      * set up the command sequence..
269      */

270     protected void prepareExecutor() {
271         // default directory to the project's base directory
272
if (owner == null) {
273             throw new RuntimeException JavaDoc("no owner");
274         }
275         if (owner.getProject() == null) {
276             throw new RuntimeException JavaDoc("Owner has no project");
277         }
278         File JavaDoc dir = owner.getProject().getBaseDir();
279         if (directory != null) {
280             dir = directory;
281         }
282
283         ExecuteStreamHandler handler = new LogStreamHandler(owner,
284                 Project.MSG_INFO, Project.MSG_WARN);
285         executable = new Execute(handler, null);
286         executable.setAntRun(owner.getProject());
287         executable.setWorkingDirectory(dir);
288     }
289
290
291     /**
292      * Run the command using the given Execute instance.
293      *
294      *@exception BuildException if something goes wrong and the
295      * failOnError flag is true
296      */

297     public void runCommand()
298              throws BuildException {
299         prepareExecutor();
300         int err = -1;
301         // assume the worst
302
try {
303             if (traceCommandLine) {
304                 owner.log("In directory " + executable.getWorkingDirectory());
305                 owner.log(commandLine.describeCommand());
306             } else {
307                 //in verbose mode we always log stuff
308
logVerbose("In directory " + executable.getWorkingDirectory());
309                 logVerbose(commandLine.describeCommand());
310             }
311             setExecutableCommandLine();
312             err = executable.execute();
313             if (Execute.isFailure(err)) {
314                 if (failOnError) {
315                     throw new BuildException(title + " returned: " + err, owner.getLocation());
316                 } else {
317                     owner.log(title + " Result: " + err, Project.MSG_ERR);
318                 }
319             }
320         } catch (IOException JavaDoc e) {
321             throw new BuildException(title + " failed: " + e, e, owner.getLocation());
322         } finally {
323             if (temporaryCommandFile != null) {
324                 temporaryCommandFile.delete();
325             }
326         }
327     }
328
329     /**
330      * set the executable command line
331      */

332     private void setExecutableCommandLine() {
333
334         String JavaDoc[] commands = commandLine.getCommandline();
335         //always trigger file mode if commands are big enough
336
if (automaticResponseFileThreshold > 0
337             && commands.length > automaticResponseFileThreshold) {
338             useResponseFile = true;
339         }
340         if (!useResponseFile || commands.length <= 1) {
341             //the simple action is to send the command line in as is
342
executable.setCommandline(commands);
343         } else {
344             //but for big operations, we save all the params to a temp file
345
//and set @tmpfile as the command -then we remember to delete the tempfile
346
//afterwards
347
FileOutputStream JavaDoc fos = null;
348
349             temporaryCommandFile = FILE_UTILS.createTempFile("cmd", ".txt", null);
350             owner.log("Using response file " + temporaryCommandFile, Project.MSG_VERBOSE);
351
352             try {
353                 fos = new FileOutputStream JavaDoc(temporaryCommandFile);
354                 PrintWriter JavaDoc out = new PrintWriter JavaDoc(new BufferedOutputStream JavaDoc(fos));
355                 //start at 1 because element 0 is the executable name
356
for (int i = 1; i < commands.length; ++i) {
357                     out.println(commands[i]);
358                 }
359                 out.flush();
360                 out.close();
361             } catch (IOException JavaDoc ex) {
362                 throw new BuildException("saving command stream to " + temporaryCommandFile, ex);
363             }
364
365             String JavaDoc[] newCommandLine = new String JavaDoc[2];
366             newCommandLine[0] = commands[0];
367             newCommandLine[1] = "@" + temporaryCommandFile.getAbsolutePath();
368             logVerbose(Commandline.describeCommand(newCommandLine));
369             executable.setCommandline(newCommandLine);
370         }
371     }
372
373
374     /**
375      * scan through one fileset for files to include
376      * @param scanner the directory scanner to use.
377      * @param filesToBuild the map to place the files.
378      * @param outputTimestamp timestamp to compare against
379      * @return #of files out of date
380      * @todo should FAT granularity be included here?
381      */

382     public int scanOneFileset(DirectoryScanner scanner, Hashtable JavaDoc filesToBuild,
383                                         long outputTimestamp) {
384         int filesOutOfDate = 0;
385         String JavaDoc[] dependencies = scanner.getIncludedFiles();
386         File JavaDoc base = scanner.getBasedir();
387         //add to the list
388
for (int i = 0; i < dependencies.length; i++) {
389             File JavaDoc targetFile = new File JavaDoc(base, dependencies[i]);
390             if (filesToBuild.get(targetFile) == null) {
391                 filesToBuild.put(targetFile, targetFile);
392                 if (targetFile.lastModified() > outputTimestamp) {
393                     filesOutOfDate++;
394                     owner.log(targetFile.toString() + " is out of date",
395                               Project.MSG_VERBOSE);
396                 } else {
397                     owner.log(targetFile.toString(),
398                               Project.MSG_VERBOSE);
399                 }
400             }
401         }
402         return filesOutOfDate;
403     }
404 }
405
Popular Tags