KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > ant > internal > core > ant > InternalAntRunner


1 /*******************************************************************************
2  * Copyright (c) 2000, 2007 IBM Corporation and others.
3  * Portions Copyright 2000-2007 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  * Blake Meike (blakem@world.std.com)- patch for bug 31691 and bug 34488
12  *******************************************************************************/

13
14 package org.eclipse.ant.internal.core.ant;
15  
16 import java.io.File 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.net.URL JavaDoc;
23 import java.text.MessageFormat JavaDoc; // don't use ICU in ant builder
24
import java.util.ArrayList JavaDoc;
25 import java.util.Arrays JavaDoc;
26 import java.util.Enumeration JavaDoc;
27 import java.util.HashMap JavaDoc;
28 import java.util.Iterator JavaDoc;
29 import java.util.List JavaDoc;
30 import java.util.Map JavaDoc;
31 import java.util.Properties JavaDoc;
32 import java.util.Vector JavaDoc;
33
34 import org.apache.tools.ant.AntTypeDefinition;
35 import org.apache.tools.ant.BuildEvent;
36 import org.apache.tools.ant.BuildException;
37 import org.apache.tools.ant.BuildListener;
38 import org.apache.tools.ant.BuildLogger;
39 import org.apache.tools.ant.ComponentHelper;
40 import org.apache.tools.ant.DefaultLogger;
41 import org.apache.tools.ant.DemuxOutputStream;
42 import org.apache.tools.ant.Diagnostics;
43 import org.apache.tools.ant.Main;
44 import org.apache.tools.ant.Project;
45 import org.apache.tools.ant.ProjectHelper;
46 import org.apache.tools.ant.Target;
47 import org.apache.tools.ant.Task;
48 import org.apache.tools.ant.TaskAdapter;
49 import org.apache.tools.ant.XmlLogger;
50 import org.eclipse.ant.core.AntCorePlugin;
51 import org.eclipse.ant.core.AntCorePreferences;
52 import org.eclipse.ant.core.AntSecurityException;
53 import org.eclipse.ant.core.Property;
54 import org.eclipse.ant.core.Type;
55 import org.eclipse.ant.internal.core.AbstractEclipseBuildLogger;
56 import org.eclipse.ant.internal.core.AntCoreUtil;
57 import org.eclipse.ant.internal.core.AntSecurityManager;
58 import org.eclipse.core.runtime.CoreException;
59 import org.eclipse.core.runtime.FileLocator;
60 import org.eclipse.core.runtime.IPath;
61 import org.eclipse.core.runtime.IProgressMonitor;
62 import org.eclipse.core.runtime.IStatus;
63 import org.eclipse.core.runtime.OperationCanceledException;
64 import org.eclipse.core.runtime.Path;
65 import org.eclipse.core.runtime.Status;
66 import org.eclipse.core.variables.VariablesPlugin;
67 import org.osgi.framework.Bundle;
68
69 /**
70  * Eclipse application entry point into Ant. Derived from the original Ant Main class
71  * to ensure that the functionality is equivalent when running in the platform.
72  */

73 public class InternalAntRunner {
74
75     private IProgressMonitor monitor;
76
77     private List JavaDoc buildListeners;
78
79     private String JavaDoc buildFileLocation;
80
81     /**
82      * Targets we want to run.
83      */

84     private Vector JavaDoc targets;
85
86     private Map JavaDoc userProperties;
87     private boolean noExplicitUserProperties= true;
88     
89     private Project currentProject;
90     
91     private String JavaDoc defaultTarget;
92     
93     private BuildLogger buildLogger= null;
94     
95     /**
96      * Cache of the Ant version number when it has been loaded
97      */

98     private String JavaDoc antVersionNumber= null;
99
100     /** Current message output status. Follows Project.MSG_XXX */
101     private int messageOutputLevel = Project.MSG_INFO;
102
103     /** Indicates whether output to the log is to be unadorned. */
104     private boolean emacsMode = false;
105
106     /** Indicates we should only parse and display the project help information */
107     private boolean projectHelp = false;
108
109     /** Stream that we are using for logging */
110     private PrintStream JavaDoc out = System.out;
111
112     /** Stream that we are using for logging error messages */
113     private PrintStream JavaDoc err = System.err;
114
115     /**
116      * The Ant logger class. There may be only one logger. It will have the
117      * right to use the 'out' PrintStream. The class must implement the BuildLogger
118      * interface. An empty String indicates that no logger is to be used. A <code>null</code>
119      * name indicates that the <code>org.apache.tools.ant.DefaultLogger</code> will be used.
120      */

121     private String JavaDoc loggerClassname = null;
122
123     /** Extra arguments to be parsed as command line arguments. */
124     private String JavaDoc[] extraArguments = null;
125     
126     private boolean executed = false;
127     
128     private List JavaDoc propertyFiles= new ArrayList JavaDoc();
129     
130     private URL JavaDoc[] customClasspath= null;
131     
132     /**
133      * The Ant InputHandler class. There may be only one input handler.
134      */

135     private String JavaDoc inputHandlerClassname = null;
136     
137     private String JavaDoc buildAntHome= null;
138     
139     /**
140      * Indicates whether to execute all targets that
141      * do not depend on failed targets
142      * @since Ant 1.6.0
143      */

144     private boolean keepGoing= false;
145
146     /**
147      * Indicates whether this build is to support interactive input
148      * @since Ant 1.6.0
149      */

150     private boolean allowInput = true;
151     
152     private String JavaDoc fEarlyErrorMessage= null;
153     
154     /**
155      * Adds a build listener.
156      *
157      * @param classNames the fully qualified names of the build listeners to be added
158      */

159     public void addBuildListeners(List JavaDoc classNames) {
160         if (buildListeners == null) {
161             buildListeners = new ArrayList JavaDoc(classNames.size());
162         }
163         buildListeners.addAll(classNames);
164     }
165
166     /**
167      * Adds a build logger. There can be only one build logger.
168      * @param className The fully qualified name of the build logger to add
169      */

170     public void addBuildLogger(String JavaDoc className) {
171         loggerClassname = className;
172     }
173
174     /**
175      * Adds user properties to the current collection of user properties.
176      * @param properties The user properties to be added
177      */

178     public void addUserProperties(Map JavaDoc properties) {
179         if (userProperties == null) {
180             userProperties= new HashMap JavaDoc(properties);
181         } else {
182             userProperties.putAll(properties);
183         }
184         noExplicitUserProperties= false;
185     }
186     
187     /**
188      * Adds user property files.
189      * @param additionalPropertyFiles The property files to add
190      * @since 2.1
191      */

192     public void addPropertyFiles(String JavaDoc[] additionalPropertyFiles) {
193         propertyFiles.addAll(Arrays.asList(additionalPropertyFiles));
194     }
195
196     private void addBuildListeners(Project project) {
197         String JavaDoc className= null;
198         try {
199             BuildLogger logger= createLogger();
200             if (logger != null) {
201                 project.addBuildListener(logger);
202             }
203             if (buildListeners != null) {
204                 for (Iterator JavaDoc iterator = buildListeners.iterator(); iterator.hasNext();) {
205                     className = (String JavaDoc) iterator.next();
206                     Class JavaDoc listener = Class.forName(className);
207                     project.addBuildListener((BuildListener) listener.newInstance());
208                 }
209             }
210         } catch (ClassCastException JavaDoc e) {
211             String JavaDoc message = MessageFormat.format(InternalAntMessages.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});
212             logMessage(null, message, Project.MSG_ERR);
213             throw new BuildException(message, e);
214         } catch (BuildException e) {
215             throw e;
216         } catch (Exception JavaDoc e) {
217             throw new BuildException(e);
218         }
219     }
220
221     private void setProperties(Project project, boolean substituteVariables) {
222         setBuiltInProperties(project);
223         if (userProperties != null) {
224             for (Iterator JavaDoc iterator = userProperties.entrySet().iterator(); iterator.hasNext();) {
225                 Map.Entry JavaDoc entry = (Map.Entry JavaDoc) iterator.next();
226                 String JavaDoc value= (String JavaDoc) entry.getValue();
227                 if (substituteVariables) {
228                     try {
229                         value= VariablesPlugin.getDefault().getStringVariableManager().performStringSubstitution((String JavaDoc) entry.getValue());
230                     } catch (CoreException e) {
231                     }
232                 }
233                 project.setUserProperty((String JavaDoc) entry.getKey(), value);
234                 
235             }
236             //may have properties set (always have the Ant process ID)
237
//using the Arguments and not the Properties page
238
//if set using the arguments, still include the global properties
239
if (noExplicitUserProperties) {
240                 setGlobalProperties(project, substituteVariables);
241             }
242         } else {
243             setGlobalProperties(project, substituteVariables);
244         }
245     }
246
247     private void setBuiltInProperties(Project project) {
248         //note also see processAntHome for system properties that are set
249
project.setUserProperty("ant.file", getBuildFileLocation()); //$NON-NLS-1$
250
project.setUserProperty("ant.version", Main.getAntVersion()); //$NON-NLS-1$
251
}
252     
253     private void setGlobalProperties(Project project, boolean substituteVariables) {
254         AntCorePreferences prefs= AntCorePlugin.getPlugin().getPreferences();
255         List JavaDoc properties= prefs.getProperties();
256         if (properties != null) {
257             for (Iterator JavaDoc iter = properties.iterator(); iter.hasNext();) {
258                 Property property = (Property) iter.next();
259                 String JavaDoc value= property.getValue(substituteVariables);
260                 if (value != null) {
261                     project.setUserProperty(property.getName(), value);
262                 }
263             }
264         }
265     }
266
267     private void setTasks(Project project) {
268         List JavaDoc tasks = AntCorePlugin.getPlugin().getPreferences().getTasks();
269         
270         for (Iterator JavaDoc iterator = tasks.iterator(); iterator.hasNext();) {
271             org.eclipse.ant.core.Task task = (org.eclipse.ant.core.Task) iterator.next();
272             
273             if (isVersionCompatible("1.6")) { //$NON-NLS-1$
274
AntTypeDefinition def= new AntTypeDefinition();
275                 String JavaDoc name = ProjectHelper.genComponentName(task.getURI(),task.getTaskName());
276                 def.setName(name);
277                 def.setClassName(task.getClassName());
278                 def.setClassLoader(this.getClass().getClassLoader());
279                 def.setAdaptToClass(Task.class);
280                 def.setAdapterClass(TaskAdapter.class);
281                 ComponentHelper.getComponentHelper(project).addDataTypeDefinition(def);
282             } else {
283                 try {
284                     Class JavaDoc taskClass = Class.forName(task.getClassName());
285                     if (isVersionCompatible("1.5")) { //$NON-NLS-1$
286
try {
287                             project.checkTaskClass(taskClass);
288                         } catch (BuildException e) {
289                             IStatus status = new Status(IStatus.ERROR, AntCorePlugin.PI_ANTCORE, AntCorePlugin.ERROR_RUNNING_BUILD, MessageFormat.format(InternalAntMessages.InternalAntRunner_Error_setting_Ant_task, new String JavaDoc[]{task.getTaskName()}), e);
290                             AntCorePlugin.getPlugin().getLog().log(status);
291                             continue;
292                         }
293                         }
294                     project.addTaskDefinition(task.getTaskName(), taskClass);
295                 } catch (ClassNotFoundException JavaDoc e) {
296                     IStatus status = new Status(IStatus.ERROR, AntCorePlugin.PI_ANTCORE, AntCorePlugin.ERROR_RUNNING_BUILD, MessageFormat.format(InternalAntMessages.InternalAntRunner_Class__0__not_found_for_task__1__1, new String JavaDoc[]{task.getClassName(), task.getTaskName()}), e);
297                     AntCorePlugin.getPlugin().getLog().log(status);
298                     }
299                 }
300         }
301     }
302
303     private void setTypes(Project project) {
304         List JavaDoc types = AntCorePlugin.getPlugin().getPreferences().getTypes();
305         for (Iterator JavaDoc iterator = types.iterator(); iterator.hasNext();) {
306             Type type = (Type) iterator.next();
307             if (isVersionCompatible("1.6")) { //$NON-NLS-1$
308
AntTypeDefinition def = new AntTypeDefinition();
309                 String JavaDoc name= ProjectHelper.genComponentName(type.getURI(), type.getTypeName());
310                 def.setName(name);
311                 def.setClassName(type.getClassName());
312                 def.setClassLoader(this.getClass().getClassLoader());
313                 ComponentHelper.getComponentHelper(project).addDataTypeDefinition(def);
314             } else {
315                 try {
316                     Class JavaDoc typeClass = Class.forName(type.getClassName());
317                     project.addDataTypeDefinition(type.getTypeName(), typeClass);
318                 } catch (ClassNotFoundException JavaDoc e) {
319                     IStatus status = new Status(IStatus.ERROR, AntCorePlugin.PI_ANTCORE, AntCorePlugin.ERROR_RUNNING_BUILD, MessageFormat.format(InternalAntMessages.InternalAntRunner_Class__0__not_found_for_type__1__2, new String JavaDoc[]{type.getClassName(), type.getTypeName()}), e);
320                     AntCorePlugin.getPlugin().getLog().log(status);
321                 }
322             }
323         }
324     }
325
326     /**
327      * Parses the build file and adds necessary information into
328      * the given project.
329      * @param project The project to configure
330      */

331     private void parseBuildFile(Project project) {
332         File JavaDoc buildFile = new File JavaDoc(getBuildFileLocation());
333         if (!buildFile.exists()) {
334             throw new BuildException(MessageFormat.format(InternalAntMessages.InternalAntRunner_Buildfile___0__does_not_exist___1,
335                          new String JavaDoc[]{buildFile.getAbsolutePath()}));
336         }
337         if (!buildFile.isFile()) {
338             throw new BuildException(MessageFormat.format(InternalAntMessages.InternalAntRunner_Buildfile___0__is_not_a_file_1,
339                             new String JavaDoc[]{buildFile.getAbsolutePath()}));
340         }
341         
342         if (!isVersionCompatible("1.5")) { //$NON-NLS-1$
343
parseBuildFile(project, buildFile);
344         } else {
345             ProjectHelper helper = ProjectHelper.getProjectHelper();
346             project.addReference("ant.projectHelper", helper); //$NON-NLS-1$
347
helper.parse(project, buildFile);
348         }
349     }
350     
351     /**
352      * @deprecated support for Ant older than 1.5
353      */

354     private void parseBuildFile(Project project, File JavaDoc buildFile) {
355         ProjectHelper.configureProject(project, buildFile);
356     }
357
358     /**
359      * Gets all the target information from the build script.
360      * Returns a list of lists. Each item in the enclosing list represents a
361      * target, where the first element is the name, the
362      * second element is the description, the third element is the
363      * project name, and the last elements is an array of dependencies.
364      * @return a list of lists representing the targets
365      */

366     public List JavaDoc getTargets() {
367         try {
368             setJavaClassPath();
369             Project antProject;
370         
371             antProject = getProject();
372             processAntHome(false);
373             antProject.init();
374             setTypes(antProject);
375             boolean exceptionState= processProperties(AntCoreUtil.getArrayList(extraArguments));
376             if (fEarlyErrorMessage != null) {
377                 if (exceptionState) {
378                     throw new BuildException(fEarlyErrorMessage);
379                 }
380             }
381             
382             setProperties(antProject, false);
383             if (isVersionCompatible("1.5")) { //$NON-NLS-1$
384
new InputHandlerSetter().setInputHandler(antProject, "org.eclipse.ant.internal.core.ant.NullInputHandler"); //$NON-NLS-1$
385
}
386             parseBuildFile(antProject);
387             defaultTarget = antProject.getDefaultTarget();
388             Enumeration JavaDoc projectTargets = antProject.getTargets().elements();
389             List JavaDoc infos= new ArrayList JavaDoc();
390             infos.add(antProject.getName());
391             infos.add(antProject.getDescription());
392             List JavaDoc info;
393             Target target;
394             boolean defaultFound= false;
395             while (projectTargets.hasMoreElements()) {
396                 target = (Target) projectTargets.nextElement();
397                 String JavaDoc name= target.getName();
398                 if (name.length() == 0) {
399                     //"no name" implicit target of Ant 1.6
400
continue;
401                 }
402                 info= new ArrayList JavaDoc(4);
403                 info.add(name);
404                 if (target.getName().equals(defaultTarget)) {
405                     defaultFound= true;
406                 }
407                 info.add(target.getDescription());
408                 List JavaDoc dependencies= new ArrayList JavaDoc();
409                 Enumeration JavaDoc enumeration= target.getDependencies();
410                 while (enumeration.hasMoreElements()) {
411                     dependencies.add(enumeration.nextElement());
412                 }
413                 String JavaDoc[] dependencyArray= new String JavaDoc[dependencies.size()];
414                 dependencies.toArray(dependencyArray);
415                 info.add(dependencyArray);
416                 infos.add(info);
417             }
418             if (!defaultFound) {
419                 //default target must exist
420
throw new BuildException(MessageFormat.format(InternalAntMessages.InternalAntRunner_Default_target__0__1__2__does_not_exist_in_this_project_1, new String JavaDoc[]{"'", defaultTarget, "'"})); //$NON-NLS-1$ //$NON-NLS-2$
421
}
422             return infos;
423         } finally {
424             processAntHome(true);
425         }
426     }
427
428     private Project getProject() {
429         Project antProject;
430         if (isVersionCompatible("1.6")) { //$NON-NLS-1$
431
//in Ant version 1.6 or greater all tasks can exist outside the scope of a target
432
if (isVersionCompatible("1.6.3")) { //$NON-NLS-1$
433
antProject= new InternalProject2();
434             } else {
435                 antProject= new Project();
436             }
437         } else {
438             antProject= new InternalProject();
439         }
440         return antProject;
441     }
442     
443     /**
444      * Returns the default target name that was last computed or <code>null</code>
445      * if no default target has been computed.
446      * @return the default target name
447      */

448     public String JavaDoc getDefaultTarget() {
449         return defaultTarget;
450     }
451
452     /**
453      * Runs the build script.
454      */

455     public void run() {
456         run(AntCoreUtil.getArrayList(extraArguments));
457     }
458
459     private void printArguments(Project project) {
460         if ((messageOutputLevel != Project.MSG_DEBUG) && (messageOutputLevel != Project.MSG_VERBOSE)) {
461             return;
462         }
463         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
464         for (int i = 0; i < extraArguments.length; i++) {
465             sb.append(extraArguments[i]);
466             sb.append(' ');
467         }
468         project.log(MessageFormat.format(InternalAntMessages.InternalAntRunner_Arguments___0__2, new String JavaDoc[]{sb.toString().trim()}));
469     }
470
471     private void createMonitorBuildListener(Project project) {
472         if (monitor == null) {
473             return;
474         }
475         List JavaDoc chosenTargets = targets;
476         if (chosenTargets == null || chosenTargets.isEmpty()) {
477             chosenTargets = new ArrayList JavaDoc(1);
478             String JavaDoc defltTarget= project.getDefaultTarget();
479             if (defltTarget != null) {
480                 chosenTargets.add(defltTarget);
481             }
482         }
483         project.addBuildListener(new ProgressBuildListener(project, chosenTargets, monitor));
484     }
485
486     /**
487      * Invokes the building of a project object and executes a build using either a given
488      * target or the default target. This method is called if running in
489      * headless mode.
490      * @see org.eclipse.ant.core.AntRunner#run(Object)
491      * @param argArray the command line arguments
492      * @exception Exception execution exceptions
493      */

494     public void run(Object JavaDoc argArray) throws Exception JavaDoc {
495         run(AntCoreUtil.getArrayList((String JavaDoc[]) argArray));
496     }
497
498     /*
499      * Note that the list passed to this method must support
500      * List#remove(Object)
501      */

502     private void run(List JavaDoc argList) {
503         setCurrentProject(new Project());
504         if (isVersionCompatible("1.6.3")) { //$NON-NLS-1$
505
new ExecutorSetter().setExecutor(getCurrentProject());
506         }
507         Throwable JavaDoc error = null;
508         PrintStream JavaDoc originalErr = System.err;
509         PrintStream JavaDoc originalOut = System.out;
510         InputStream JavaDoc originalIn= System.in;
511         
512         SecurityManager JavaDoc originalSM= System.getSecurityManager();
513         setJavaClassPath();
514         executed = true;
515         processAntHome(false);
516         try {
517             if (argList != null && (argList.remove("-projecthelp") || argList.remove("-p"))) { //$NON-NLS-1$ //$NON-NLS-2$
518
projectHelp = true;
519             }
520             getCurrentProject().init();
521             if (argList != null) {
522                 executed = preprocessCommandLine(argList);
523                 if (!executed) {
524                     return;
525                 }
526             }
527             
528             boolean exceptionState= processProperties(argList);
529             
530             addBuildListeners(getCurrentProject());
531             
532             addInputHandler(getCurrentProject());
533             
534             remapSystemIn();
535             System.setOut(new PrintStream JavaDoc(new DemuxOutputStream(getCurrentProject(), false)));
536             System.setErr(new PrintStream JavaDoc(new DemuxOutputStream(getCurrentProject(), true)));
537             
538             if (!projectHelp) {
539                 fireBuildStarted(getCurrentProject());
540             }
541             
542             if (fEarlyErrorMessage != null) {
543                 //an error occurred processing the properties
544
//build started has fired and we have
545
//listeners/loggers to report the error
546
logMessage(getCurrentProject(), fEarlyErrorMessage, Project.MSG_ERR);
547                 if (exceptionState) {
548                     throw new BuildException(fEarlyErrorMessage);
549                 }
550             }
551             
552             //properties can only be set after buildStarted as some listeners/loggers
553
//depend on this (e.g. XMLLogger)
554
setProperties(getCurrentProject(), true);
555             
556             if (argList != null && !argList.isEmpty()) {
557                 try {
558                     executed = processCommandLine(argList);
559                 } catch (BuildException e) {
560                     executed = false;
561                     throw e;
562                 }
563             }
564             if (!executed) {
565                 return;
566             }
567             
568             //needs to occur after processCommandLine(List)
569
if (allowInput && (inputHandlerClassname != null && inputHandlerClassname.length() > 0)) {
570                 if (isVersionCompatible("1.6")) { //$NON-NLS-1$
571
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=182577
572
//getCurrentProject().setDefaultInputStream(originalIn);
573
System.getProperties().remove("eclipse.ant.noInput"); //$NON-NLS-1$
574
}
575             } else {
576                 //set the system property that any input handler
577
//can check to see if handling input is allowed
578
System.setProperty("eclipse.ant.noInput", "true"); //$NON-NLS-1$//$NON-NLS-2$
579
if (isVersionCompatible("1.5") && (inputHandlerClassname == null || inputHandlerClassname.length() == 0)) { //$NON-NLS-1$
580
InputHandlerSetter setter= new InputHandlerSetter();
581                     setter.setInputHandler(getCurrentProject(), "org.eclipse.ant.internal.core.ant.FailInputHandler"); //$NON-NLS-1$
582
}
583             }
584
585             if(!projectHelp) {
586                 getCurrentProject().log(MessageFormat.format(InternalAntMessages.InternalAntRunner_Build_file___0__1, new String JavaDoc[]{getBuildFileLocation()}));
587
588                 setTasks(getCurrentProject());
589                 setTypes(getCurrentProject());
590
591                 if (isVersionCompatible("1.6")) { //$NON-NLS-1$
592
getCurrentProject().setKeepGoingMode(keepGoing);
593                 }
594                 parseBuildFile(getCurrentProject());
595             }
596             
597             createMonitorBuildListener(getCurrentProject());
598             
599             if (projectHelp) {
600                 if (isVersionCompatible("1.7")) { //$NON-NLS-1$
601
new EclipseMainHelper().runProjectHelp(getBuildFileLocation(), getCurrentProject());
602                     return;
603                 }
604                 getCurrentProject().log(InternalAntMessages.InternalAntRunner_3);
605                 executed = false;
606                 return;
607             }
608             
609             if (extraArguments != null) {
610                 printArguments(getCurrentProject());
611             }
612             System.setSecurityManager(new AntSecurityManager(originalSM, Thread.currentThread()));
613             
614             if (targets == null) {
615                 targets= new Vector JavaDoc(1);
616             }
617             if (targets.isEmpty() && getCurrentProject().getDefaultTarget() != null) {
618                 targets.add(getCurrentProject().getDefaultTarget());
619             }
620             if (!isVersionCompatible("1.6.3")) { //$NON-NLS-1$
621
getCurrentProject().addReference("eclipse.ant.targetVector", targets); //$NON-NLS-1$
622
}
623             getCurrentProject().executeTargets(targets);
624         } catch (OperationCanceledException e) {
625             executed = false;
626             logMessage(getCurrentProject(), e.getMessage(), Project.MSG_INFO);
627             throw e;
628         } catch (AntSecurityException e) {
629             //expected
630
} catch (RuntimeException JavaDoc e) {
631             error = e;
632             throw e;
633         } catch (Error JavaDoc e) {
634             error = e;
635             throw e;
636         } finally {
637             System.setErr(originalErr);
638             System.setOut(originalOut);
639             System.setIn(originalIn);
640             if (System.getSecurityManager() instanceof AntSecurityManager) {
641                 System.setSecurityManager(originalSM);
642             }
643             
644             if (!projectHelp) {
645                 if (AntCorePlugin.getPlugin().getBundle().getState() != Bundle.ACTIVE) {
646                     return;
647                 }
648                 fireBuildFinished(getCurrentProject(), error);
649             }
650                         
651             //close any user specified build log
652
if (err != originalErr) {
653                 err.close();
654             }
655             if (out != originalOut) {
656                 out.close();
657             }
658             
659             processAntHome(true);
660             if (!allowInput) {
661                 System.getProperties().remove("eclipse.ant.noInput"); //$NON-NLS-1$
662
}
663         }
664     }
665     
666     private void remapSystemIn() {
667         if (!isVersionCompatible("1.6")) { //$NON-NLS-1$
668
return;
669         }
670         DemuxInputStreamSetter setter= new DemuxInputStreamSetter();
671         setter.remapSystemIn(getCurrentProject());
672     }
673
674     private void processAntHome(boolean finished) {
675         AntCorePreferences prefs= AntCorePlugin.getPlugin().getPreferences();
676         String JavaDoc antHome= prefs.getAntHome();
677         if (buildAntHome != null && !finished) {
678             antHome= buildAntHome;
679         }
680         if (antHome == null || antHome.length() == 0) {
681             System.getProperties().remove("ant.home"); //$NON-NLS-1$
682
System.getProperties().remove("ant.library.dir"); //$NON-NLS-1$
683
} else {
684             System.setProperty("ant.home", antHome); //$NON-NLS-1$
685
File JavaDoc antLibDir= new File JavaDoc(antHome, "lib"); //$NON-NLS-1$
686
System.setProperty("ant.library.dir", antLibDir.getAbsolutePath()); //$NON-NLS-1$
687
}
688     }
689     
690     public void setAntHome(String JavaDoc antHome) {
691         this.buildAntHome= antHome;
692     }
693
694     /**
695      * Creates and returns the default build logger for logging build events to the ant log.
696      *
697      * @return the default build logger for logging build events to the ant log
698      * can return <code>null</code> if no logging is to occur
699      */

700     private BuildLogger createLogger() {
701         if (loggerClassname == null) {
702             buildLogger= new DefaultLogger();
703         } else if (!"".equals(loggerClassname)) { //$NON-NLS-1$
704
try {
705                 buildLogger = (BuildLogger) (Class.forName(loggerClassname).newInstance());
706             } catch (ClassCastException JavaDoc e) {
707                 String JavaDoc message = MessageFormat.format(InternalAntMessages.InternalAntRunner__0__which_was_specified_to_perform_logging_is_not_an_instance_of_org_apache_tools_ant_BuildLogger__2, new String JavaDoc[]{loggerClassname});
708                 logMessage(null, message, Project.MSG_ERR);
709                 throw new BuildException(message, e);
710             } catch (Exception JavaDoc e) {
711                 String JavaDoc message = MessageFormat.format(InternalAntMessages.InternalAntRunner_Unable_to_instantiate_logger___0__6, new String JavaDoc[]{loggerClassname});
712                 logMessage(null, message, Project.MSG_ERR);
713                 throw new BuildException(message, e);
714             }
715         }
716         
717         if (buildLogger != null) {
718             buildLogger.setMessageOutputLevel(messageOutputLevel);
719             buildLogger.setOutputPrintStream(out);
720             buildLogger.setErrorPrintStream(err);
721             buildLogger.setEmacsMode(emacsMode);
722             if (buildLogger instanceof AbstractEclipseBuildLogger) {
723                 ((AbstractEclipseBuildLogger) buildLogger).configure(userProperties);
724             }
725         }
726
727         return buildLogger;
728     }
729
730     /**
731      * Project.fireBuildStarted is protected in Ant earlier than 1.5.*.
732      * Provides backwards compatibility with old Ant installs.
733      */

734     private void fireBuildStarted(Project project) {
735         if (!isVersionCompatible("1.5")) { //$NON-NLS-1$
736
BuildEvent event = new BuildEvent(project);
737             Vector JavaDoc listeners= (Vector JavaDoc) project.getBuildListeners().clone();
738             for (Iterator JavaDoc iterator = listeners.iterator(); iterator.hasNext();) {
739                 BuildListener listener = (BuildListener) iterator.next();
740                 listener.buildStarted(event);
741             }
742         } else {
743             project.fireBuildStarted();
744         }
745     }
746
747     private void fireBuildFinished(Project project, Throwable JavaDoc error) {
748         if(usingXmlLogger()) {
749             //generate the log file in the correct location
750
String JavaDoc fileName= project.getProperty("XmlLogger.file"); //$NON-NLS-1$
751
if (fileName == null) {
752                 fileName= "log.xml"; //$NON-NLS-1$
753
}
754             String JavaDoc realPath= new Path(getBuildFileLocation()).toFile().getAbsolutePath();
755             IPath path= new Path(realPath);
756             path= path.removeLastSegments(1);
757             path= path.addTrailingSeparator();
758             path= path.append(fileName);
759         
760             project.setProperty("XmlLogger.file", path.toOSString()); //$NON-NLS-1$
761
}
762         if (error == null && executed) {
763             logMessage(project, InternalAntMessages.InternalAntRunner_BUILD_SUCCESSFUL_1, messageOutputLevel);
764         }
765         if (!isVersionCompatible("1.5")) { //$NON-NLS-1$
766
BuildEvent event = new BuildEvent(project);
767             event.setException(error);
768             Vector JavaDoc listeners= (Vector JavaDoc) project.getBuildListeners().clone();
769             Iterator JavaDoc iter= listeners.iterator();
770             while (iter.hasNext()) {
771                 BuildListener listener= (BuildListener) iter.next();
772                 listener.buildFinished(event);
773             }
774         } else {
775             project.fireBuildFinished(error);
776         }
777     }
778
779     private boolean usingXmlLogger() {
780         if (buildLogger instanceof XmlLogger) {
781             return true;
782         }
783         if (buildListeners != null) {
784             Enumeration JavaDoc e= getCurrentProject().getBuildListeners().elements();
785             while (e.hasMoreElements()) {
786                 BuildListener element = (BuildListener) e.nextElement();
787                 if (element instanceof XmlLogger) {
788                     return true;
789                 }
790             }
791         }
792         
793         return false;
794     }
795
796     private void logMessage(Project project, String JavaDoc message, int priority) {
797         if (project != null) {
798             project.log(message, priority);
799         } else {
800             if (buildListeners != null) {
801                 project = new Project();
802                 BuildEvent event = new BuildEvent(project);
803                 event.setMessage(message, priority);
804                 //notify the build listeners that are not registered as
805
//no project existed
806
for (Iterator JavaDoc iterator = buildListeners.iterator(); iterator.hasNext();) {
807                     try {
808                         BuildListener listener = (BuildListener) iterator.next();
809                         listener.messageLogged(event);
810                     } catch (ClassCastException JavaDoc e) {
811                         //ignore we could be trying to log that a build listener is the
812
//wrong type of class
813
}
814                 }
815             } else {
816                 IStatus s = new Status(IStatus.ERROR, AntCorePlugin.PI_ANTCORE, AntCorePlugin.INTERNAL_ERROR, message, null);
817                 AntCorePlugin.getPlugin().getLog().log(s);
818             }
819         }
820     }
821
822     /**
823      * Sets the buildFileLocation.
824      *
825      * @param buildFileLocation the file system location of the build file
826      */

827     public void setBuildFileLocation(String JavaDoc buildFileLocation) {
828         this.buildFileLocation = buildFileLocation;
829         if (getCurrentProject() != null) {
830             getCurrentProject().setUserProperty("ant.file", buildFileLocation); //$NON-NLS-1$
831
}
832     }
833     
834     /**
835      * Sets the input handler class name.
836      *
837      * @param inputHandlerClassname the name of the class to use for the input handler
838      */

839     public void setInputHandler(String JavaDoc inputHandlerClassname) {
840         this.inputHandlerClassname= inputHandlerClassname;
841     }
842
843     private String JavaDoc getBuildFileLocation() {
844         if (buildFileLocation == null) {
845             buildFileLocation = new File JavaDoc("build.xml").getAbsolutePath(); //$NON-NLS-1$
846
}
847         return buildFileLocation;
848     }
849
850     /**
851      * Sets the message output level. Use -1 for none.
852      * @param level The message output level
853      */

854     public void setMessageOutputLevel(int level) {
855         messageOutputLevel = level;
856         if (buildLogger != null) {
857             buildLogger.setMessageOutputLevel(level);
858         }
859     }
860
861     /**
862      * Sets the extra user arguments
863      * @param args The extra user arguments
864      */

865     public void setArguments(String JavaDoc[] args) {
866         extraArguments = args;
867     }
868
869     /**
870      * Sets the execution targets.
871      * @param executionTargets The targets to execute for the build
872      */

873     public void setExecutionTargets(String JavaDoc[] executionTargets) {
874         targets = new Vector JavaDoc(executionTargets.length);
875         for (int i = 0; i < executionTargets.length; i++) {
876             targets.add(executionTargets[i]);
877         }
878     }
879     
880     /*
881      * Returns a String representation of the Ant version number as specified
882      * in the version.txt file.
883      */

884     private String JavaDoc getAntVersionNumber() throws BuildException {
885         if (antVersionNumber == null) {
886             try {
887                 Properties JavaDoc props = new Properties JavaDoc();
888                 InputStream JavaDoc in = Main.class.getResourceAsStream("/org/apache/tools/ant/version.txt"); //$NON-NLS-1$
889
props.load(in);
890                 in.close();
891                 String JavaDoc versionNumber= props.getProperty("VERSION"); //$NON-NLS-1$
892
antVersionNumber= versionNumber;
893             } catch (IOException JavaDoc ioe) {
894                 throw new BuildException(MessageFormat.format(InternalAntMessages.InternalAntRunner_Could_not_load_the_version_information___0__9, new String JavaDoc[]{ioe.getMessage()}));
895             } catch (NullPointerException JavaDoc npe) {
896                 throw new BuildException(InternalAntMessages.InternalAntRunner_Could_not_load_the_version_information__10);
897             }
898         }
899         return antVersionNumber;
900     }
901     
902     /*
903      * Returns whether the given version is compatible with the
904      * current Ant version. A version is compatible if it is less
905      * than or equal to the current version.
906      */

907     private boolean isVersionCompatible(String JavaDoc comparison) {
908         String JavaDoc version= getAntVersionNumber();
909         return version.compareTo(comparison) >= 0;
910     }
911     
912     private boolean preprocessCommandLine(List JavaDoc commands) {
913         
914         String JavaDoc arg = AntCoreUtil.getArgument(commands, "-listener"); //$NON-NLS-1$
915
while (arg != null) {
916             if (arg.length() == 0) {
917                 throw new BuildException(InternalAntMessages.InternalAntRunner_You_must_specify_a_classname_when_using_the__listener_argument_1);
918             }
919             if (buildListeners == null) {
920                 buildListeners= new ArrayList JavaDoc(1);
921             }
922             buildListeners.add(arg);
923             arg = AntCoreUtil.getArgument(commands, "-listener"); //$NON-NLS-1$
924
}
925
926         arg = AntCoreUtil.getArgument(commands, "-logger"); //$NON-NLS-1$
927
if (arg != null) {
928             if (arg.length() == 0) {
929                 throw new BuildException(InternalAntMessages.InternalAntRunner_You_must_specify_a_classname_when_using_the__logger_argument_2);
930             }
931             loggerClassname = arg;
932         }
933         arg = AntCoreUtil.getArgument(commands, "-logger"); //$NON-NLS-1$
934
if (arg != null) {
935             throw new BuildException(InternalAntMessages.InternalAntRunner_Only_one_logger_class_may_be_specified_1);
936         }
937         
938         arg = AntCoreUtil.getArgument(commands, "-inputhandler"); //$NON-NLS-1$
939
if (arg != null) {
940             if (!isVersionCompatible("1.5")) { //$NON-NLS-1$
941
throw new BuildException(InternalAntMessages.InternalAntRunner_Specifying_an_InputHandler_is_an_Ant_1_5___feature__Please_update_your_Ant_classpath_to_include_an_Ant_version_greater_than_this__2);
942             }
943             if (arg.length() == 0) {
944                 throw new BuildException(InternalAntMessages.InternalAntRunner_You_must_specify_a_classname_when_using_the__inputhandler_argument_1);
945             }
946             inputHandlerClassname = arg;
947         }
948         arg = AntCoreUtil.getArgument(commands, "-inputhandler"); //$NON-NLS-1$
949
if (arg != null) {
950             throw new BuildException(InternalAntMessages.InternalAntRunner_Only_one_input_handler_class_may_be_specified__2);
951         }
952         return true;
953     }
954     
955     /*
956      * Looks for interesting command line arguments.
957      * Returns whether it is OK to run the script.
958      */

959     private boolean processCommandLine(List JavaDoc commands) {
960         
961         if (commands.remove("-help") || commands.remove("-h")) { //$NON-NLS-1$ //$NON-NLS-2$
962
if (isVersionCompatible("1.7")) { //$NON-NLS-1$
963
new EclipseMainHelper().runUsage(getBuildFileLocation(), getCurrentProject());
964             } else {
965                 getCurrentProject().log(InternalAntMessages.InternalAntRunner_2);
966             }
967             return false;
968         }
969         
970         if (commands.remove("-version")) { //$NON-NLS-1$
971
printVersion();
972             return false;
973         }
974         
975         if (commands.remove("-verbose") || commands.remove("-v")) { //$NON-NLS-1$ //$NON-NLS-2$
976
printVersion();
977             setMessageOutputLevel(Project.MSG_VERBOSE);
978         }
979         
980         if (commands.remove("-debug") || commands.remove("-d")) { //$NON-NLS-1$ //$NON-NLS-2$
981
printVersion();
982             setMessageOutputLevel(Project.MSG_DEBUG);
983         }
984         
985         if (commands.remove("-quiet") || commands.remove("-q")) { //$NON-NLS-1$ //$NON-NLS-2$
986
setMessageOutputLevel(Project.MSG_WARN);
987         }
988
989         if (commands.remove("-emacs") || commands.remove("-e")) { //$NON-NLS-1$ //$NON-NLS-2$
990
emacsMode = true;
991             if (buildLogger != null) {
992                 buildLogger.setEmacsMode(true);
993             }
994         }
995         
996         if (commands.remove("-diagnostics")) { //$NON-NLS-1$
997
if (!isVersionCompatible("1.5")) { //$NON-NLS-1$
998
throw new BuildException(InternalAntMessages.InternalAntRunner_The_diagnositics_options_is_an_Ant_1_5___feature__Please_update_your_Ant_classpath_to_include_an_Ant_version_greater_than_this__4);
999             }
1000            try {
1001                Diagnostics.doReport(System.out);
1002            } catch (NullPointerException JavaDoc e) {
1003                logMessage(getCurrentProject(), InternalAntMessages.InternalAntRunner_ANT_HOME_must_be_set_to_use_Ant_diagnostics_2, Project.MSG_ERR);
1004            }
1005            return false;
1006        }
1007        
1008        String JavaDoc arg = AntCoreUtil.getArgument(commands, "-logfile"); //$NON-NLS-1$
1009
if (arg == null) {
1010            arg = AntCoreUtil.getArgument(commands, "-l"); //$NON-NLS-1$
1011
}
1012        if (arg != null) {
1013            if (arg.length() == 0) {
1014                String JavaDoc message= InternalAntMessages.InternalAntRunner_You_must_specify_a_log_file_when_using_the__log_argument_3;
1015                logMessage(currentProject, message, Project.MSG_ERR);
1016                throw new BuildException(message);
1017            }
1018            try {
1019                createLogFile(arg);
1020            } catch (IOException JavaDoc e) {
1021                // just log message and ignore exception
1022
logMessage(getCurrentProject(), MessageFormat.format(InternalAntMessages.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);
1023                return false;
1024            }
1025        
1026        }
1027        
1028        arg = AntCoreUtil.getArgument(commands, "-buildfile"); //$NON-NLS-1$
1029
if (arg == null) {
1030            arg = AntCoreUtil.getArgument(commands, "-file"); //$NON-NLS-1$
1031
if (arg == null) {
1032                arg = AntCoreUtil.getArgument(commands, "-f"); //$NON-NLS-1$
1033
}
1034        }
1035        
1036        if (arg != null) {
1037            if (arg.length() == 0) {
1038                String JavaDoc message= InternalAntMessages.InternalAntRunner_You_must_specify_a_buildfile_when_using_the__buildfile_argument_4;
1039                logMessage(currentProject, message, Project.MSG_ERR);
1040                throw new BuildException(message);
1041            }
1042            setBuildFileLocation(arg);
1043        }
1044        
1045        if (isVersionCompatible("1.6")) { //$NON-NLS-1$
1046
if (commands.remove("-k") || commands.remove("-keep-going")) { //$NON-NLS-1$ //$NON-NLS-2$
1047
keepGoing= true;
1048            }
1049            if (commands.remove("-noinput")) { //$NON-NLS-1$
1050
allowInput= false;
1051            }
1052            arg= AntCoreUtil.getArgument(commands, "-lib"); //$NON-NLS-1$
1053
if (arg != null) {
1054                logMessage(currentProject, InternalAntMessages.InternalAntRunner_157, Project.MSG_ERR);
1055                return false;
1056            }
1057        }
1058        
1059        arg= AntCoreUtil.getArgument(commands, "-find"); //$NON-NLS-1$
1060
if (arg == null) {
1061            arg= AntCoreUtil.getArgument(commands, "-s"); //$NON-NLS-1$
1062
}
1063        if (arg != null) {
1064            logMessage(currentProject, InternalAntMessages.InternalAntRunner__find_not_supported, Project.MSG_ERR);
1065            return false;
1066        }
1067
1068        if (!commands.isEmpty()) {
1069            processUnrecognizedCommands(commands);
1070        }
1071
1072        if (!commands.isEmpty()) {
1073            processTargets(commands);
1074        }
1075        
1076        return true;
1077    }
1078    
1079    /*
1080     * Checks for unrecognized arguments on the command line.
1081     * Since there is no syntactic way to distingush between
1082     * ant -foo target1 target2
1083     * ant -foo fooarg target
1084     * we remove everything up to the last argument that
1085     * begins with a '-'. In the latter case, above, that
1086     * means that there will be an extra target, 'fooarg',
1087     * left lying around.
1088     */

1089    private void processUnrecognizedCommands(List JavaDoc commands) {
1090        int p = -1;
1091
1092        // find the last arg that begins with '-'
1093
for (int i = commands.size() - 1; i >= 0; i--) {
1094            if (((String JavaDoc) commands.get(0)).startsWith("-")) { //$NON-NLS-1$
1095
p = i;
1096                break;
1097            }
1098        }
1099        if (p < 0) { return; }
1100
1101        // remove everything preceding that last '-arg'
1102
String JavaDoc s = ""; //$NON-NLS-1$
1103
for (int i = 0; i <= p; i++) {
1104            s += " " + ((String JavaDoc) commands.get(0)); //$NON-NLS-1$
1105
commands.remove(0);
1106        }
1107        
1108        // warn of ignored commands
1109
String JavaDoc message = MessageFormat.format(InternalAntMessages.InternalAntRunner_Unknown_argument___0__2, new Object JavaDoc[]{ s.substring(1) });
1110        logMessage(currentProject, message, Project.MSG_WARN);
1111    }
1112    
1113
1114    /*
1115     * Checks for targets specified at the command line.
1116     */

1117    private void processTargets(List JavaDoc commands) {
1118        if (targets == null) {
1119            targets = new Vector JavaDoc(commands.size());
1120        }
1121        for (Iterator JavaDoc iter = commands.iterator(); iter.hasNext();) {
1122            targets.add(iter.next());
1123        }
1124    }
1125
1126    /*
1127     * Creates the log file with the name specified by the user.
1128     * If the fileName is not absolute, the file will be created in the
1129     * working directory if specified or in the same directory as the location
1130     * of the build file.
1131     */

1132    private void createLogFile(String JavaDoc fileName) throws FileNotFoundException JavaDoc, IOException JavaDoc {
1133        File JavaDoc logFile = getFileRelativeToBaseDir(fileName);
1134        
1135        //this stream is closed in the finally block of run(list)
1136
out = new PrintStream JavaDoc(new FileOutputStream JavaDoc(logFile));
1137        err = out;
1138        logMessage(getCurrentProject(), MessageFormat.format(InternalAntMessages.InternalAntRunner_Using__0__file_as_build_log__1, new String JavaDoc[]{logFile.getCanonicalPath()}), Project.MSG_INFO);
1139        if (buildLogger != null) {
1140            buildLogger.setErrorPrintStream(err);
1141            buildLogger.setOutputPrintStream(out);
1142        }
1143    }
1144
1145    private File JavaDoc getFileRelativeToBaseDir(String JavaDoc fileName) {
1146        return AntCoreUtil.getFileRelativeToBaseDir(fileName, getCurrentProject().getUserProperty("basedir"), getBuildFileLocation()); //$NON-NLS-1$
1147
}
1148
1149    /*
1150     * Processes cmd line properties and adds the user properties
1151     * Any user properties that have been explicitly set are set as well.
1152     * Ensures that -D properties take precedence.
1153     */

1154    private boolean processProperties(List JavaDoc commands) {
1155        boolean exceptionToBeThrown= false;
1156        //MULTIPLE property files are allowed
1157
String JavaDoc arg= AntCoreUtil.getArgument(commands, "-propertyfile"); //$NON-NLS-1$
1158
while (arg != null) {
1159            if (!isVersionCompatible("1.5")) { //$NON-NLS-1$
1160
fEarlyErrorMessage= InternalAntMessages.InternalAntRunner_Specifying_property_files_is_a_Ant_1_5___feature__Please_update_your_Ant_classpath__6;
1161                break;
1162            }
1163            if (arg.length() == 0) {
1164                fEarlyErrorMessage= InternalAntMessages.InternalAntRunner_You_must_specify_a_property_filename_when_using_the__propertyfile_argument_3;
1165                exceptionToBeThrown= true;
1166                break;
1167            }
1168            
1169            propertyFiles.add(arg);
1170            arg= AntCoreUtil.getArgument(commands, "-propertyfile"); //$NON-NLS-1$
1171
}
1172        
1173        String JavaDoc[] globalPropertyFiles= AntCorePlugin.getPlugin().getPreferences().getCustomPropertyFiles();
1174        if (globalPropertyFiles.length > 0) {
1175            if (!isVersionCompatible("1.5")) { //$NON-NLS-1$
1176
fEarlyErrorMessage= InternalAntMessages.InternalAntRunner_Specifying_property_files_is_a_Ant_1_5___feature__Please_update_your_Ant_classpath__6;
1177            } else {
1178                if (propertyFiles == null) {
1179                    propertyFiles= new ArrayList JavaDoc(globalPropertyFiles.length);
1180                }
1181                propertyFiles.addAll(Arrays.asList(globalPropertyFiles));
1182            }
1183        }
1184        
1185        if (propertyFiles != null && !propertyFiles.isEmpty()) {
1186            loadPropertyFiles();
1187        }
1188        
1189        if (commands != null) {
1190            processMinusDProperties(commands);
1191        }
1192        return exceptionToBeThrown;
1193    }
1194
1195    private void processMinusDProperties(List JavaDoc commands) {
1196        if (!commands.isEmpty() && userProperties == null) {
1197            userProperties= new HashMap JavaDoc();
1198        }
1199        AntCoreUtil.processMinusDProperties(commands, userProperties);
1200    }
1201
1202    /*
1203     * Logs a message with the client indicating the version of <b>Ant</b> that this class
1204     * fronts.
1205     */

1206    private void printVersion() {
1207        logMessage(getCurrentProject(), Main.getAntVersion(), Project.MSG_INFO);
1208    }
1209
1210    
1211    /**
1212     * Sets the build progress monitor.
1213     * @param monitor The progress monitor to use
1214     */

1215    public void setProgressMonitor(IProgressMonitor monitor) {
1216        this.monitor = monitor;
1217    }
1218
1219    private Project getCurrentProject() {
1220        return currentProject;
1221    }
1222
1223    private void setCurrentProject(Project currentProject) {
1224        this.currentProject = currentProject;
1225    }
1226    
1227    public String JavaDoc getBuildExceptionErrorMessage(Throwable JavaDoc t) {
1228        if (t instanceof BuildException) {
1229            return t.toString();
1230        }
1231        return null;
1232    }
1233    
1234    /**
1235     * Load all properties from the files
1236     * specified by -propertyfile.
1237     */

1238    private void loadPropertyFiles() {
1239        if (userProperties == null) {
1240            userProperties= new HashMap JavaDoc();
1241        }
1242        try {
1243            List JavaDoc allProperties = AntCoreUtil.loadPropertyFiles(propertyFiles, getCurrentProject().getUserProperty("basedir"), getBuildFileLocation()); //$NON-NLS-1$
1244
Iterator JavaDoc iter= allProperties.iterator();
1245            while (iter.hasNext()) {
1246                Properties JavaDoc props = (Properties JavaDoc) iter.next();
1247                Enumeration JavaDoc propertyNames = props.propertyNames();
1248                while (propertyNames.hasMoreElements()) {
1249                    String JavaDoc name = (String JavaDoc) propertyNames.nextElement();
1250                    //most specific to global
1251
//do not overwrite specific with a global property
1252
if (userProperties.get(name) == null) {
1253                        userProperties.put(name, props.getProperty(name));
1254                    }
1255                }
1256            }
1257        } catch (IOException JavaDoc e) {
1258            fEarlyErrorMessage= MessageFormat.format(InternalAntMessages.InternalAntRunner_4, new String JavaDoc[]{e.getMessage()});
1259        }
1260    }
1261    
1262    /*
1263     * Creates the InputHandler and adds it to the project.
1264     *
1265     * @exception BuildException if a specified InputHandler
1266     * implementation could not be loaded.
1267     */

1268    private void addInputHandler(Project project) {
1269        if (!isVersionCompatible("1.5") || (inputHandlerClassname != null && inputHandlerClassname.length() == 0)) { //$NON-NLS-1$
1270
return;
1271        }
1272        InputHandlerSetter setter= new InputHandlerSetter();
1273        setter.setInputHandler(project, inputHandlerClassname);
1274    }
1275
1276    /*
1277     * Sets the Java class path in org.apache.tools.ant.types.Path
1278     */

1279    private void setJavaClassPath() {
1280        URL JavaDoc[] antClasspath= null;
1281        AntCorePreferences prefs= AntCorePlugin.getPlugin().getPreferences();
1282        if (customClasspath == null) {
1283            antClasspath= prefs.getURLs();
1284        } else {
1285            URL JavaDoc[] extraClasspath= prefs.getExtraClasspathURLs();
1286            antClasspath= new URL JavaDoc[customClasspath.length + extraClasspath.length];
1287            System.arraycopy(customClasspath, 0, antClasspath, 0, customClasspath.length);
1288            System.arraycopy(extraClasspath, 0, antClasspath, customClasspath.length, extraClasspath.length);
1289        }
1290        StringBuffer JavaDoc buff= new StringBuffer JavaDoc();
1291        File JavaDoc file= null;
1292        for (int i = 0; i < antClasspath.length; i++) {
1293            try {
1294                file = new File JavaDoc(FileLocator.toFileURL(antClasspath[i]).getPath());
1295            } catch (IOException JavaDoc e) {
1296                continue;
1297            }
1298            buff.append(file.getAbsolutePath());
1299            buff.append("; "); //$NON-NLS-1$
1300
}
1301
1302        org.apache.tools.ant.types.Path systemClasspath= new org.apache.tools.ant.types.Path(null, buff.substring(0, buff.length() - 2));
1303        org.apache.tools.ant.types.Path.systemClasspath= systemClasspath;
1304    }
1305    
1306    /**
1307     * Sets the custom classpath to be included when setting the Java classpath for this build.
1308     * @param classpath The custom classpath for this build.
1309     */

1310    public void setCustomClasspath(URL JavaDoc[] classpath) {
1311        customClasspath= classpath;
1312    }
1313}
Popular Tags