KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > ant > internal > ui > AntUtil


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  *******************************************************************************/

11 package org.eclipse.ant.internal.ui;
12
13 import java.io.File JavaDoc;
14 import java.io.IOException JavaDoc;
15 import java.net.MalformedURLException JavaDoc;
16 import java.net.URL JavaDoc;
17 import com.ibm.icu.text.MessageFormat;
18 import java.util.ArrayList JavaDoc;
19 import java.util.HashMap JavaDoc;
20 import java.util.Hashtable JavaDoc;
21 import java.util.Iterator JavaDoc;
22 import java.util.List JavaDoc;
23 import java.util.Map JavaDoc;
24 import java.util.StringTokenizer JavaDoc;
25
26 import org.apache.tools.ant.BuildException;
27 import org.apache.tools.ant.Target;
28 import org.apache.tools.ant.util.FileUtils;
29 import org.eclipse.ant.core.AntCorePlugin;
30 import org.eclipse.ant.internal.core.AntCoreUtil;
31 import org.eclipse.ant.internal.ui.editor.AntEditor;
32 import org.eclipse.ant.internal.ui.launchConfigurations.AntHomeClasspathEntry;
33 import org.eclipse.ant.internal.ui.launchConfigurations.IAntLaunchConfigurationConstants;
34 import org.eclipse.ant.internal.ui.launchConfigurations.TaskLinkManager;
35 import org.eclipse.ant.internal.ui.model.AntElementNode;
36 import org.eclipse.ant.internal.ui.model.AntModel;
37 import org.eclipse.ant.internal.ui.model.AntProjectNode;
38 import org.eclipse.ant.internal.ui.model.AntTargetNode;
39 import org.eclipse.ant.internal.ui.model.IAntModel;
40 import org.eclipse.ant.internal.ui.model.LocationProvider;
41 import org.eclipse.core.filebuffers.FileBuffers;
42 import org.eclipse.core.filebuffers.ITextFileBuffer;
43 import org.eclipse.core.filebuffers.ITextFileBufferManager;
44 import org.eclipse.core.filebuffers.LocationKind;
45 import org.eclipse.core.resources.IFile;
46 import org.eclipse.core.resources.IWorkspaceRoot;
47 import org.eclipse.core.resources.ResourcesPlugin;
48 import org.eclipse.core.runtime.CoreException;
49 import org.eclipse.core.runtime.IPath;
50 import org.eclipse.core.runtime.IStatus;
51 import org.eclipse.core.runtime.NullProgressMonitor;
52 import org.eclipse.core.runtime.Path;
53 import org.eclipse.core.runtime.Status;
54 import org.eclipse.core.variables.VariablesPlugin;
55 import org.eclipse.debug.core.ILaunchConfiguration;
56 import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
57 import org.eclipse.debug.core.model.IProcess;
58 import org.eclipse.debug.ui.console.FileLink;
59 import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
60 import org.eclipse.jdt.launching.IRuntimeClasspathEntry;
61 import org.eclipse.jdt.launching.IRuntimeClasspathEntry2;
62 import org.eclipse.jdt.launching.JavaRuntime;
63 import org.eclipse.jface.dialogs.MessageDialog;
64 import org.eclipse.jface.text.BadLocationException;
65 import org.eclipse.jface.text.IDocument;
66 import org.eclipse.jface.text.Region;
67 import org.eclipse.swt.SWT;
68 import org.eclipse.swt.program.Program;
69 import org.eclipse.swt.widgets.Shell;
70 import org.eclipse.ui.IEditorDescriptor;
71 import org.eclipse.ui.IEditorInput;
72 import org.eclipse.ui.IEditorPart;
73 import org.eclipse.ui.IEditorRegistry;
74 import org.eclipse.ui.IWorkbenchPage;
75 import org.eclipse.ui.PartInitException;
76 import org.eclipse.ui.PlatformUI;
77 import org.eclipse.ui.browser.IWebBrowser;
78 import org.eclipse.ui.browser.IWorkbenchBrowserSupport;
79 import org.eclipse.ui.console.IHyperlink;
80 import org.eclipse.ui.externaltools.internal.launchConfigurations.ExternalToolsUtil;
81 import org.eclipse.ui.externaltools.internal.model.ExternalToolBuilder;
82 import org.eclipse.ui.externaltools.internal.model.IExternalToolConstants;
83 import org.eclipse.ui.ide.IDE;
84 import org.eclipse.ui.part.FileEditorInput;
85 import org.eclipse.ui.texteditor.IDocumentProvider;
86 import org.eclipse.ui.texteditor.ITextEditor;
87
88 /**
89  * General utility class dealing with Ant build files
90  */

91 public final class AntUtil {
92     public static final String JavaDoc ATTRIBUTE_SEPARATOR = ","; //$NON-NLS-1$;
93
public static final char ANT_CLASSPATH_DELIMITER= '*';
94     public static final String JavaDoc ANT_HOME_CLASSPATH_PLACEHOLDER= "G"; //$NON-NLS-1$
95
public static final String JavaDoc ANT_GLOBAL_USER_CLASSPATH_PLACEHOLDER= "UG"; //$NON-NLS-1$
96

97     private static String JavaDoc fgBrowserId;
98     
99     /**
100      * No instances allowed
101      */

102     private AntUtil() {
103         super();
104     }
105     
106     /**
107      * Returns a single-string of the strings for storage.
108      *
109      * @param strings the array of strings
110      * @return a single-string representation of the strings or
111      * <code>null</code> if the array is empty.
112      */

113     public static String JavaDoc combineStrings(String JavaDoc[] strings) {
114         if (strings.length == 0)
115             return null;
116
117         if (strings.length == 1)
118             return strings[0];
119
120         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
121         for (int i = 0; i < strings.length - 1; i++) {
122             buf.append(strings[i]);
123             buf.append(ATTRIBUTE_SEPARATOR);
124         }
125         buf.append(strings[strings.length - 1]);
126         return buf.toString();
127     }
128
129     /**
130      * Returns an array of targets to be run, or <code>null</code> if none are
131      * specified (indicating the default target or implicit target should be run).
132      *
133      * @param configuration launch configuration
134      * @return array of target names, or <code>null</code>
135      * @throws CoreException if unable to access the associated attribute
136      */

137     public static String JavaDoc[] getTargetNames(ILaunchConfiguration configuration) throws CoreException {
138         String JavaDoc attribute= null;
139         if (IAntLaunchConfigurationConstants.ID_ANT_BUILDER_LAUNCH_CONFIGURATION_TYPE.equals(configuration.getType().getIdentifier())) {
140             attribute= getTargetNamesForAntBuilder(configuration);
141         }
142         if (attribute == null) {
143             attribute = configuration.getAttribute(IAntLaunchConfigurationConstants.ATTR_ANT_TARGETS, (String JavaDoc) null);
144             if (attribute == null) {
145                 return null;
146             }
147         }
148         
149         return AntUtil.parseRunTargets(attribute);
150     }
151     
152     private static String JavaDoc getTargetNamesForAntBuilder(ILaunchConfiguration configuration) throws CoreException {
153         String JavaDoc buildType= ExternalToolBuilder.getBuildType();
154         String JavaDoc targets= null;
155         if (IExternalToolConstants.BUILD_TYPE_AUTO.equals(buildType)) {
156             targets= configuration.getAttribute(IAntLaunchConfigurationConstants.ATTR_ANT_AUTO_TARGETS, (String JavaDoc)null);
157         } else if (IExternalToolConstants.BUILD_TYPE_CLEAN.equals(buildType)) {
158             targets = configuration.getAttribute(IAntLaunchConfigurationConstants.ATTR_ANT_CLEAN_TARGETS, (String JavaDoc) null);
159         } else if (IExternalToolConstants.BUILD_TYPE_FULL.equals(buildType)) {
160             targets = configuration.getAttribute(IAntLaunchConfigurationConstants.ATTR_ANT_AFTER_CLEAN_TARGETS, (String JavaDoc) null);
161         } else if (IExternalToolConstants.BUILD_TYPE_INCREMENTAL.equals(buildType)) {
162             targets = configuration.getAttribute(IAntLaunchConfigurationConstants.ATTR_ANT_MANUAL_TARGETS, (String JavaDoc) null);
163         }
164        
165         return targets;
166     }
167
168     /**
169      * Returns a map of properties to be defined for the build, or
170      * <code>null</code> if none are specified (indicating no additional
171      * properties specified for the build).
172      *
173      * @param configuration launch configuration
174      * @return map of properties (name --> value), or <code>null</code>
175      * @throws CoreException if unable to access the associated attribute
176      */

177     public static Map JavaDoc getProperties(ILaunchConfiguration configuration) throws CoreException {
178         Map JavaDoc map = configuration.getAttribute(IAntLaunchConfigurationConstants.ATTR_ANT_PROPERTIES, (Map JavaDoc) null);
179         return map;
180     }
181     
182     /**
183      * Returns a String specifying the Ant home to use for the build.
184      *
185      * @param configuration launch configuration
186      * @return String specifying Ant home to use or <code>null</code>
187      * @throws CoreException if unable to access the associated attribute
188      */

189     public static String JavaDoc getAntHome(ILaunchConfiguration configuration) throws CoreException {
190         IRuntimeClasspathEntry[] entries = JavaRuntime.computeUnresolvedRuntimeClasspath(configuration);
191         for (int i = 0; i < entries.length; i++) {
192             IRuntimeClasspathEntry entry = entries[i];
193             if (entry.getType() == IRuntimeClasspathEntry.OTHER) {
194                 IRuntimeClasspathEntry2 entry2 = (IRuntimeClasspathEntry2)entry;
195                 if (entry2.getTypeId().equals(AntHomeClasspathEntry.TYPE_ID)) {
196                     return ((AntHomeClasspathEntry)entry2).getAntHome();
197                 }
198             }
199         }
200         return null;
201     }
202
203     /**
204      * Returns an array of property files to be used for the build, or
205      * <code>null</code> if none are specified (indicating no additional
206      * property files specified for the build).
207      *
208      * @param configuration launch configuration
209      * @return array of property file names, or <code>null</code>
210      * @throws CoreException if unable to access the associated attribute
211      */

212     public static String JavaDoc[] getPropertyFiles(ILaunchConfiguration configuration) throws CoreException {
213         String JavaDoc attribute = configuration.getAttribute(IAntLaunchConfigurationConstants.ATTR_ANT_PROPERTY_FILES, (String JavaDoc) null);
214         if (attribute == null) {
215             return null;
216         }
217         String JavaDoc[] propertyFiles= AntUtil.parseString(attribute, ","); //$NON-NLS-1$
218
for (int i = 0; i < propertyFiles.length; i++) {
219             String JavaDoc propertyFile = propertyFiles[i];
220             propertyFile= expandVariableString(propertyFile, AntUIModelMessages.AntUtil_6);
221             propertyFiles[i]= propertyFile;
222         }
223         return propertyFiles;
224     }
225     
226     public static AntTargetNode[] getTargets(String JavaDoc path, ILaunchConfiguration config) throws CoreException {
227         File JavaDoc buildfile= getBuildFile(path);
228         if (buildfile == null) {
229             return null;
230         }
231         URL JavaDoc[] urls= getCustomClasspath(config);
232         //no lexical, no position, no task
233
IAntModel model= getAntModel(buildfile, urls, false, false, false);
234         
235         model.setProperties(getAllProperties(config));
236         model.setPropertyFiles(getPropertyFiles(config));
237         AntProjectNode project= model.getProjectNode(); //forces a reconcile
238
model.dispose();
239         return getTargets(project);
240     }
241     
242     private static Map JavaDoc getAllProperties(ILaunchConfiguration config) throws CoreException {
243         String JavaDoc[] arguments = ExternalToolsUtil.getArguments(config);
244         Map JavaDoc properties= new HashMap JavaDoc();
245         if (arguments != null) {
246             AntCoreUtil.processMinusDProperties(AntCoreUtil.getArrayList(arguments), properties);
247         }
248         Map JavaDoc configProperties= getProperties(config);
249         if (configProperties != null) {
250             Iterator JavaDoc keys= configProperties.keySet().iterator();
251             while (keys.hasNext()) {
252                 String JavaDoc name = (String JavaDoc) keys.next();
253                 if (properties.get(name) == null) {
254                     properties.put(name, configProperties.get(name));
255                 }
256             }
257         }
258         return properties;
259     }
260
261     private static AntTargetNode[] getTargets(AntProjectNode project) {
262         if (project == null || !project.hasChildren()) {
263             return null;
264         }
265         List JavaDoc targets= new ArrayList JavaDoc();
266         Iterator JavaDoc possibleTargets= project.getChildNodes().iterator();
267         while (possibleTargets.hasNext()) {
268             AntElementNode node= (AntElementNode)possibleTargets.next();
269             if (node instanceof AntTargetNode) {
270                 targets.add(node);
271             }
272         }
273         if (targets.size() == 0) {
274             return null;
275         }
276         return (AntTargetNode[])targets.toArray(new AntTargetNode[targets.size()]);
277     }
278
279     public static AntTargetNode[] getTargets(String JavaDoc path) {
280         File JavaDoc buildfile= getBuildFile(path);
281         if (buildfile == null) {
282             return null;
283         }
284         //tasks and position info but no lexical info
285
IAntModel model= getAntModel(buildfile, null, false, true, true);
286         AntProjectNode project= model.getProjectNode();
287         if (project == null) {
288             model.dispose();
289             return null;
290         }
291         AntTargetNode[] targets= getTargets(project);
292         if (targets == null) {
293             Hashtable JavaDoc antTargets= project.getProject().getTargets();
294             Target implicitTarget= (Target) antTargets.get(""); //$NON-NLS-1$
295
if (implicitTarget != null) {
296                 AntTargetNode implicitTargetNode= new AntTargetNode(implicitTarget);
297                 project.addChildNode(implicitTargetNode);
298                 return new AntTargetNode[] {implicitTargetNode};
299             }
300         }
301         return targets;
302     }
303     
304     public static IAntModel getAntModel(String JavaDoc buildFilePath, boolean needsLexicalResolution, boolean needsPositionResolution, boolean needsTaskResolution) {
305         IAntModel model= getAntModel(getBuildFile(buildFilePath), null, needsLexicalResolution, needsPositionResolution, needsTaskResolution);
306         return model;
307     }
308     
309     /**
310      * Return a buildfile from the specified location.
311      * If there isn't one return null.
312      */

313     private static File JavaDoc getBuildFile(String JavaDoc path) {
314         File JavaDoc buildFile = new File JavaDoc(path);
315         if (!buildFile.isFile() || !buildFile.exists()) {
316             return null;
317         }
318
319         return buildFile;
320     }
321     
322     private static IAntModel getAntModel(final File JavaDoc buildFile, URL JavaDoc[] urls, boolean needsLexical, boolean needsPosition, boolean needsTask) {
323         if (buildFile == null || !buildFile.exists()) {
324             return null;
325         }
326         IDocument doc= getDocument(buildFile);
327         if (doc == null) {
328             return null;
329         }
330         final IFile file= getFileForLocation(buildFile.getAbsolutePath(), null);
331         LocationProvider provider= new LocationProvider(null) {
332             /* (non-Javadoc)
333              * @see org.eclipse.ant.internal.ui.model.LocationProvider#getFile()
334              */

335             public IFile getFile() {
336                 return file;
337             }
338             /* (non-Javadoc)
339              * @see org.eclipse.ant.internal.ui.model.LocationProvider#getLocation()
340              */

341             public IPath getLocation() {
342                 if (file == null) {
343                     return new Path(buildFile.getAbsolutePath());
344                 }
345                 return file.getLocation();
346             }
347         };
348         IAntModel model= new AntModel(doc, null, provider, needsLexical, needsPosition, needsTask);
349         
350         if (urls != null) {
351             model.setClassLoader(AntCorePlugin.getPlugin().getNewClassLoader(urls));
352         }
353         return model;
354     }
355     
356     private static IDocument getDocument(File JavaDoc buildFile) {
357         ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager();
358         IPath location= new Path(buildFile.getAbsolutePath());
359         boolean connected= false;
360         try {
361             ITextFileBuffer buffer= manager.getTextFileBuffer(location, LocationKind.NORMALIZE);
362             if (buffer == null) {
363                 //no existing file buffer..create one
364
manager.connect(location, LocationKind.NORMALIZE, new NullProgressMonitor());
365                 connected= true;
366                 buffer= manager.getTextFileBuffer(location, LocationKind.NORMALIZE);
367                 if (buffer == null) {
368                     return null;
369                 }
370             }
371             
372             return buffer.getDocument();
373         } catch (CoreException ce) {
374             AntUIPlugin.log(ce.getStatus());
375             return null;
376         } finally {
377             if (connected) {
378                 try {
379                     manager.disconnect(location, LocationKind.NORMALIZE, new NullProgressMonitor());
380                 } catch (CoreException e) {
381                     AntUIPlugin.log(e.getStatus());
382                 }
383             }
384         }
385     }
386     
387     /**
388      * Returns the list of URLs that define the custom classpath for the Ant
389      * build, or <code>null</code> if the global classpath is to be used.
390      *
391      * @param config launch configuration
392      * @return a list of <code>URL</code>
393      *
394      * @throws CoreException if file does not exist, IO problems, or invalid format.
395      */

396     public static URL JavaDoc[] getCustomClasspath(ILaunchConfiguration config) throws CoreException {
397         boolean useDefault = config.getAttribute(IJavaLaunchConfigurationConstants.ATTR_DEFAULT_CLASSPATH, true);
398         if (useDefault) {
399             return null;
400         }
401         IRuntimeClasspathEntry[] unresolved = JavaRuntime.computeUnresolvedRuntimeClasspath(config);
402         // don't consider bootpath entries
403
List JavaDoc userEntries = new ArrayList JavaDoc(unresolved.length);
404         for (int i = 0; i < unresolved.length; i++) {
405             IRuntimeClasspathEntry entry = unresolved[i];
406             if (entry.getClasspathProperty() == IRuntimeClasspathEntry.USER_CLASSES) {
407                 userEntries.add(entry);
408             }
409         }
410         IRuntimeClasspathEntry[] entries = JavaRuntime.resolveRuntimeClasspath((IRuntimeClasspathEntry[])userEntries.toArray(new IRuntimeClasspathEntry[userEntries.size()]), config);
411         URL JavaDoc[] urls = new URL JavaDoc[entries.length];
412         for (int i = 0; i < entries.length; i++) {
413             IRuntimeClasspathEntry entry = entries[i];
414             try {
415                 urls[i] = new URL JavaDoc("file:"+entry.getLocation()); //$NON-NLS-1$
416
} catch (MalformedURLException JavaDoc e) {
417                 throw new CoreException(new Status(IStatus.ERROR, AntUIPlugin.getUniqueIdentifier(), AntUIPlugin.INTERNAL_ERROR, AntUIModelMessages.AntUtil_7, e));
418             }
419         }
420         return urls;
421     }
422
423     private static String JavaDoc expandVariableString(String JavaDoc variableString, String JavaDoc invalidMessage) throws CoreException {
424         String JavaDoc expandedString = VariablesPlugin.getDefault().getStringVariableManager().performStringSubstitution(variableString);
425         if (expandedString == null || expandedString.length() == 0) {
426             String JavaDoc msg = MessageFormat.format(invalidMessage, new String JavaDoc[] {variableString});
427             throw new CoreException(new Status(IStatus.ERROR, IAntUIConstants.PLUGIN_ID, 0, msg, null));
428         }
429         
430         return expandedString;
431     }
432     
433     /**
434      * Returns the list of target names to run
435      *
436      * @param extraAttibuteValue the external tool's extra attribute value
437      * for the run targets key.
438      * @return a list of target names
439      */

440     public static String JavaDoc[] parseRunTargets(String JavaDoc extraAttibuteValue) {
441         return parseString(extraAttibuteValue, ATTRIBUTE_SEPARATOR);
442     }
443     
444     /**
445      * Returns the list of Strings that were delimiter separated.
446      *
447      * @param delimString the String to be tokenized based on the delimiter
448      * @return a list of Strings
449      */

450     public static String JavaDoc[] parseString(String JavaDoc delimString, String JavaDoc delim) {
451         if (delimString == null) {
452             return new String JavaDoc[0];
453         }
454         
455         // Need to handle case where separator character is
456
// actually part of the target name!
457
StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(delimString, delim);
458         String JavaDoc[] results = new String JavaDoc[tokenizer.countTokens()];
459         for (int i = 0; i < results.length; i++) {
460             results[i] = tokenizer.nextToken();
461         }
462         
463         return results;
464     }
465     
466     /**
467      * Returns an IFile with the given fully qualified path (relative to the workspace root).
468      * The returned IFile may or may not exist.
469      */

470     public static IFile getFile(String JavaDoc fullPath) {
471         IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
472         return root.getFile(new Path(fullPath));
473     }
474
475     public static IHyperlink getLocationLink(String JavaDoc path, File JavaDoc buildFileParent) {
476         path = path.trim();
477         if (path.length() == 0) {
478             return null;
479         }
480         if (path.startsWith("file:")) { //$NON-NLS-1$
481
// remove "file:"
482
path= path.substring(5, path.length());
483         }
484         // format is file:F:L: where F is file path, and L is line number
485
int index = path.lastIndexOf(':');
486         if (index == -1) {
487             //incorrect format
488
return null;
489         }
490         if (index == path.length() - 1) {
491             // remove trailing ':'
492
path = path.substring(0, index);
493             index = path.lastIndexOf(':');
494         }
495         // split file and line number
496
String JavaDoc fileName = path.substring(0, index);
497         try {
498             String JavaDoc lineNumber = path.substring(index + 1);
499             int line = Integer.parseInt(lineNumber);
500             IFile file = getFileForLocation(fileName, buildFileParent);
501             if (file != null) {
502                 return new FileLink(file, null, -1, -1, line);
503             }
504         } catch (NumberFormatException JavaDoc e) {
505         }
506         
507         return null;
508     }
509
510     /**
511      * Returns the workspace file associated with the given path in the
512      * local file system, or <code>null</code> if none.
513      * If the path happens to be a relative path, then the path is interpreted as
514      * relative to the specified parent file.
515      *
516      * Attempts to handle linked files; the first found linked file with the correct
517      * path is returned.
518      *
519      * @param path
520      * @param buildFileParent
521      * @return file or <code>null</code>
522      * @see org.eclipse.core.resources.IWorkspaceRoot#findFilesForLocation(IPath)
523      */

524     public static IFile getFileForLocation(String JavaDoc path, File JavaDoc buildFileParent) {
525         if (path == null) {
526             return null;
527         }
528         IPath filePath= new Path(path);
529         IFile file = null;
530         IFile[] files= ResourcesPlugin.getWorkspace().getRoot().findFilesForLocation(filePath);
531         if (files.length > 0) {
532             file= files[0];
533         }
534         if (file == null) {
535             //relative path
536
File JavaDoc relativeFile= null;
537             try {
538                 //this call is ok if buildFileParent is null
539
relativeFile= FileUtils.getFileUtils().resolveFile(buildFileParent, path);
540                 filePath= new Path(relativeFile.getAbsolutePath());
541                 files= ResourcesPlugin.getWorkspace().getRoot().findFilesForLocation(filePath);
542                 if (files.length > 0) {
543                     file= files[0];
544                 } else {
545                     return null;
546                 }
547             } catch (BuildException be) {
548                 return null;
549             }
550         }
551         
552         if (file.exists()) {
553             return file;
554         }
555         File JavaDoc ioFile= file.getLocation().toFile();
556         if (ioFile.exists()) {//needs to handle case insensitivity on WINOS
557
try {
558                 files= ResourcesPlugin.getWorkspace().getRoot().findFilesForLocation(new Path(ioFile.getCanonicalPath()));
559                 if (files.length > 0) {
560                     return files[0];
561                 }
562             } catch (IOException JavaDoc e) {
563             }
564         }
565             
566         return null;
567     }
568
569     /**
570      * Migrates the classpath in the given configuration from the old format
571      * to the new format. The old format is not preserved. Instead, the default
572      * classpath will be used. However, ANT_HOME settings are preserved.
573      *
574      * @param configuration a configuration to migrate
575      * @throws CoreException if unable to migrate
576      * @since 3.0
577      */

578     public static void migrateToNewClasspathFormat(ILaunchConfiguration configuration) throws CoreException {
579         String JavaDoc oldClasspath = configuration.getAttribute(IAntLaunchConfigurationConstants.ATTR_ANT_CUSTOM_CLASSPATH, (String JavaDoc)null);
580         String JavaDoc oldAntHome = configuration.getAttribute(IAntLaunchConfigurationConstants.ATTR_ANT_HOME, (String JavaDoc)null);
581         String JavaDoc provider = configuration.getAttribute(IJavaLaunchConfigurationConstants.ATTR_CLASSPATH_PROVIDER, (String JavaDoc)null);
582         if (oldClasspath != null || oldAntHome != null || provider == null) {
583             ILaunchConfigurationWorkingCopy workingCopy = null;
584             if (configuration.isWorkingCopy()) {
585                 workingCopy = (ILaunchConfigurationWorkingCopy) configuration;
586             } else {
587                 workingCopy = configuration.getWorkingCopy();
588             }
589             workingCopy.setAttribute(IAntLaunchConfigurationConstants.ATTR_ANT_CUSTOM_CLASSPATH, (String JavaDoc)null);
590             workingCopy.setAttribute(IAntLaunchConfigurationConstants.ATTR_ANT_HOME, (String JavaDoc)null);
591             workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_CLASSPATH_PROVIDER, "org.eclipse.ant.ui.AntClasspathProvider"); //$NON-NLS-1$
592
workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_DEFAULT_CLASSPATH, true);
593             if (oldAntHome != null) {
594                 IRuntimeClasspathEntry[] entries = JavaRuntime.computeUnresolvedRuntimeClasspath(workingCopy);
595                 List JavaDoc mementos = new ArrayList JavaDoc(entries.length);
596                 for (int i = 0; i < entries.length; i++) {
597                     IRuntimeClasspathEntry entry = entries[i];
598                     if (entry.getType() == IRuntimeClasspathEntry.OTHER) {
599                         IRuntimeClasspathEntry2 entry2 = (IRuntimeClasspathEntry2) entry;
600                         if (entry2.getTypeId().equals(AntHomeClasspathEntry.TYPE_ID)) {
601                             AntHomeClasspathEntry homeEntry = new AntHomeClasspathEntry(oldAntHome);
602                             mementos.add(homeEntry.getMemento());
603                             continue;
604                         }
605                     }
606                     mementos.add(entry.getMemento());
607                 }
608                 workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_DEFAULT_CLASSPATH, false);
609                 workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_CLASSPATH, mementos);
610             }
611             workingCopy.doSave();
612         }
613     }
614
615     private static int getOffset(int line, int column, ITextEditor editor) {
616         IDocumentProvider provider= editor.getDocumentProvider();
617         IEditorInput input= editor.getEditorInput();
618         try {
619             provider.connect(input);
620         } catch (CoreException e) {
621             return -1;
622         }
623         try {
624             IDocument document= provider.getDocument(input);
625             if (document != null) {
626                 if (column > -1) {
627                      //column marks the length..adjust to 0 index and to be within the element's source range
628
return document.getLineOffset(line - 1) + column - 1 - 2;
629                 }
630                 return document.getLineOffset(line - 1);
631             }
632         } catch (BadLocationException e) {
633         } finally {
634             provider.disconnect(input);
635         }
636         return -1;
637     }
638
639     /**
640      * Opens the given editor on the buildfile of the provided node and selects that node in the editor.
641      *
642      * @param page the page to open the editor in
643      * @param editorDescriptor the editor descriptor, or <code>null</code> for the system editor
644      * @param node the node from the buildfile to open and then select in the editor
645      */

646     public static void openInEditor(IWorkbenchPage page, IEditorDescriptor editorDescriptor, AntElementNode node) {
647         IEditorPart editorPart= null;
648         IFile fileResource = node.getIFile();
649         try {
650             if (editorDescriptor == null) {
651                 editorPart= page.openEditor(new FileEditorInput(fileResource), IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID);
652             } else {
653                 editorPart= page.openEditor(new FileEditorInput(fileResource), editorDescriptor.getId());
654             }
655         } catch (PartInitException e) {
656             AntUIPlugin.log(MessageFormat.format(AntUIModelMessages.AntUtil_0, new String JavaDoc[]{fileResource.getLocation().toOSString()}), e);
657         }
658         
659         if (editorPart instanceof AntEditor) {
660             AntEditor editor= (AntEditor)editorPart;
661             if (node.getImportNode() != null) {
662                 AntModel model= editor.getAntModel();
663                 AntProjectNode project= model.getProjectNode();
664                 if (project == null) {
665                     return;
666                 }
667                 int[] info= node.getExternalInfo();
668                 int offset= getOffset(info[0], info[1], editor);
669                 node= project.getNode(offset);
670             }
671             editor.setSelection(node, true);
672         }
673     }
674
675     /**
676      * Opens an editor on the buildfile of the provided node and selects that node in the editor.
677      *
678      * @param page the page to open the editor in
679      * @param node the node from the buildfile to open and then select in the editor
680      */

681     public static void openInEditor(IWorkbenchPage page, AntElementNode node) {
682         IFile file= node.getIFile();
683         IEditorDescriptor editorDesc;
684         try {
685             editorDesc = IDE.getEditorDescriptor(file);
686         } catch (PartInitException e) {
687            return;
688         }
689         openInEditor(page, editorDesc, node);
690     }
691     
692     /**
693      * Opens an external browser on the provided <code>urlString</code>
694      * @param urlString The url to open
695      * @param shell the shell
696      * @param errorDialogTitle the title of any error dialog
697      */

698     public static void openBrowser(final String JavaDoc urlString, final Shell shell, final String JavaDoc errorDialogTitle) {
699         shell.getDisplay().syncExec(new Runnable JavaDoc() {
700             public void run() {
701                 IWorkbenchBrowserSupport support= PlatformUI.getWorkbench().getBrowserSupport();
702                 try {
703                     IWebBrowser browser= support.createBrowser(fgBrowserId);
704                     fgBrowserId= browser.getId();
705                     browser.openURL(new URL JavaDoc(urlString));
706                     return;
707                 } catch (PartInitException e) {
708                     AntUIPlugin.log(e.getStatus());
709                 } catch (MalformedURLException JavaDoc e) {
710                     AntUIPlugin.log(e);
711                 }
712                 
713                 String JavaDoc platform= SWT.getPlatform();
714                 boolean succeeded= true;
715                 if ("motif".equals(platform) || "gtk".equals(platform)) { //$NON-NLS-1$ //$NON-NLS-2$
716
Program program= Program.findProgram("html"); //$NON-NLS-1$
717
if (program == null) {
718                         program= Program.findProgram("htm"); //$NON-NLS-1$
719
}
720                     if (program != null) {
721                         succeeded= program.execute(urlString.toString());
722                     }
723                 } else {
724                     succeeded= Program.launch(urlString.toString());
725                 }
726                 if (!succeeded) {
727                     MessageDialog.openInformation(shell, errorDialogTitle, AntUIModelMessages.AntUtil_1);
728                 }
729             }
730         });
731     }
732     
733     public static boolean isSeparateJREAntBuild(ILaunchConfiguration configuration) {
734         boolean separateJRE= true;
735         try {
736             //always null for same JRE
737
separateJRE = configuration.getAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, (String JavaDoc)null) != null;
738         } catch (CoreException e) {
739             AntUIPlugin.log(AntUIModelMessages.AntUtil_2, e);
740         }
741         
742         return separateJRE;
743     }
744     
745     public static void linkBuildFailedMessage(String JavaDoc message, IProcess process) {
746         String JavaDoc fileName = null;
747         String JavaDoc lineNumber = ""; //$NON-NLS-1$
748
int fileStart = 0;
749         int index = message.indexOf("xml"); //$NON-NLS-1$
750
if (index > 0) {
751             int numberStart= index + 4;
752             int numberEnd= message.indexOf(':', numberStart);
753             int fileEnd = index + 3;
754             if (numberStart > 0 && fileEnd > 0) {
755                 fileName = message.substring(fileStart, fileEnd).trim();
756                 if (numberEnd > 0) {
757                     lineNumber = message.substring(numberStart, numberEnd).trim();
758                 }
759             }
760         }
761         
762         if (fileName != null) {
763             int num = -1;
764             try {
765                 num = Integer.parseInt(lineNumber);
766             } catch (NumberFormatException JavaDoc e) {
767             }
768             IFile[] files = ResourcesPlugin.getWorkspace().getRoot().findFilesForLocation(new Path(fileName));
769             IFile file= null;
770             if (files.length > 0) {
771                 file= files[0];
772             }
773             if (file != null && file.exists()) {
774                 FileLink link = new FileLink(file, null, -1, -1, num);
775                 TaskLinkManager.addTaskHyperlink(process, link, new Region(0, message.length()), message);
776             }
777         }
778     }
779 }
Popular Tags