KickJava   Java API By Example, From Geeks To Geeks.

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


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  * Juan A. Hernandez - bug 89926
11  *******************************************************************************/

12 package org.eclipse.ant.internal.ui.launchConfigurations;
13
14 import java.io.File JavaDoc;
15 import java.io.IOException JavaDoc;
16 import java.net.URL JavaDoc;
17 import com.ibm.icu.text.MessageFormat;
18 import java.util.HashMap JavaDoc;
19 import java.util.Iterator JavaDoc;
20 import java.util.List JavaDoc;
21 import java.util.Map JavaDoc;
22
23 import org.apache.tools.ant.ProjectHelper;
24 import org.eclipse.ant.core.AntCorePlugin;
25 import org.eclipse.ant.core.AntCorePreferences;
26 import org.eclipse.ant.core.AntRunner;
27 import org.eclipse.ant.core.Property;
28 import org.eclipse.ant.core.Task;
29 import org.eclipse.ant.core.Type;
30 import org.eclipse.ant.internal.core.AbstractEclipseBuildLogger;
31 import org.eclipse.ant.internal.ui.AntUIPlugin;
32 import org.eclipse.ant.internal.ui.AntUtil;
33 import org.eclipse.ant.internal.ui.IAntUIConstants;
34 import org.eclipse.ant.internal.ui.IAntUIPreferenceConstants;
35 import org.eclipse.ant.internal.ui.debug.IAntDebugConstants;
36 import org.eclipse.ant.internal.ui.debug.model.RemoteAntDebugBuildListener;
37 import org.eclipse.core.resources.IProject;
38 import org.eclipse.core.runtime.CoreException;
39 import org.eclipse.core.runtime.FileLocator;
40 import org.eclipse.core.runtime.IPath;
41 import org.eclipse.core.runtime.IProgressMonitor;
42 import org.eclipse.core.runtime.IStatus;
43 import org.eclipse.core.runtime.Path;
44 import org.eclipse.core.runtime.Platform;
45 import org.eclipse.core.runtime.Status;
46 import org.eclipse.core.runtime.SubProgressMonitor;
47 import org.eclipse.core.variables.VariablesPlugin;
48 import org.eclipse.debug.core.DebugEvent;
49 import org.eclipse.debug.core.DebugPlugin;
50 import org.eclipse.debug.core.IBreakpointManager;
51 import org.eclipse.debug.core.IDebugEventSetListener;
52 import org.eclipse.debug.core.ILaunch;
53 import org.eclipse.debug.core.ILaunchConfiguration;
54 import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
55 import org.eclipse.debug.core.ILaunchManager;
56 import org.eclipse.debug.core.model.IBreakpoint;
57 import org.eclipse.debug.core.model.IProcess;
58 import org.eclipse.debug.core.model.LaunchConfigurationDelegate;
59 import org.eclipse.debug.ui.CommonTab;
60 import org.eclipse.debug.ui.IDebugUIConstants;
61 import org.eclipse.debug.ui.RefreshTab;
62 import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
63 import org.eclipse.jdt.launching.IVMInstall;
64 import org.eclipse.jdt.launching.JavaRuntime;
65 import org.eclipse.jdt.launching.SocketUtil;
66 import org.eclipse.jface.dialogs.MessageDialogWithToggle;
67 import org.eclipse.jface.preference.IPreferenceStore;
68 import org.eclipse.osgi.service.resolver.BundleDescription;
69 import org.eclipse.ui.externaltools.internal.launchConfigurations.ExternalToolsUtil;
70 import org.eclipse.ui.externaltools.internal.model.IExternalToolConstants;
71 import org.eclipse.ui.externaltools.internal.program.launchConfigurations.BackgroundResourceRefresher;
72 import org.osgi.framework.Bundle;
73
74 /**
75  * Launch delegate for Ant builds
76  */

77 public class AntLaunchDelegate extends LaunchConfigurationDelegate {
78     
79     private static final String JavaDoc ANT_LOGGER_CLASS = "org.eclipse.ant.internal.ui.antsupport.logger.AntProcessBuildLogger"; //$NON-NLS-1$
80
private static final String JavaDoc ANT_DEBUG_LOGGER_CLASS = "org.eclipse.ant.internal.ui.antsupport.logger.AntProcessDebugBuildLogger"; //$NON-NLS-1$
81
private static final String JavaDoc NULL_LOGGER_CLASS = "org.eclipse.ant.internal.ui.antsupport.logger.NullBuildLogger"; //$NON-NLS-1$
82
private static final String JavaDoc REMOTE_ANT_LOGGER_CLASS = "org.eclipse.ant.internal.ui.antsupport.logger.RemoteAntBuildLogger"; //$NON-NLS-1$
83
private static final String JavaDoc REMOTE_ANT_DEBUG_LOGGER_CLASS = "org.eclipse.ant.internal.ui.antsupport.logger.debug.RemoteAntDebugBuildLogger"; //$NON-NLS-1$
84
private static final String JavaDoc BASE_DIR_PREFIX = "-Dbasedir="; //$NON-NLS-1$
85
private static final String JavaDoc INPUT_HANDLER_CLASS = "org.eclipse.ant.internal.ui.antsupport.inputhandler.AntInputHandler"; //$NON-NLS-1$
86
private static final String JavaDoc REMOTE_INPUT_HANDLER_CLASS = "org.eclipse.ant.internal.ui.antsupport.inputhandler.ProxyInputHandler"; //$NON-NLS-1$
87

88     private static String JavaDoc fgSWTLibraryLocation;
89     
90     private String JavaDoc fMode;
91     private boolean fUserSpecifiedLogger= false;
92     
93     private String JavaDoc getProgramArguments(ILaunchConfiguration configuration) throws CoreException {
94         String JavaDoc arguments = configuration.getAttribute(IExternalToolConstants.ATTR_TOOL_ARGUMENTS, ""); //$NON-NLS-1$
95
return VariablesPlugin.getDefault().getStringVariableManager().performStringSubstitution(arguments);
96     }
97     
98     /**
99      * @see org.eclipse.debug.core.model.ILaunchConfigurationDelegate#launch(org.eclipse.debug.core.ILaunchConfiguration,
100      * java.lang.String, org.eclipse.debug.core.ILaunch,
101      * org.eclipse.core.runtime.IProgressMonitor)
102      */

103     public void launch(ILaunchConfiguration configuration, String JavaDoc mode, ILaunch launch, IProgressMonitor monitor) throws CoreException {
104         if (monitor.isCanceled()) {
105             return;
106         }
107         fUserSpecifiedLogger= false;
108         fMode= mode;
109         
110         // migrate the config to the new classpath format if required
111
AntUtil.migrateToNewClasspathFormat(configuration);
112         
113         boolean isSeparateJRE= AntUtil.isSeparateJREAntBuild(configuration);
114         
115         if (CommonTab.isLaunchInBackground(configuration)) {
116             monitor.beginTask(MessageFormat.format(AntLaunchConfigurationMessages.AntLaunchDelegate_Launching__0__1, new String JavaDoc[] {configuration.getName()}), 10);
117         } else {
118             monitor.beginTask(MessageFormat.format(AntLaunchConfigurationMessages.AntLaunchDelegate_Running__0__2, new String JavaDoc[] {configuration.getName()}), 100);
119         }
120         
121         // resolve location
122
IPath location = ExternalToolsUtil.getLocation(configuration);
123         monitor.worked(1);
124         
125         if (monitor.isCanceled()) {
126             return;
127         }
128         
129         if (!isSeparateJRE && AntRunner.isBuildRunning()) {
130             IStatus status= new Status(IStatus.ERROR, IAntUIConstants.PLUGIN_ID, 1, MessageFormat.format(AntLaunchConfigurationMessages.AntLaunchDelegate_Build_In_Progress, new String JavaDoc[]{location.toOSString()}), null);
131             throw new CoreException(status);
132         }
133         
134         // resolve working directory
135
IPath workingDirectory = ExternalToolsUtil.getWorkingDirectory(configuration);
136         String JavaDoc basedir = null;
137         if (workingDirectory != null) {
138             basedir= workingDirectory.toOSString();
139         }
140         monitor.worked(1);
141         
142         if (monitor.isCanceled()) {
143             return;
144         }
145
146         // link the process to its build logger via a timestamp
147
long timeStamp = System.currentTimeMillis();
148         String JavaDoc idStamp = Long.toString(timeStamp);
149         StringBuffer JavaDoc idProperty = new StringBuffer JavaDoc("-D"); //$NON-NLS-1$
150
idProperty.append(AbstractEclipseBuildLogger.ANT_PROCESS_ID);
151         idProperty.append('=');
152         idProperty.append(idStamp);
153         
154         // resolve arguments
155
String JavaDoc[] arguments = null;
156         if (isSeparateJRE) {
157             arguments = new String JavaDoc[] {getProgramArguments(configuration)};
158         } else {
159             arguments = ExternalToolsUtil.getArguments(configuration);
160         }
161         
162         Map JavaDoc userProperties= AntUtil.getProperties(configuration);
163         if (userProperties != null) {//create a copy so as to not affect the configuration with transient properties
164
userProperties= new HashMap JavaDoc(userProperties);
165         }
166         String JavaDoc[] propertyFiles= AntUtil.getPropertyFiles(configuration);
167         String JavaDoc[] targets = AntUtil.getTargetNames(configuration);
168         URL JavaDoc[] customClasspath= AntUtil.getCustomClasspath(configuration);
169         String JavaDoc antHome= AntUtil.getAntHome(configuration);
170         
171         boolean setInputHandler= true;
172         try {
173             //check if set specify inputhandler
174
setInputHandler = configuration.getAttribute(IAntUIConstants.SET_INPUTHANDLER, true);
175         } catch (CoreException ce) {
176             AntUIPlugin.log(ce);
177         }
178         
179         AntRunner runner= null;
180         if (!isSeparateJRE) {
181             runner = configureAntRunner(configuration, location, basedir, idProperty, arguments, userProperties, propertyFiles, targets, customClasspath, antHome, setInputHandler);
182         }
183          
184         monitor.worked(1);
185                                 
186         if (monitor.isCanceled()) {
187             return;
188         }
189         boolean captureOutput= ExternalToolsUtil.getCaptureOutput(configuration);
190         int port= -1;
191         int requestPort= -1;
192         if (isSeparateJRE && captureOutput) {
193             if (userProperties == null) {
194                 userProperties= new HashMap JavaDoc();
195             }
196             port= SocketUtil.findFreePort();
197             userProperties.put(AbstractEclipseBuildLogger.ANT_PROCESS_ID, idStamp);
198             userProperties.put("eclipse.connect.port", Integer.toString(port)); //$NON-NLS-1$
199
if (fMode.equals(ILaunchManager.DEBUG_MODE)) {
200                 requestPort= SocketUtil.findFreePort();
201                 userProperties.put("eclipse.connect.request_port", Integer.toString(requestPort)); //$NON-NLS-1$
202
}
203         }
204         
205         StringBuffer JavaDoc commandLine= generateCommandLine(location, arguments, userProperties, propertyFiles, targets, antHome, basedir, isSeparateJRE, captureOutput, setInputHandler);
206         
207         if (isSeparateJRE) {
208             monitor.beginTask(MessageFormat.format(AntLaunchConfigurationMessages.AntLaunchDelegate_Launching__0__1, new String JavaDoc[] {configuration.getName()}), 10);
209             runInSeparateVM(configuration, launch, monitor, idStamp, antHome, port, requestPort, commandLine, captureOutput, setInputHandler);
210         } else {
211             runInSameVM(configuration, launch, monitor, location, idStamp, runner, commandLine, captureOutput);
212         }
213         
214         monitor.done();
215     }
216     
217     private void runInSameVM(ILaunchConfiguration configuration, ILaunch launch, IProgressMonitor monitor, IPath location, String JavaDoc idStamp, AntRunner runner, StringBuffer JavaDoc commandLine, boolean captureOutput) throws CoreException {
218         Map JavaDoc attributes= new HashMap JavaDoc(2);
219         attributes.put(IProcess.ATTR_PROCESS_TYPE, IAntLaunchConfigurationConstants.ID_ANT_PROCESS_TYPE);
220         attributes.put(AbstractEclipseBuildLogger.ANT_PROCESS_ID, idStamp);
221                 
222         final AntProcess process = new AntProcess(location.toOSString(), launch, attributes);
223         setProcessAttributes(process, idStamp, commandLine, captureOutput);
224         boolean debug= fMode.equals(ILaunchManager.DEBUG_MODE);
225         if (debug || CommonTab.isLaunchInBackground(configuration)) {
226             final AntRunner finalRunner= runner;
227             Runnable JavaDoc r = new Runnable JavaDoc() {
228                 public void run() {
229                     try {
230                         finalRunner.run(process);
231                     } catch (CoreException e) {
232                         handleException(e, AntLaunchConfigurationMessages.AntLaunchDelegate_Failure);
233                     }
234                     process.terminated();
235                 }
236             };
237             Thread JavaDoc background = new Thread JavaDoc(r);
238             background.setDaemon(true);
239             background.start();
240             monitor.worked(1);
241             //refresh resources after process finishes
242
if (RefreshTab.getRefreshScope(configuration) != null) {
243                 BackgroundResourceRefresher refresher = new BackgroundResourceRefresher(configuration, process);
244                 refresher.startBackgroundRefresh();
245             }
246         } else {
247             // execute the build
248
try {
249                 runner.run(monitor);
250             } catch (CoreException e) {
251                 process.terminated();
252                 monitor.done();
253                 handleException(e, AntLaunchConfigurationMessages.AntLaunchDelegate_23);
254                 return;
255             }
256             process.terminated();
257             
258             // refresh resources
259
RefreshTab.refreshResources(configuration, monitor);
260         }
261     }
262
263     private AntRunner configureAntRunner(ILaunchConfiguration configuration, IPath location, String JavaDoc baseDir, StringBuffer JavaDoc idProperty, String JavaDoc[] arguments, Map JavaDoc userProperties, String JavaDoc[] propertyFiles, String JavaDoc[] targets, URL JavaDoc[] customClasspath, String JavaDoc antHome, boolean setInputHandler) throws CoreException {
264         int argLength = 1; // at least one user property - timestamp
265
if (arguments != null) {
266             argLength += arguments.length;
267         }
268         if (baseDir != null && baseDir.length() > 0) {
269             argLength++;
270         }
271         String JavaDoc[] runnerArgs = new String JavaDoc[argLength];
272         if (arguments != null) {
273             System.arraycopy(arguments, 0, runnerArgs, 0, arguments.length);
274         }
275         if (baseDir != null && baseDir.length() > 0) {
276             runnerArgs[runnerArgs.length - 2] = BASE_DIR_PREFIX + baseDir;
277         }
278         runnerArgs[runnerArgs.length -1] = idProperty.toString();
279         
280         AntRunner runner= new AntRunner();
281         runner.setBuildFileLocation(location.toOSString());
282         boolean captureOutput= ExternalToolsUtil.getCaptureOutput(configuration);
283         if (captureOutput) {
284             if (fMode.equals(ILaunchManager.DEBUG_MODE)) {
285                 runner.addBuildLogger(ANT_DEBUG_LOGGER_CLASS);
286             } else {
287                 runner.addBuildLogger(ANT_LOGGER_CLASS);
288             }
289         } else {
290             runner.addBuildLogger(NULL_LOGGER_CLASS);
291         }
292         if (setInputHandler) {
293             runner.setInputHandler(INPUT_HANDLER_CLASS);
294         } else {
295             runner.setInputHandler(""); //$NON-NLS-1$
296
}
297         runner.setArguments(runnerArgs);
298         if (userProperties != null) {
299             runner.addUserProperties(userProperties);
300         }
301
302         if (propertyFiles != null) {
303             runner.setPropertyFiles(propertyFiles);
304         }
305
306         if (targets != null) {
307             runner.setExecutionTargets(targets);
308         }
309
310         if (customClasspath != null) {
311             runner.setCustomClasspath(customClasspath);
312         }
313
314         if (antHome != null) {
315             runner.setAntHome(antHome);
316         }
317         return runner;
318     }
319
320     private void handleException(final CoreException e, final String JavaDoc title) {
321         IPreferenceStore store= AntUIPlugin.getDefault().getPreferenceStore();
322         if (store.getBoolean(IAntUIPreferenceConstants.ANT_ERROR_DIALOG)) {
323             AntUIPlugin.getStandardDisplay().asyncExec(new Runnable JavaDoc() {
324                 public void run() {
325                     MessageDialogWithToggle.openError(null, title, e.getMessage(), AntLaunchConfigurationMessages.AntLaunchDelegate_22, false, AntUIPlugin.getDefault().getPreferenceStore(), IAntUIPreferenceConstants.ANT_ERROR_DIALOG);
326                 }
327             });
328         }
329     }
330
331     private void setProcessAttributes(IProcess process, String JavaDoc idStamp, StringBuffer JavaDoc commandLine, boolean captureOutput) {
332         // link the process to the Eclipse build logger via a timestamp
333
if (!fUserSpecifiedLogger) {
334             process.setAttribute(AbstractEclipseBuildLogger.ANT_PROCESS_ID, idStamp);
335         }
336         
337         // create "fake" command line for the process
338
if (commandLine != null) {
339             process.setAttribute(IProcess.ATTR_CMDLINE, commandLine.toString());
340         }
341         if (captureOutput && !fUserSpecifiedLogger) {
342             TaskLinkManager.registerAntBuild(process);
343         }
344     }
345
346     private StringBuffer JavaDoc generateCommandLine(IPath location, String JavaDoc[] arguments, Map JavaDoc userProperties, String JavaDoc[] propertyFiles, String JavaDoc[] targets, String JavaDoc antHome, String JavaDoc basedir, boolean separateVM, boolean captureOutput, boolean setInputHandler) {
347         StringBuffer JavaDoc commandLine= new StringBuffer JavaDoc();
348
349         if (!separateVM) {
350             commandLine.append("ant"); //$NON-NLS-1$
351
}
352         
353         if (arguments != null) {
354             for (int i = 0; i < arguments.length; i++) {
355                 commandLine.append(' ');
356                 commandLine.append(arguments[i]);
357             }
358         }
359         
360         AntCorePreferences prefs= AntCorePlugin.getPlugin().getPreferences();
361         if (propertyFiles == null) { //global
362
String JavaDoc[] files= prefs.getCustomPropertyFiles();
363             for (int i = 0; i < files.length; i++) {
364                 String JavaDoc path = files[i];
365                 commandLine.append(" -propertyfile \""); //$NON-NLS-1$
366
commandLine.append(path);
367                 commandLine.append('\"');
368             }
369         } else {//"local" configuration
370
for (int i = 0; i < propertyFiles.length; i++) {
371                 String JavaDoc path = propertyFiles[i];
372                 commandLine.append(" -propertyfile \""); //$NON-NLS-1$
373
commandLine.append(path);
374                 commandLine.append('\"');
375             }
376         }
377         //"local" configuration
378
if (userProperties != null) {
379             Iterator JavaDoc keys = userProperties.keySet().iterator();
380             String JavaDoc key;
381             while (keys.hasNext()) {
382                 key= (String JavaDoc)keys.next();
383                 appendProperty(commandLine, key, (String JavaDoc)userProperties.get(key));
384             }
385         }
386         
387         //global
388
List JavaDoc properties= null;
389         if (!separateVM) {
390             properties= prefs.getProperties();
391         } else {
392             properties= prefs.getRemoteAntProperties();
393         }
394         
395         //if we have user properties this means that the user has chosen to override the global properties
396
//if in a separate VM and have only two (or three if debug) user properties these are really only Eclipse generated properties
397
//and the user is still using the global properties
398
int numberOfEclipseProperties= 2;
399         if (userProperties != null && userProperties.get("eclipse.connect.request_port") != null){ //$NON-NLS-1$
400
numberOfEclipseProperties= 3; //debug mode
401
}
402         boolean useGlobalProperties = userProperties == null || (separateVM && userProperties.size() == numberOfEclipseProperties);
403         if (useGlobalProperties) {
404             for (Iterator JavaDoc iter = properties.iterator(); iter.hasNext();) {
405                 Property property = (Property) iter.next();
406                 String JavaDoc key= property.getName();
407                 String JavaDoc value= property.getValue(false);
408                 if (value != null) {
409                     appendProperty(commandLine, key, value);
410                 }
411             }
412         }
413         
414         if (basedir != null && basedir.length() > 0) {
415             appendProperty(commandLine, "basedir", basedir); //$NON-NLS-1$
416
}
417         
418         if (antHome != null) {
419             commandLine.append(" \"-Dant.home="); //$NON-NLS-1$
420
commandLine.append(antHome);
421             commandLine.append('\"');
422         }
423         
424         if (separateVM) {
425             if (commandLine.indexOf("-logger") == -1) { //$NON-NLS-1$
426
if (captureOutput) {
427                 commandLine.append(" -logger "); //$NON-NLS-1$
428
if (fMode.equals(ILaunchManager.DEBUG_MODE)) {
429                     commandLine.append(REMOTE_ANT_DEBUG_LOGGER_CLASS);
430                     } else {
431                     commandLine.append(REMOTE_ANT_LOGGER_CLASS);
432                 }
433                 }
434             } else {
435                 fUserSpecifiedLogger= true;
436             }
437             if (commandLine.indexOf("-inputhandler") == -1 && setInputHandler) { //$NON-NLS-1$
438
commandLine.append(" -inputhandler "); //$NON-NLS-1$
439
commandLine.append(REMOTE_INPUT_HANDLER_CLASS);
440             }
441         } else {
442             if (commandLine.indexOf("-inputhandler") == -1 && setInputHandler) { //$NON-NLS-1$
443
commandLine.append(" -inputhandler "); //$NON-NLS-1$
444
commandLine.append(INPUT_HANDLER_CLASS);
445             }
446             if (commandLine.indexOf("-logger") == -1) { //$NON-NLS-1$
447
commandLine.append(" -logger "); //$NON-NLS-1$
448
if (fMode.equals(ILaunchManager.DEBUG_MODE)) {
449                     commandLine.append(ANT_DEBUG_LOGGER_CLASS);
450                 } else if (captureOutput) {
451                     commandLine.append(ANT_LOGGER_CLASS);
452                 } else {
453                     commandLine.append(NULL_LOGGER_CLASS);
454                 }
455             }
456         }
457         
458         if (separateVM) {
459             appendTaskAndTypes(prefs, commandLine);
460         }
461         commandLine.append(" -buildfile \""); //$NON-NLS-1$
462
commandLine.append(location.toOSString());
463         commandLine.append('\"');
464         
465         if (targets != null) {
466             for (int i = 0; i < targets.length; i++) {
467                 commandLine.append(" \""); //$NON-NLS-1$
468
commandLine.append(targets[i]);
469                 commandLine.append('\"');
470             }
471         }
472         return commandLine;
473     }
474     
475     private void appendTaskAndTypes(AntCorePreferences prefs, StringBuffer JavaDoc commandLine) {
476         List JavaDoc tasks= prefs.getRemoteTasks();
477         Iterator JavaDoc itr= tasks.iterator();
478         while (itr.hasNext()) {
479             Task task = (Task) itr.next();
480             commandLine.append(" -eclipseTask "); //$NON-NLS-1$
481
String JavaDoc name= ProjectHelper.genComponentName(task.getURI(), task.getTaskName());
482             commandLine.append(name);
483             commandLine.append(',');
484             commandLine.append(task.getClassName());
485         }
486         
487         List JavaDoc types= prefs.getRemoteTypes();
488         itr= types.iterator();
489         while (itr.hasNext()) {
490             Type type = (Type) itr.next();
491             commandLine.append(" -eclipseType "); //$NON-NLS-1$
492
String JavaDoc name= ProjectHelper.genComponentName(type.getURI(), type.getTypeName());
493             commandLine.append(name);
494             commandLine.append(',');
495             commandLine.append(type.getClassName());
496         }
497     }
498
499     private void appendProperty(StringBuffer JavaDoc commandLine, String JavaDoc name, String JavaDoc value) {
500         commandLine.append(" \"-D"); //$NON-NLS-1$
501
commandLine.append(name);
502         commandLine.append('=');
503         commandLine.append(value);
504         if (value.length() > 0 && value.charAt(value.length() - 1) == File.separatorChar) {
505             commandLine.append(File.separatorChar);
506         }
507         commandLine.append("\""); //$NON-NLS-1$
508
}
509     
510     private void runInSeparateVM(ILaunchConfiguration configuration, ILaunch launch, IProgressMonitor monitor, String JavaDoc idStamp, String JavaDoc antHome, int port, int requestPort, StringBuffer JavaDoc commandLine, boolean captureOutput, boolean setInputHandler) throws CoreException {
511         boolean debug= fMode.equals(ILaunchManager.DEBUG_MODE);
512         if (captureOutput) {
513             if (debug) {
514                 RemoteAntDebugBuildListener listener= new RemoteAntDebugBuildListener(launch);
515                 if (requestPort != -1) {
516                     listener.startListening(port, requestPort);
517                 }
518             } else if (!fUserSpecifiedLogger) {
519                 RemoteAntBuildListener client= new RemoteAntBuildListener(launch);
520                 if (port != -1) {
521                     client.startListening(port);
522                 }
523             }
524         }
525         
526         ILaunchConfigurationWorkingCopy copy= configuration.getWorkingCopy();
527         setDefaultWorkingDirectory(copy);
528         copy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROGRAM_ARGUMENTS, commandLine.toString());
529         StringBuffer JavaDoc vmArgs= generateVMArguments(copy, setInputHandler, antHome);
530         copy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_VM_ARGUMENTS, vmArgs.toString());
531         copy.setAttribute(IDebugUIConstants.ATTR_PRIVATE, true);
532         if (copy.getAttribute(IAntUIConstants.ATTR_DEFAULT_VM_INSTALL, false)) {
533             setDefaultVM(configuration, copy);
534         }
535         if (debug) { //do not allow launch in foreground bug 83254
536
copy.setAttribute(IDebugUIConstants.ATTR_LAUNCH_IN_BACKGROUND, true);
537         }
538         
539         //set the ANT_HOME environment variable
540
if (antHome != null) {
541             Map JavaDoc vars = copy.getAttribute(ILaunchManager.ATTR_ENVIRONMENT_VARIABLES, new HashMap JavaDoc(1));
542             vars.put("ANT_HOME", antHome); //$NON-NLS-1$
543
copy.setAttribute(ILaunchManager.ATTR_ENVIRONMENT_VARIABLES, vars);
544         }
545
546         //copy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_VM_ARGUMENTS, "-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000");
547
IProgressMonitor subMonitor= new SubProgressMonitor(monitor, 10);
548         AntJavaLaunchDelegate delegate= new AntJavaLaunchDelegate();
549         delegate.preLaunchCheck(copy, ILaunchManager.RUN_MODE, subMonitor);
550         delegate.launch(copy, ILaunchManager.RUN_MODE, launch, subMonitor);
551         final IProcess[] processes= launch.getProcesses();
552         for (int i = 0; i < processes.length; i++) {
553             setProcessAttributes(processes[i], idStamp, null, captureOutput);
554         }
555
556         if (CommonTab.isLaunchInBackground(copy)) {
557             // refresh resources after process finishes
558
if (RefreshTab.getRefreshScope(configuration) != null) {
559                 BackgroundResourceRefresher refresher = new BackgroundResourceRefresher(configuration, processes[0]);
560                 refresher.startBackgroundRefresh();
561             }
562         } else {
563             final boolean[] terminated= new boolean[1];
564             terminated[0]= launch.isTerminated();
565             IDebugEventSetListener listener= new IDebugEventSetListener() {
566                 public void handleDebugEvents(DebugEvent[] events) {
567                     for (int i = 0; i < events.length; i++) {
568                         DebugEvent event = events[i];
569                         for (int j= 0, numProcesses= processes.length; j < numProcesses; j++) {
570                             if (event.getSource() == processes[j] && event.getKind() == DebugEvent.TERMINATE) {
571                                 terminated[0]= true;
572                                 break;
573                             }
574                         }
575                     }
576                 }
577             };
578             DebugPlugin.getDefault().addDebugEventListener(listener);
579             monitor.subTask(AntLaunchConfigurationMessages.AntLaunchDelegate_28);
580             while (!monitor.isCanceled() && !terminated[0]) {
581                 try {
582                     Thread.sleep(50);
583                 } catch (InterruptedException JavaDoc e) {
584                 }
585             }
586             DebugPlugin.getDefault().removeDebugEventListener(listener);
587             if (!monitor.isCanceled()) {
588                 // refresh resources
589
RefreshTab.refreshResources(configuration, monitor);
590             }
591         }
592     }
593
594     private void setDefaultVM(ILaunchConfiguration configuration, ILaunchConfigurationWorkingCopy copy) {
595         try {
596             JavaRuntime.getJavaProject(configuration);
597             //remove the vm name, install type and jre container path for the Java launching concept of default VM
598
copy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_VM_INSTALL_NAME, (String JavaDoc)null);
599             copy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_VM_INSTALL_TYPE, (String JavaDoc)null);
600             copy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_JRE_CONTAINER_PATH, (String JavaDoc)null);
601         } catch (CoreException ce) {
602             //not in a Java project
603
IVMInstall defaultVMInstall= JavaRuntime.getDefaultVMInstall();
604             copy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_VM_INSTALL_NAME, defaultVMInstall.getName());
605             copy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_VM_INSTALL_TYPE, defaultVMInstall.getVMInstallType().getId());
606         }
607     }
608     
609     private StringBuffer JavaDoc generateVMArguments(ILaunchConfiguration config, boolean setInputHandler, String JavaDoc antHome) {
610         StringBuffer JavaDoc vmArgs= new StringBuffer JavaDoc();
611         try {
612             String JavaDoc configArgs= config.getAttribute(IJavaLaunchConfigurationConstants.ATTR_VM_ARGUMENTS, (String JavaDoc)null);
613             if (configArgs != null) {
614                 vmArgs.append(configArgs);
615                 vmArgs.append(' ');
616             }
617         } catch (CoreException e) {
618         }
619     
620         if (antHome != null) {
621             vmArgs.append("-Dant.home=\""); //$NON-NLS-1$
622
vmArgs.append(antHome);
623             vmArgs.append("\" "); //$NON-NLS-1$
624

625             File JavaDoc antLibDir= new File JavaDoc(antHome, "lib"); //$NON-NLS-1$
626
vmArgs.append("-Dant.library.dir=\""); //$NON-NLS-1$
627
vmArgs.append(antLibDir.getAbsolutePath());
628             vmArgs.append('\"');
629         }
630         if (setInputHandler) {
631             String JavaDoc swtLocation= getSWTLibraryLocation();
632             if (swtLocation != null) {
633                 vmArgs.append(" -Djava.library.path=\""); //$NON-NLS-1$
634
String JavaDoc javaLibPath= System.getProperty("java.library.path"); //$NON-NLS-1$
635
javaLibPath= stripUnescapedQuotes(javaLibPath);
636                 if (javaLibPath != null) {
637                     vmArgs.append(javaLibPath);
638                     if (vmArgs.charAt(vmArgs.length() - 1) != File.pathSeparatorChar) {
639                         vmArgs.append(File.pathSeparatorChar);
640                     }
641                 }
642                 vmArgs.append(swtLocation);
643                 vmArgs.append('"');
644             }
645         }
646         return vmArgs;
647     }
648
649     private String JavaDoc stripUnescapedQuotes(String JavaDoc javaLibPath) {
650         StringBuffer JavaDoc buf = new StringBuffer JavaDoc(javaLibPath.length());
651         for (int i = 0; i < javaLibPath.length(); i++) {
652             char c = javaLibPath.charAt(i);
653             switch (c) {
654                 case '"':
655                     if (i != 0 && javaLibPath.charAt(i-1) == '\\') {
656                         buf.append(c);
657                     }
658                     break;
659                 default:
660                     buf.append(c);
661                     break;
662             }
663         }
664         return buf.toString();
665     }
666
667     /* (non-Javadoc)
668      * @see org.eclipse.debug.core.model.LaunchConfigurationDelegate#getBuildOrder(org.eclipse.debug.core.ILaunchConfiguration, java.lang.String)
669      */

670     protected IProject[] getBuildOrder(ILaunchConfiguration configuration, String JavaDoc mode) throws CoreException {
671         String JavaDoc scope = null;
672         try {
673             scope = configuration.getAttribute(AntBuildTab.ATTR_BUILD_SCOPE, (String JavaDoc)null);
674         } catch (CoreException e) {
675             return null;
676         }
677         if (scope == null) {
678             return null;
679         }
680         IProject[] projects = AntBuildTab.getBuildProjects(scope);
681         boolean isRef = AntBuildTab.isIncludeReferencedProjects(configuration);
682         if (isRef) {
683             return computeReferencedBuildOrder(projects);
684         }
685         return computeBuildOrder(projects);
686     }
687
688     private String JavaDoc getSWTLibraryLocation() {
689        if (fgSWTLibraryLocation == null) {
690             Bundle bundle= Platform.getBundle("org.eclipse.swt"); //$NON-NLS-1$
691
BundleDescription description= Platform.getPlatformAdmin().getState(false).getBundle(bundle.getBundleId());
692             BundleDescription[] fragments= description.getFragments();
693             if (fragments == null || fragments.length == 0) {
694                 return null;
695             }
696             Bundle fragBundle= Platform.getBundle(fragments[0].getSymbolicName());
697             try {
698                 URL JavaDoc url= FileLocator.toFileURL(fragBundle.getEntry("/")); //$NON-NLS-1$
699
IPath path= new Path(url.getPath());
700                 path= path.removeTrailingSeparator();
701                 fgSWTLibraryLocation= path.toOSString();
702             } catch (IOException JavaDoc e) {
703             }
704         }
705         return fgSWTLibraryLocation;
706     }
707     
708      /* (non-Javadoc)
709      * @see org.eclipse.debug.core.model.LaunchConfigurationDelegate#getBreakpoints(org.eclipse.debug.core.ILaunchConfiguration)
710      */

711     protected IBreakpoint[] getBreakpoints(ILaunchConfiguration configuration) {
712          IBreakpointManager breakpointManager = DebugPlugin.getDefault().getBreakpointManager();
713          if (!breakpointManager.isEnabled()) {
714              // no need to check breakpoints individually.
715
return null;
716          }
717          return breakpointManager.getBreakpoints(IAntDebugConstants.ID_ANT_DEBUG_MODEL);
718      }
719
720     /* (non-Javadoc)
721      * @see org.eclipse.debug.core.model.LaunchConfigurationDelegate#saveBeforeLaunch(org.eclipse.debug.core.ILaunchConfiguration, java.lang.String, org.eclipse.core.runtime.IProgressMonitor)
722      */

723     protected boolean saveBeforeLaunch(ILaunchConfiguration configuration, String JavaDoc mode, IProgressMonitor monitor) throws CoreException {
724         if (IExternalToolConstants.ID_EXTERNAL_TOOLS_BUILDER_LAUNCH_CATEGORY.equals(
725                 configuration.getType().getCategory())) {
726                     // don't prompt for builders
727
return true;
728         }
729         return super.saveBeforeLaunch(configuration, mode, monitor);
730     }
731     
732     /**
733      * Sets the default working directory to be the parent folder of the buildfile if
734      * the user has not explicitly set the working directory.
735      */

736     private void setDefaultWorkingDirectory(ILaunchConfigurationWorkingCopy copy) {
737         try {
738             String JavaDoc wd = copy.getAttribute(IJavaLaunchConfigurationConstants.ATTR_WORKING_DIRECTORY, (String JavaDoc)null);
739             if (wd == null) {
740                 wd= ExternalToolsUtil.getLocation(copy).removeLastSegments(1).toOSString();
741                 copy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_WORKING_DIRECTORY, wd);
742             }
743         } catch (CoreException e) {
744             AntUIPlugin.log(e.getStatus());
745         }
746     }
747 }
748
Popular Tags