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 Juan A. Hernandez - bug 89926 dakshinamurthy.karra@gmail.com - bug 165371 /
 
 package org.eclipse.ant.internal.ui.launchConfigurations;
 
 import java.io.File;
 import java.net.URL;
 import java.util.List;
 import java.util.Map;
 
 import  org.apache.tools.ant.ProjectHelper;
 
Launch delegate for Ant builds
 
 public class AntLaunchDelegate extends LaunchConfigurationDelegate  {
 	
 	private static final String ANT_LOGGER_CLASS = "org.eclipse.ant.internal.ui.antsupport.logger.AntProcessBuildLogger"//$NON-NLS-1$
 	private static final String ANT_DEBUG_LOGGER_CLASS = "org.eclipse.ant.internal.ui.antsupport.logger.AntProcessDebugBuildLogger"//$NON-NLS-1$
 	private static final String NULL_LOGGER_CLASS = "org.eclipse.ant.internal.ui.antsupport.logger.NullBuildLogger"//$NON-NLS-1$
 	private static final String REMOTE_ANT_LOGGER_CLASS = "org.eclipse.ant.internal.ui.antsupport.logger.RemoteAntBuildLogger"//$NON-NLS-1$
 	private static final String REMOTE_ANT_DEBUG_LOGGER_CLASS = "org.eclipse.ant.internal.ui.antsupport.logger.debug.RemoteAntDebugBuildLogger"//$NON-NLS-1$
 	private static final String BASE_DIR_PREFIX = "-Dbasedir="//$NON-NLS-1$
 	private static final String INPUT_HANDLER_CLASS = "org.eclipse.ant.internal.ui.antsupport.inputhandler.AntInputHandler"//$NON-NLS-1$
 	private static final String REMOTE_INPUT_HANDLER_CLASS = "org.eclipse.ant.internal.ui.antsupport.inputhandler.ProxyInputHandler"//$NON-NLS-1$
     
String attribute identifying the build scope for a launch configuration. null indicates the default workspace build. Note: this attribute was used with the old 'AntBuildTab' which has been replaced by the 'ExternalToolsBuildTab'. The 'ExternalToolsBuildTab' uses a different attribute key, so use the external tools attribute when present: IExternalToolConstants.ATTR_BUILD_SCOPE
	private static final String ATTR_BUILD_SCOPE = AntUIPlugin.getUniqueIdentifier() + ".ATTR_BUILD_SCOPE"//$NON-NLS-1$
Attribute identifier specifying whether referenced projects should be considered when computing the projects to build. Default value is true. Note: this attribute was used with the old 'AntBuildTab' which has been replaced by the 'ExternalToolsBuildTab'. The 'ExternalToolsBuildTab' uses a different attribute key, so use the external tools attribute when present: IExternalToolConstants.ATTR_INCLUDE_REFERENCED_PROJECTS
	private static final String ATTR_INCLUDE_REFERENCED_PROJECTS = AntUIPlugin.getUniqueIdentifier() + ".ATTR_INCLUDE_REFERENCED_PROJECTS"//$NON-NLS-1$
    private static String fgSWTLibraryLocation;
	private String fMode;
    private boolean fUserSpecifiedLoggerfalse;
    
    private String getProgramArguments(ILaunchConfiguration configurationthrows CoreException {
		String arguments = configuration.getAttribute(.""); //$NON-NLS-1$
		return VariablesPlugin.getDefault().getStringVariableManager().performStringSubstitution(arguments);
	}

See also:
org.eclipse.debug.core.model.ILaunchConfigurationDelegate.launch(org.eclipse.debug.core.ILaunchConfiguration, java.lang.String, org.eclipse.debug.core.ILaunch, org.eclipse.core.runtime.IProgressMonitor)
	public void launch(ILaunchConfiguration configurationString modeILaunch launchIProgressMonitor monitorthrows CoreException {
		if (monitor.isCanceled()) {
			return;
		}
		mode;
		// migrate the config to the new classpath format if required
		AntUtil.migrateToNewClasspathFormat(configuration);
		boolean isSeparateJRE= AntUtil.isSeparateJREAntBuild(configuration);
		if (CommonTab.isLaunchInBackground(configuration)) {
			monitor.beginTask(MessageFormat.format(.new String[] {configuration.getName()}), 10);
else {
			monitor.beginTask(MessageFormat.format(.new String[] {configuration.getName()}), 100);
		}
		// resolve location
		IPath location = ExternalToolsUtil.getLocation(configuration);
		monitor.worked(1);
		if (monitor.isCanceled()) {
			return;
		}
		if (!isSeparateJRE && AntRunner.isBuildRunning()) {
			throw new CoreException(status);
		}		
		// resolve working directory
		IPath workingDirectory = ExternalToolsUtil.getWorkingDirectory(configuration);
		String basedir = null;
		if (workingDirectory != null) {
			basedirworkingDirectory.toOSString();
		}
		monitor.worked(1);
		if (monitor.isCanceled()) {
			return;
		}
		// link the process to its build logger via a timestamp
		long timeStamp = System.currentTimeMillis();
		String idStamp = Long.toString(timeStamp);
		StringBuffer idProperty = new StringBuffer("-D"); //$NON-NLS-1$
		idProperty.append('=');
		idProperty.append(idStamp);
		// resolve arguments	
		String[] arguments = null;
		if (isSeparateJRE) {
			arguments = new String[] {getProgramArguments(configuration)};
        } else { 
			arguments = ExternalToolsUtil.getArguments(configuration);
        }
		Map userProperties= AntUtil.getProperties(configuration);
		if (userProperties != null) {//create a copy so as to not affect the configuration with transient properties
			userPropertiesnew HashMap(userProperties);
		}
		String[] propertyFiles= AntUtil.getPropertyFiles(configuration);
		String[] targets = AntUtil.getTargetNames(configuration);
		URL[] customClasspath= AntUtil.getCustomClasspath(configuration);
		String antHome= AntUtil.getAntHome(configuration);
		boolean setInputHandlertrue;
		try {
			//check if set specify inputhandler
			setInputHandler = configuration.getAttribute(.true);
catch (CoreException ce) {
			AntUIPlugin.log(ce);			
		}
		AntRunner runnernull;
		if (!isSeparateJRE) {
			runner = configureAntRunner(configurationlocationbasediridPropertyargumentsuserPropertiespropertyFilestargetscustomClasspathantHomesetInputHandler);
		}
		 
		monitor.worked(1);
		if (monitor.isCanceled()) {
			return;
		}
		boolean captureOutput= ExternalToolsUtil.getCaptureOutput(configuration);
		int port= -1;
		int requestPort= -1;
		if (isSeparateJRE && captureOutput) {
			if (userProperties == null) {
				userPropertiesnew HashMap();
			}
			port= SocketUtil.findFreePort();
			userProperties.put("eclipse.connect.port", Integer.toString(port)); //$NON-NLS-1$
				requestPort= SocketUtil.findFreePort();
				userProperties.put("eclipse.connect.request_port", Integer.toString(requestPort)); //$NON-NLS-1$
			}
		}
		StringBuffer commandLinegenerateCommandLine(locationargumentsuserPropertiespropertyFilestargetsantHomebasedirisSeparateJREcaptureOutputsetInputHandler);
		if (isSeparateJRE) {
			monitor.beginTask(MessageFormat.format(.new String[] {configuration.getName()}), 10);
			runInSeparateVM(configurationlaunchmonitoridStampantHomeportrequestPortcommandLinecaptureOutputsetInputHandler);
else {
			runInSameVM(configurationlaunchmonitorlocationidStamprunnercommandLinecaptureOutput);
		}
		monitor.done();	
	}
	private void runInSameVM(ILaunchConfiguration configurationILaunch launchIProgressMonitor monitorIPath locationString idStampAntRunner runnerStringBuffer commandLineboolean captureOutputthrows CoreException {
		Map attributesnew HashMap(2);
		final AntProcess process = new AntProcess(location.toOSString(), launchattributes);
		setProcessAttributes(processidStampcommandLinecaptureOutput);
		if (debug || CommonTab.isLaunchInBackground(configuration)) {
			final AntRunner finalRunnerrunner;
			Runnable r = new Runnable() {
				public void run() {
					try {
						finalRunner.run(process);
catch (CoreException e) {
					}
					process.terminated();
				}
			};
			Thread background = new Thread(r);
            background.setDaemon(true);
			background.start();
			monitor.worked(1);
			//refresh resources after process finishes
			if (RefreshTab.getRefreshScope(configuration) != null) {
				BackgroundResourceRefresher refresher = new BackgroundResourceRefresher(configurationprocess);
			}	
else {
			// execute the build 
			try {
				runner.run(monitor);
catch (CoreException e) {
				process.terminated();
				monitor.done();
				return;
			}
			process.terminated();
			// refresh resources
			RefreshTab.refreshResources(configurationmonitor);
		}
	}
	private AntRunner configureAntRunner(ILaunchConfiguration configurationIPath locationString baseDirStringBuffer idPropertyString[] argumentsMap userPropertiesString[] propertyFilesString[] targetsURL[] customClasspathString antHomeboolean setInputHandlerthrows CoreException {
		int argLength = 1; // at least one user property - timestamp
		if (arguments != null) {
			argLength += arguments.length;
		}		
		if (baseDir != null && baseDir.length() > 0) {
			argLength++;
		}
		String[] runnerArgs = new String[argLength];
		if (arguments != null) {
			System.arraycopy(arguments, 0, runnerArgs, 0, arguments.length);
		}
		if (baseDir != null && baseDir.length() > 0) {
			runnerArgs[runnerArgs.length - 2] =  + baseDir;
		}
		runnerArgs[runnerArgs.length -1] = idProperty.toString();
		AntRunner runnernew AntRunner();
		runner.setBuildFileLocation(location.toOSString());
		boolean captureOutput= ExternalToolsUtil.getCaptureOutput(configuration);
		if (captureOutput) {
else {
			}
else {
		}
		if (setInputHandler) {
else {
			runner.setInputHandler(""); //$NON-NLS-1$
		}
		runner.setArguments(runnerArgs);
		if (userProperties != null) {
			runner.addUserProperties(userProperties);
		}
		if (propertyFiles != null) {
			runner.setPropertyFiles(propertyFiles);
		}
		if (targets != null) {
			runner.setExecutionTargets(targets);
		}
		if (customClasspath != null) {
			runner.setCustomClasspath(customClasspath);
		}
		if (antHome != null) {
			runner.setAntHome(antHome);
		}
		return runner;
	}
	private void handleException(final CoreException efinal String title) {
			AntUIPlugin.getStandardDisplay().asyncExec(new Runnable() {
				public void run() {
				}
			});
		}
	}
	private void setProcessAttributes(IProcess processString idStampStringBuffer commandLineboolean captureOutput) {
		// link the process to the Eclipse build logger via a timestamp
        if (!) {
            process.setAttribute(.idStamp);
        }
		// create "fake" command line for the process
		if (commandLine != null) {
			process.setAttribute(.commandLine.toString());
		}
		if (captureOutput && !) {
			TaskLinkManager.registerAntBuild(process);
		}
	}
	private StringBuffer generateCommandLine(IPath locationString[] argumentsMap userPropertiesString[] propertyFilesString[] targetsString antHomeString basedirboolean separateVMboolean captureOutputboolean setInputHandler) {
		StringBuffer commandLinenew StringBuffer();
		if (!separateVM) {
			commandLine.append("ant"); //$NON-NLS-1$
		}
		if (arguments != null) {
			for (int i = 0; i < arguments.lengthi++) {
				commandLine.append(' ');
				commandLine.append(arguments[i]);
			}
		}
		AntCorePreferences prefs= AntCorePlugin.getPlugin().getPreferences();
		if (propertyFiles == null) { //global
			String[] filesprefs.getCustomPropertyFiles();
			for (int i = 0; i < files.lengthi++) {
				String path = files[i];
				commandLine.append(" -propertyfile \""); //$NON-NLS-1$
				commandLine.append(path);
				commandLine.append('\"');
			}
else {//"local" configuration
			for (int i = 0; i < propertyFiles.lengthi++) {
				String path = propertyFiles[i];
				commandLine.append(" -propertyfile \""); //$NON-NLS-1$
				commandLine.append(path);
				commandLine.append('\"');
			}
		}
		//"local" configuration
		if (userProperties != null) {
			Iterator keys = userProperties.keySet().iterator();
			String key;
			while (keys.hasNext()) {
				key= (String)keys.next();
				appendProperty(commandLinekey, (String)userProperties.get(key));
			}
		}
		//global
		List propertiesnull;
		if (!separateVM) {
			propertiesprefs.getProperties();
else {
			propertiesprefs.getRemoteAntProperties();
		}
		//if we have user properties this means that the user has chosen to override the global properties
		//if in a separate VM and have only two (or three if debug) user properties these are really only Eclipse generated properties
		//and the user is still using the global properties
		int numberOfEclipseProperties= 2;
		if (userProperties != null && userProperties.get("eclipse.connect.request_port") != null){ //$NON-NLS-1$
			numberOfEclipseProperties= 3; //debug mode
		}
		boolean useGlobalProperties = userProperties == null || (separateVM && userProperties.size() == numberOfEclipseProperties);
		if (useGlobalProperties) {
			for (Iterator iter = properties.iterator(); iter.hasNext();) {
				Property property = (Propertyiter.next();
				String keyproperty.getName();
				String valueproperty.getValue(false);
				if (value != null) {
					appendProperty(commandLinekeyvalue);
				}
			}
		}
		if (basedir != null && basedir.length() > 0) {
			appendProperty(commandLine"basedir"basedir); //$NON-NLS-1$
		}
		if (antHome != null) {
			commandLine.append(" \"-Dant.home="); //$NON-NLS-1$
			commandLine.append(antHome);
			commandLine.append('\"');
		}
		if (separateVM) { 
			if (commandLine.indexOf("-logger") == -1) { //$NON-NLS-1$
				if (captureOutput) {
				commandLine.append(" -logger "); //$NON-NLS-1$
else {
				}
				}
else {
			    true;
            }
			if (commandLine.indexOf("-inputhandler") == -1 && setInputHandler) { //$NON-NLS-1$
				commandLine.append(" -inputhandler "); //$NON-NLS-1$
			}
else {
			if (commandLine.indexOf("-inputhandler") == -1 && setInputHandler) { //$NON-NLS-1$
				commandLine.append(" -inputhandler "); //$NON-NLS-1$
			}
            if (commandLine.indexOf("-logger") == -1) { //$NON-NLS-1$
    			commandLine.append(" -logger "); //$NON-NLS-1$
    				commandLine.append();
    			} else if (captureOutput) {
    				commandLine.append();
    			} else {
    				commandLine.append();
    			}
            }
		}
		if (separateVM) {
			appendTaskAndTypes(prefscommandLine);
		}
		commandLine.append(" -buildfile \""); //$NON-NLS-1$
		commandLine.append(location.toOSString());
		commandLine.append('\"');
		if (targets != null) {
			for (int i = 0; i < targets.lengthi++) {
				commandLine.append(" \""); //$NON-NLS-1$
				commandLine.append(targets[i]);
				commandLine.append('\"');
			}
		}
		return commandLine;
	}
	private void appendTaskAndTypes(AntCorePreferences prefsStringBuffer commandLine) {
		List tasksprefs.getRemoteTasks();
		Iterator itrtasks.iterator();
		while (itr.hasNext()) {
			Task task = (Taskitr.next();
			commandLine.append(" -eclipseTask "); //$NON-NLS-1$
			String name= ProjectHelper.genComponentName(task.getURI(), task.getTaskName());
			commandLine.append(name);
			commandLine.append(',');
			commandLine.append(task.getClassName());
		}
		List typesprefs.getRemoteTypes();
		itrtypes.iterator();
		while (itr.hasNext()) {
			Type type = (Typeitr.next();
			commandLine.append(" -eclipseType "); //$NON-NLS-1$
			String name= ProjectHelper.genComponentName(type.getURI(), type.getTypeName());
			commandLine.append(name);
			commandLine.append(',');
			commandLine.append(type.getClassName());
		}
	}
	private void appendProperty(StringBuffer commandLineString nameString value) {
		commandLine.append(" \"-D"); //$NON-NLS-1$
		commandLine.append(name);
		commandLine.append('=');
		commandLine.append(value);
        if (value.length() > 0 && value.charAt(value.length() - 1) == .) {
            commandLine.append(.);
        }
		commandLine.append("\""); //$NON-NLS-1$
	}
	private void runInSeparateVM(ILaunchConfiguration configurationILaunch launchIProgressMonitor monitorString idStampString antHomeint portint requestPortStringBuffer commandLineboolean captureOutputboolean setInputHandlerthrows CoreException {
        boolean debug.equals(.);
		if (captureOutput) {
			if (debug) {
				if (requestPort != -1) {
					listener.startListening(portrequestPort);
				}
else if (!) {
				if (port != -1) {
					client.startListening(port);
				}
			}
		}
		StringBuffer vmArgsgenerateVMArguments(copysetInputHandlerantHome);
        copy.setAttribute(.true);
        	setDefaultVM(configurationcopy);
        }
        if (debug) { //do not allow launch in foreground bug 83254
            copy.setAttribute(.true);
        }
        
        //set the ANT_HOME environment variable
        if (antHome != null) {
            Map vars = copy.getAttribute(.new HashMap(1));
            vars.put("ANT_HOME"antHome); //$NON-NLS-1$
            copy.setAttribute(.vars);
        }
		//copy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_VM_ARGUMENTS, "-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000");
		IProgressMonitor subMonitornew SubProgressMonitor(monitor, 10);
		delegate.preLaunchCheck(copy.subMonitor);
		delegate.launch(copy.launchsubMonitor);
		final IProcess[] processeslaunch.getProcesses();
		for (int i = 0; i < processes.lengthi++) {
			setProcessAttributes(processes[i], idStampnullcaptureOutput);
		}
		if (CommonTab.isLaunchInBackground(copy)) {
			// refresh resources after process finishes
			if (RefreshTab.getRefreshScope(configuration) != null) {
				BackgroundResourceRefresher refresher = new BackgroundResourceRefresher(configurationprocesses[0]);
			}
else {
			final boolean[] terminatednew boolean[1];
			terminated[0]= launch.isTerminated();
				public void handleDebugEvents(DebugEvent[] events) {
					for (int i = 0; i < events.lengthi++) {
						DebugEvent event = events[i];
						for (int j= 0, numProcessesprocesses.lengthj < numProcessesj++) {
							if (event.getSource() == processes[j] && event.getKind() == .) {
								terminated[0]= true;
								break;
							}
						}
					}
				}
			};
			DebugPlugin.getDefault().addDebugEventListener(listener);
			while (!monitor.isCanceled() && !terminated[0]) {
				try {
					Thread.sleep(50);
catch (InterruptedException e) {
				}
			}
			DebugPlugin.getDefault().removeDebugEventListener(listener);
			if (!monitor.isCanceled()) {
				// refresh resources
				RefreshTab.refreshResources(configurationmonitor);
			}
		}
	}
	private void setDefaultVM(ILaunchConfiguration configurationILaunchConfigurationWorkingCopy copy) {
		try {
			JavaRuntime.getJavaProject(configuration);
			//remove the vm name, install type and jre container path for the Java launching concept of default VM
catch (CoreException ce) {
			//not in a Java project
			IVMInstall defaultVMInstall= JavaRuntime.getDefaultVMInstall();
		}
	}
	private StringBuffer generateVMArguments(ILaunchConfiguration configboolean setInputHandlerString antHome) {
		StringBuffer vmArgsnew StringBuffer();
		try {
			if (configArgs != null) {
				vmArgs.append(configArgs);
				vmArgs.append(' ');
			}
catch (CoreException e) {
		}
        if (antHome != null) {
            vmArgs.append("-Dant.home=\""); //$NON-NLS-1$
            vmArgs.append(antHome);
            vmArgs.append("\" "); //$NON-NLS-1$
        
            File antLibDirnew File(antHome"lib"); //$NON-NLS-1$
            vmArgs.append("-Dant.library.dir=\""); //$NON-NLS-1$
            vmArgs.append(antLibDir.getAbsolutePath());
            vmArgs.append('\"');
        }
		if (setInputHandler) {
			String swtLocationgetSWTLibraryLocation();
			if (swtLocation != null) {
				vmArgs.append(" -Djava.library.path=\""); //$NON-NLS-1$
				String javaLibPath= System.getProperty("java.library.path"); //$NON-NLS-1$
                javaLibPathstripUnescapedQuotes(javaLibPath);
				if (javaLibPath != null) {
					vmArgs.append(javaLibPath);
					if (vmArgs.charAt(vmArgs.length() - 1) != .) {
					}
				}
				vmArgs.append(swtLocation);
				vmArgs.append('"');
			}
		}
		return vmArgs;
    }
    private String stripUnescapedQuotes(String javaLibPath) {
        StringBuffer buf = new StringBuffer(javaLibPath.length());
        for (int i = 0; i < javaLibPath.length(); i++) {
            char c = javaLibPath.charAt(i);
            switch (c) {
                case '"':
                    if (i != 0 && javaLibPath.charAt(i-1) == '\\') {
                        buf.append(c);
                    }
                    break;
                default:
                    buf.append(c);
                    break;
            }
        }
        return buf.toString();
    }
    /* (non-Javadoc)
	 * @see org.eclipse.debug.core.model.LaunchConfigurationDelegate#getBuildOrder(org.eclipse.debug.core.ILaunchConfiguration, java.lang.String)
	 */
	protected IProject[] getBuildOrder(ILaunchConfiguration configurationString modethrows CoreException {
		String scopeKey = ;
				// use new attributes when present - see bug 282581
		}
		IProject[] projects = ExternalToolsBuildTab.getBuildProjects(configurationscopeKey);
		if (projects == null) {
			return null// null scope indicates workspace build, vs. empty projects == empty scope
		}
		boolean isRef = ExternalToolsBuildTab.isIncludeReferencedProjects(configurationrefKey);
		if (isRef) {
			return computeReferencedBuildOrder(projects);
		}
		return computeBuildOrder(projects);
	}
       if ( == null) {
            Bundle bundle= Platform.getBundle("org.eclipse.swt"); //$NON-NLS-1$
            BundleDescription description= Platform.getPlatformAdmin().getState(false).getBundle(bundle.getBundleId());
            BundleDescription[] fragmentsdescription.getFragments();
            if (fragments == null || fragments.length == 0) {
                return null;
            }
            Bundle fragBundle= Platform.getBundle(fragments[0].getSymbolicName());
            try {
                URL url= FileLocator.toFileURL(fragBundle.getEntry("/")); //$NON-NLS-1$
                IPath pathnew Path(url.getPath());
                pathpath.removeTrailingSeparator();
                path.toOSString();
            } catch (IOException e) {
            }
		}
        return ;
	}
    
     /* (non-Javadoc)
     * @see org.eclipse.debug.core.model.LaunchConfigurationDelegate#getBreakpoints(org.eclipse.debug.core.ILaunchConfiguration)
     */
    protected IBreakpoint[] getBreakpoints(ILaunchConfiguration configuration) {
         IBreakpointManager breakpointManager = DebugPlugin.getDefault().getBreakpointManager();
         if (!breakpointManager.isEnabled()) {
             // no need to check breakpoints individually.
             return null;
         }
         return breakpointManager.getBreakpoints(.);
     }
	/* (non-Javadoc)
	 * @see org.eclipse.debug.core.model.LaunchConfigurationDelegate#saveBeforeLaunch(org.eclipse.debug.core.ILaunchConfiguration, java.lang.String, org.eclipse.core.runtime.IProgressMonitor)
	 */
	protected boolean saveBeforeLaunch(ILaunchConfiguration configurationString modeIProgressMonitor monitorthrows CoreException {
				configuration.getType().getCategory())) {
					// don't prompt for builders
					return true;
		}
		return super.saveBeforeLaunch(configurationmodemonitor);
	}

Sets the default working directory to be the parent folder of the buildfile if the user has not explicitly set the working directory.
		try {
			if (wd == null) {
				wd= ExternalToolsUtil.getLocation(copy).removeLastSegments(1).toOSString();
			}
catch (CoreException e) {
			AntUIPlugin.log(e.getStatus());
		}
	}
New to GrepCode? Check out our FAQ X