Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Copyright (c) 2000, 2009 IBM Corporation and others. All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/epl-v10.html Contributors: IBM Corporation - initial API and implementation /
 
 package org.eclipse.ant.internal.ui;
 
 import java.io.File;
 import java.net.URL;
 import java.util.List;
 import java.util.Map;
 
 import  org.apache.tools.ant.BuildException;
 import  org.apache.tools.ant.Target;
 import  org.apache.tools.ant.util.FileUtils;
 import  org.eclipse.swt.SWT;
 import  org.eclipse.swt.program.Program;
 import  org.eclipse.swt.widgets.Shell;
 
General utility class dealing with Ant build files
 
 public final class AntUtil {
 	public static final String ATTRIBUTE_SEPARATOR = ","//$NON-NLS-1$;
 	public static final char ANT_CLASSPATH_DELIMITER'*';
 	public static final String ANT_HOME_CLASSPATH_PLACEHOLDER"G"//$NON-NLS-1$
 	public static final String ANT_GLOBAL_USER_CLASSPATH_PLACEHOLDER"UG"//$NON-NLS-1$
 	
	private static String fgBrowserId;

No instances allowed
	private AntUtil() {
		super();
	}

Returns a single-string of the strings for storage.

Parameters:
strings the array of strings
Returns:
a single-string representation of the strings or null if the array is empty.
	public static String combineStrings(String[] strings) {
		if (strings.length == 0)
			return null;
		if (strings.length == 1)
			return strings[0];
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < strings.length - 1; i++) {
			buf.append(strings[i]);
		}
		buf.append(strings[strings.length - 1]);
		return buf.toString();
	}

Returns an array of targets to be run, or null if none are specified (indicating the default target or implicit target should be run).

Parameters:
configuration launch configuration
Returns:
array of target names, or null
Throws:
CoreException if unable to access the associated attribute
	public static String[] getTargetNames(ILaunchConfiguration configurationthrows CoreException {
        String attributenull;
            attributegetTargetNamesForAntBuilder(configuration);
        }
        if (attribute == null) {
            attribute = configuration.getAttribute(., (Stringnull);
            if (attribute == null) {
                return null;
            } 
        }
		return AntUtil.parseRunTargets(attribute);
	}
	private static String getTargetNamesForAntBuilder(ILaunchConfiguration configurationthrows CoreException {
        String buildType= ExternalToolBuilder.getBuildType();
        String targetsnull;
        if (..equals(buildType)) {
            targetsconfiguration.getAttribute(., (String)null);
        } else if (..equals(buildType)) {
            targets = configuration.getAttribute(., (Stringnull);
        } else if (..equals(buildType)) {
            targets = configuration.getAttribute(., (Stringnull);
        } else if (..equals(buildType)) {
            targets = configuration.getAttribute(., (Stringnull);
        }
       
        return targets;
    }

    
Returns a map of properties to be defined for the build, or null if none are specified (indicating no additional properties specified for the build).

Parameters:
configuration launch configuration
Returns:
map of properties (name --> value), or null
Throws:
CoreException if unable to access the associated attribute
	public static Map getProperties(ILaunchConfiguration configurationthrows CoreException {
		return map;
	}

Returns a String specifying the Ant home to use for the build.

Parameters:
configuration launch configuration
Returns:
String specifying Ant home to use or null
Throws:
CoreException if unable to access the associated attribute
	public static String getAntHome(ILaunchConfiguration configurationthrows CoreException {
		IRuntimeClasspathEntry[] entries = JavaRuntime.computeUnresolvedRuntimeClasspath(configuration);
		for (int i = 0; i < entries.lengthi++) {
			IRuntimeClasspathEntry entry = entries[i];
			if (entry.getType() == .) {
					return ((AntHomeClasspathEntry)entry2).getAntHome();
				}
			}
		}
		return null;
	}

Returns an array of property files to be used for the build, or null if none are specified (indicating no additional property files specified for the build).

Parameters:
configuration launch configuration
Returns:
array of property file names, or null
Throws:
CoreException if unable to access the associated attribute
	public static String[] getPropertyFiles(ILaunchConfiguration configurationthrows CoreException {
		if (attribute == null) {
			return null;
		}
		String[] propertyFiles= AntUtil.parseString(attribute","); //$NON-NLS-1$
		for (int i = 0; i < propertyFiles.lengthi++) {
			String propertyFile = propertyFiles[i];
			propertyFileexpandVariableString(propertyFile.);
			propertyFiles[i]= propertyFile;
		}
		return propertyFiles;
	}
	public static AntTargetNode[] getTargets(String pathILaunchConfiguration configthrows CoreException {
		File buildfilegetBuildFile(path);
		if (buildfile == null) {
		    return null;
		}
		URL[] urlsgetCustomClasspath(config);
		//no lexical, no position, no task
		IAntModel modelgetAntModel(buildfileurlsfalsefalsefalse);
		try {
catch (CoreException ex){
		}
		AntProjectNode projectmodel.getProjectNode(); //forces a reconcile
		model.dispose();
		return getTargets(project);
	}
    private static Map getAllProperties(ILaunchConfiguration configthrows CoreException {
        String allArgs = config.getAttribute(., (Stringnull);
		Map propertiesnew HashMap();
		if (allArgs != null) {
			String[] arguments = ExternalToolsUtil.parseStringIntoList(allArgs);
			// filter arguments to avoid resolving variables that will prompt the user
			List filtered = new ArrayList();
			Pattern pattern = Pattern.compile("\\$\\{.*_prompt.*\\}"); //$NON-NLS-1$
			for (int i = 0; i < arguments.lengthi++) {
				String arg = arguments[i];
				if (arg.startsWith("-D")) { //$NON-NLS-1$
					if (!pattern.matcher(arg).find()) {
						filtered.add(manager.performStringSubstitution(argfalse));
					}
				}
			}
		    AntCoreUtil.processMinusDProperties(filteredproperties);
		}
		Map configPropertiesgetProperties(config);
		if (configProperties != null) {
		    Iterator keysconfigProperties.keySet().iterator();
		    while (keys.hasNext()) {
		        String name = (Stringkeys.next();
		        if (properties.get(name) == null) {
		            properties.put(nameconfigProperties.get(name));
		        }
		    }
		}
		return properties;
    }
    private static AntTargetNode[] getTargets(AntProjectNode project) {
        if (project == null || !project.hasChildren()) {
		    return null;
		}
		List targetsnew ArrayList();
		Iterator possibleTargetsproject.getChildNodes().iterator();
		while (possibleTargets.hasNext()) {
			AntElementNode node= (AntElementNode)possibleTargets.next();
			if (node instanceof AntTargetNode) {
				targets.add(node);
			}
		}
		if (targets.size() == 0) {
		    return null;
		}
		return (AntTargetNode[])targets.toArray(new AntTargetNode[targets.size()]);
    }
    public static AntTargetNode[] getTargets(String path) {
		File buildfilegetBuildFile(path);
		if (buildfile == null) {
		    return null;
		}
		//tasks and position info but no lexical info
		IAntModel modelgetAntModel(buildfilenullfalsetruetrue);
		AntProjectNode projectmodel.getProjectNode();
		if (project == null) {
			model.dispose();
			return null;
		}
		AntTargetNode[] targetsgetTargets(project);
        if (targets == null) {
            Hashtable antTargetsproject.getProject().getTargets();
            Target implicitTarget= (Target) antTargets.get(""); //$NON-NLS-1$
            if (implicitTarget != null) {
                AntTargetNode implicitTargetNodenew AntTargetNode(implicitTarget);
                project.addChildNode(implicitTargetNode);
                return new AntTargetNode[] {implicitTargetNode};
            }
        }
        return targets;
	}
	public static IAntModel getAntModel(String buildFilePathboolean needsLexicalResolutionboolean needsPositionResolutionboolean needsTaskResolution) {
	    IAntModel modelgetAntModel(getBuildFile(buildFilePath), nullneedsLexicalResolutionneedsPositionResolutionneedsTaskResolution);
	    return model;   
	}

Return a buildfile from the specified location. If there isn't one return null.
	private static File getBuildFile(String path) {
		File buildFile = new File(path);
		if (!buildFile.isFile() || !buildFile.exists()) { 
			return null;
		}
		return buildFile;
	}
	private static IAntModel getAntModel(final File buildFileURL[] urlsboolean needsLexicalboolean needsPositionboolean needsTask) {
	    if (buildFile == null || !buildFile.exists()) {
	        return null;
	    }
		IDocument docgetDocument(buildFile);
		if (doc == null) {
			return null;
		}
		final IFile filegetFileForLocation(buildFile.getAbsolutePath(), null);
		LocationProvider providernew LocationProvider(null) {
		    /* (non-Javadoc)
		     * @see org.eclipse.ant.internal.ui.model.LocationProvider#getFile()
		     */
		    public IFile getFile() {
		        return file;
		    }
			/* (non-Javadoc)
			 * @see org.eclipse.ant.internal.ui.model.LocationProvider#getLocation()
			 */
			public IPath getLocation() {
			    if (file == null) {
			        return new Path(buildFile.getAbsolutePath());   
			    } 
			    return file.getLocation();
			}
		};
		IAntModel modelnew AntModel(docnullproviderneedsLexicalneedsPositionneedsTask);
		if (urls != null) {
		    model.setClassLoader(AntCorePlugin.getPlugin().getNewClassLoader(urls));
		}
		return model;
	}
	private static IDocument getDocument(File buildFile) {
		IPath locationnew Path(buildFile.getAbsolutePath());
		boolean connectedfalse;
		try {
			if (buffer == null) {
				//no existing file buffer..create one
				manager.connect(location.new NullProgressMonitor());
				connectedtrue;
				buffermanager.getTextFileBuffer(location.);
				if (buffer == null) {
					return null;
				}
			}
			return buffer.getDocument();
catch (CoreException ce) {
			AntUIPlugin.log(ce.getStatus());
			return null;
finally {
			if (connected) {
				try {
catch (CoreException e) {
					AntUIPlugin.log(e.getStatus());
				}
			}
		}
	}

Returns the list of URLs that define the custom classpath for the Ant build, or null if the global classpath is to be used.

Parameters:
config launch configuration
Returns:
a list of URL
Throws:
CoreException if file does not exist, IO problems, or invalid format.
	public static URL[] getCustomClasspath(ILaunchConfiguration configthrows CoreException {
		if (useDefault) {
			return null;
		}
		IRuntimeClasspathEntry[] unresolved = JavaRuntime.computeUnresolvedRuntimeClasspath(config);
		// don't consider bootpath entries
		List userEntries = new ArrayList(unresolved.length);
		for (int i = 0; i < unresolved.lengthi++) {
			IRuntimeClasspathEntry entry = unresolved[i];
				userEntries.add(entry);
			}
		}
		IRuntimeClasspathEntry[] entries = JavaRuntime.resolveRuntimeClasspath((IRuntimeClasspathEntry[])userEntries.toArray(new IRuntimeClasspathEntry[userEntries.size()]), config);
		URL[] urls = new URL[entries.length];
		for (int i = 0; i < entries.lengthi++) {
			IRuntimeClasspathEntry entry = entries[i];
			try {
				urls[i] = new URL("file:"+entry.getLocation()); //$NON-NLS-1$
catch (MalformedURLException e) {
			}
		}
		return urls;		
	}
	private static String expandVariableString(String variableStringString invalidMessagethrows CoreException {
		String expandedString = VariablesPlugin.getDefault().getStringVariableManager().performStringSubstitution(variableString);
		if (expandedString == null || expandedString.length() == 0) {
			String msg = MessageFormat.format(invalidMessagenew String[] {variableString});
			throw new CoreException(new Status(.., 0, msgnull));
		return expandedString;
	}

Returns the list of target names to run

Parameters:
extraAttibuteValue the external tool's extra attribute value for the run targets key.
Returns:
a list of target names
	public static String[] parseRunTargets(String extraAttibuteValue) {
		return parseString(extraAttibuteValue);
	}

Returns the list of Strings that were delimiter separated.

Parameters:
delimString the String to be tokenized based on the delimiter
Returns:
a list of Strings
	public static String[] parseString(String delimStringString delim) {
		if (delimString == null) {
			return new String[0];
		}
		// Need to handle case where separator character is
		// actually part of the target name!
		StringTokenizer tokenizer = new StringTokenizer(delimStringdelim);
		String[] results = new String[tokenizer.countTokens()];
		for (int i = 0; i < results.lengthi++) {
			results[i] = tokenizer.nextToken();
		}
		return results;
	}

Returns an IFile with the given fully qualified path (relative to the workspace root). The returned IFile may or may not exist.
	public static IFile getFile(String fullPath) {
		IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
		return root.getFile(new Path(fullPath));
	}
	public static IHyperlink getLocationLink(String pathFile buildFileParent) {
		path = path.trim();
		if (path.length() == 0) {
			return null;
		}
		if (path.startsWith("file:")) { //$NON-NLS-1$
			// remove "file:"
			pathpath.substring(5, path.length());
		}
		// format is file:F:L: where F is file path, and L is line number
		int index = path.lastIndexOf(':');
		if (index == -1) {
			//incorrect format
			return null;
		}
		if (index == path.length() - 1) {
			// remove trailing ':'
			path = path.substring(0, index);
			index = path.lastIndexOf(':');
		}
		// split file and line number
		String fileName = path.substring(0, index);
		try {
			String lineNumber = path.substring(index + 1);
			int line = Integer.parseInt(lineNumber);
			IFile file = getFileForLocation(fileNamebuildFileParent);
			if (file != null) {
				return new FileLink(filenull, -1, -1, line);
			}
catch (NumberFormatException e) {
		}
		return null;
	}

Returns the workspace file associated with the given path in the local file system, or null if none. If the path happens to be a relative path, then the path is interpreted as relative to the specified parent file. Attempts to handle linked files; the first found linked file with the correct path is returned.

Parameters:
path
buildFileParent
Returns:
file or null
See also:
org.eclipse.core.resources.IWorkspaceRoot.findFilesForLocation(IPath)
	public static IFile getFileForLocation(String pathFile buildFileParent) {
		if (path == null) {
			return null;
		}
		IPath filePathnew Path(path);
		IFile file = null;
		IFile[] files= ResourcesPlugin.getWorkspace().getRoot().findFilesForLocation(filePath);
		if (files.length > 0) {
			filefiles[0];
		}
		if (file == null) {
			//relative path
			File relativeFilenull;
			try {
				//this call is ok if buildFileParent is null
				relativeFile= FileUtils.getFileUtils().resolveFile(buildFileParentpath);
				filePathnew Path(relativeFile.getAbsolutePath());
				files= ResourcesPlugin.getWorkspace().getRoot().findFilesForLocation(filePath);
				if (files.length > 0) {
					filefiles[0];
else {
					return null;
				}
catch (BuildException be) {
				return null;
			}
		}
		if (file.exists()) {
			return file;
		File ioFilefile.getLocation().toFile();
		if (ioFile.exists()) {//needs to handle case insensitivity on WINOS
			try {
				files= ResourcesPlugin.getWorkspace().getRoot().findFilesForLocation(new Path(ioFile.getCanonicalPath()));
				if (files.length > 0) {
					return files[0];
				}
catch (IOException e) {
			}			
		}
		return null;
	}

Migrates the classpath in the given configuration from the old format to the new format. The old format is not preserved. Instead, the default classpath will be used. However, ANT_HOME settings are preserved.

Parameters:
configuration a configuration to migrate
Throws:
CoreException if unable to migrate
Since:
3.0
	public static void migrateToNewClasspathFormat(ILaunchConfiguration configurationthrows CoreException {
		if (oldClasspath != null || oldAntHome != null || provider == null) {
			ILaunchConfigurationWorkingCopy workingCopy = null;
			if (configuration.isWorkingCopy()) {
				workingCopy = (ILaunchConfigurationWorkingCopyconfiguration;
else {
				workingCopy = configuration.getWorkingCopy();
			}
			workingCopy.setAttribute(."org.eclipse.ant.ui.AntClasspathProvider"); //$NON-NLS-1$
			if (oldAntHome != null) {
				IRuntimeClasspathEntry[] entries = JavaRuntime.computeUnresolvedRuntimeClasspath(workingCopy);
				List mementos = new ArrayList(entries.length);
				for (int i = 0; i < entries.lengthi++) {
					IRuntimeClasspathEntry entry = entries[i];
					if (entry.getType() == .) {
							AntHomeClasspathEntry homeEntry = new AntHomeClasspathEntry(oldAntHome);
							mementos.add(homeEntry.getMemento());
							continue;
						}
					}
					mementos.add(entry.getMemento());
				}
			}
			workingCopy.doSave();
		}
	}
    private static int getOffset(int lineint columnITextEditor editor) {
    	IDocumentProvider providereditor.getDocumentProvider();
    	IEditorInput inputeditor.getEditorInput();
    	try {
    		provider.connect(input);
    	} catch (CoreException e) {
    		return -1;
    	}
    	try {
    		IDocument documentprovider.getDocument(input);
    		if (document != null) {
    			if (column > -1) {
    				 //column marks the length..adjust to 0 index and to be within the element's source range
    				return document.getLineOffset(line - 1) + column - 1 - 2;
    			} 
    			return document.getLineOffset(line - 1);
    		}
    	} catch (BadLocationException e) {
    	} finally {
    		provider.disconnect(input);
    	}
    	return -1;
    }

    
Opens the given editor on the buildfile of the provided node and selects that node in the editor.

Parameters:
page the page to open the editor in
editorDescriptor the editor descriptor, or null for the system editor
node the node from the buildfile to open and then select in the editor
    public static void openInEditor(IWorkbenchPage pageIEditorDescriptor editorDescriptorAntElementNode node) {
    	IEditorPart editorPartnull;
    	IFile fileResource = node.getIFile();
    	try {
    		if (editorDescriptor == null) {
    			editorPartpage.openEditor(new FileEditorInput(fileResource), .);
    		} else {
    			editorPartpage.openEditor(new FileEditorInput(fileResource), editorDescriptor.getId());
    		}
    	} catch (PartInitException e) {
    		AntUIPlugin.log(MessageFormat.format(.new String[]{fileResource.getLocation().toOSString()}), e);
    	}
    	
    	if (editorPart instanceof AntEditor) {
    	    AntEditor editor= (AntEditor)editorPart;
    		if (node.getImportNode() != null) {	
    			AntModel modeleditor.getAntModel();
    			AntProjectNode projectmodel.getProjectNode();
    			if (project == null) {
    				return;
    			}
    			int[] infonode.getExternalInfo();
    			int offsetgetOffset(info[0], info[1], editor);
    			nodeproject.getNode(offset);
    		}
    		editor.setSelection(nodetrue);
    	}
    }

    
Opens an editor on the buildfile of the provided node and selects that node in the editor.

Parameters:
page the page to open the editor in
node the node from the buildfile to open and then select in the editor
    public static void openInEditor(IWorkbenchPage pageAntElementNode node) {
    	IFile filenode.getIFile();
    	IEditorDescriptor editorDesc;
        try {
            editorDesc = IDE.getEditorDescriptor(file);
        } catch (PartInitException e) {
           return;
        }
        openInEditor(pageeditorDescnode);
    }
    
    
Opens an external browser on the provided urlString

Parameters:
urlString The url to open
shell the shell
errorDialogTitle the title of any error dialog
    public static void openBrowser(final String urlStringfinal Shell shellfinal String errorDialogTitle) {
    	shell.getDisplay().syncExec(new Runnable() {
    		public void run() {
    			IWorkbenchBrowserSupport support= PlatformUI.getWorkbench().getBrowserSupport();
    			try {
    				IWebBrowser browsersupport.createBrowser();
    				browser.getId();
    				browser.openURL(new URL(urlString));
    				return;
    			} catch (PartInitException e) {
    				AntUIPlugin.log(e.getStatus());
    			} catch (MalformedURLException e) {
    				AntUIPlugin.log(e);
				}
    			
    			String platform= SWT.getPlatform();
    			boolean succeededtrue;
    			if ("motif".equals(platform) || "gtk".equals(platform)) { //$NON-NLS-1$ //$NON-NLS-2$
    				Program program= Program.findProgram("html"); //$NON-NLS-1$
    				if (program == null) {
    					program= Program.findProgram("htm"); //$NON-NLS-1$
    				}
    				if (program != null) {
    					succeededprogram.execute(urlString.toString());
    				}
    			} else {
    				succeeded= Program.launch(urlString.toString());
    			}
    			if (!succeeded) {
    				MessageDialog.openInformation(shellerrorDialogTitle.);
    			}
    		}
    	});
	}
    
    public static boolean isSeparateJREAntBuild(ILaunchConfiguration configuration) {
    	boolean separateJREtrue;
		try {
			//always null for same JRE
			separateJRE = configuration.getAttribute(., (String)null) != null;
catch (CoreException e) {
		}
    	
		return separateJRE;
    }
    
    public static void linkBuildFailedMessage(String messageIProcess process) {
        String fileName = null;
        String lineNumber = ""//$NON-NLS-1$
        int fileStart = 0;
        int index = message.indexOf("xml"); //$NON-NLS-1$
        if (index > 0) {
            int numberStartindex + 4;
            int numberEndmessage.indexOf(':'numberStart);
            int fileEnd = index + 3;
            if (numberStart > 0 && fileEnd > 0) {
                fileName = message.substring(fileStartfileEnd).trim();
                if (numberEnd > 0) {
                    lineNumber = message.substring(numberStartnumberEnd).trim();
                }
            }
        }
        
        if (fileName != null) {
            int num = -1;
            try {
                num = Integer.parseInt(lineNumber);
            } catch (NumberFormatException e) {
            }
            IFile[] files = ResourcesPlugin.getWorkspace().getRoot().findFilesForLocation(new Path(fileName));
            IFile filenull;
            if (files.length > 0) {
                filefiles[0];
            }
            if (file != null && file.exists()) {
                FileLink link = new FileLink(filenull, -1, -1, num);
                TaskLinkManager.addTaskHyperlink(processlinknew Region(0, message.length()), message);
            }
        }
    }
New to GrepCode? Check out our FAQ X