KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > ant > core > AntCorePreferences


1 /*******************************************************************************
2  * Copyright (c) 2000, 2007 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  * Thierry Lach (thierry.lach@bbdodetroit.com) - bug 40502
11  *******************************************************************************/

12 package org.eclipse.ant.core;
13
14 import java.io.File JavaDoc;
15 import java.io.FilenameFilter JavaDoc;
16 import java.io.IOException JavaDoc;
17 import java.net.MalformedURLException JavaDoc;
18 import java.net.URL JavaDoc;
19 import java.util.ArrayList JavaDoc;
20 import java.util.Arrays JavaDoc;
21 import java.util.Collections JavaDoc;
22 import java.util.Enumeration JavaDoc;
23 import java.util.HashMap JavaDoc;
24 import java.util.Iterator JavaDoc;
25 import java.util.List JavaDoc;
26 import java.util.Map JavaDoc;
27 import java.util.StringTokenizer JavaDoc;
28
29 import org.eclipse.ant.internal.core.AntClasspathEntry;
30 import org.eclipse.ant.internal.core.AntObject;
31 import org.eclipse.ant.internal.core.IAntCoreConstants;
32 import org.eclipse.ant.internal.core.InternalCoreAntMessages;
33 import org.eclipse.core.runtime.CoreException;
34 import org.eclipse.core.runtime.FileLocator;
35 import org.eclipse.core.runtime.IConfigurationElement;
36 import org.eclipse.core.runtime.IContributor;
37 import org.eclipse.core.runtime.IPath;
38 import org.eclipse.core.runtime.IStatus;
39 import org.eclipse.core.runtime.Path;
40 import org.eclipse.core.runtime.Platform;
41 import org.eclipse.core.runtime.Preferences;
42 import org.eclipse.core.runtime.Status;
43 import org.eclipse.core.variables.IDynamicVariable;
44 import org.eclipse.core.variables.VariablesPlugin;
45 import org.eclipse.osgi.service.resolver.BundleDescription;
46 import org.eclipse.osgi.service.resolver.ExportPackageDescription;
47 import org.eclipse.osgi.util.ManifestElement;
48 import org.eclipse.osgi.util.NLS;
49 import org.osgi.framework.Bundle;
50 import org.osgi.framework.BundleException;
51 import org.osgi.framework.Constants;
52 import org.osgi.service.packageadmin.ExportedPackage;
53 import org.osgi.service.packageadmin.PackageAdmin;
54 import org.osgi.util.tracker.ServiceTracker;
55
56
57 /**
58  * Represents the Ant Core plug-in's preferences providing utilities for
59  * extracting, changing and updating the underlying preferences.
60  * Clients may not instantiate or subclass this class.
61  * @since 2.1
62  */

63 public class AntCorePreferences implements org.eclipse.core.runtime.Preferences.IPropertyChangeListener {
64
65     private List JavaDoc defaultTasks;
66     private List JavaDoc defaultTypes;
67     private List JavaDoc extraClasspathURLs;
68     private List JavaDoc defaultProperties;
69     private IAntClasspathEntry[] defaultAntHomeEntries;
70     
71     private Task[] customTasks;
72     private Task[] oldCustomTasks;
73     private Type[] customTypes;
74     private Type[] oldCustomTypes;
75     private IAntClasspathEntry[] antHomeEntries;
76     private IAntClasspathEntry[] additionalEntries;
77     private Property[] customProperties;
78     private Property[] oldCustomProperties;
79     private String JavaDoc[] customPropertyFiles;
80     
81     private List JavaDoc pluginClassLoaders;
82     
83     private ClassLoader JavaDoc[] orderedPluginClassLoaders;
84     
85     private String JavaDoc antHome;
86     
87     private boolean runningHeadless= false;
88
89     static private class Relation {
90         Object JavaDoc from;
91         Object JavaDoc to;
92
93         Relation(Object JavaDoc from, Object JavaDoc to) {
94             this.from = from;
95             this.to = to;
96         }
97
98         public String JavaDoc toString() {
99             return from.toString() + "->" + (to == null ? "" : to.toString()); //$NON-NLS-1$//$NON-NLS-2$
100
}
101     }
102
103     class WrappedClassLoader extends ClassLoader JavaDoc {
104         private Bundle bundle;
105         public WrappedClassLoader(Bundle bundle) {
106             super();
107             this.bundle = bundle;
108         }
109         /* (non-Javadoc)
110          * @see java.lang.ClassLoader#findClass(java.lang.String)
111          */

112         public Class JavaDoc findClass(String JavaDoc name) throws ClassNotFoundException JavaDoc {
113             return bundle.loadClass(name);
114         }
115         /* (non-Javadoc)
116          * @see java.lang.ClassLoader#findResource(java.lang.String)
117          */

118         public URL JavaDoc findResource(String JavaDoc name) {
119             return bundle.getResource(name);
120         }
121         
122         /* (non-Javadoc)
123          * @see java.lang.ClassLoader#findResources(java.lang.String)
124          */

125         protected Enumeration JavaDoc findResources(String JavaDoc name) throws IOException JavaDoc {
126             return bundle.getResources(name);
127         }
128         /* (non-Javadoc)
129          * @see java.lang.Object#equals(java.lang.Object)
130          */

131         public boolean equals(Object JavaDoc obj) {
132             if (!(obj instanceof WrappedClassLoader)) {
133                 return false;
134             }
135             return bundle == ((WrappedClassLoader) obj).bundle;
136         }
137         /* (non-Javadoc)
138          * @see java.lang.Object#hashCode()
139          */

140         public int hashCode() {
141             return bundle.hashCode();
142         }
143         public String JavaDoc toString() {
144             return "WrappedClassLoader(" + bundle.toString() + ")"; //$NON-NLS-1$ //$NON-NLS-2$
145
}
146     }
147     
148     protected AntCorePreferences(List JavaDoc defaultTasks, List JavaDoc defaultExtraClasspath, List JavaDoc defaultTypes, boolean headless) {
149         this(defaultTasks, defaultExtraClasspath, defaultTypes, Collections.EMPTY_LIST, headless);
150     }
151     
152     protected AntCorePreferences(List JavaDoc defaultTasks, List JavaDoc defaultExtraClasspath, List JavaDoc defaultTypes, List JavaDoc defaultProperties, boolean headless) {
153         runningHeadless= headless;
154         initializePluginClassLoaders();
155         extraClasspathURLs = new ArrayList JavaDoc(20);
156         this.defaultTasks = computeDefaultTasks(defaultTasks);
157         this.defaultTypes = computeDefaultTypes(defaultTypes);
158         computeDefaultExtraClasspathEntries(defaultExtraClasspath);
159         computeDefaultProperties(defaultProperties);
160         restoreCustomObjects();
161         
162     }
163     
164     /**
165      * When a preference changes, update the in-memory cache of the preference.
166      * @param event The property change event that has occurred.
167      * @see org.eclipse.core.runtime.Preferences.IPropertyChangeListener#propertyChange(org.eclipse.core.runtime.Preferences.PropertyChangeEvent)
168      */

169     public void propertyChange(Preferences.PropertyChangeEvent event) {
170         Preferences prefs = AntCorePlugin.getPlugin().getPluginPreferences();
171         String JavaDoc property= event.getProperty();
172         if (property.equals(IAntCoreConstants.PREFERENCE_TASKS) || property.startsWith(IAntCoreConstants.PREFIX_TASK)) {
173             restoreTasks(prefs);
174         } else if (property.equals(IAntCoreConstants.PREFERENCE_TYPES) || property.startsWith(IAntCoreConstants.PREFIX_TYPE)) {
175             restoreTypes(prefs);
176         } else if (property.equals(IAntCoreConstants.PREFERENCE_ANT_HOME_ENTRIES)) {
177             restoreAntHomeEntries(prefs);
178         } else if (property.equals(IAntCoreConstants.PREFERENCE_ADDITIONAL_ENTRIES)) {
179             restoreAdditionalEntries(prefs);
180         } else if (property.equals(IAntCoreConstants.PREFERENCE_ANT_HOME)) {
181             restoreAntHome(prefs);
182         } else if (property.equals(IAntCoreConstants.PREFERENCE_PROPERTIES) || property.startsWith(IAntCoreConstants.PREFIX_PROPERTY)) {
183             restoreCustomProperties(prefs);
184         } else if (property.equals(IAntCoreConstants.PREFERENCE_PROPERTY_FILES)) {
185             restoreCustomPropertyFiles(prefs);
186         }
187     }
188
189     /**
190      * Restores the in-memory model of the preferences from the preference store
191      */

192     private void restoreCustomObjects() {
193         Preferences prefs = AntCorePlugin.getPlugin().getPluginPreferences();
194         restoreAntHome(prefs);
195         restoreTasks(prefs);
196         restoreTypes(prefs);
197         restoreAntHomeEntries(prefs);
198         restoreAdditionalEntries(prefs);
199         restoreCustomProperties(prefs);
200         restoreCustomPropertyFiles(prefs);
201         prefs.addPropertyChangeListener(this);
202     }
203     
204     private void restoreTasks(Preferences prefs) {
205          String JavaDoc tasks = prefs.getString(IAntCoreConstants.PREFERENCE_TASKS);
206          if (tasks.equals("")) { //$NON-NLS-1$
207
customTasks = new Task[0];
208          } else {
209              customTasks = extractTasks(prefs, getArrayFromString(tasks));
210          }
211     }
212     
213     private void restoreTypes(Preferences prefs) {
214         String JavaDoc types = prefs.getString(IAntCoreConstants.PREFERENCE_TYPES);
215         if (types.equals("")) {//$NON-NLS-1$
216
customTypes = new Type[0];
217         } else {
218             customTypes = extractTypes(prefs, getArrayFromString(types));
219         }
220     }
221     
222     private void restoreAntHomeEntries(Preferences prefs) {
223         String JavaDoc entries = prefs.getString("ant_urls"); //old constant //$NON-NLS-1$
224
if (entries.equals("")) {//$NON-NLS-1$
225
entries= prefs.getString(IAntCoreConstants.PREFERENCE_ANT_HOME_ENTRIES);
226         } else {
227             prefs.setToDefault("ant_urls"); //$NON-NLS-1$
228
antHomeEntries= migrateURLEntries(getArrayFromString(entries));
229             return;
230         }
231         if (entries.equals("")) {//$NON-NLS-1$
232
antHomeEntries= getDefaultAntHomeEntries();
233         } else {
234             antHomeEntries= extractEntries(getArrayFromString(entries));
235         }
236     }
237     
238     private void restoreAdditionalEntries(Preferences prefs) {
239         String JavaDoc entries = prefs.getString("urls"); //old constant //$NON-NLS-1$
240
if (entries.equals("")) {//$NON-NLS-1$
241
entries = prefs.getString(IAntCoreConstants.PREFERENCE_ADDITIONAL_ENTRIES);
242         } else {
243             prefs.setToDefault("urls"); //$NON-NLS-1$
244
additionalEntries= migrateURLEntries(getArrayFromString(entries));
245             return;
246         }
247         if (entries.equals("")) {//$NON-NLS-1$
248
IAntClasspathEntry toolsJarEntry= getToolsJarEntry();
249             List JavaDoc userLibs= getUserLibraries();
250             if (toolsJarEntry == null) {
251                 if (userLibs == null) {
252                     additionalEntries= new IAntClasspathEntry[0];
253                 } else {
254                     additionalEntries= (IAntClasspathEntry[]) userLibs.toArray(new IAntClasspathEntry[userLibs.size()]);
255                 }
256             } else {
257                 if (userLibs == null) {
258                     additionalEntries= new IAntClasspathEntry[] {toolsJarEntry};
259                 } else {
260                     userLibs.add(toolsJarEntry);
261                     additionalEntries= (IAntClasspathEntry[]) userLibs.toArray(new IAntClasspathEntry[userLibs.size()]);
262                 }
263             }
264         } else {
265             additionalEntries= extractEntries(getArrayFromString(entries));
266         }
267     }
268     
269     /*
270      * Migrates the persisted url entries restored from a workspace older than 3.0
271      */

272     private IAntClasspathEntry[] migrateURLEntries(String JavaDoc[] urlEntries) {
273         List JavaDoc result = new ArrayList JavaDoc(urlEntries.length);
274         for (int i = 0; i < urlEntries.length; i++) {
275             URL JavaDoc url;
276             try {
277                 url = new URL JavaDoc (urlEntries[i]);
278             } catch (MalformedURLException JavaDoc e) {
279                 continue;
280             }
281             result.add(new AntClasspathEntry(url));
282         }
283         return (IAntClasspathEntry[])result.toArray(new IAntClasspathEntry[result.size()]);
284     }
285
286     private void restoreAntHome(Preferences prefs) {
287         antHome= prefs.getString(IAntCoreConstants.PREFERENCE_ANT_HOME);
288         if (antHome == null || antHome.length() == 0) {
289             antHome= getDefaultAntHome();
290         }
291     }
292     
293     /**
294      * Returns the absolute path of the default ant.home to use for the build.
295      * The default is the org.apache.ant plug-in folder provided with Eclipse.
296      *
297      * @return String absolute path of the default ant.home
298      * @since 3.0
299      */

300     public String JavaDoc getDefaultAntHome() {
301         IAntClasspathEntry[] entries= getDefaultAntHomeEntries();
302         if (entries.length > 0) {
303             URL JavaDoc antjar= entries[0].getEntryURL();
304             IPath antHomePath= new Path(antjar.getFile());
305             //parent directory of the lib directory
306
antHomePath= antHomePath.removeLastSegments(2);
307             return antHomePath.toFile().getAbsolutePath();
308         }
309         return null;
310     }
311     
312     private void restoreCustomProperties(Preferences prefs) {
313         String JavaDoc properties = prefs.getString(IAntCoreConstants.PREFERENCE_PROPERTIES);
314         if (properties.equals("")) {//$NON-NLS-1$
315
customProperties = new Property[0];
316         } else {
317             customProperties = extractProperties(prefs, getArrayFromString(properties));
318         }
319     }
320     
321     private void restoreCustomPropertyFiles(Preferences prefs) {
322         String JavaDoc propertyFiles= prefs.getString(IAntCoreConstants.PREFERENCE_PROPERTY_FILES);
323         if (propertyFiles.equals("")) { //$NON-NLS-1$
324
customPropertyFiles= new String JavaDoc[0];
325         } else {
326             customPropertyFiles= getArrayFromString(propertyFiles);
327         }
328     }
329
330     protected Task[] extractTasks(Preferences prefs, String JavaDoc[] tasks) {
331         List JavaDoc result = new ArrayList JavaDoc(tasks.length);
332         for (int i = 0; i < tasks.length; i++) {
333             String JavaDoc taskName = tasks[i];
334             String JavaDoc[] values = getArrayFromString(prefs.getString(IAntCoreConstants.PREFIX_TASK + taskName));
335             if (values.length < 2) {
336                 continue;
337             }
338             Task task = new Task();
339             task.setTaskName(taskName);
340             task.setClassName(values[0]);
341             String JavaDoc library= values[1];
342             if (library.startsWith("file:")) { //$NON-NLS-1$
343
//old format where URLs were persisted
344
library= library.substring(5);
345             }
346             task.setLibraryEntry(new AntClasspathEntry(library));
347             result.add(task);
348         }
349         return (Task[]) result.toArray(new Task[result.size()]);
350     }
351
352     protected Type[] extractTypes(Preferences prefs, String JavaDoc[] types) {
353         List JavaDoc result = new ArrayList JavaDoc(types.length);
354         for (int i = 0; i < types.length; i++) {
355             String JavaDoc typeName = types[i];
356             String JavaDoc[] values = getArrayFromString(prefs.getString(IAntCoreConstants.PREFIX_TYPE + typeName));
357             if (values.length < 2) {
358                 continue;
359             }
360             Type type = new Type();
361             type.setTypeName(typeName);
362             type.setClassName(values[0]);
363             String JavaDoc library= values[1];
364             if (library.startsWith("file:")) { //$NON-NLS-1$
365
//old format where URLs were persisted
366
library= library.substring(5);
367             }
368             type.setLibraryEntry(new AntClasspathEntry(library));
369             result.add(type);
370         }
371         return (Type[]) result.toArray(new Type[result.size()]);
372     }
373     
374     protected Property[] extractProperties(Preferences prefs, String JavaDoc[] properties) {
375         Property[] result = new Property[properties.length];
376         for (int i = 0; i < properties.length; i++) {
377             String JavaDoc propertyName = properties[i];
378             String JavaDoc[] values = getArrayFromString(prefs.getString(IAntCoreConstants.PREFIX_PROPERTY + propertyName));
379             if (values.length < 1) {
380                 continue;
381             }
382             Property property = new Property();
383             property.setName(propertyName);
384             property.setValue(values[0]);
385             result[i]= property;
386         }
387         return result;
388     }
389
390     private IAntClasspathEntry[] extractEntries(String JavaDoc[] entries) {
391         IAntClasspathEntry[] result = new IAntClasspathEntry[entries.length];
392         for (int i = 0; i < entries.length; i++) {
393             result[i]= new AntClasspathEntry(entries[i]);
394         }
395         return result;
396     }
397
398     /**
399      * Returns the array of URLs that is the default set of URLs defining
400      * the Ant classpath.
401      *
402      * Ant running through the command line tries to find tools.jar to help the
403      * user. Try emulating the same behavior here.
404      *
405      * @return the default set of URLs defining the Ant classpath
406      * @deprecated
407      */

408     public URL JavaDoc[] getDefaultAntURLs() {
409         IAntClasspathEntry[] entries= getDefaultAntHomeEntries();
410         List JavaDoc result= new ArrayList JavaDoc(3);
411         for (int i = 0; i < entries.length; i++) {
412             IAntClasspathEntry entry = entries[i];
413             result.add(entry.getEntryURL());
414         }
415         URL JavaDoc toolsURL= getToolsJarURL();
416         if (toolsURL != null) {
417             result.add(toolsURL);
418         }
419         return (URL JavaDoc[]) result.toArray(new URL JavaDoc[result.size()]);
420     }
421     
422     /**
423      * Returns the array of classpath entries that is the default set of entries defining
424      * the Ant classpath.
425      *
426      * @return the default set of classpath entries defining the Ant classpath
427      */

428     public IAntClasspathEntry[] getDefaultAntHomeEntries() {
429         if (defaultAntHomeEntries== null) {
430             ServiceTracker tracker = new ServiceTracker(AntCorePlugin.getPlugin().getBundle().getBundleContext(), PackageAdmin.class.getName(), null);
431             tracker.open();
432             try {
433                 List JavaDoc result = new ArrayList JavaDoc(29);
434                 PackageAdmin packageAdmin = (PackageAdmin) tracker.getService();
435                 if (packageAdmin != null) {
436                     ExportedPackage exportedPackage = packageAdmin.getExportedPackage("org.apache.tools.ant"); //$NON-NLS-1$
437
if (exportedPackage != null) {
438                         Bundle bundle = exportedPackage.getExportingBundle();
439                         if (bundle != null) {
440                             addLibraries(bundle, result);
441                         }
442                     }
443                 }
444                 defaultAntHomeEntries= (IAntClasspathEntry[]) result.toArray(new IAntClasspathEntry[result.size()]);
445             } finally {
446                 tracker.close();
447             }
448         }
449         return defaultAntHomeEntries;
450     }
451     
452     /**
453      * Returns the array of URLs that is the set of URLs defining the Ant
454      * classpath.
455      *
456      * @return the set of URLs defining the Ant classpath
457      * @deprecated use getAntHomeClasspathEntries and getToolsJarEntry
458      */

459     public URL JavaDoc[] getAntURLs() {
460         int extra= 0;
461         IAntClasspathEntry entry= getToolsJarEntry();
462         if (entry != null) {
463             extra++;
464         }
465         URL JavaDoc[] urls= new URL JavaDoc[antHomeEntries.length + extra];
466         int i;
467         for (i = 0; i < antHomeEntries.length; i++) {
468             URL JavaDoc url = antHomeEntries[i].getEntryURL();
469             if (url != null) {
470                 urls[i]= url;
471             }
472         }
473         if (entry != null) {
474             urls[i]= entry.getEntryURL();
475         }
476         return urls;
477         
478     }
479
480     protected List JavaDoc computeDefaultTasks(List JavaDoc tasks) {
481         List JavaDoc result = new ArrayList JavaDoc(tasks.size());
482         for (Iterator JavaDoc iterator = tasks.iterator(); iterator.hasNext();) {
483             IConfigurationElement element = (IConfigurationElement) iterator.next();
484             if (!relevantRunningHeadless(element)) {
485                 continue;
486             }
487             Task task = new Task();
488             task.setTaskName(element.getAttribute(AntCorePlugin.NAME));
489             task.setClassName(element.getAttribute(AntCorePlugin.CLASS));
490             
491             configureAntObject(result, element, task, task.getTaskName(), InternalCoreAntMessages.AntCorePreferences_No_library_for_task);
492         }
493         return result;
494     }
495
496     private void addURLToExtraClasspathEntries(URL JavaDoc url, IConfigurationElement element) {
497         String JavaDoc eclipseRuntime= element.getAttribute(AntCorePlugin.ECLIPSE_RUNTIME);
498         boolean eclipseRuntimeRequired= true;
499         if (eclipseRuntime != null) {
500             eclipseRuntimeRequired= Boolean.valueOf(eclipseRuntime).booleanValue();
501         }
502         Iterator JavaDoc itr= extraClasspathURLs.iterator();
503         while (itr.hasNext()) {
504             IAntClasspathEntry entry = (IAntClasspathEntry) itr.next();
505             if (entry.getEntryURL().equals(url)) {
506                 return;
507             }
508         }
509         
510         AntClasspathEntry entry= new AntClasspathEntry(url);
511         entry.setEclipseRuntimeRequired(eclipseRuntimeRequired);
512         extraClasspathURLs.add(entry);
513     }
514
515     protected List JavaDoc computeDefaultTypes(List JavaDoc types) {
516         List JavaDoc result = new ArrayList JavaDoc(types.size());
517         for (Iterator JavaDoc iterator = types.iterator(); iterator.hasNext();) {
518             IConfigurationElement element = (IConfigurationElement) iterator.next();
519             if (!relevantRunningHeadless(element)) {
520                 continue;
521             }
522             Type type = new Type();
523             type.setTypeName(element.getAttribute(AntCorePlugin.NAME));
524             type.setClassName(element.getAttribute(AntCorePlugin.CLASS));
525             
526             configureAntObject(result, element, type, type.getTypeName(), InternalCoreAntMessages.AntCorePreferences_No_library_for_type);
527         }
528         return result;
529     }
530
531     private void configureAntObject(List JavaDoc result, IConfigurationElement element, AntObject antObject, String JavaDoc objectName, String JavaDoc errorMessage) {
532         String JavaDoc runtime = element.getAttribute(AntCorePlugin.ECLIPSE_RUNTIME);
533         if (runtime != null) {
534             antObject.setEclipseRuntimeRequired(Boolean.valueOf(runtime).booleanValue());
535         }
536         
537         String JavaDoc uri = element.getAttribute(AntCorePlugin.URI);
538         if (uri != null) {
539             antObject.setURI(uri);
540         }
541         
542         String JavaDoc library = element.getAttribute(AntCorePlugin.LIBRARY);
543         if (library == null) {
544             IStatus status = new Status(IStatus.ERROR, AntCorePlugin.PI_ANTCORE, AntCorePlugin.ERROR_LIBRARY_NOT_SPECIFIED, NLS.bind(InternalCoreAntMessages.AntCorePreferences_Library_not_specified_for___0__4, new String JavaDoc[]{objectName}), null);
545             AntCorePlugin.getPlugin().getLog().log(status);
546             return;
547         }
548         
549         try {
550             IContributor contributor= element.getContributor();
551             antObject.setPluginLabel(contributor.getName());
552             Bundle bundle = Platform.getBundle(contributor.getName());
553             URL JavaDoc url = FileLocator.toFileURL(bundle.getEntry(library));
554             File JavaDoc urlFile = new File JavaDoc(url.getPath());
555             if (urlFile.exists()) {
556                 url = new URL JavaDoc("file:" + urlFile.getAbsolutePath()); //$NON-NLS-1$
557
addURLToExtraClasspathEntries(url, element);
558                 result.add(antObject);
559                 addPluginClassLoader(bundle);
560                 antObject.setLibraryEntry(new AntClasspathEntry(url));
561                 return;
562             }
563
564             //type specifies a library that does not exist
565
IStatus status = new Status(IStatus.ERROR, AntCorePlugin.PI_ANTCORE, AntCorePlugin.ERROR_LIBRARY_NOT_SPECIFIED, NLS.bind(errorMessage, new String JavaDoc[]{url.toExternalForm(), element.getContributor().getName()}), null);
566             AntCorePlugin.getPlugin().getLog().log(status);
567             return;
568         } catch (MalformedURLException JavaDoc e) {
569             // if the URL does not have a valid format, just log and ignore the exception
570
IStatus status = new Status(IStatus.ERROR, AntCorePlugin.PI_ANTCORE, AntCorePlugin.ERROR_MALFORMED_URL, InternalCoreAntMessages.AntCorePreferences_Malformed_URL__1, e);
571             AntCorePlugin.getPlugin().getLog().log(status);
572             return;
573         } catch (Exception JavaDoc e) {
574             //likely extra classpath entry library that does not exist
575
IStatus status = new Status(IStatus.ERROR, AntCorePlugin.PI_ANTCORE, AntCorePlugin.ERROR_LIBRARY_NOT_SPECIFIED, NLS.bind(InternalCoreAntMessages.AntCorePreferences_8, new String JavaDoc[]{library, element.getContributor().getName()}), null);
576             AntCorePlugin.getPlugin().getLog().log(status);
577             return;
578         }
579     }
580
581     /*
582      * Computes the extra classpath entries defined plug-ins and fragments.
583      */

584     protected void computeDefaultExtraClasspathEntries(List JavaDoc entries) {
585         for (Iterator JavaDoc iterator = entries.iterator(); iterator.hasNext();) {
586             IConfigurationElement element = (IConfigurationElement) iterator.next();
587             if (!relevantRunningHeadless(element)) {
588                 continue;
589             }
590             String JavaDoc library = element.getAttribute(AntCorePlugin.LIBRARY);
591             Bundle bundle = Platform.getBundle(element.getContributor().getName());
592             try {
593                 URL JavaDoc url = FileLocator.toFileURL(bundle.getEntry(library));
594                 File JavaDoc urlFile = new File JavaDoc(url.getPath());
595                 if (urlFile.exists()) {
596                     url = new URL JavaDoc("file:" + urlFile.getAbsolutePath()); //$NON-NLS-1$
597
addURLToExtraClasspathEntries(url, element);
598                     addPluginClassLoader(bundle);
599                 } else {
600                     //extra classpath entry that does not exist
601
IStatus status = new Status(IStatus.ERROR, AntCorePlugin.PI_ANTCORE, AntCorePlugin.ERROR_LIBRARY_NOT_SPECIFIED, NLS.bind(InternalCoreAntMessages.AntCorePreferences_6, new String JavaDoc[]{url.toExternalForm(), element.getContributor().getName()}), null);
602                     AntCorePlugin.getPlugin().getLog().log(status);
603                     continue;
604                 }
605             } catch (MalformedURLException JavaDoc e) {
606                 //if the URL does not have a valid format, just log and ignore the exception
607
IStatus status = new Status(IStatus.ERROR, AntCorePlugin.PI_ANTCORE, AntCorePlugin.ERROR_MALFORMED_URL, InternalCoreAntMessages.AntCorePreferences_Malformed_URL__1, e);
608                 AntCorePlugin.getPlugin().getLog().log(status);
609                 continue;
610             } catch (Exception JavaDoc e) {
611                 //likely extra classpath entry that does not exist
612
IStatus status = new Status(IStatus.ERROR, AntCorePlugin.PI_ANTCORE, AntCorePlugin.ERROR_LIBRARY_NOT_SPECIFIED, NLS.bind(InternalCoreAntMessages.AntCorePreferences_6, new String JavaDoc[]{library, element.getContributor().getName()}), null);
613                 AntCorePlugin.getPlugin().getLog().log(status);
614                 continue;
615             }
616         }
617     }
618     
619     private boolean relevantRunningHeadless(IConfigurationElement element) {
620         if (runningHeadless) {
621             String JavaDoc headless = element.getAttribute(AntCorePlugin.HEADLESS);
622             if (headless != null) {
623                 boolean headlessProperty= Boolean.valueOf(headless).booleanValue();
624                 if (!headlessProperty) {
625                     return false;
626                 }
627             }
628         }
629         return true;
630     }
631     
632     /*
633      * Scan the Ant property extensions for properties to set.
634      *
635      * @since 3.0
636      */

637     private void computeDefaultProperties(List JavaDoc properties) {
638         defaultProperties = new ArrayList JavaDoc(properties.size());
639         for (Iterator JavaDoc iterator = properties.iterator(); iterator.hasNext();) {
640             IConfigurationElement element = (IConfigurationElement) iterator.next();
641             if (!relevantRunningHeadless(element)) {
642                 continue;
643             }
644             String JavaDoc name = element.getAttribute(AntCorePlugin.NAME);
645             if (name == null) {
646                 continue;
647             }
648             String JavaDoc value = element.getAttribute(AntCorePlugin.VALUE);
649             Property property= null;
650             if (value != null) {
651                 property = new Property(name, value);
652                 property.setPluginLabel(element.getContributor().getName());
653             } else {
654                 Bundle bundle= Platform.getBundle(element.getContributor().getName());
655                 if (bundle == null) {
656                     continue;
657                 }
658                 property = new Property();
659                 property.setName(name);
660                 property.setPluginLabel(element.getContributor().getName());
661                 String JavaDoc className = element.getAttribute(AntCorePlugin.CLASS);
662                 property.setValueProvider(className, new WrappedClassLoader(bundle));
663             }
664             defaultProperties.add(property);
665             String JavaDoc runtime = element.getAttribute(AntCorePlugin.ECLIPSE_RUNTIME);
666             if (runtime != null) {
667                 property.setEclipseRuntimeRequired(Boolean.valueOf(runtime).booleanValue());
668             }
669         }
670     }
671
672     /**
673      * Returns the IAntClasspathEntry for the tools.jar associated with the path supplied.
674      * May return <code>null</code> if no tools.jar is found (e.g. the path
675      * points to a JRE install).
676      *
677      * @param javaHomePath path for Java home
678      * @return IAntClasspathEntry tools.jar IAntClasspathEntry or <code>null</code>
679      * @since 3.0
680      */

681     public IAntClasspathEntry getToolsJarEntry(IPath javaHomePath) {
682         if ("jre".equalsIgnoreCase(javaHomePath.lastSegment())) { //$NON-NLS-1$
683
javaHomePath = javaHomePath.removeLastSegments(1);
684         }
685         javaHomePath= javaHomePath.append("lib").append("tools.jar"); //$NON-NLS-1$ //$NON-NLS-2$
686
File JavaDoc tools= javaHomePath.toFile();
687         if (!tools.exists()) {
688             //attempt to find in the older 1.1.*
689
javaHomePath= javaHomePath.removeLastSegments(1);
690             javaHomePath= javaHomePath.append("classes.zip"); //$NON-NLS-1$
691
tools= javaHomePath.toFile();
692             if (!tools.exists()) {
693                 return null;
694             }
695         }
696         
697         return new AntClasspathEntry(tools.getAbsolutePath());
698     }
699
700     /**
701      * Returns the URL for the tools.jar associated with the System property "java.home"
702      * location. If "java.home" has no associated tools.jar (such as a JRE install), the environment variable "JAVA_HOME" is
703      * resolved to check for a tools.jar.
704      * May return <code>null</code> if no tools.jar is found.
705      *
706      * @return URL tools.jar URL or <code>null</code>
707      * @deprecated use getToolsJarEntry()
708      */

709     public URL JavaDoc getToolsJarURL() {
710         IPath path = new Path(System.getProperty("java.home")); //$NON-NLS-1$
711
IAntClasspathEntry entry= getToolsJarEntry(path);
712         if (entry == null) {
713             IDynamicVariable variable = VariablesPlugin.getDefault().getStringVariableManager().getDynamicVariable("env_var"); //$NON-NLS-1$
714
String JavaDoc javaHome= null;
715             try {
716                 if (variable != null) {
717                     javaHome = variable.getValue("JAVA_HOME"); //$NON-NLS-1$
718
}
719                 if (javaHome != null) {
720                     path= new Path(javaHome);
721                     entry= getToolsJarEntry(path);
722                 }
723             } catch (CoreException e) {
724             }
725         }
726         if (entry != null) {
727             return entry.getEntryURL();
728         }
729         return null;
730     }
731     
732     /**
733      * Returns the <code>IAntClasspathEntry</code> for the tools.jar associated with the System property "java.home"
734      * location.
735      * If "java.home" has no associated tools.jar (such as a JRE install), the environment variable "JAVA_HOME" is
736      * resolved to check for a tools.jar.
737      * May return <code>null</code> if no tools.jar is found.
738      *
739      * @return IAntClasspathEntry tools.jar IAntClasspathEntry or <code>null</code>
740      */

741     public IAntClasspathEntry getToolsJarEntry() {
742         IPath path = new Path(System.getProperty("java.home")); //$NON-NLS-1$
743
IAntClasspathEntry entry= getToolsJarEntry(path);
744         if (entry == null) {
745             IDynamicVariable variable = VariablesPlugin.getDefault().getStringVariableManager().getDynamicVariable("env_var"); //$NON-NLS-1$
746
String JavaDoc javaHome= null;
747             try {
748                 if (variable != null) {
749                     javaHome = variable.getValue("JAVA_HOME"); //$NON-NLS-1$
750
}
751                 if (javaHome != null) {
752                     path= new Path(javaHome);
753                     entry= getToolsJarEntry(path);
754                 }
755             } catch (CoreException e) {
756             }
757         }
758         return entry;
759     }
760     
761     /**
762      * Returns the <code>IAntClasspathEntry</code>s for the jars from ${user.home}/.ant/lib
763      * May return <code>null</code> if jars are found.
764      *
765      * TODO Should be promoted to API post 3.1
766      *
767      * @return the collection of <code>IAntClasspathEntry</code> found at ${user.home}/.ant/lib or
768      * <code>null</code> if none found of location does not exist
769      */

770     private List JavaDoc getUserLibraries() {
771         File JavaDoc libDir= new File JavaDoc(System.getProperty("user.home"), ".ant" + File.separatorChar + "lib"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
772
URL JavaDoc[] urls= null;
773         try {
774             urls = getLocationURLs(libDir);
775         } catch (MalformedURLException JavaDoc e) {
776         }
777         if (urls == null) {
778             return null;
779         }
780         
781         List JavaDoc entries= new ArrayList JavaDoc(urls.length);
782         for (int i = 0; i < urls.length; i++) {
783             AntClasspathEntry entry= new AntClasspathEntry(urls[i]);
784             entries.add(entry);
785         }
786         return entries;
787     }
788     
789      private URL JavaDoc[] getLocationURLs(File JavaDoc location) throws MalformedURLException JavaDoc {
790          URL JavaDoc[] urls= null;
791          if (!location.exists()) {
792              return urls;
793          }
794          final String JavaDoc extension= ".jar"; //$NON-NLS-1$
795
if (!location.isDirectory()) {
796              urls = new URL JavaDoc[1];
797              String JavaDoc path= location.getPath();
798              if (path.toLowerCase().endsWith(extension)) {
799                  urls[0]= location.toURL();
800              }
801              return urls;
802          }
803          
804          File JavaDoc[] matches= location.listFiles(
805              new FilenameFilter JavaDoc() {
806                  public boolean accept(File JavaDoc dir, String JavaDoc name) {
807                      return name.toLowerCase().endsWith(extension);
808                  }
809              });
810          
811          urls= new URL JavaDoc[matches.length];
812          for (int i = 0; i < matches.length; ++i) {
813              urls[i] = matches[i].toURL();
814          }
815          return urls;
816      }
817
818     /*
819      * Add the libraries contributed by the Ant plug-in, to the classpath.
820      */

821     private void addLibraries(Bundle source, List JavaDoc destination) {
822         ManifestElement[] libraries = null;
823         try {
824             libraries = ManifestElement.parseHeader(Constants.BUNDLE_CLASSPATH, (String JavaDoc) source.getHeaders("").get(Constants.BUNDLE_CLASSPATH)); //$NON-NLS-1$
825
} catch (BundleException e) {
826             IStatus status = new Status(IStatus.ERROR, AntCorePlugin.PI_ANTCORE, AntCorePlugin.ERROR_MALFORMED_URL, InternalCoreAntMessages.AntCorePreferences_0, e);
827             AntCorePlugin.getPlugin().getLog().log(status);
828             return;
829         }
830         if (libraries == null)
831             return;
832         for (int i = 0; i < libraries.length; i++) {
833             try {
834                 URL JavaDoc url = FileLocator.toFileURL(source.getEntry(libraries[i].getValue()));
835                 File JavaDoc urlFile = new File JavaDoc(url.getPath());
836                 url = new URL JavaDoc("file:" + urlFile.getAbsolutePath()); //$NON-NLS-1$
837
destination.add(new AntClasspathEntry(url));
838             } catch (Exception JavaDoc e) {
839                 // if the URL does not have a valid format, just log and ignore the exception
840
IStatus status = new Status(IStatus.ERROR, AntCorePlugin.PI_ANTCORE, AntCorePlugin.ERROR_MALFORMED_URL, InternalCoreAntMessages.AntCorePreferences_Malformed_URL__1, e);
841                 AntCorePlugin.getPlugin().getLog().log(status);
842             }
843         }
844     }
845
846     protected void addPluginClassLoader(Bundle bundle) {
847         WrappedClassLoader loader = new WrappedClassLoader(bundle);
848         if (!pluginClassLoaders.contains(loader)) {
849             pluginClassLoaders.add(loader);
850         }
851     }
852
853     /**
854      * Returns the list of URLs added to the classpath by the extra classpath
855      * entries extension point.
856      *
857      * @return the list of extra classpath URLs
858      */

859     public URL JavaDoc[] getExtraClasspathURLs() {
860         URL JavaDoc[] urls= new URL JavaDoc[extraClasspathURLs.size()];
861         
862         for (int i = 0; i < extraClasspathURLs.size(); i++) {
863                 IAntClasspathEntry entry = (IAntClasspathEntry) extraClasspathURLs.get(i);
864                 urls[i]= entry.getEntryURL();
865         }
866         return urls;
867     }
868     
869     /**
870      * Returns the list of URLs added to the classpath by the extra classpath
871      * entries extension point for an Ant build that is occurring without the Eclipse runtime.
872      *
873      * @return the list of extra classpath URLs
874      * @since 3.0
875      */

876     public URL JavaDoc[] getRemoteExtraClasspathURLs() {
877         List JavaDoc urls= new ArrayList JavaDoc(extraClasspathURLs.size());
878         
879         for (int i = 0; i < extraClasspathURLs.size(); i++) {
880                 IAntClasspathEntry entry = (IAntClasspathEntry) extraClasspathURLs.get(i);
881                 if (!entry.isEclipseRuntimeRequired()) {
882                     urls.add(entry.getEntryURL());
883                 }
884         }
885         return (URL JavaDoc[])urls.toArray(new URL JavaDoc[urls.size()]);
886     }
887     
888     /**
889      * Returns the entire set of URLs that define the Ant runtime classpath.
890      * Includes the Ant URLs, the additional URLs and extra classpath URLs.
891      *
892      * @return the entire runtime classpath of URLs
893      */

894     public URL JavaDoc[] getURLs() {
895         List JavaDoc result = new ArrayList JavaDoc(60);
896         if (antHomeEntries != null) {
897             addEntryURLs(result, antHomeEntries);
898         }
899         if (additionalEntries != null && additionalEntries.length > 0) {
900             addEntryURLs(result, additionalEntries);
901         }
902         
903         for (int i = 0; i < extraClasspathURLs.size(); i++) {
904             IAntClasspathEntry entry = (IAntClasspathEntry) extraClasspathURLs.get(i);
905             URL JavaDoc url= entry.getEntryURL();
906             if (url != null) {
907                 result.add(url);
908             }
909         }
910         
911         return (URL JavaDoc[]) result.toArray(new URL JavaDoc[result.size()]);
912     }
913
914     private void addEntryURLs(List JavaDoc result, IAntClasspathEntry[] entries) {
915         for (int i = 0; i < entries.length; i++) {
916             IAntClasspathEntry entry = entries[i];
917             URL JavaDoc url= entry.getEntryURL();
918             if (url != null) {
919                 result.add(url);
920             }
921         }
922     }
923
924     protected ClassLoader JavaDoc[] getPluginClassLoaders() {
925         if (orderedPluginClassLoaders == null) {
926             Iterator JavaDoc classLoaders= pluginClassLoaders.iterator();
927             Map JavaDoc idToLoader= new HashMap JavaDoc(pluginClassLoaders.size());
928             List JavaDoc bundles = new ArrayList JavaDoc(pluginClassLoaders.size());
929             while (classLoaders.hasNext()) {
930                 WrappedClassLoader loader = (WrappedClassLoader) classLoaders.next();
931                 idToLoader.put(loader.bundle.getSymbolicName(), loader);
932                 bundles.add(Platform.getPlatformAdmin().getState(false).getBundle(loader.bundle.getBundleId()));
933             }
934             List JavaDoc descriptions = computePrerequisiteOrder(bundles);
935             List JavaDoc loaders = new ArrayList JavaDoc(descriptions.size());
936             for (Iterator JavaDoc iter = descriptions.iterator(); iter.hasNext(); ) {
937                 String JavaDoc id =((BundleDescription) iter.next()).getSymbolicName();
938                 loaders.add(idToLoader.get(id));
939             }
940             orderedPluginClassLoaders = (WrappedClassLoader[]) loaders.toArray(new WrappedClassLoader[loaders.size()]);
941         }
942         return orderedPluginClassLoaders;
943     }
944     
945     /*
946      * Copied from org.eclipse.pde.internal.build.Utils
947      */

948     private List JavaDoc computePrerequisiteOrder(List JavaDoc plugins) {
949         List JavaDoc prereqs = new ArrayList JavaDoc(plugins.size());
950         List JavaDoc fragments = new ArrayList JavaDoc();
951
952         // create a collection of directed edges from plugin to prereq
953
for (Iterator JavaDoc iter = plugins.iterator(); iter.hasNext();) {
954             BundleDescription current = (BundleDescription) iter.next();
955             if (current.getHost() != null) {
956                 fragments.add(current);
957                 continue;
958             }
959             boolean found = false;
960
961             BundleDescription[] prereqList = getDependentBundles(current);
962             for (int j = 0; j < prereqList.length; j++) {
963                 // ensure that we only include values from the original set.
964
if (plugins.contains(prereqList[j])) {
965                     found = true;
966                     prereqs.add(new Relation(current, prereqList[j]));
967                 }
968             }
969
970             // if we didn't find any prereqs for this plugin, add a null prereq
971
// to ensure the value is in the output
972
if (!found) {
973                 prereqs.add(new Relation(current, null));
974             }
975         }
976
977         //The fragments needs to added relatively to their host and to their
978
// own prerequisite (bug #43244)
979
for (Iterator JavaDoc iter = fragments.iterator(); iter.hasNext();) {
980             BundleDescription current = (BundleDescription) iter.next();
981
982             if (plugins.contains(current.getHost().getBundle())) {
983                 prereqs.add(new Relation(current, current.getHost().getSupplier()));
984             } else {
985                 AntCorePlugin.getPlugin().getLog().log(new Status(IStatus.ERROR, AntCorePlugin.PI_ANTCORE, AntCorePlugin.ERROR_MALFORMED_URL, NLS.bind(InternalCoreAntMessages.AntCorePreferences_1, new String JavaDoc[] {current.getSymbolicName()}), null));
986             }
987
988             BundleDescription[] prereqList = getDependentBundles(current);
989             for (int j = 0; j < prereqList.length; j++) {
990                 // ensure that we only include values from the original set.
991
if (plugins.contains(prereqList[j])) {
992                     prereqs.add(new Relation(current, prereqList[j]));
993                 }
994             }
995         }
996
997         // do a topological sort, insert the fragments into the sorted elements
998
return computeNodeOrder(prereqs);
999     }
1000
1001    /*
1002     * Copied from org.eclipse.pde.internal.build.site.PDEState.
1003     */

1004    private BundleDescription[] getDependentBundles(BundleDescription root) {
1005        BundleDescription[] imported = getImportedBundles(root);
1006        BundleDescription[] required = getRequiredBundles(root);
1007        BundleDescription[] dependents = new BundleDescription[imported.length + required.length];
1008        System.arraycopy(imported, 0, dependents, 0, imported.length);
1009        System.arraycopy(required, 0, dependents, imported.length, required.length);
1010        return dependents;
1011    }
1012    
1013    /*
1014     * Copied from org.eclipse.pde.internal.build.site.PDEState.
1015     */

1016    private BundleDescription[] getRequiredBundles(BundleDescription root) {
1017        if (root == null) {
1018            return new BundleDescription[0];
1019        }
1020        return root.getResolvedRequires();
1021    }
1022
1023    /*
1024     * Copied from org.eclipse.pde.internal.build.site.PDEState.
1025     */

1026    private BundleDescription[] getImportedBundles(BundleDescription root) {
1027        if (root == null) {
1028            return new BundleDescription[0];
1029        }
1030        ExportPackageDescription[] packages = root.getResolvedImports();
1031        ArrayList JavaDoc resolvedImports = new ArrayList JavaDoc(packages.length);
1032        for (int i = 0; i < packages.length; i++) {
1033            if (!root.getLocation().equals(packages[i].getExporter().getLocation()) && !resolvedImports.contains(packages[i].getExporter())) {
1034                resolvedImports.add(packages[i].getExporter());
1035            }
1036        }
1037        return (BundleDescription[]) resolvedImports.toArray(new BundleDescription[resolvedImports.size()]);
1038    }
1039
1040    /*
1041     * Copied from org.eclipse.pde.internal.build.Utils
1042     */

1043    private void removeArcs(List JavaDoc edges, List JavaDoc roots, Map JavaDoc counts) {
1044        for (Iterator JavaDoc j = roots.iterator(); j.hasNext();) {
1045            Object JavaDoc root = j.next();
1046            for (int i = 0; i < edges.size(); i++) {
1047                if (root.equals(((Relation) edges.get(i)).to)) {
1048                    Object JavaDoc input = ((Relation) edges.get(i)).from;
1049                    Integer JavaDoc count = (Integer JavaDoc) counts.get(input);
1050                    if (count != null) {
1051                        counts.put(input, new Integer JavaDoc(count.intValue() - 1));
1052                    }
1053                }
1054            }
1055        }
1056    }
1057
1058    /*
1059     * Copied from org.eclipse.pde.internal.build.Utils
1060     */

1061    private List JavaDoc computeNodeOrder(List JavaDoc edges) {
1062        Map JavaDoc counts = computeCounts(edges);
1063        List JavaDoc nodes = new ArrayList JavaDoc(counts.size());
1064        while (!counts.isEmpty()) {
1065            List JavaDoc roots = findRootNodes(counts);
1066            if (roots.isEmpty()) {
1067                break;
1068            }
1069            for (Iterator JavaDoc i = roots.iterator(); i.hasNext();) {
1070                counts.remove(i.next());
1071            }
1072            nodes.addAll(roots);
1073            removeArcs(edges, roots, counts);
1074        }
1075        return nodes;
1076    }
1077
1078    /*
1079     * Copied from org.eclipse.pde.internal.build.Utils
1080     */

1081    private Map JavaDoc computeCounts(List JavaDoc mappings) {
1082        Map JavaDoc counts = new HashMap JavaDoc(5);
1083        for (int i = 0; i < mappings.size(); i++) {
1084            Object JavaDoc from = ((Relation) mappings.get(i)).from;
1085            Integer JavaDoc fromCount = (Integer JavaDoc) counts.get(from);
1086            Object JavaDoc to = ((Relation) mappings.get(i)).to;
1087            if (to == null)
1088                counts.put(from, new Integer JavaDoc(0));
1089            else {
1090                if (((Integer JavaDoc) counts.get(to)) == null)
1091                    counts.put(to, new Integer JavaDoc(0));
1092                fromCount = fromCount == null ? new Integer JavaDoc(1) : new Integer JavaDoc(fromCount.intValue() + 1);
1093                counts.put(from, fromCount);
1094            }
1095        }
1096        return counts;
1097    }
1098
1099    /*
1100     * Copied from org.eclipse.pde.internal.build.Utils
1101     */

1102    private List JavaDoc findRootNodes(Map JavaDoc counts) {
1103        List JavaDoc result = new ArrayList JavaDoc(5);
1104        for (Iterator JavaDoc i = counts.keySet().iterator(); i.hasNext();) {
1105            Object JavaDoc node = i.next();
1106            int count = ((Integer JavaDoc) counts.get(node)).intValue();
1107            if (count == 0) {
1108                result.add(node);
1109            }
1110        }
1111        return result;
1112    }
1113    
1114    private void initializePluginClassLoaders() {
1115        pluginClassLoaders = new ArrayList JavaDoc(10);
1116        // ant.core should always be present
1117
pluginClassLoaders.add(new WrappedClassLoader(AntCorePlugin.getPlugin().getBundle()));
1118    }
1119
1120    /**
1121     * Returns the default and custom tasks.
1122     *
1123     * @return the list of default and custom tasks.
1124     */

1125    public List JavaDoc getTasks() {
1126        List JavaDoc result = new ArrayList JavaDoc(10);
1127        if (defaultTasks != null && !defaultTasks.isEmpty()) {
1128            result.addAll(defaultTasks);
1129        }
1130        if (customTasks != null && customTasks.length != 0) {
1131            result.addAll(Arrays.asList(customTasks));
1132        }
1133        return result;
1134    }
1135    
1136    /**
1137     * Returns the default and custom tasks that are relevant when there is no
1138     * Eclipse runtime context (an Ant build in a separate VM).
1139     *
1140     * @return the list of default and custom tasks.
1141     */

1142    public List JavaDoc getRemoteTasks() {
1143        List JavaDoc result = new ArrayList JavaDoc(10);
1144        if (defaultTasks != null && !defaultTasks.isEmpty()) {
1145            Iterator JavaDoc iter= defaultTasks.iterator();
1146            while (iter.hasNext()) {
1147                Task task = (Task) iter.next();
1148                if (!task.isEclipseRuntimeRequired()) {
1149                    result.add(task);
1150                }
1151            }
1152        }
1153        if (customTasks != null && customTasks.length != 0) {
1154            result.addAll(Arrays.asList(customTasks));
1155        }
1156        return result;
1157    }
1158
1159    /**
1160     * Returns the user defined custom tasks
1161     * @return the user defined tasks
1162     */

1163    public Task[] getCustomTasks() {
1164        return customTasks;
1165    }
1166
1167    /**
1168     * Returns the user defined custom types
1169     * @return the user defined types
1170     */

1171    public Type[] getCustomTypes() {
1172        return customTypes;
1173    }
1174
1175    /**
1176     * Returns the custom user properties specified for Ant builds.
1177     *
1178     * @return the properties defined for Ant builds.
1179     */

1180    public Property[] getCustomProperties() {
1181        return customProperties;
1182    }
1183    
1184    /**
1185     * Returns the default and custom properties.
1186     *
1187     * @return the list of default and custom properties.
1188     * @since 3.0
1189     */

1190    public List JavaDoc getProperties() {
1191        List JavaDoc result = new ArrayList JavaDoc(10);
1192        if (defaultProperties != null && !defaultProperties.isEmpty()) {
1193            result.addAll(defaultProperties);
1194        }
1195        if (customProperties != null && customProperties.length != 0) {
1196            result.addAll(Arrays.asList(customProperties));
1197        }
1198        return result;
1199    }
1200    
1201    /**
1202     * Returns the default and custom properties that are relevant when there is no
1203     * Eclipse runtime context (Ant build in a separate VM).
1204     *
1205     * @return the list of default and custom properties.
1206     * @since 3.0
1207     */

1208    public List JavaDoc getRemoteAntProperties() {
1209        List JavaDoc result = new ArrayList JavaDoc(10);
1210        if (defaultProperties != null && !defaultProperties.isEmpty()) {
1211            Iterator JavaDoc iter= defaultProperties.iterator();
1212            while (iter.hasNext()) {
1213                Property property = (Property) iter.next();
1214                if (!property.isEclipseRuntimeRequired()) {
1215                    result.add(property);
1216                }
1217            }
1218        }
1219        if (customProperties != null && customProperties.length != 0) {
1220            result.addAll(Arrays.asList(customProperties));
1221        }
1222        return result;
1223    }
1224    
1225    /**
1226     * Returns the custom property files specified for Ant builds performing any required
1227     * string substitution if indicated.
1228     *
1229     * @param performStringSubstition whether or not to perform the string substitution on the property file strings
1230     * @return the property files defined for Ant builds.
1231     * @since 3.0
1232     */

1233    public String JavaDoc[] getCustomPropertyFiles(boolean performStringSubstition) {
1234        if (!performStringSubstition || customPropertyFiles == null || customPropertyFiles.length == 0) {
1235            return customPropertyFiles;
1236        }
1237        List JavaDoc files= new ArrayList JavaDoc(customPropertyFiles.length);
1238        for (int i = 0; i < customPropertyFiles.length; i++) {
1239            String JavaDoc filename= customPropertyFiles[i];
1240             try {
1241                filename = VariablesPlugin.getDefault().getStringVariableManager().performStringSubstitution(filename);
1242                files.add(filename);
1243            } catch (CoreException e) {
1244                //notify the user via the Ant console of the missing file
1245
files.add(filename);
1246            }
1247        }
1248        return (String JavaDoc[])files.toArray(new String JavaDoc[files.size()]);
1249    }
1250    
1251    /**
1252     * Returns the custom property files specified for Ant builds.
1253     *
1254     * @return the property files defined for Ant builds.
1255     */

1256    public String JavaDoc[] getCustomPropertyFiles() {
1257        return getCustomPropertyFiles(true);
1258    }
1259    
1260    /**
1261     * Returns the custom URLs specified for the Ant classpath
1262     *
1263     * @return the URLs defining the Ant classpath
1264     * @deprecated
1265     */

1266    public URL JavaDoc[] getCustomURLs() {
1267        URL JavaDoc[] urls= new URL JavaDoc[additionalEntries.length];
1268        int i;
1269        for (i = 0; i < additionalEntries.length; i++) {
1270            URL JavaDoc url = additionalEntries[i].getEntryURL();
1271            if (url != null) {
1272                urls[i]=url;
1273            }
1274        }
1275    
1276        return urls;
1277    }
1278
1279    /**
1280     * Sets the user defined custom tasks.
1281     * To commit the changes, updatePluginPreferences must be
1282     * called.
1283     * @param tasks
1284     */

1285    public void setCustomTasks(Task[] tasks) {
1286        oldCustomTasks= customTasks;
1287        customTasks = tasks;
1288    }
1289
1290    /**
1291     * Sets the user defined custom types.
1292     * To commit the changes, updatePluginPreferences must be
1293     * called.
1294     * @param types The custom types
1295     */

1296    public void setCustomTypes(Type[] types) {
1297        oldCustomTypes= customTypes;
1298        customTypes = types;
1299    }
1300
1301    /**
1302     * Sets the custom URLs specified for the Ant classpath.
1303     * To commit the changes, updatePluginPreferences must be
1304     * called.
1305     *
1306     * @param urls the URLs defining the Ant classpath
1307     * @deprecated use setAdditionalEntries(IAntClasspathEntry)[]
1308     */

1309    public void setCustomURLs(URL JavaDoc[] urls) {
1310        additionalEntries= new IAntClasspathEntry[urls.length];
1311        for (int i = 0; i < urls.length; i++) {
1312            URL JavaDoc url = urls[i];
1313            IAntClasspathEntry entry= new AntClasspathEntry(url);
1314            additionalEntries[i]= entry;
1315        }
1316    }
1317    
1318    /**
1319     * Sets the Ant URLs specified for the Ant classpath. To commit the changes,
1320     * updatePluginPreferences must be called.
1321     *
1322     * @param urls the URLs defining the Ant classpath
1323     * @deprecated use setAntHomeEntires(IAntClasspathEntry[])
1324     */

1325    public void setAntURLs(URL JavaDoc[] urls) {
1326        antHomeEntries= new IAntClasspathEntry[urls.length];
1327        for (int i = 0; i < urls.length; i++) {
1328            URL JavaDoc url = urls[i];
1329            IAntClasspathEntry entry= new AntClasspathEntry(url);
1330            antHomeEntries[i]= entry;
1331        }
1332    }
1333    
1334    /**
1335     * Sets the custom property files specified for Ant builds. To commit the
1336     * changes, updatePluginPreferences must be called.
1337     *
1338     * @param paths the absolute paths defining the property files to use.
1339     */

1340    public void setCustomPropertyFiles(String JavaDoc[] paths) {
1341        customPropertyFiles = paths;
1342    }
1343    
1344    /**
1345     * Sets the custom user properties specified for Ant builds. To commit the
1346     * changes, updatePluginPreferences must be called.
1347     *
1348     * @param properties the properties defining the Ant properties
1349     */

1350    public void setCustomProperties(Property[] properties) {
1351        oldCustomProperties= customProperties;
1352        customProperties = properties;
1353    }
1354
1355    /**
1356     * Returns the default and custom types.
1357     *
1358     * @return all of the defined types
1359     */

1360    public List JavaDoc getTypes() {
1361        List JavaDoc result = new ArrayList JavaDoc(10);
1362        if (defaultTypes != null && !defaultTypes.isEmpty()) {
1363            result.addAll(defaultTypes);
1364        }
1365        if (customTypes != null && customTypes.length != 0) {
1366            result.addAll(Arrays.asList(customTypes));
1367        }
1368        return result;
1369    }
1370    
1371    /**
1372     * Returns the default and custom types that are relevant when there is no
1373     * Eclipse runtime context (an Ant build in a separate VM).
1374     *
1375     * @return the list of default and custom types.
1376     */

1377    public List JavaDoc getRemoteTypes() {
1378        List JavaDoc result = new ArrayList JavaDoc(10);
1379        if (defaultTypes != null && !defaultTypes.isEmpty()) {
1380            Iterator JavaDoc iter= defaultTypes.iterator();
1381            while (iter.hasNext()) {
1382                Type type = (Type) iter.next();
1383                if (!type.isEclipseRuntimeRequired()) {
1384                    result.add(type);
1385                }
1386            }
1387        }
1388        if (customTypes != null && customTypes.length != 0) {
1389            result.addAll(Arrays.asList(customTypes));
1390        }
1391        return result;
1392    }
1393    
1394    /**
1395     * Returns the default types defined via the type extension point
1396     *
1397     * @return all of the default types
1398     */

1399    public List JavaDoc getDefaultTypes() {
1400        List JavaDoc result = new ArrayList JavaDoc(10);
1401        if (defaultTypes != null && !defaultTypes.isEmpty()) {
1402            result.addAll(defaultTypes);
1403        }
1404        return result;
1405    }
1406    
1407    /**
1408     * Returns the default tasks defined via the task extension point
1409     *
1410     * @return all of the default tasks
1411     */

1412    public List JavaDoc getDefaultTasks() {
1413        List JavaDoc result = new ArrayList JavaDoc(10);
1414        if (defaultTasks != null && !defaultTasks.isEmpty()) {
1415            result.addAll(defaultTasks);
1416        }
1417        return result;
1418    }
1419    
1420    /**
1421     * Returns the default properties defined via the properties extension point
1422     *
1423     * @return all of the default properties
1424     * @since 3.0
1425     */

1426    public List JavaDoc getDefaultProperties() {
1427        List JavaDoc result = new ArrayList JavaDoc(10);
1428        if (defaultProperties != null && !defaultProperties.isEmpty()) {
1429            result.addAll(defaultProperties);
1430        }
1431        return result;
1432    }
1433
1434    /*
1435     * Convert a list of tokens into an array using "," as the tokenizer.
1436     */

1437    protected String JavaDoc[] getArrayFromString(String JavaDoc list) {
1438        String JavaDoc separator= ","; //$NON-NLS-1$
1439
if (list == null || list.trim().equals("")) { //$NON-NLS-1$
1440
return new String JavaDoc[0];
1441        }
1442        ArrayList JavaDoc result = new ArrayList JavaDoc();
1443        for (StringTokenizer JavaDoc tokens = new StringTokenizer JavaDoc(list, separator); tokens.hasMoreTokens();) {
1444            String JavaDoc token = tokens.nextToken().trim();
1445            if (!token.equals("")) { //$NON-NLS-1$
1446
result.add(token);
1447            }
1448        }
1449        return (String JavaDoc[]) result.toArray(new String JavaDoc[result.size()]);
1450    }
1451
1452    /**
1453     * Updates the underlying plug-in preferences to the current state.
1454     */

1455    public void updatePluginPreferences() {
1456        Preferences prefs = AntCorePlugin.getPlugin().getPluginPreferences();
1457        prefs.removePropertyChangeListener(this);
1458        updateTasks(prefs);
1459        updateTypes(prefs);
1460        updateAntHomeEntries(prefs);
1461        updateAdditionalEntries(prefs);
1462        updateProperties(prefs);
1463        updatePropertyFiles(prefs);
1464        boolean classpathChanged= AntCorePlugin.getPlugin().getPluginPreferences().needsSaving();
1465        AntCorePlugin.getPlugin().savePluginPreferences();
1466        if (classpathChanged) {
1467            prefs.setValue(IAntCoreConstants.PREFERENCE_CLASSPATH_CHANGED, true);
1468        }
1469        prefs.setValue(IAntCoreConstants.PREFERENCE_CLASSPATH_CHANGED, false);
1470        prefs.addPropertyChangeListener(this);
1471    }
1472
1473    protected void updateTasks(Preferences prefs) {
1474        if (oldCustomTasks != null) {
1475            for (int i = 0; i < oldCustomTasks.length; i++) {
1476                Task oldTask = oldCustomTasks[i];
1477                prefs.setToDefault(IAntCoreConstants.PREFIX_TASK + oldTask.getTaskName());
1478            }
1479            oldCustomTasks= null;
1480        }
1481        
1482        if (customTasks.length == 0) {
1483            prefs.setValue(IAntCoreConstants.PREFERENCE_TASKS, ""); //$NON-NLS-1$
1484
return;
1485        }
1486        StringBuffer JavaDoc tasks = new StringBuffer JavaDoc();
1487        for (int i = 0; i < customTasks.length; i++) {
1488            tasks.append(customTasks[i].getTaskName());
1489            tasks.append(',');
1490            prefs.setValue(IAntCoreConstants.PREFIX_TASK + customTasks[i].getTaskName(), customTasks[i].getClassName() + "," + customTasks[i].getLibraryEntry().getLabel()); //$NON-NLS-1$
1491
}
1492        prefs.setValue(IAntCoreConstants.PREFERENCE_TASKS, tasks.toString());
1493    }
1494
1495    protected void updateTypes(Preferences prefs) {
1496        if (oldCustomTypes != null) {
1497            for (int i = 0; i < oldCustomTypes.length; i++) {
1498                Type oldType = oldCustomTypes[i];
1499                prefs.setToDefault(IAntCoreConstants.PREFIX_TYPE + oldType.getTypeName());
1500            }
1501            oldCustomTypes= null;
1502        }
1503                
1504        if (customTypes.length == 0) {
1505            prefs.setValue(IAntCoreConstants.PREFERENCE_TYPES, ""); //$NON-NLS-1$
1506
return;
1507        }
1508        StringBuffer JavaDoc types = new StringBuffer JavaDoc();
1509        for (int i = 0; i < customTypes.length; i++) {
1510            types.append(customTypes[i].getTypeName());
1511            types.append(',');
1512            prefs.setValue(IAntCoreConstants.PREFIX_TYPE + customTypes[i].getTypeName(), customTypes[i].getClassName() + "," + customTypes[i].getLibraryEntry().getLabel()); //$NON-NLS-1$
1513
}
1514        prefs.setValue(IAntCoreConstants.PREFERENCE_TYPES, types.toString());
1515    }
1516    
1517    protected void updateProperties(Preferences prefs) {
1518        if (oldCustomProperties != null) {
1519            for (int i = 0; i < oldCustomProperties.length; i++) {
1520                Property oldProperty = oldCustomProperties[i];
1521                prefs.setToDefault(IAntCoreConstants.PREFIX_PROPERTY + oldProperty.getName());
1522            }
1523            oldCustomProperties= null;
1524        }
1525        
1526        if (customProperties.length == 0) {
1527            prefs.setValue(IAntCoreConstants.PREFERENCE_PROPERTIES, ""); //$NON-NLS-1$
1528
return;
1529        }
1530        StringBuffer JavaDoc properties = new StringBuffer JavaDoc();
1531        for (int i = 0; i < customProperties.length; i++) {
1532            properties.append(customProperties[i].getName());
1533            properties.append(',');
1534            prefs.setValue(IAntCoreConstants.PREFIX_PROPERTY + customProperties[i].getName(), customProperties[i].getValue(false));
1535        }
1536        prefs.setValue(IAntCoreConstants.PREFERENCE_PROPERTIES, properties.toString());
1537    }
1538
1539    protected void updateAdditionalEntries(Preferences prefs) {
1540        prefs.setValue("urls", ""); //old constant removed //$NON-NLS-1$//$NON-NLS-2$
1541
String JavaDoc serialized= ""; //$NON-NLS-1$
1542
IAntClasspathEntry toolsJarEntry= getToolsJarEntry();
1543        List JavaDoc userLibs= getUserLibraries();
1544        if (userLibs == null) {
1545            userLibs= new ArrayList JavaDoc();
1546        }
1547        if (toolsJarEntry != null) {
1548            userLibs.add(toolsJarEntry);
1549        }
1550        boolean changed= true;
1551        if (additionalEntries.length == userLibs.size()) {
1552            changed= false;
1553            for (int i = 0; i < additionalEntries.length; i++) {
1554                if (!additionalEntries[i].equals(userLibs.get(i))) {
1555                    changed= true;
1556                    break;
1557                }
1558            }
1559        }
1560        if (changed) {
1561            StringBuffer JavaDoc entries = new StringBuffer JavaDoc();
1562            for (int i = 0; i < additionalEntries.length; i++) {
1563                entries.append(additionalEntries[i].getLabel());
1564                entries.append(',');
1565            }
1566            serialized= entries.toString();
1567        }
1568        
1569        prefs.setValue(IAntCoreConstants.PREFERENCE_ADDITIONAL_ENTRIES, serialized);
1570        
1571        String JavaDoc prefAntHome= ""; //$NON-NLS-1$
1572
if (antHome != null && !antHome.equals(getDefaultAntHome())) {
1573            prefAntHome= antHome;
1574        }
1575        prefs.setValue(IAntCoreConstants.PREFERENCE_ANT_HOME, prefAntHome);
1576    }
1577    
1578    protected void updateAntHomeEntries(Preferences prefs) {
1579        prefs.setValue("ant_urls", ""); //old constant removed //$NON-NLS-1$//$NON-NLS-2$
1580

1581        //see if the custom entries are just the default entries
1582
IAntClasspathEntry[] defaultEntries= getDefaultAntHomeEntries();
1583        boolean dflt= false;
1584        if (defaultEntries.length == antHomeEntries.length) {
1585            dflt= true;
1586            for (int i = 0; i < antHomeEntries.length; i++) {
1587                if (!antHomeEntries[i].equals(defaultEntries[i])) {
1588                    dflt= false;
1589                    break;
1590                }
1591            }
1592        }
1593        if (dflt) {
1594            //always want to recalculate the default Ant urls
1595
//to pick up any changes in the default Ant classpath
1596
prefs.setValue(IAntCoreConstants.PREFERENCE_ANT_HOME_ENTRIES, ""); //$NON-NLS-1$
1597
return;
1598        }
1599        StringBuffer JavaDoc entries = new StringBuffer JavaDoc();
1600        for (int i = 0; i < antHomeEntries.length; i++) {
1601            entries.append(antHomeEntries[i].getLabel());
1602            entries.append(',');
1603        }
1604        
1605        prefs.setValue(IAntCoreConstants.PREFERENCE_ANT_HOME_ENTRIES, entries.toString());
1606    }
1607    
1608    protected void updatePropertyFiles(Preferences prefs) {
1609        StringBuffer JavaDoc files = new StringBuffer JavaDoc();
1610        for (int i = 0; i < customPropertyFiles.length; i++) {
1611            files.append(customPropertyFiles[i]);
1612            files.append(',');
1613        }
1614        
1615        prefs.setValue(IAntCoreConstants.PREFERENCE_PROPERTY_FILES, files.toString());
1616    }
1617    
1618    /**
1619     * Sets the string that defines the Ant home set by the user.
1620     * May be set to <code>null</code>.
1621     *
1622     * @param antHome the fully qualified path to Ant home
1623     */

1624    public void setAntHome(String JavaDoc antHome) {
1625        this.antHome= antHome;
1626    }
1627    
1628    /**
1629     * Returns the string that defines the Ant home set by the user or the location
1630     * of the Eclipse Ant plug-in if Ant home has not been specifically set by the user.
1631     * Can return <code>null</code>
1632     *
1633     * @return the fully qualified path to Ant home
1634     */

1635    public String JavaDoc getAntHome() {
1636        return antHome;
1637    }
1638    
1639    /**
1640     * Returns the set of classpath entries that compose the libraries added to the
1641     * Ant runtime classpath from the Ant home location.
1642     *
1643     * @return the set of ant home classpath entries
1644     * @since 3.0
1645     */

1646    public IAntClasspathEntry[] getAntHomeClasspathEntries() {
1647        return antHomeEntries;
1648    }
1649    
1650    /**
1651     * Returns the set of classpath entries that the user has added to the
1652     * Ant runtime classpath.
1653     *
1654     * @return the set of user classpath entries
1655     * @since 3.0
1656     */

1657    public IAntClasspathEntry[] getAdditionalClasspathEntries() {
1658        return additionalEntries;
1659    }
1660    
1661    /**
1662     * Sets the set of classpath entries that compose the libraries added to the
1663     * Ant runtime classpath from the Ant home location.
1664     *
1665     * @param entries the set of ant home classpath entries
1666     * @since 3.0
1667     */

1668    public void setAntHomeClasspathEntries(IAntClasspathEntry[] entries) {
1669        antHomeEntries= entries;
1670    }
1671    
1672    /**
1673     * Sets the set of classpath entries that the user has added to the
1674     * Ant runtime classpath.
1675     *
1676     * @param entries the set of user classpath entries
1677     * @since 3.0
1678     */

1679    public void setAdditionalClasspathEntries(IAntClasspathEntry[] entries) {
1680        additionalEntries= entries;
1681    }
1682
1683    /**
1684     * Returns the list of URLs to added to the classpath for an Ant build that is
1685     * occurring without the Eclipse runtime.
1686     *
1687     * @return the list of classpath entries
1688     * @since 3.0
1689     */

1690    public URL JavaDoc[] getRemoteAntURLs() {
1691        List JavaDoc result = new ArrayList JavaDoc(40);
1692        if (antHomeEntries != null) {
1693            for (int i = 0; i < antHomeEntries.length; i++) {
1694                IAntClasspathEntry entry = antHomeEntries[i];
1695                result.add(entry.getEntryURL());
1696            }
1697        }
1698        if (additionalEntries != null && additionalEntries.length > 0) {
1699            for (int i = 0; i < additionalEntries.length; i++) {
1700                IAntClasspathEntry entry = additionalEntries[i];
1701                result.add(entry.getEntryURL());
1702            }
1703        }
1704        if (extraClasspathURLs != null) {
1705            for (int i = 0; i < extraClasspathURLs.size(); i++) {
1706                IAntClasspathEntry entry = (IAntClasspathEntry) extraClasspathURLs.get(i);
1707                if (!entry.isEclipseRuntimeRequired()) {
1708                    result.add(entry.getEntryURL());
1709                }
1710            }
1711        }
1712        
1713        return (URL JavaDoc[]) result.toArray(new URL JavaDoc[result.size()]);
1714    }
1715    
1716    /**
1717     * Returns all contributed classpath entries via the
1718     * <code>extraClasspathEntries</code> extension point.
1719     *
1720     * @return all contributed classpath entries via the
1721     * <code>extraClasspathEntries</code> extension point
1722     * @since 3.0
1723     */

1724    public IAntClasspathEntry[]getContributedClasspathEntries() {
1725        return (IAntClasspathEntry[]) extraClasspathURLs.toArray(new IAntClasspathEntry[extraClasspathURLs.size()]);
1726    }
1727}
Popular Tags