KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > ant > internal > ui > launchConfigurations > AntLaunchShortcut


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  * John-Mason P. Shackelford - bug 34548
11  *******************************************************************************/

12 package org.eclipse.ant.internal.ui.launchConfigurations;
13
14
15 import java.util.ArrayList JavaDoc;
16 import java.util.List JavaDoc;
17
18 import org.eclipse.ant.internal.ui.AntUIPlugin;
19 import org.eclipse.ant.internal.ui.AntUtil;
20 import org.eclipse.ant.internal.ui.IAntUIConstants;
21 import org.eclipse.ant.internal.ui.IAntUIPreferenceConstants;
22 import org.eclipse.ant.internal.ui.model.AntElementNode;
23 import org.eclipse.ant.internal.ui.model.AntProjectNode;
24 import org.eclipse.ant.internal.ui.model.AntTargetNode;
25 import org.eclipse.ant.internal.ui.model.AntTaskNode;
26 import org.eclipse.core.resources.IContainer;
27 import org.eclipse.core.resources.IFile;
28 import org.eclipse.core.resources.IProject;
29 import org.eclipse.core.resources.IResource;
30 import org.eclipse.core.runtime.CoreException;
31 import org.eclipse.core.runtime.IAdaptable;
32 import org.eclipse.core.runtime.IPath;
33 import org.eclipse.core.runtime.IStatus;
34 import org.eclipse.core.runtime.Status;
35 import org.eclipse.core.variables.VariablesPlugin;
36 import org.eclipse.debug.core.DebugPlugin;
37 import org.eclipse.debug.core.ILaunchConfiguration;
38 import org.eclipse.debug.core.ILaunchConfigurationType;
39 import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
40 import org.eclipse.debug.core.ILaunchManager;
41 import org.eclipse.debug.ui.CommonTab;
42 import org.eclipse.debug.ui.DebugUITools;
43 import org.eclipse.debug.ui.IDebugUIConstants;
44 import org.eclipse.debug.ui.ILaunchShortcut;
45 import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
46 import org.eclipse.jface.dialogs.ErrorDialog;
47 import org.eclipse.jface.preference.IPreferenceStore;
48 import org.eclipse.jface.viewers.ILabelProvider;
49 import org.eclipse.jface.viewers.ISelection;
50 import org.eclipse.jface.viewers.IStructuredSelection;
51 import org.eclipse.jface.window.Window;
52 import org.eclipse.swt.widgets.Display;
53 import org.eclipse.ui.IEditorInput;
54 import org.eclipse.ui.IEditorPart;
55 import org.eclipse.ui.IWorkbenchPage;
56 import org.eclipse.ui.dialogs.ElementListSelectionDialog;
57 import org.eclipse.ui.editors.text.ILocationProvider;
58 import org.eclipse.ui.externaltools.internal.launchConfigurations.ExternalToolsUtil;
59 import org.eclipse.ui.externaltools.internal.model.IExternalToolConstants;
60
61 import com.ibm.icu.text.MessageFormat;
62
63
64 public class AntLaunchShortcut implements ILaunchShortcut {
65
66     private boolean fShowDialog= false;
67     private static final int MAX_TARGET_APPEND_LENGTH = 30;
68
69     /**
70      * Constructor for AntLaunchShortcut.
71      */

72     public AntLaunchShortcut() {
73         super();
74     }
75
76     /**
77      * @see org.eclipse.debug.ui.ILaunchShortcut#launch(org.eclipse.jface.viewers.ISelection, java.lang.String)
78      */

79     public void launch(ISelection selection, String JavaDoc mode) {
80         if (selection instanceof IStructuredSelection) {
81             IStructuredSelection structuredSelection = (IStructuredSelection)selection;
82             Object JavaDoc object = structuredSelection.getFirstElement();
83             if (object instanceof IAdaptable) {
84                 IResource resource = (IResource)((IAdaptable)object).getAdapter(IResource.class);
85                 if (resource != null) {
86                     launch(resource, mode);
87                     return;
88                 } else if (object instanceof AntElementNode){
89                     launch((AntElementNode) object, mode);
90                     return;
91                 }
92             }
93         }
94         antFileNotFound();
95     }
96     
97     /**
98      * Launches the given Ant node.
99      * <ul><li>AntProjectNodes: the default target is executed</li>
100      * <li>AntTargetNodes: that target is executed</li>
101      * <li>AntTaskNodes: the owning target is executed</li>
102      * </ul>
103      * @param node the Ant node to use as the context for the launch
104      * @param mode the mode of the launch
105      */

106     public void launch(AntElementNode node, String JavaDoc mode) {
107         String JavaDoc selectedTargetName= null;
108         if (node instanceof AntTargetNode) {
109             AntTargetNode targetNode= (AntTargetNode) node;
110             if (targetNode.isDefaultTarget()) {
111                 selectedTargetName= ""; //$NON-NLS-1$
112
} else {
113                 selectedTargetName= targetNode.getTarget().getName();
114             }
115         } else if (node instanceof AntProjectNode) {
116             selectedTargetName = ""; //$NON-NLS-1$
117
} else if (node instanceof AntTaskNode) {
118             AntTaskNode taskNode= (AntTaskNode) node;
119             selectedTargetName= taskNode.getTask().getOwningTarget().getName();
120         }
121     
122         if (selectedTargetName == null) {
123             return;
124         }
125         IFile file= node.getBuildFileResource();
126         if (file != null) {
127             launch(file, mode, selectedTargetName);
128             return;
129         }
130         //external buildfile
131
IPath filePath= getExternalBuildFilePath();
132         if (filePath != null) {
133             launch(filePath, mode, selectedTargetName);
134             return;
135         }
136         
137         antFileNotFound();
138     }
139     
140     private IPath getExternalBuildFilePath() {
141         IWorkbenchPage page= AntUIPlugin.getActiveWorkbenchWindow().getActivePage();
142         IPath filePath= null;
143         IEditorPart editor= page.getActiveEditor();
144         if (editor != null) {
145             IEditorInput editorInput= editor.getEditorInput();
146             ILocationProvider locationProvider= (ILocationProvider)editorInput.getAdapter(ILocationProvider.class);
147             if (locationProvider != null) {
148                 filePath= locationProvider.getPath(editorInput);
149             }
150         }
151         return filePath;
152     }
153     
154     /**
155      * Inform the user that an ant file was not found to run.
156      */

157     private void antFileNotFound() {
158         reportError(AntLaunchConfigurationMessages.AntLaunchShortcut_Unable, null);
159     }
160     
161     /**
162      * Launch the given file in the specified mode.
163      *
164      * @param resource either a build file (*.xml file) to execute or a resource
165      * from whose location a build file should be searched for. If the given
166      * resource is a file that does not end in ".xml", a search will begin at
167      * the resource's enclosing folder. The given resource must be of type IFile
168      * or IContainer.
169      * @param mode the mode in which the build file should be executed
170      */

171     protected void launch(IResource resource, String JavaDoc mode) {
172         if (!("xml".equalsIgnoreCase(resource.getFileExtension()))) { //$NON-NLS-1$
173
if (resource.getType() == IResource.FILE) {
174                 resource= resource.getParent();
175             }
176             resource= findBuildFile((IContainer)resource);
177         }
178         if (resource != null) {
179             launch((IFile)resource, mode, null);
180         } else {
181             antFileNotFound();
182          }
183     }
184     
185     /**
186      * Launch the given targets in the given build file. The targets are
187      * launched in the given mode.
188      *
189      * @param file the build file to launch
190      * @param mode the mode in which the build file should be executed
191      * @param targetAttribute the targets to launch, in the form of the launch
192      * configuration targets attribute.
193      */

194     public void launch(IFile file, String JavaDoc mode, String JavaDoc targetAttribute) {
195         ILaunchConfiguration configuration= null;
196         
197         List JavaDoc configurations = findExistingLaunchConfigurations(file);
198         if (configurations.isEmpty()) {
199             configuration = createDefaultLaunchConfiguration(file);
200         } else {
201             if (configurations.size() == 1) {
202                 configuration= (ILaunchConfiguration)configurations.get(0);
203             } else {
204                 configuration= chooseConfig(configurations);
205                 if (configuration == null) {
206                     // User cancelled selection
207
return;
208                 }
209             }
210         }
211
212         if (configuration == null) {
213             antFileNotFound();
214         }
215         // ensure that the targets are selected in the launch configuration
216
try {
217             if (targetAttribute != null && ! targetAttribute.equals(configuration.getAttribute(IAntLaunchConfigurationConstants.ATTR_ANT_TARGETS, ""))) { //$NON-NLS-1$
218
String JavaDoc projectName= null;
219                 try {
220                     projectName= configuration.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, (String JavaDoc) null);
221                 } catch (CoreException e) {
222                 }
223                 String JavaDoc newName= getNewLaunchConfigurationName(file.getFullPath(), projectName, targetAttribute);
224                 configuration= configuration.copy(newName);
225                 ((ILaunchConfigurationWorkingCopy) configuration).setAttribute(IAntLaunchConfigurationConstants.ATTR_ANT_TARGETS, targetAttribute);
226                 if (fShowDialog) {
227                     configuration= ((ILaunchConfigurationWorkingCopy) configuration).doSave();
228                 }
229             }
230         } catch (CoreException exception) {
231             reportError(MessageFormat.format(AntLaunchConfigurationMessages.AntLaunchShortcut_Exception_launching, new String JavaDoc[] {file.getName()}), exception);
232             return;
233         }
234         launch(mode, configuration);
235     }
236     
237     /**
238      * Returns a unique name for a copy of the given launch configuration with the given
239      * targets. The name seed is the same as the name for a new launch configuration with
240      * &quot; [targetList]&quot; appended to the end.
241      * @param filePath the path to the buildfile
242      * @param projectName the name of the project containing the buildfile or <code>null</code> if no project is known
243      * @param targetAttribute the listing of targets to execute or <code>null</code> for default target execution
244      * @return a unique name for the copy
245      */

246     public static String JavaDoc getNewLaunchConfigurationName(IPath filePath, String JavaDoc projectName, String JavaDoc targetAttribute) {
247         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
248         if (projectName != null) {
249             buffer.append(projectName);
250             buffer.append(' ');
251             buffer.append(filePath.lastSegment());
252         } else {
253             buffer.append(filePath.lastSegment());
254         }
255         
256         if (targetAttribute != null) {
257             buffer.append(" ["); //$NON-NLS-1$
258
if (targetAttribute.length() > MAX_TARGET_APPEND_LENGTH + 3) {
259                 // The target attribute can potentially be a long, comma-separated list
260
// of target. Make sure the generated name isn't extremely long.
261
buffer.append(targetAttribute.substring(0, MAX_TARGET_APPEND_LENGTH));
262                 buffer.append("..."); //$NON-NLS-1$
263
} else {
264                 buffer.append(targetAttribute);
265             }
266             buffer.append(']');
267         }
268         
269         String JavaDoc name= DebugPlugin.getDefault().getLaunchManager().generateUniqueLaunchConfigurationNameFrom(buffer.toString());
270         return name;
271     }
272     
273     /**
274      * Launch the given targets in the given build file. The targets are
275      * launched in the given mode.
276      *
277      * @param filePath the path to the build file to launch
278      * @param mode the mode in which the build file should be executed
279      * @param targetAttribute the targets to launch, in the form of the launch
280      * configuration targets attribute.
281      */

282     public void launch(IPath filePath, String JavaDoc mode, String JavaDoc targetAttribute) {
283         ILaunchConfiguration configuration= null;
284         
285         List JavaDoc configurations = findExistingLaunchConfigurations(filePath);
286         if (configurations.isEmpty()) {
287             configuration = createDefaultLaunchConfiguration(filePath, null);
288         } else {
289             if (configurations.size() == 1) {
290                 configuration= (ILaunchConfiguration)configurations.get(0);
291             } else {
292                 configuration= chooseConfig(configurations);
293                 if (configuration == null) {
294                     // User cancelled selection
295
return;
296                 }
297             }
298         }
299         
300         if (configuration == null) {
301             antFileNotFound();
302         }
303         // ensure that the targets are selected in the launch configuration
304
try {
305             if (targetAttribute != null && ! targetAttribute.equals(configuration.getAttribute(IAntLaunchConfigurationConstants.ATTR_ANT_TARGETS, ""))) { //$NON-NLS-1$
306
String JavaDoc projectName= null;
307                 try {
308                     projectName= configuration.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, (String JavaDoc) null);
309                 } catch (CoreException e) {
310                 }
311                 String JavaDoc newName= getNewLaunchConfigurationName(filePath, projectName, targetAttribute);
312                 configuration= configuration.copy(newName);
313                 ((ILaunchConfigurationWorkingCopy) configuration).setAttribute(IAntLaunchConfigurationConstants.ATTR_ANT_TARGETS, targetAttribute);
314                 if (fShowDialog) {
315                     configuration= ((ILaunchConfigurationWorkingCopy) configuration).doSave();
316                 }
317             }
318         } catch (CoreException exception) {
319             reportError(MessageFormat.format(AntLaunchConfigurationMessages.AntLaunchShortcut_Exception_launching, new String JavaDoc[] {filePath.toFile().getName()}), exception);
320             return;
321         }
322         launch(mode, configuration);
323     }
324     
325     private void launch(String JavaDoc mode, ILaunchConfiguration configuration) {
326         if (fShowDialog) {
327             // Offer to save dirty editors before opening the dialog as the contents
328
// of an Ant editor often affect the contents of the dialog.
329
if (!DebugUITools.saveBeforeLaunch()) {
330                 return;
331             }
332             IStatus status = new Status(IStatus.INFO, IAntUIConstants.PLUGIN_ID, IAntUIConstants.STATUS_INIT_RUN_ANT, "", null); //$NON-NLS-1$
333
String JavaDoc groupId;
334             if (mode.equals(ILaunchManager.DEBUG_MODE)) {
335                 groupId= IDebugUIConstants.ID_DEBUG_LAUNCH_GROUP;
336             } else {
337                 groupId= IExternalToolConstants.ID_EXTERNAL_TOOLS_LAUNCH_GROUP;
338             }
339             DebugUITools.openLaunchConfigurationDialog(AntUIPlugin.getActiveWorkbenchWindow().getShell(), configuration, groupId, status);
340         } else {
341             DebugUITools.launch(configuration, mode);
342         }
343     }
344
345     /**
346      * Walks the file hierarchy looking for a build file.
347      * Returns the first build file found that matches the
348      * search criteria.
349      */

350     private IFile findBuildFile(IContainer parent) {
351         String JavaDoc[] names= getBuildFileNames();
352         if (names == null) {
353             return null;
354         }
355         IResource file= null;
356         while (file == null || file.getType() != IResource.FILE) {
357             for (int i = 0; i < names.length; i++) {
358                 String JavaDoc string = names[i];
359                 file= parent.findMember(string);
360                 if (file != null && file.getType() == IResource.FILE) {
361                     break;
362                 }
363             }
364             parent = parent.getParent();
365             if (parent == null) {
366                 return null;
367             }
368         }
369         return (IFile)file;
370     }
371     
372     private String JavaDoc[] getBuildFileNames() {
373         IPreferenceStore prefs= AntUIPlugin.getDefault().getPreferenceStore();
374         String JavaDoc buildFileNames= prefs.getString(IAntUIPreferenceConstants.ANT_FIND_BUILD_FILE_NAMES);
375         if (buildFileNames.length() == 0) {
376             //the user has not specified any names to look for
377
return null;
378         }
379         return AntUtil.parseString(buildFileNames, ","); //$NON-NLS-1$
380
}
381     
382     /**
383      * Creates and returns a default launch configuration for the given file.
384      *
385      * @param file
386      * @return default launch configuration
387      */

388     public static ILaunchConfiguration createDefaultLaunchConfiguration(IFile file) {
389         return createDefaultLaunchConfiguration(file.getFullPath(), file.getProject());
390     }
391
392     /**
393      * Creates and returns a default launch configuration for the given file path
394      * and project.
395      *
396      * @param filePath the path to the buildfile
397      * @param project the project containing the buildfile or <code>null</code> if the
398      * buildfile is not contained in a project (is external).
399      * @return default launch configuration or <code>null</code> if one could not be created
400      */

401     public static ILaunchConfiguration createDefaultLaunchConfiguration(IPath filePath, IProject project) {
402         ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager();
403         ILaunchConfigurationType type = manager.getLaunchConfigurationType(IAntLaunchConfigurationConstants.ID_ANT_LAUNCH_CONFIGURATION_TYPE);
404                 
405         String JavaDoc projectName= project != null ? project.getName() : null;
406         String JavaDoc name = getNewLaunchConfigurationName(filePath, projectName, null);
407         try {
408             ILaunchConfigurationWorkingCopy workingCopy = type.newInstance(null, name);
409             if (project != null) {
410                 workingCopy.setAttribute(IExternalToolConstants.ATTR_LOCATION,
411                         VariablesPlugin.getDefault().getStringVariableManager().generateVariableExpression("workspace_loc", filePath.toString())); //$NON-NLS-1$
412
} else {
413                 workingCopy.setAttribute(IExternalToolConstants.ATTR_LOCATION, filePath.toString());
414             }
415             workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_CLASSPATH_PROVIDER, "org.eclipse.ant.ui.AntClasspathProvider"); //$NON-NLS-1$
416
// set default for common settings
417
CommonTab tab = new CommonTab();
418             tab.setDefaults(workingCopy);
419             tab.dispose();
420             
421             //set the project name so that the correct default VM install can be determined
422
if (project != null) {
423                 workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, project.getName());
424             }
425             AntJRETab jreTab = new AntJRETab();
426             jreTab.setDefaults(workingCopy);
427             jreTab.dispose();
428             
429             IFile file= AntUtil.getFileForLocation(filePath.toString(), null);
430             workingCopy.setMappedResources(new IResource[] {file});
431             
432             return workingCopy.doSave();
433         } catch (CoreException e) {
434             reportError(MessageFormat.format(AntLaunchConfigurationMessages.AntLaunchShortcut_2, new String JavaDoc[]{filePath.toString()}), e);
435         }
436         return null;
437     }
438     
439     /**
440      * Returns a list of existing launch configuration for the given file.
441      *
442      * @param file the buildfile resource
443      * @return list of launch configurations
444      */

445     public static List JavaDoc findExistingLaunchConfigurations(IFile file) {
446         IPath filePath = file.getLocation();
447         return findExistingLaunchConfigurations(filePath);
448     }
449     
450     /**
451      * Returns a list of existing launch configuration for the given file.
452      *
453      * @param filePath the fully qualified path for the buildfile
454      * @return list of launch configurations
455      */

456     public static List JavaDoc findExistingLaunchConfigurations(IPath filePath) {
457         ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager();
458         ILaunchConfigurationType type = manager.getLaunchConfigurationType(IAntLaunchConfigurationConstants.ID_ANT_LAUNCH_CONFIGURATION_TYPE);
459         List JavaDoc validConfigs= new ArrayList JavaDoc();
460         if (type != null) {
461             ILaunchConfiguration[] configs = null;
462             try {
463                 configs = manager.getLaunchConfigurations(type);
464             } catch (CoreException e) {
465                 reportError(AntLaunchConfigurationMessages.AntLaunchShortcut_3, e);
466             }
467             if (configs != null && configs.length > 0) {
468                 if (filePath == null) {
469                     reportError(AntLaunchConfigurationMessages.AntLaunchShortcut_0, null);
470                 } else {
471                     for (int i = 0; i < configs.length; i++) {
472                         ILaunchConfiguration configuration = configs[i];
473                         IPath location;
474                         try {
475                             location = ExternalToolsUtil.getLocation(configuration);
476                             if (filePath.equals(location)) {
477                                 validConfigs.add(configuration);
478                             }
479                         } catch (CoreException e) {
480                             // error occurred in variable expand - ignore
481
}
482                     }
483                 }
484             }
485         }
486         return validConfigs;
487     }
488     
489     /**
490      * Prompts the user to choose from the list of given launch configurations
491      * and returns the config the user choose or <code>null</code> if the user
492      * pressed Cancel or if the given list is empty.
493      */

494     public static ILaunchConfiguration chooseConfig(List JavaDoc configs) {
495         if (configs.isEmpty()) {
496             return null;
497         }
498         ILabelProvider labelProvider = DebugUITools.newDebugModelPresentation();
499         ElementListSelectionDialog dialog= new ElementListSelectionDialog(Display.getDefault().getActiveShell(), labelProvider);
500         dialog.setElements(configs.toArray(new ILaunchConfiguration[configs.size()]));
501         dialog.setTitle(AntLaunchConfigurationMessages.AntLaunchShortcut_4);
502         dialog.setMessage(AntLaunchConfigurationMessages.AntLaunchShortcut_5);
503         dialog.setMultipleSelection(false);
504         int result = dialog.open();
505         labelProvider.dispose();
506         if (result == Window.OK) {
507             return (ILaunchConfiguration) dialog.getFirstResult();
508         }
509         return null;
510     }
511
512     /**
513      * @see org.eclipse.debug.ui.ILaunchShortcut#launch(org.eclipse.ui.IEditorPart, java.lang.String)
514      */

515     public void launch(IEditorPart editor, String JavaDoc mode) {
516         IEditorInput input = editor.getEditorInput();
517         IFile file = (IFile)input.getAdapter(IFile.class);
518         if (file != null) {
519             launch(file, mode);
520             return;
521         }
522         ILocationProvider locationProvider= (ILocationProvider)input.getAdapter(ILocationProvider.class);
523         if (locationProvider != null) {
524             IPath filePath= locationProvider.getPath(input);
525             if ("xml".equals(filePath.getFileExtension())) { //$NON-NLS-1$
526
launch(filePath, mode, null);
527                 return;
528             }
529         }
530     
531         antFileNotFound();
532     }
533     
534     protected static void reportError(String JavaDoc message, Throwable JavaDoc throwable) {
535         IStatus status = null;
536         if (throwable instanceof CoreException) {
537             status = ((CoreException)throwable).getStatus();
538         } else {
539             status = new Status(IStatus.ERROR, IAntUIConstants.PLUGIN_ID, 0, message, throwable);
540         }
541         ErrorDialog.openError(AntUIPlugin.getActiveWorkbenchWindow().getShell(), AntLaunchConfigurationMessages.AntLaunchShortcut_Error_7, AntLaunchConfigurationMessages.AntLaunchShortcut_Build_Failed_2, status);
542     }
543
544     /**
545      * Sets whether to show the external tools launch configuration dialog
546      *
547      * @param showDialog If true the launch configuration dialog will always be
548      * shown
549      */

550     public void setShowDialog(boolean showDialog) {
551         fShowDialog = showDialog;
552     }
553 }
554
Popular Tags