KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > ant > internal > ui > antsupport > InternalAntRunner


1 /*******************************************************************************
2  * Copyright (c) 2000, 2007 IBM Corporation and others.
3  * Portions Copyright 2000-2005 The Apache Software Foundation
4  * All rights reserved. This program and the accompanying materials are made
5  * available under the terms of the Apache Software License v2.0 which
6  * accompanies this distribution and is available at
7  * http://www.apache.org/licenses/LICENSE-2.0.
8  *
9  * Contributors:
10  * IBM Corporation - derived implementation
11  *******************************************************************************/

12
13 package org.eclipse.ant.internal.ui.antsupport;
14
15 import java.io.File JavaDoc;
16 import java.io.FileInputStream JavaDoc;
17 import java.io.FileNotFoundException JavaDoc;
18 import java.io.FileOutputStream JavaDoc;
19 import java.io.IOException JavaDoc;
20 import java.io.InputStream JavaDoc;
21 import java.io.PrintStream JavaDoc;
22 import java.text.MessageFormat JavaDoc; // can't use ICU, used by ant build
23
import java.util.ArrayList JavaDoc;
24 import java.util.Collections JavaDoc;
25 import java.util.Enumeration JavaDoc;
26 import java.util.HashMap JavaDoc;
27 import java.util.Iterator JavaDoc;
28 import java.util.List JavaDoc;
29 import java.util.Map JavaDoc;
30 import java.util.Properties JavaDoc;
31 import java.util.Vector JavaDoc;
32
33 import org.apache.tools.ant.AntTypeDefinition;
34 import org.apache.tools.ant.BuildEvent;
35 import org.apache.tools.ant.BuildException;
36 import org.apache.tools.ant.BuildListener;
37 import org.apache.tools.ant.BuildLogger;
38 import org.apache.tools.ant.ComponentHelper;
39 import org.apache.tools.ant.DefaultLogger;
40 import org.apache.tools.ant.DemuxOutputStream;
41 import org.apache.tools.ant.Diagnostics;
42 import org.apache.tools.ant.Main;
43 import org.apache.tools.ant.Project;
44 import org.apache.tools.ant.ProjectHelper;
45 import org.apache.tools.ant.Target;
46 import org.apache.tools.ant.Task;
47 import org.apache.tools.ant.TaskAdapter;
48 import org.apache.tools.ant.util.FileUtils;
49 import org.eclipse.ant.internal.ui.antsupport.logger.RemoteAntBuildLogger;
50
51 /**
52  * Eclipse application entry point into Ant in a separate VM. Derived from the original Ant Main class
53  * to ensure that the functionality is equivalent when running in the platform.
54  */

55 public class InternalAntRunner {
56
57     /**
58      * Message priority for project help messages.
59      */

60     public static final int MSG_PROJECT_HELP= Project.MSG_DEBUG + 1;
61     
62     private List JavaDoc buildListeners;
63
64     private String JavaDoc buildFileLocation;
65
66     /**
67      * Targets we want to run.
68      */

69     private Vector JavaDoc targets;
70
71     private Map JavaDoc userProperties;
72     
73     private Project currentProject;
74     
75     private BuildLogger buildLogger= null;
76     
77     private Map JavaDoc eclipseSpecifiedTasks;
78     private Map JavaDoc eclipseSpecifiedTypes;
79     
80     /**
81      * Cache of the Ant version number when it has been loaded
82      */

83     private String JavaDoc antVersionNumber= null;
84
85     /** Our current message output status. Follows Project.MSG_XXX */
86     private int messageOutputLevel = Project.MSG_INFO;
87
88     /** Indicates whether output to the log is to be unadorned. */
89     private boolean emacsMode = false;
90
91     /** Indicates we should only parse and display the project help information */
92     private boolean projectHelp = false;
93
94     /** Stream that we are using for logging */
95     private PrintStream JavaDoc out = System.out;
96
97     /** Stream that we are using for logging error messages */
98     private PrintStream JavaDoc err = System.err;
99
100     /**
101      * The Ant logger class. There may be only one logger. It will have the
102      * right to use the 'out' PrintStream. The class must implement the BuildLogger
103      * interface. An empty String indicates that no logger is to be used. A <code>null</code>
104      * name indicates that the <code>org.apache.tools.ant.DefaultLogger</code> will be used.
105      */

106     private String JavaDoc loggerClassname = null;
107
108     /** Extra arguments to be parsed as command line arguments. */
109     private String JavaDoc[] extraArguments = null;
110     
111     private boolean scriptExecuted= false;
112     
113     private List JavaDoc propertyFiles= new ArrayList JavaDoc();
114     
115     /**
116      * The Ant InputHandler class. There may be only one input handler.
117      */

118     private String JavaDoc inputHandlerClassname = null;
119     
120     /**
121      * Indicates whether to execute all targets that
122      * do not depend on failed targets
123      * @since Ant 1.6.0
124      */

125     private boolean keepGoing= false;
126
127     /**
128      * Indicates whether this build is to support interactive input
129      * @since Ant 1.6.0
130      */

131     private boolean allowInput = true;
132     
133     private String JavaDoc fEarlyErrorMessage= null;
134     
135     public static void main(String JavaDoc[] args) {
136         try {
137             new InternalAntRunner().run(getArrayList(args));
138         } catch (Throwable JavaDoc t) {
139             t.printStackTrace();
140             System.exit(1);
141         }
142         System.exit(0);
143     }
144
145     private void addBuildListeners(Project project) {
146         String JavaDoc className= null;
147         try {
148             BuildLogger logger= createLogger();
149             if (logger != null) {
150                 project.addBuildListener(logger);
151             }
152             if (buildListeners != null) {
153                 for (Iterator JavaDoc iterator = buildListeners.iterator(); iterator.hasNext();) {
154                     className = (String JavaDoc) iterator.next();
155                     Class JavaDoc listener = Class.forName(className);
156                     project.addBuildListener((BuildListener) listener.newInstance());
157                 }
158             }
159         } catch (ClassCastException JavaDoc e) {
160             String JavaDoc message = MessageFormat.format(RemoteAntMessages.getString("InternalAntRunner.{0}_which_was_specified_to_be_a_build_listener_is_not_an_instance_of_org.apache.tools.ant.BuildListener._1"), new String JavaDoc[]{className}); //$NON-NLS-1$
161
logMessage(null, message, Project.MSG_ERR);
162             throw new BuildException(message, e);
163         } catch (BuildException e) {
164             throw e;
165         } catch (Exception JavaDoc e) {
166             throw new BuildException(e);
167         }
168     }
169
170     /**
171      * Parses the build file and adds necessary information into
172      * the given project.
173      * @param project The project to configure
174      */

175     private void parseBuildFile(Project project) {
176         File JavaDoc buildFile = new File JavaDoc(getBuildFileLocation());
177         if (!buildFile.exists()) {
178             throw new BuildException(MessageFormat.format(RemoteAntMessages.getString("InternalAntRunner.Buildfile__{0}_does_not_exist_!_1"), //$NON-NLS-1$
179
new String JavaDoc[]{buildFile.getAbsolutePath()}));
180         }
181         if (!buildFile.isFile()) {
182             throw new BuildException(MessageFormat.format(RemoteAntMessages.getString("InternalAntRunner.Buildfile__{0}_is_not_a_file_1"), //$NON-NLS-1$
183
new String JavaDoc[]{buildFile.getAbsolutePath()}));
184         }
185         
186         if (!isVersionCompatible("1.5")) { //$NON-NLS-1$
187
parseBuildFile(project, buildFile);
188         } else {
189             ProjectHelper helper = ProjectHelper.getProjectHelper();
190             project.addReference("ant.projectHelper", helper); //$NON-NLS-1$
191
helper.parse(project, buildFile);
192         }
193     }
194     
195     /**
196      * @deprecated support for Ant older than 1.5
197      */

198     private void parseBuildFile(Project project, File JavaDoc buildFile) {
199         ProjectHelper.configureProject(project, buildFile);
200     }
201
202     private void printArguments(Project project) {
203         if ((messageOutputLevel != Project.MSG_DEBUG) && (messageOutputLevel != Project.MSG_VERBOSE)) {
204             return;
205         }
206         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
207         for (int i = 0; i < extraArguments.length; i++) {
208             sb.append(extraArguments[i]);
209             sb.append(' ');
210         }
211         project.log(MessageFormat.format(RemoteAntMessages.getString("InternalAntRunner.Arguments__{0}_2"), new String JavaDoc[]{sb.toString().trim()})); //$NON-NLS-1$
212
}
213
214
215     /**
216      * Logs a message with the client that lists the targets
217      * in a project
218      *
219      * @param project the project to list targets from
220      */

221     private void printTargets(Project project) {
222         //notify the logger that project help message are coming
223
//since there is no buildstarted or targetstarted to
224
//to be used to establish the connection
225
logMessage(project, "", MSG_PROJECT_HELP); //$NON-NLS-1$
226
// find the target with the longest name
227
int maxLength = 0;
228         Enumeration JavaDoc ptargets = project.getTargets().elements();
229         String JavaDoc targetName;
230         String JavaDoc targetDescription;
231         Target currentTarget;
232         // split the targets in top-level and sub-targets depending
233
// on the presence of a description
234
List JavaDoc topNames = new ArrayList JavaDoc();
235         List JavaDoc topDescriptions = new ArrayList JavaDoc();
236         List JavaDoc subNames = new ArrayList JavaDoc();
237
238         while (ptargets.hasMoreElements()) {
239             currentTarget = (Target) ptargets.nextElement();
240             targetName = currentTarget.getName();
241             targetDescription = currentTarget.getDescription();
242             if (targetDescription == null) {
243                 subNames.add(targetName);
244             } else {
245                 topNames.add(targetName);
246                 topDescriptions.add(targetDescription);
247                 if (targetName.length() > maxLength) {
248                     maxLength = targetName.length();
249                 }
250             }
251         }
252
253         Collections.sort(subNames);
254         Collections.sort(topNames);
255         Collections.sort(topDescriptions);
256         
257         String JavaDoc defaultTargetName = project.getDefaultTarget();
258         if (defaultTargetName != null && !"".equals(defaultTargetName)) { // shouldn't need to check but... //$NON-NLS-1$
259
List JavaDoc defaultName = new ArrayList JavaDoc(1);
260             List JavaDoc defaultDesc = null;
261             defaultName.add(defaultTargetName);
262
263             int indexOfDefDesc = topNames.indexOf(defaultTargetName);
264             if (indexOfDefDesc >= 0) {
265                 defaultDesc = new ArrayList JavaDoc(1);
266                 defaultDesc.add(topDescriptions.get(indexOfDefDesc));
267             }
268             printTargets(project, defaultName, defaultDesc, RemoteAntMessages.getString("InternalAntRunner.Default_target__3"), maxLength); //$NON-NLS-1$
269

270         }
271
272         printTargets(project, topNames, topDescriptions, RemoteAntMessages.getString("InternalAntRunner.Main_targets__4"), maxLength); //$NON-NLS-1$
273
printTargets(project, subNames, null, RemoteAntMessages.getString("InternalAntRunner.Subtargets__5"), 0); //$NON-NLS-1$
274
}
275
276     /**
277      * Logs a message with the client that lists the target names and optional descriptions
278      *
279      * @param project the enclosing target
280      * @param names the targets names
281      * @param descriptions the corresponding descriptions
282      * @param heading the message heading
283      * @param maxlen maximum length that can be allocated for a name
284      */

285     private void printTargets(Project project, List JavaDoc names, List JavaDoc descriptions, String JavaDoc heading, int maxlen) {
286         // now, start printing the targets and their descriptions
287
String JavaDoc lSep = System.getProperty("line.separator"); //$NON-NLS-1$
288

289         String JavaDoc spaces = " "; //$NON-NLS-1$
290
while (spaces.length() < maxlen) {
291             spaces += spaces;
292         }
293         StringBuffer JavaDoc msg = new StringBuffer JavaDoc();
294         msg.append(heading + lSep + lSep);
295         for (int i = 0; i < names.size(); i++) {
296             msg.append(' ');
297             msg.append(names.get(i));
298             if (descriptions != null) {
299                 msg.append(spaces.substring(0, maxlen - ((String JavaDoc) names.get(i)).length() + 2));
300                 msg.append(descriptions.get(i));
301             }
302             msg.append(lSep);
303         }
304         logMessage(project, msg.toString(), Project.MSG_INFO);
305     }
306
307     /*
308      * Note that the list passed to this method must support
309      * List#remove(Object)
310      */

311     private void run(List JavaDoc argList) {
312         setCurrentProject(new Project());
313          if (isVersionCompatible("1.6.3")) { //$NON-NLS-1$
314
new ExecutorSetter().setExecutor(getCurrentProject());
315             }
316         Throwable JavaDoc error = null;
317         PrintStream JavaDoc originalErr = System.err;
318         PrintStream JavaDoc originalOut = System.out;
319         InputStream JavaDoc originalIn= System.in;
320         
321         SecurityManager JavaDoc originalSM= System.getSecurityManager();
322         scriptExecuted= true;
323         try {
324             if (argList != null && (argList.remove("-projecthelp") || argList.remove("-p"))) { //$NON-NLS-1$ //$NON-NLS-2$
325
projectHelp = true;
326             }
327             getCurrentProject().init();
328             if (argList != null) {
329                 scriptExecuted= preprocessCommandLine(argList);
330             
331                 if (!scriptExecuted) {
332                     return;
333                 }
334             }
335             
336             boolean exceptionState= processProperties(argList);
337             
338             addBuildListeners(getCurrentProject());
339             
340             addInputHandler(getCurrentProject());
341             
342             remapSystemIn();
343             System.setOut(new PrintStream JavaDoc(new DemuxOutputStream(getCurrentProject(), false)));
344             System.setErr(new PrintStream JavaDoc(new DemuxOutputStream(getCurrentProject(), true)));
345             
346             if (!projectHelp) {
347                 fireBuildStarted(getCurrentProject());
348             }
349             
350             if (fEarlyErrorMessage != null) {
351                 //an error occurred processing the properties
352
//build started has fired and we have
353
//listeners/loggers to report the error
354
logMessage(getCurrentProject(), fEarlyErrorMessage, Project.MSG_ERR);
355                 if (exceptionState) {
356                     throw new BuildException(fEarlyErrorMessage);
357                 }
358             }
359             
360             //properties can only be set after buildStarted as some listeners/loggers
361
//depend on this (e.g. XMLLogger)
362
setProperties(getCurrentProject());
363             
364             if (argList != null && !argList.isEmpty()) {
365                 try {
366                     scriptExecuted= processCommandLine(argList);
367                 } catch (BuildException e) {
368                     scriptExecuted= false;
369                     throw e;
370                 }
371             }
372             if (!scriptExecuted) {
373                 return;
374             }
375             
376             //needs to occur after processCommandLine(List)
377
if (allowInput && (inputHandlerClassname != null && inputHandlerClassname.length() > 0)) {
378                 if (isVersionCompatible("1.6")) { //$NON-NLS-1$
379
getCurrentProject().setDefaultInputStream(originalIn);
380                 }
381             } else {
382                 //set the system property that any input handler
383
//can check to see if handling input is allowed
384
System.setProperty("eclipse.ant.noInput", "true"); //$NON-NLS-1$//$NON-NLS-2$
385
if (isVersionCompatible("1.5") && (inputHandlerClassname == null || inputHandlerClassname.length() == 0)) { //$NON-NLS-1$
386
InputHandlerSetter setter= new InputHandlerSetter();
387                     setter.setInputHandler(getCurrentProject(), "org.eclipse.ant.internal.ui.antsupport.inputhandler.FailInputHandler"); //$NON-NLS-1$
388
}
389             }
390             
391             getCurrentProject().log(MessageFormat.format(RemoteAntMessages.getString("InternalAntRunner.Build_file__{0}_1"), new String JavaDoc[]{getBuildFileLocation()})); //$NON-NLS-1$
392

393             setTasks();
394             setTypes();
395             
396             if (isVersionCompatible("1.6")) { //$NON-NLS-1$
397
getCurrentProject().setKeepGoingMode(keepGoing);
398             }
399             
400             parseBuildFile(getCurrentProject());
401             
402             if (projectHelp) {
403                 printHelp(getCurrentProject());
404                 scriptExecuted= false;
405                 return;
406             }
407             
408             if (extraArguments != null) {
409                 printArguments(getCurrentProject());
410             }
411             
412             System.setSecurityManager(new AntSecurityManager(originalSM, Thread.currentThread()));
413             
414             if (targets == null) {
415                 targets= new Vector JavaDoc(1);
416             }
417             if (targets.isEmpty() && getCurrentProject().getDefaultTarget() != null) {
418                 targets.add(getCurrentProject().getDefaultTarget());
419             }
420             if (!isVersionCompatible("1.6.3")) { //$NON-NLS-1$
421
getCurrentProject().addReference("eclipse.ant.targetVector", targets); //$NON-NLS-1$
422
}
423             getCurrentProject().executeTargets(targets);
424         } catch (AntSecurityException e) {
425             //expected
426
} catch (Throwable JavaDoc e) {
427             error = e;
428         } finally {
429             System.setErr(originalErr);
430             System.setOut(originalOut);
431             System.setIn(originalIn);
432             if (System.getSecurityManager() instanceof AntSecurityManager) {
433                 System.setSecurityManager(originalSM);
434             }
435             
436             if (!projectHelp) {
437                 fireBuildFinished(getCurrentProject(), error);
438             }
439                         
440             //close any user specified build log
441
if (err != originalErr) {
442                 err.close();
443             }
444             if (out != originalOut) {
445                 out.close();
446             }
447         }
448     }
449     
450     private void setTasks() {
451         if (eclipseSpecifiedTasks != null) {
452             Iterator JavaDoc itr= eclipseSpecifiedTasks.keySet().iterator();
453             String JavaDoc taskName;
454             String JavaDoc taskClassName;
455             while (itr.hasNext()) {
456                 taskName= (String JavaDoc) itr.next();
457                 taskClassName= (String JavaDoc) eclipseSpecifiedTasks.get(taskName);
458                 
459                 if (isVersionCompatible("1.6")) { //$NON-NLS-1$
460
AntTypeDefinition def= new AntTypeDefinition();
461                     def.setName(taskName);
462                     def.setClassName(taskClassName);
463                     def.setClassLoader(this.getClass().getClassLoader());
464                     def.setAdaptToClass(Task.class);
465                     def.setAdapterClass(TaskAdapter.class);
466                     ComponentHelper.getComponentHelper(getCurrentProject()).addDataTypeDefinition(def);
467                 } else {
468                     try {
469                         Class JavaDoc taskClass = Class.forName(taskClassName);
470                         getCurrentProject().addTaskDefinition(taskName, taskClass);
471                     } catch (ClassNotFoundException JavaDoc e) {
472                         String JavaDoc message= MessageFormat.format(RemoteAntMessages.getString("InternalAntRunner.161"), new String JavaDoc[]{taskClassName, taskName}); //$NON-NLS-1$
473
getCurrentProject().log(message, Project.MSG_WARN);
474                     }
475                 }
476             }
477         }
478     }
479
480     private void setTypes() {
481         if (eclipseSpecifiedTypes != null) {
482             Iterator JavaDoc itr= eclipseSpecifiedTypes.keySet().iterator();
483             String JavaDoc typeName;
484             String JavaDoc typeClassName;
485             while (itr.hasNext()) {
486                 typeName = (String JavaDoc) itr.next();
487                 typeClassName= (String JavaDoc) eclipseSpecifiedTypes.get(typeName);
488                 if (isVersionCompatible("1.6")) { //$NON-NLS-1$
489
AntTypeDefinition def = new AntTypeDefinition();
490                     def.setName(typeName);
491                     def.setClassName(typeClassName);
492                     def.setClassLoader(this.getClass().getClassLoader());
493                     ComponentHelper.getComponentHelper(getCurrentProject()).addDataTypeDefinition(def);
494                 } else {
495                     try {
496                         Class JavaDoc typeClass = Class.forName(typeClassName);
497                         getCurrentProject().addDataTypeDefinition(typeName, typeClass);
498                     } catch (ClassNotFoundException JavaDoc e) {
499                         String JavaDoc message= MessageFormat.format(RemoteAntMessages.getString("InternalAntRunner.162"), new String JavaDoc[]{typeClassName, typeName}); //$NON-NLS-1$
500
getCurrentProject().log(message, Project.MSG_WARN);
501                     }
502                 }
503             }
504         }
505     }
506
507     private void remapSystemIn() {
508         if (!isVersionCompatible("1.6")) { //$NON-NLS-1$
509
return;
510         }
511         DemuxInputStreamSetter setter= new DemuxInputStreamSetter();
512         setter.remapSystemIn(getCurrentProject());
513     }
514     
515     /**
516      * Creates and returns the default build logger for logging build events to the ant log.
517      *
518      * @return the default build logger for logging build events to the ant log
519      * can return <code>null</code> if no logging is to occur
520      */

521     private BuildLogger createLogger() {
522         if (loggerClassname == null) {
523             buildLogger= new DefaultLogger();
524         } else if (!"".equals(loggerClassname)) { //$NON-NLS-1$
525
try {
526                 buildLogger = (BuildLogger) (Class.forName(loggerClassname).newInstance());
527             } catch (ClassCastException JavaDoc e) {
528                 String JavaDoc message = MessageFormat.format(RemoteAntMessages.getString("InternalAntRunner.{0}_which_was_specified_to_perform_logging_is_not_an_instance_of_org.apache.tools.ant.BuildLogger._2"), new String JavaDoc[]{loggerClassname}); //$NON-NLS-1$
529
logMessage(null, message, Project.MSG_ERR);
530                 throw new BuildException(message, e);
531             } catch (Exception JavaDoc e) {
532                 String JavaDoc message = MessageFormat.format(RemoteAntMessages.getString("InternalAntRunner.Unable_to_instantiate_logger__{0}_6"), new String JavaDoc[]{loggerClassname}); //$NON-NLS-1$
533
logMessage(null, message, Project.MSG_ERR);
534                 throw new BuildException(message, e);
535             }
536         }
537         
538         if (buildLogger != null) {
539             buildLogger.setMessageOutputLevel(messageOutputLevel);
540             buildLogger.setOutputPrintStream(out);
541             buildLogger.setErrorPrintStream(err);
542             buildLogger.setEmacsMode(emacsMode);
543             if (buildLogger instanceof RemoteAntBuildLogger) {
544                 ((RemoteAntBuildLogger) buildLogger).configure(userProperties);
545             }
546         }
547
548         return buildLogger;
549     }
550     
551     /**
552      * Project.fireBuildStarted is protected in Ant earlier than 1.5.*.
553      * Provides backwards compatibility with old Ant installs.
554      */

555     private void fireBuildStarted(Project project) {
556         if (!isVersionCompatible("1.5")) { //$NON-NLS-1$
557
BuildEvent event = new BuildEvent(project);
558             for (Iterator JavaDoc iterator = project.getBuildListeners().iterator(); iterator.hasNext();) {
559                 BuildListener listener = (BuildListener) iterator.next();
560                 listener.buildStarted(event);
561             }
562         } else {
563             project.fireBuildStarted();
564         }
565     }
566
567     private void fireBuildFinished(Project project, Throwable JavaDoc error) {
568         if (error == null && scriptExecuted) {
569             logMessage(project, RemoteAntMessages.getString("InternalAntRunner.BUILD_SUCCESSFUL_1"), messageOutputLevel); //$NON-NLS-1$
570
}
571         if (!isVersionCompatible("1.5")) { //$NON-NLS-1$
572
BuildEvent event = new BuildEvent(project);
573             event.setException(error);
574             Iterator JavaDoc iter = project.getBuildListeners().iterator();
575             while (iter.hasNext()) {
576                 BuildListener listener = (BuildListener) iter.next();
577                 listener.buildFinished(event);
578             }
579         } else {
580             project.fireBuildFinished(error);
581         }
582     }
583
584     private void logMessage(Project project, String JavaDoc message, int priority) {
585         if (project != null) {
586             project.log(message, priority);
587         } else {
588             if (buildListeners != null) {
589                 project = new Project();
590                 BuildEvent event = new BuildEvent(project);
591                 event.setMessage(message, priority);
592                 //notify the build listeners that are not registered as
593
//no project existed
594
for (Iterator JavaDoc iterator = buildListeners.iterator(); iterator.hasNext();) {
595                     try {
596                         BuildListener listener = (BuildListener) iterator.next();
597                         listener.messageLogged(event);
598                     } catch (ClassCastException JavaDoc e) {
599                         //ignore we could be trying to log that a build listener is the
600
//wrong type of class
601
}
602                 }
603             }
604         }
605     }
606
607     /**
608      * Sets the buildFileLocation.
609      *
610      * @param buildFileLocation the file system location of the build file
611      */

612     private void setBuildFileLocation(String JavaDoc buildFileLocation) {
613         this.buildFileLocation = buildFileLocation;
614         if (getCurrentProject() != null) {
615             getCurrentProject().setUserProperty("ant.file", buildFileLocation); //$NON-NLS-1$
616
}
617     }
618
619     private String JavaDoc getBuildFileLocation() {
620         if (buildFileLocation == null) {
621             buildFileLocation = new File JavaDoc("build.xml").getAbsolutePath(); //$NON-NLS-1$
622
}
623         return buildFileLocation;
624     }
625
626     /**
627      * Sets the message output level. Use -1 for none.
628      * @param level The message output level
629      */

630     private void setMessageOutputLevel(int level) {
631         messageOutputLevel = level;
632         if (buildLogger != null) {
633             buildLogger.setMessageOutputLevel(level);
634         }
635     }
636     
637     /*
638      * Returns a String representation of the Ant version number as specified
639      * in the version.txt file.
640      */

641     private String JavaDoc getAntVersionNumber() throws BuildException {
642         if (antVersionNumber == null) {
643             try {
644                 Properties JavaDoc props = new Properties JavaDoc();
645                 InputStream JavaDoc in = Main.class.getResourceAsStream("/org/apache/tools/ant/version.txt"); //$NON-NLS-1$
646
props.load(in);
647                 in.close();
648                 String JavaDoc versionNumber= props.getProperty("VERSION"); //$NON-NLS-1$
649
antVersionNumber= versionNumber;
650             } catch (IOException JavaDoc ioe) {
651                 throw new BuildException(MessageFormat.format(RemoteAntMessages.getString("InternalAntRunner.Could_not_load_the_version_information._{0}_9"), new String JavaDoc[]{ioe.getMessage()})); //$NON-NLS-1$
652
} catch (NullPointerException JavaDoc npe) {
653                 throw new BuildException(RemoteAntMessages.getString("InternalAntRunner.Could_not_load_the_version_information._10")); //$NON-NLS-1$
654
}
655         }
656         return antVersionNumber;
657     }
658     
659     /*
660      * Returns whether the given version is compatible with the
661      * current Ant version. A version is compatible if it is less
662      * than or equal to the current version.
663      */

664     private boolean isVersionCompatible(String JavaDoc comparison) {
665         String JavaDoc version= getAntVersionNumber();
666         return version.compareTo(comparison) >= 0;
667     }
668     
669     private boolean preprocessCommandLine(List JavaDoc commands) {
670         
671         String JavaDoc arg = getArgument(commands, "-listener"); //$NON-NLS-1$
672
while (arg != null) {
673             if (arg.length() == 0) {
674                 throw new BuildException(RemoteAntMessages.getString("InternalAntRunner.You_must_specify_a_classname_when_using_the_-listener_argument_1")); //$NON-NLS-1$
675
}
676             if (buildListeners == null) {
677                 buildListeners= new ArrayList JavaDoc(1);
678             }
679             buildListeners.add(arg);
680             arg = getArgument(commands, "-listener"); //$NON-NLS-1$
681
}
682
683         arg = getArgument(commands, "-logger"); //$NON-NLS-1$
684
if (arg != null) {
685             //allow empty string to mean no logger
686
loggerClassname = arg;
687         }
688         arg = getArgument(commands, "-logger"); //$NON-NLS-1$
689
if (arg != null) {
690             throw new BuildException(RemoteAntMessages.getString("InternalAntRunner.Only_one_logger_class_may_be_specified_1")); //$NON-NLS-1$
691
}
692         
693         arg = getArgument(commands, "-inputhandler"); //$NON-NLS-1$
694
if (arg != null) {
695             if (arg.length() == 0) {
696                 throw new BuildException(RemoteAntMessages.getString("InternalAntRunner.You_must_specify_a_classname_when_using_the_-inputhandler_argument_1")); //$NON-NLS-1$
697
}
698             inputHandlerClassname = arg;
699         }
700         arg = getArgument(commands, "-inputhandler"); //$NON-NLS-1$
701
if (arg != null) {
702             throw new BuildException(RemoteAntMessages.getString("InternalAntRunner.Only_one_input_handler_class_may_be_specified._2")); //$NON-NLS-1$
703
}
704         return true;
705     }
706     
707     /*
708      * Looks for interesting command line arguments.
709      * Returns whether it is OK to run the script.
710      */

711     private boolean processCommandLine(List JavaDoc commands) {
712         
713         if (commands.remove("-help") || commands.remove("-h")) { //$NON-NLS-1$ //$NON-NLS-2$
714
printUsage();
715             return false;
716         }
717         
718         if (commands.remove("-version")) { //$NON-NLS-1$
719
printVersion();
720             return false;
721         }
722         
723         if (commands.remove("-verbose") || commands.remove("-v")) { //$NON-NLS-1$ //$NON-NLS-2$
724
printVersion();
725             setMessageOutputLevel(Project.MSG_VERBOSE);
726         }
727         
728         if (commands.remove("-debug") || commands.remove("-d")) { //$NON-NLS-1$ //$NON-NLS-2$
729
printVersion();
730             setMessageOutputLevel(Project.MSG_DEBUG);
731         }
732         
733         if (commands.remove("-quiet") || commands.remove("-q")) { //$NON-NLS-1$ //$NON-NLS-2$
734
setMessageOutputLevel(Project.MSG_WARN);
735         }
736
737         if (commands.remove("-emacs") || commands.remove("-e")) { //$NON-NLS-1$ //$NON-NLS-2$
738
emacsMode = true;
739             if (buildLogger != null) {
740                 buildLogger.setEmacsMode(true);
741             }
742         }
743         
744         if (commands.remove("-diagnostics")) { //$NON-NLS-1$
745
if (!isVersionCompatible("1.5")) { //$NON-NLS-1$
746
throw new BuildException(RemoteAntMessages.getString("InternalAntRunner.The_diagnositics_options_is_an_Ant_1.5.*_feature._Please_update_your_Ant_classpath_to_include_an_Ant_version_greater_than_this._4")); //$NON-NLS-1$
747
}
748             try {
749                 Diagnostics.doReport(System.out);
750             } catch (NullPointerException JavaDoc e) {
751                 logMessage(getCurrentProject(), RemoteAntMessages.getString("InternalAntRunner.ANT_HOME_must_be_set_to_use_Ant_diagnostics_2"), Project.MSG_ERR); //$NON-NLS-1$
752
}
753             return false;
754         }
755         
756         String JavaDoc arg = getArgument(commands, "-logfile"); //$NON-NLS-1$
757
if (arg == null) {
758             arg = getArgument(commands, "-l"); //$NON-NLS-1$
759
}
760         if (arg != null) {
761             if (arg.length() == 0) {
762                 String JavaDoc message= RemoteAntMessages.getString("InternalAntRunner.You_must_specify_a_log_file_when_using_the_-log_argument_3"); //$NON-NLS-1$
763
logMessage(currentProject, message, Project.MSG_ERR);
764                 throw new BuildException(message);
765             }
766             try {
767                 createLogFile(arg);
768             } catch (IOException JavaDoc e) {
769                 // just log message and ignore exception
770
logMessage(getCurrentProject(), MessageFormat.format(RemoteAntMessages.getString("InternalAntRunner.Could_not_write_to_the_specified_log_file__{0}._Make_sure_the_path_exists_and_you_have_write_permissions._2"), new String JavaDoc[]{arg}), Project.MSG_ERR); //$NON-NLS-1$
771
return false;
772             }
773         
774         }
775         
776         arg = getArgument(commands, "-buildfile"); //$NON-NLS-1$
777
if (arg == null) {
778             arg = getArgument(commands, "-file"); //$NON-NLS-1$
779
if (arg == null) {
780                 arg = getArgument(commands, "-f"); //$NON-NLS-1$
781
}
782         }
783         
784         if (arg != null) {
785             if (arg.length() == 0) {
786                 String JavaDoc message= RemoteAntMessages.getString("InternalAntRunner.You_must_specify_a_buildfile_when_using_the_-buildfile_argument_4"); //$NON-NLS-1$
787
logMessage(currentProject, message, Project.MSG_ERR);
788                 throw new BuildException(message);
789             }
790             setBuildFileLocation(arg);
791         }
792         
793         if (isVersionCompatible("1.6")) { //$NON-NLS-1$
794
if (commands.remove("-k") || commands.remove("-keep-going")) { //$NON-NLS-1$ //$NON-NLS-2$
795
keepGoing= true;
796             }
797             if (commands.remove("-noinput")) { //$NON-NLS-1$
798
allowInput= false;
799             }
800             arg= getArgument(commands, "-lib"); //$NON-NLS-1$
801
if (arg != null) {
802                 logMessage(currentProject, RemoteAntMessages.getString("InternalAntRunner.157"), Project.MSG_ERR); //$NON-NLS-1$
803
return false;
804             }
805         }
806         
807         arg= getArgument(commands, "-find"); //$NON-NLS-1$
808
if (arg == null) {
809             arg= getArgument(commands, "-s"); //$NON-NLS-1$
810
}
811         if (arg != null) {
812             logMessage(currentProject, RemoteAntMessages.getString("InternalAntRunner.-find_not_supported"), Project.MSG_ERR); //$NON-NLS-1$
813
return false;
814         }
815         
816         processTasksAndTypes(commands);
817         
818         if (!commands.isEmpty()) {
819             processUnrecognizedCommands(commands);
820         }
821
822         if (!commands.isEmpty()) {
823             processTargets(commands);
824         }
825         
826         return true;
827     }
828     
829     private void processTasksAndTypes(List JavaDoc commands) {
830         String JavaDoc arg = getArgument(commands, "-eclipseTask"); //$NON-NLS-1$
831
while (arg != null) {
832             if (eclipseSpecifiedTasks == null) {
833                 eclipseSpecifiedTasks= new HashMap JavaDoc();
834             }
835             int index= arg.indexOf(',');
836             if (index != -1) {
837                 String JavaDoc name= arg.substring(0, index);
838                 String JavaDoc className= arg.substring(index + 1);
839                 eclipseSpecifiedTasks.put(name, className);
840             }
841             arg = getArgument(commands, "-eclipseTask"); //$NON-NLS-1$
842
}
843         
844         arg = getArgument(commands, "-eclipseType"); //$NON-NLS-1$
845
while (arg != null) {
846             if (eclipseSpecifiedTypes == null) {
847                 eclipseSpecifiedTypes= new HashMap JavaDoc();
848             }
849             int index= arg.indexOf(',');
850             if (index != -1) {
851                 String JavaDoc name= arg.substring(0, index);
852                 String JavaDoc className= arg.substring(index + 1);
853                 eclipseSpecifiedTypes.put(name, className);
854             }
855             arg = getArgument(commands, "-eclipseType"); //$NON-NLS-1$
856
}
857     }
858
859     /*
860      * Checks for unrecognized arguments on the command line.
861      * Since there is no syntactic way to distingush between
862      * ant -foo target1 target2
863      * ant -foo fooarg target
864      * we remove everything up to the last argument that
865      * begins with a '-'. In the latter case, above, that
866      * means that there will be an extra target, 'fooarg',
867      * left lying around.
868      */

869     private void processUnrecognizedCommands(List JavaDoc commands) {
870         int p = -1;
871
872         // find the last arg that begins with '-'
873
for (int i = commands.size() - 1; i >= 0; i--) {
874             if (((String JavaDoc) commands.get(0)).startsWith("-")) { //$NON-NLS-1$
875
p = i;
876                 break;
877             }
878         }
879         if (p < 0) { return; }
880
881         // remove everything preceding that last '-arg'
882
String JavaDoc s = ""; //$NON-NLS-1$
883
for (int i = 0; i <= p; i++) {
884             s += " " + ((String JavaDoc) commands.get(0)); //$NON-NLS-1$
885
commands.remove(0);
886         }
887         
888         // warn of ignored commands
889
String JavaDoc message = MessageFormat.format(RemoteAntMessages.getString("InternalAntRunner.Unknown_argument__{0}_2"), new Object JavaDoc[]{ s.substring(1) }); //$NON-NLS-1$
890
logMessage(currentProject, message, Project.MSG_WARN);
891     }
892     
893
894     /*
895      * Checks for targets specified at the command line.
896      */

897     private void processTargets(List JavaDoc commands) {
898         if (targets == null) {
899             targets = new Vector JavaDoc(commands.size());
900         }
901         for (Iterator JavaDoc iter = commands.iterator(); iter.hasNext();) {
902             targets.add(iter.next());
903         }
904     }
905
906     /*
907      * Creates the log file with the name specified by the user.
908      * If the fileName is not absolute, the file will be created in the
909      * working directory if specified or in the same directory as the location
910      * of the build file.
911      */

912     private void createLogFile(String JavaDoc fileName) throws FileNotFoundException JavaDoc, IOException JavaDoc {
913         File JavaDoc logFile = getFileRelativeToBaseDir(fileName);
914         
915         //this stream is closed in the finally block of run(list)
916
out = new PrintStream JavaDoc(new FileOutputStream JavaDoc(logFile));
917         err = out;
918         logMessage(getCurrentProject(), MessageFormat.format(RemoteAntMessages.getString("InternalAntRunner.Using_{0}_file_as_build_log._1"), new String JavaDoc[]{logFile.getCanonicalPath()}), Project.MSG_INFO); //$NON-NLS-1$
919
if (buildLogger != null) {
920             buildLogger.setErrorPrintStream(err);
921             buildLogger.setOutputPrintStream(out);
922         }
923     }
924
925     private File JavaDoc getFileRelativeToBaseDir(String JavaDoc fileName) {
926         File JavaDoc parentFile= null;
927         
928         String JavaDoc base= getCurrentProject().getUserProperty("basedir"); //$NON-NLS-1$
929
if (base != null) {
930             parentFile= new File JavaDoc(base);
931         } else {
932             //relative to the build file location
933
parentFile= new File JavaDoc(getBuildFileLocation()).getParentFile();
934         }
935         
936         //remain backwards compatible for older Ant usage
937
return FileUtils.newFileUtils().resolveFile(parentFile, fileName);
938     }
939
940     /*
941      * Processes cmd line properties and adds the user properties
942      * Any user properties that have been explicitly set are set as well.
943      * Ensures that -D properties take precedence.
944      */

945     private boolean processProperties(List JavaDoc commands) {
946         boolean exceptionToBeThrown= false;
947         //MULTIPLE property files are allowed
948
String JavaDoc arg= getArgument(commands, "-propertyfile"); //$NON-NLS-1$
949
while (arg != null) {
950             if (!isVersionCompatible("1.5")) { //$NON-NLS-1$
951
fEarlyErrorMessage= RemoteAntMessages.getString("InternalAntRunner.Specifying_property_files_is_a_Ant_1.5.*_feature._Please_update_your_Ant_classpath._6"); //$NON-NLS-1$
952
break;
953             }
954             if (arg.length() == 0) {
955                 fEarlyErrorMessage= RemoteAntMessages.getString("InternalAntRunner.You_must_specify_a_property_filename_when_using_the_-propertyfile_argument_3"); //$NON-NLS-1$
956
exceptionToBeThrown= true;
957                 break;
958             }
959             
960             propertyFiles.add(arg);
961             arg= getArgument(commands, "-propertyfile"); //$NON-NLS-1$
962
}
963         
964         if (propertyFiles != null && !propertyFiles.isEmpty()) {
965             loadPropertyFiles();
966         }
967         
968         if (commands != null) {
969             processMinusDProperties(commands);
970         }
971         return exceptionToBeThrown;
972     }
973
974     private void processMinusDProperties(List JavaDoc commands) {
975         String JavaDoc[] args = (String JavaDoc[]) commands.toArray(new String JavaDoc[commands.size()]);
976         for (int i = 0; i < args.length; i++) {
977             String JavaDoc arg = args[i];
978             if (arg.startsWith("-D")) { //$NON-NLS-1$
979
String JavaDoc name = arg.substring(2, arg.length());
980                 String JavaDoc value = null;
981                 int posEq = name.indexOf("="); //$NON-NLS-1$
982
if (posEq == 0) {
983                     value= name.substring(1);
984                     name= ""; //$NON-NLS-1$
985
} else if (posEq > 0 && posEq != name.length() - 1) {
986                     value = name.substring(posEq + 1).trim();
987                     name = name.substring(0, posEq);
988                 }
989                 
990                 if (value == null) {
991                     //the user has specified something like "-Debug"
992
continue;
993                 }
994                 if (userProperties == null) {
995                     userProperties= new HashMap JavaDoc();
996                 }
997                 userProperties.put(name, value);
998                 commands.remove(args[i]);
999             }
1000        }
1001    }
1002    
1003    private void setProperties(Project project) {
1004        setBuiltInProperties(project);
1005        if (userProperties != null) {
1006            for (Iterator JavaDoc iterator = userProperties.entrySet().iterator(); iterator.hasNext();) {
1007                Map.Entry JavaDoc entry = (Map.Entry JavaDoc) iterator.next();
1008                project.setUserProperty((String JavaDoc) entry.getKey(), (String JavaDoc) entry.getValue());
1009            }
1010        }
1011    }
1012
1013    private void setBuiltInProperties(Project project) {
1014        project.setUserProperty("ant.file", getBuildFileLocation()); //$NON-NLS-1$
1015
project.setUserProperty("ant.version", Main.getAntVersion()); //$NON-NLS-1$
1016
}
1017
1018    /*
1019     * Print the project description, if any
1020     */

1021    private void printHelp(Project project) {
1022        if (project.getDescription() != null) {
1023            logMessage(project, project.getDescription(), Project.MSG_INFO);
1024        }
1025        printTargets(project);
1026    }
1027
1028    /*
1029     * Logs a message with the client indicating the version of <b>Ant</b> that this class
1030     * fronts.
1031     */

1032    private void printVersion() {
1033        logMessage(getCurrentProject(), Main.getAntVersion(), Project.MSG_INFO);
1034    }
1035
1036    /*
1037     * Logs a message with the client outlining the usage of <b>Ant</b>.
1038     */

1039    private void printUsage() {
1040        String JavaDoc lSep = System.getProperty("line.separator"); //$NON-NLS-1$
1041
StringBuffer JavaDoc msg = new StringBuffer JavaDoc();
1042        msg.append("ant ["); //$NON-NLS-1$
1043
msg.append(RemoteAntMessages.getString("InternalAntRunner.options_13")); //$NON-NLS-1$
1044
msg.append("] ["); //$NON-NLS-1$
1045
msg.append(RemoteAntMessages.getString("InternalAntRunner.target_15")); //$NON-NLS-1$
1046
msg.append(" ["); //$NON-NLS-1$
1047
msg.append(RemoteAntMessages.getString("InternalAntRunner.target_15")); //$NON-NLS-1$
1048
msg.append("2 ["); //$NON-NLS-1$
1049
msg.append(RemoteAntMessages.getString("InternalAntRunner.target_15")); //$NON-NLS-1$
1050
msg.append("3] ...]]"); //$NON-NLS-1$
1051
msg.append(lSep);
1052        msg.append(RemoteAntMessages.getString("InternalAntRunner.Options___21")); //$NON-NLS-1$
1053
msg.append(lSep);
1054        msg.append("\t-help, -h\t\t\t\t"); //$NON-NLS-1$
1055
msg.append(RemoteAntMessages.getString("InternalAntRunner.print_this_message_23")); //$NON-NLS-1$
1056
msg.append(lSep);
1057        msg.append("\t-projecthelp, -p\t\t"); //$NON-NLS-1$
1058
msg.append(RemoteAntMessages.getString("InternalAntRunner.print_project_help_information_25")); //$NON-NLS-1$
1059
msg.append(lSep);
1060        msg.append("\t-version\t\t\t\t"); //$NON-NLS-1$
1061
msg.append(RemoteAntMessages.getString("InternalAntRunner.print_the_version_information_and_exit_27")); //$NON-NLS-1$
1062
msg.append(lSep);
1063        msg.append("\t-diagnostics\t\t\t"); //$NON-NLS-1$
1064
msg.append(RemoteAntMessages.getString("InternalAntRunner.12")); //$NON-NLS-1$
1065
msg.append(lSep);
1066        msg.append(RemoteAntMessages.getString("InternalAntRunner.13")); //$NON-NLS-1$
1067
msg.append(lSep);
1068        msg.append("\t-quiet, -q\t\t\t"); //$NON-NLS-1$
1069
msg.append(RemoteAntMessages.getString("InternalAntRunner.be_extra_quiet_29")); //$NON-NLS-1$
1070
msg.append(lSep);
1071        msg.append("\t-verbose, -v\t\t\t"); //$NON-NLS-1$
1072
msg.append(RemoteAntMessages.getString("InternalAntRunner.be_extra_verbose_31")); //$NON-NLS-1$
1073
msg.append(lSep);
1074        msg.append("\t-debug, -d\t\t\t"); //$NON-NLS-1$
1075
msg.append(RemoteAntMessages.getString("InternalAntRunner.print_debugging_information_33")); //$NON-NLS-1$
1076
msg.append(lSep);
1077        msg.append("\t-emacs, -e\t\t\t"); //$NON-NLS-1$
1078
msg.append(RemoteAntMessages.getString("InternalAntRunner.produce_logging_information_without_adornments_35")); //$NON-NLS-1$
1079
msg.append(lSep);
1080        msg.append("\t-logfile\t<file>\t\t"); //$NON-NLS-1$
1081
msg.append(RemoteAntMessages.getString("InternalAntRunner.use_given_file_for_log_37")); //$NON-NLS-1$
1082
msg.append(lSep);
1083        msg.append("\t\t-l\t<file>"); //$NON-NLS-1$
1084
msg.append(RemoteAntMessages.getString("InternalAntRunner.1")); //$NON-NLS-1$
1085
msg.append(lSep);
1086        msg.append("\t-logger <classname>\t\t"); //$NON-NLS-1$
1087
msg.append(RemoteAntMessages.getString("InternalAntRunner.the_class_which_is_to_perform_logging_39")); //$NON-NLS-1$
1088
msg.append(lSep);
1089        msg.append("\t-listener <classname>\t"); //$NON-NLS-1$
1090
msg.append(RemoteAntMessages.getString("InternalAntRunner.add_an_instance_of_class_as_a_project_listener_41")); //$NON-NLS-1$
1091
msg.append(lSep);
1092        msg.append("\t-noinput\t"); //$NON-NLS-1$
1093
msg.append(RemoteAntMessages.getString("InternalAntRunner.158")); //$NON-NLS-1$
1094
msg.append(lSep);
1095        msg.append("\t-buildfile\t<file>\t"); //$NON-NLS-1$
1096
msg.append(RemoteAntMessages.getString("InternalAntRunner.use_given_buildfile_43")); //$NON-NLS-1$
1097
msg.append(lSep);
1098        msg.append("\t\t-file\t<file>"); //$NON-NLS-1$
1099
msg.append(RemoteAntMessages.getString("InternalAntRunner.1")); //$NON-NLS-1$
1100
msg.append(lSep);
1101        msg.append("\t\t-f\t\t<file>"); //$NON-NLS-1$
1102
msg.append(RemoteAntMessages.getString("InternalAntRunner.1")); //$NON-NLS-1$
1103
msg.append(lSep);
1104        msg.append("\t-D<property>=<value>\t"); //$NON-NLS-1$
1105
msg.append(RemoteAntMessages.getString("InternalAntRunner.use_value_for_given_property_45")); //$NON-NLS-1$
1106
msg.append(lSep);
1107        msg.append("\t-keep-going, -k"); //$NON-NLS-1$
1108
msg.append(RemoteAntMessages.getString("InternalAntRunner.159")); //$NON-NLS-1$
1109
msg.append(lSep);
1110        msg.append(RemoteAntMessages.getString("InternalAntRunner.160")); //$NON-NLS-1$
1111
msg.append(lSep);
1112        msg.append("\t-propertyfile <name>\t"); //$NON-NLS-1$
1113
msg.append(RemoteAntMessages.getString("InternalAntRunner.19")); //$NON-NLS-1$
1114
msg.append(lSep);
1115        msg.append(RemoteAntMessages.getString("InternalAntRunner.20")); //$NON-NLS-1$
1116
msg.append(lSep);
1117        msg.append("\t-inputhandler <class>\t"); //$NON-NLS-1$
1118
msg.append(RemoteAntMessages.getString("InternalAntRunner.22")); //$NON-NLS-1$
1119
msg.append(lSep);
1120
1121        logMessage(getCurrentProject(), msg.toString(), Project.MSG_INFO);
1122    }
1123
1124    /*
1125     * From a command line list, return the argument for the given parameter.
1126     * The parameter and its argument are removed from the list.
1127     *
1128     * @return <code>null</code> if the parameter is not found
1129     * or an empty String if no arguments are found
1130     */

1131    private String JavaDoc getArgument(List JavaDoc commands, String JavaDoc param) {
1132        if (commands == null) {
1133            return null;
1134        }
1135        int index = commands.indexOf(param);
1136        if (index == -1) {
1137            return null;
1138        }
1139        commands.remove(index);
1140        if (index == commands.size()) {// if this is the last command
1141
return ""; //$NON-NLS-1$
1142
}
1143        
1144        String JavaDoc command = (String JavaDoc) commands.get(index);
1145        if (command.startsWith("-")) { //new parameter //$NON-NLS-1$
1146
return ""; //$NON-NLS-1$
1147
}
1148        
1149        commands.remove(index);
1150        return command;
1151    }
1152
1153    /*
1154     * Helper method to ensure an array is converted into an ArrayList.
1155     */

1156    private static ArrayList JavaDoc getArrayList(String JavaDoc[] args) {
1157        if (args == null) {
1158            return null;
1159        }
1160        // We could be using Arrays.asList() here, but it does not specify
1161
// what kind of list it will return. We need a list that
1162
// implements the method List.remove(Object) and ArrayList does.
1163
ArrayList JavaDoc result = new ArrayList JavaDoc(args.length);
1164        for (int i = 0; i < args.length; i++) {
1165            result.add(args[i]);
1166        }
1167        return result;
1168    }
1169
1170    private Project getCurrentProject() {
1171        return currentProject;
1172    }
1173
1174    private void setCurrentProject(Project currentProject) {
1175        this.currentProject = currentProject;
1176    }
1177    
1178    /**
1179     * Load all properties from the files
1180     * specified by -propertyfile.
1181     */

1182    private void loadPropertyFiles() {
1183        Iterator JavaDoc itr= propertyFiles.iterator();
1184        while (itr.hasNext()) {
1185            String JavaDoc filename= (String JavaDoc) itr.next();
1186            File JavaDoc file= getFileRelativeToBaseDir(filename);
1187            Properties JavaDoc props = new Properties JavaDoc();
1188            FileInputStream JavaDoc fis = null;
1189            try {
1190                fis = new FileInputStream JavaDoc(file);
1191                props.load(fis);
1192            } catch (IOException JavaDoc e) {
1193                fEarlyErrorMessage= MessageFormat.format(RemoteAntMessages.getString("InternalAntRunner.Could_not_load_property_file_{0}__{1}_4"), new String JavaDoc[]{filename, e.getMessage()}); //$NON-NLS-1$
1194
} finally {
1195                if (fis != null) {
1196                    try {
1197                        fis.close();
1198                    } catch (IOException JavaDoc e){
1199                    }
1200                }
1201            }
1202
1203            if (userProperties == null) {
1204                userProperties= new HashMap JavaDoc();
1205            }
1206            Enumeration JavaDoc propertyNames = props.propertyNames();
1207            while (propertyNames.hasMoreElements()) {
1208                String JavaDoc name = (String JavaDoc) propertyNames.nextElement();
1209                //most specific to global
1210
//do not overwrite specific with a global property
1211
if (userProperties.get(name) == null) {
1212                    userProperties.put(name, props.getProperty(name));
1213                }
1214            }
1215        }
1216    }
1217    
1218    /*
1219     * Creates the InputHandler and adds it to the project.
1220     *
1221     * @exception BuildException if a specified InputHandler
1222     * implementation could not be loaded.
1223     */

1224    private void addInputHandler(Project project) {
1225        if (!isVersionCompatible("1.5")) { //$NON-NLS-1$
1226
return;
1227        }
1228        InputHandlerSetter setter= new InputHandlerSetter();
1229        setter.setInputHandler(project, inputHandlerClassname);
1230    }
1231}
Popular Tags