下面列出了怎么用org.eclipse.debug.core.ILaunch的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public final ILaunch getLaunch(ILaunchConfiguration configuration, String mode) throws CoreException {
try {
buildTargetSettings = getBuildTargetSettings(configuration);
buildTarget = buildTargetSettings.getValidBuildTarget();
processLauncher = getValidLaunchInfo(configuration, buildTargetSettings);
} catch(CommonException ce) {
throw EclipseCore.createCoreException(ce);
}
if(ILaunchManager.RUN_MODE.equals(mode)) {
return getLaunchForRunMode(configuration, mode);
}
if(ILaunchManager.DEBUG_MODE.equals(mode)) {
return getLaunchForDebugMode(configuration, mode);
}
throw abort_UnsupportedMode(mode);
}
@Override
public void launchesTerminated(ILaunch[] launches) {
for (ILaunch launch : launches) {
ILaunchConfiguration config = launch.getLaunchConfiguration();
try {
if (config.hasAttribute(CodewindLaunchConfigDelegate.CONNECTION_ID_ATTR) && config.hasAttribute(CodewindLaunchConfigDelegate.PROJECT_ID_ATTR)) {
CodewindConnection conn = CodewindConnectionManager.getConnectionById(config.getAttribute(CodewindLaunchConfigDelegate.CONNECTION_ID_ATTR, ""));
CodewindApplication app = conn == null ? null : conn.getAppByID(config.getAttribute(CodewindLaunchConfigDelegate.PROJECT_ID_ATTR, ""));
if (app != null) {
app.launchTerminated(launch);
}
}
} catch (CoreException e) {
Logger.logError("An error occurred trying to look up the application for a launch configuration", e);
}
}
}
/**
* Create a new instance.
*
* @param name The name of the launch configuration.
* @param model The model associated with this launch configuration
*/
LaunchConfiguration(ILaunch launch, String name, WebAppDebugModel model) {
id = model.getModelNodeNextId();
this.launch = launch;
this.name = name;
this.model = model;
// We're caching the type ID as
// ModelLabelProvider.getLaunchConfigurationImage() may request it even
// after the actual launch configuration has been deleted.
String typeId = WebAppLaunchConfiguration.TYPE_ID;
ILaunchConfiguration launchConfiguration = launch.getLaunchConfiguration();
if (launchConfiguration != null) {
try {
typeId = launchConfiguration.getType().getIdentifier();
} catch (CoreException e) {
GWTPluginLog.logError(e,
"Could not determine the launch configuration type");
}
}
this.launchTypeId = typeId;
}
public static ILaunch startDiagnostics(String connectionName, String conid, boolean includeEclipseWorkspace, boolean includeProjectInfo, IProgressMonitor monitor) throws IOException, CoreException {
List<String> options = new ArrayList<String>();
options.add(CLIUtil.CON_ID_OPTION);
options.add(conid);
if (includeEclipseWorkspace) {
options.add(ECLIPSE_WORKSPACE_OPTION);
options.add(ResourcesPlugin.getWorkspace().getRoot().getLocation().toOSString());
}
if (includeProjectInfo) {
options.add(PROJECTS_OPTION);
}
List<String> command = CLIUtil.getCWCTLCommandList(null, DIAGNOSTICS_COLLECT_CMD, options.toArray(new String[options.size()]), null);
ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager();
ILaunchConfigurationType launchConfigurationType = launchManager.getLaunchConfigurationType(UtilityLaunchConfigDelegate.LAUNCH_CONFIG_ID);
ILaunchConfigurationWorkingCopy workingCopy = launchConfigurationType.newInstance((IContainer) null, connectionName);
workingCopy.setAttribute(UtilityLaunchConfigDelegate.TITLE_ATTR, Messages.UtilGenDiagnosticsTitle);
workingCopy.setAttribute(UtilityLaunchConfigDelegate.COMMAND_ATTR, command);
ILaunchConfiguration launchConfig = workingCopy.doSave();
return launchConfig.launch(ILaunchManager.RUN_MODE, monitor);
}
@Override
public void launchTerminated(ILaunch launch) {
if (debugPFInfo != null && launch == debugPFInfo.launch) {
// The user terminated the port forwarding
IPreferenceStore prefs = CodewindCorePlugin.getDefault().getPreferenceStore();
if (!prefs.getBoolean(NOTIFY_PORT_FORWARD_TERMINATED_PREFSKEY)) {
Display.getDefault().asyncExec(() -> {
MessageDialogWithToggle portForwardEndDialog = MessageDialogWithToggle.openInformation(Display.getDefault().getActiveShell(),
Messages.PortForwardTerminateTitle,
NLS.bind(Messages.PortForwardTerminateMsg, new String[] {name, connection.getName(), Integer.toString(debugPFInfo.remotePort)}),
Messages.PortForwardTerminateToggleMsg, false, null, null);
prefs.setValue(NOTIFY_PORT_FORWARD_TERMINATED_PREFSKEY, portForwardEndDialog.getToggleState());
});
}
debugPFInfo = null;
CoreUtil.updateApplication(this);
} else if (launch == getLaunch()) {
// Make sure the port forward process is terminated
if (debugPFInfo != null) {
debugPFInfo.terminate();
debugPFInfo = null;
}
CoreUtil.updateApplication(this);
}
}
private void displayCodeServerUrlInDevMode(final ILaunch launch, String text) {
if (!text.contains("http")) {
return;
}
// Extract URL http://localhost:9876/
String url = text.replaceAll(".*(http.*).*?", "$1").trim();
if (url.matches(".*/")) {
url = url.substring(0, url.length() - 1);
launchUrls.add(url);
}
// Dev Mode View, add url
LaunchConfiguration lc = WebAppDebugModel.getInstance().addOrReturnExistingLaunchConfiguration(launch, "", null);
lc.setLaunchUrls(launchUrls);
}
public PyDebugTargetServer(ILaunch launch, IPath[] file, RemoteDebuggerServer debugger) {
this.file = file;
this.debugger = debugger;
this.threads = new PyThread[0];
this.launch = launch;
if (launch != null) {
for (IDebugTarget target : launch.getDebugTargets()) {
if (target instanceof PyDebugTargetServer && target.isTerminated()) {
launch.removeDebugTarget(target);
}
}
launch.addDebugTarget(this);
}
debugger.addTarget(this);
PyExceptionBreakPointManager.getInstance().addListener(this);
PyPropertyTraceManager.getInstance().addListener(this);
IBreakpointManager breakpointManager = DebugPlugin.getDefault().getBreakpointManager();
breakpointManager.addBreakpointListener(this);
// we have to know when we get removed, so that we can shut off the debugger
DebugPlugin.getDefault().getLaunchManager().addLaunchListener(this);
}
@Override
public void run() {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
IDebugTarget[] debugTargets = debugTarget.getLaunch().getDebugTargets();
for (IDebugTarget current : debugTargets) {
ILaunch launch = current.getLaunch();
SCTDebugTarget target = (SCTDebugTarget) launch.getDebugTarget();
try {
target.getLaunch().terminate();
} catch (CoreException e) {
e.printStackTrace();
}
}
ILaunchConfiguration launchConfiguration = debugTarget.getLaunch().getLaunchConfiguration();
DebugUITools.launch(launchConfiguration, debugTarget.getLaunch().getLaunchMode());
}
});
}
/**
* Removes a launch from a pydev console and stops the related process (may be called from a thread).
*
* @param launch the launch to be removed
*/
public void removeConsoleLaunch(ILaunch launch) {
boolean removed;
synchronized (consoleLaunchesLock) {
removed = consoleLaunches.remove(launch);
}
if (removed) {
IProcess[] processes = launch.getProcesses();
if (processes != null) {
for (IProcess p : processes) {
try {
p.terminate();
} catch (Exception e) {
Log.log(e);
}
}
}
}
}
@Test
public void testLaunchTerminatedAfterSessionStarted() {
ITestRunSession testRunSession = mockTestRunSession( OK, mockTestCaseElement() );
testRunListener.sessionLaunched( testRunSession );
testRunListener.sessionStarted( testRunSession );
ILaunch launch = mockLaunch( testRunSession.getTestRunName() );
fireLaunchTerminated( launch );
InOrder order = inOrder( progressUI );
order.verify( progressUI ).update( STARTING, SWT.LEFT, null, 0, 0 );
order.verify( progressUI ).setToolTipText( testRunSession.getTestRunName() );
order.verify( progressUI ).update( "0 / 1", SWT.CENTER, successColor(), 0, 1 );
order.verify( progressUI ).setToolTipText( testRunSession.getTestRunName() );
order.verifyNoMoreInteractions();
}
public static String getEncodingFromFrame(PyStackFrame selectedFrame) {
try {
IDebugTarget adapter = selectedFrame.getAdapter(IDebugTarget.class);
if (adapter == null) {
return "UTF-8";
}
IProcess process = adapter.getProcess();
if (process == null) {
return "UTF-8";
}
ILaunch launch = process.getLaunch();
if (launch == null) {
Log.log("Unable to get launch for: " + process);
return "UTF-8";
}
return getEncodingFromLaunch(launch);
} catch (Exception e) {
Log.log(e);
return "UTF-8";
}
}
@Override
protected ISimulationEngine createExecutionContainer(final ILaunch launch, Statechart statechart) {
try {
Injector injector = getInjector(statechart, launch);
IFile file = WorkspaceSynchronizer.getFile(statechart.eResource());
injector.injectMembers(this);
for (IOperationExecutor mockup : mockups) {
if (mockup instanceof JavaOperationMockup) {
IProject project = file.getProject();
String classes = launch.getLaunchConfiguration().getAttribute(ISCTLaunchParameters.OPERATION_CLASS,
"");
String[] split = classes.split(",");
((JavaOperationMockup) mockup).initOperationCallbacks(project, split);
}
}
return factory.createExecutionContainer(statechart, launch);
} catch (CoreException e) {
e.printStackTrace();
return null;
}
}
public boolean isRunning() {
final ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager();
final ILaunch[] launches = launchManager.getLaunches();
for (int i = 0; i < launches.length; i++) {
final ILaunch launch = launches[i];
if (launch.getLaunchConfiguration() != null
&& launch.getLaunchConfiguration().contentsEqual(this.launchConfig)) {
if (!launch.isTerminated()) {
return true;
}
}
}
return false;
}
public ILaunch getLaunch(ILaunchConfiguration configuration, String mode) {
if (TestabilityConstants.TESTABILITY.equals(mode)) {
return new Launch(configuration, mode, null);
} else {
throw new IllegalStateException(
"Cannot launch testability configuration when not in testability mode.");
}
}
public ISimulationEngine createExecutionContainer(Statechart statechart, ILaunch launch) throws CoreException {
ISimulationEngine controller = createController(statechart);
injector.injectMembers(controller);
// For restoring execution context
String attribute = launch.getLaunchConfiguration().getAttribute(ISCTLaunchParameters.EXECUTION_CONTEXT, "");
if (attribute != null && attribute.trim().length() > 0) {
ExecutionContext context = restore(attribute, statechart);
controller.setExecutionContext(context);
}
return controller;
}
@SuppressWarnings("unchecked")
@Override
protected <T> T createModelAdapter(Class<T> adapterType, ILaunch launch, DsfSession session) {
if (IViewerInputProvider.class.equals(adapterType)) {
return (T) createGdbViewModelAdapter(session, getSteppingController());
}
return super.createModelAdapter(adapterType, launch, session);
}
/**
* Waits until a debug target is available in the passed launch
* @return the debug target found
*/
public IDebugTarget waitForDebugTargetAvailable(final ILaunch launch) throws Throwable {
waitForCondition(new ICallback() {
@Override
public Object call(Object args) throws Exception {
return launch.getDebugTarget() != null;
}
}, "waitForDebugTargetAvailable");
return launch.getDebugTarget();
}
public static Optional<IConsole> getConsoleForLaunch(ILaunch launch) {
List<IProcess> processes = Arrays.asList(launch.getProcesses());
return Arrays.stream(ConsolePlugin.getDefault().getConsoleManager().getConsoles())
.filter(console -> console instanceof org.eclipse.debug.ui.console.IConsole
&& processes.contains(((org.eclipse.debug.ui.console.IConsole) console).getProcess()))
.findFirst();
}
@Override
public void launchRemoved(ILaunch launch) {
// shut down the remote debugger when parent launch
if (launch == this.launch) {
IBreakpointManager breakpointManager = DebugPlugin.getDefault().getBreakpointManager();
breakpointManager.removeBreakpointListener(this);
PyExceptionBreakPointManager.getInstance().removeListener(this);
PyPropertyTraceManager.getInstance().removeListener(this);
debugger.dispose();
debugger = null;
}
}
protected ILaunch getLaunch(CodewindApplication app) throws Exception {
for (ILaunch launch : DebugPlugin.getDefault().getLaunchManager().getLaunches()) {
ILaunchConfiguration config = launch.getLaunchConfiguration();
if (config != null && CodewindLaunchConfigDelegate.LAUNCH_CONFIG_ID.equals(config.getType().getIdentifier()) &&
app.projectID.equals(config.getAttribute(CodewindLaunchConfigDelegate.PROJECT_ID_ATTR, "")) &&
app.connection.getConid().equals(config.getAttribute(CodewindLaunchConfigDelegate.CONNECTION_ID_ATTR, ""))) {
return launch;
}
}
return null;
}
private void removeAllLaunches() throws DebugException {
for (ILaunch launch : this.launchManager.getLaunches()) {
launch.terminate();
for (IDebugTarget debugTarget : launch.getDebugTargets()) {
debugTarget.terminate();
launch.removeDebugTarget(debugTarget);
}
launchManager.removeLaunch(launch);
}
}
public void testXmlUtils2() throws Exception {
String payload = "<xml><thread id=\"pid25170_seq1\" stop_reason=\"111\">\n"
+ "<frame id=\"28191216\" name=\"<module>\" file=\"helloWorld.py\" line=\"6\"></frame><frame id=\"27818048\" name=\"run\" file=\"pydevd.py\" line=\"1355\">\"</frame>\n"
+ "<frame id=\"25798272\" name=\"<module>\" file=\"pydevd.py\" line=\"1738\"></frame></thread></xml>";
AbstractDebugTarget target = new AbstractDebugTarget() {
@Override
public void launchRemoved(ILaunch launch) {
throw new RuntimeException("not implemented");
}
@Override
public IProcess getProcess() {
throw new RuntimeException("not implemented");
}
@Override
public boolean isTerminated() {
throw new RuntimeException("not implemented");
}
@Override
public boolean canTerminate() {
throw new RuntimeException("not implemented");
}
@Override
protected PyThread findThreadByID(String thread_id) {
return new PyThread(this, "bar", "10");
}
};
XMLUtils.XMLToStack(target, payload);
}
private static ILaunch mockLaunch( String launchConfigName ) {
ILaunch result = mock( ILaunch.class );
ILaunchConfiguration launchConfig = mock( ILaunchConfiguration.class );
when( launchConfig.getName() ).thenReturn( launchConfigName );
when( result.getLaunchConfiguration() ).thenReturn( launchConfig );
return result;
}
private void updateProjectAndWorkingDir() {
if (updatedProjectAndWorkingDir) {
return;
}
IProcess process = DebugUITools.getCurrentProcess();
if (process != null) {
ILaunch launch = process.getLaunch();
if (launch != null) {
updatedProjectAndWorkingDir = true;
ILaunchConfiguration lc = launch.getLaunchConfiguration();
initLaunchConfiguration(lc);
}
}
}
public void startDerbyServer( IProject proj) throws CoreException {
String args = CommonNames.START_DERBY_SERVER;
String vmargs="";
DerbyProperties dprop=new DerbyProperties(proj);
//Starts the server as a Java app
args+=" -h "+dprop.getHost()+ " -p "+dprop.getPort();
//Set Derby System Home from the Derby Properties
if((dprop.getSystemHome()!=null)&& !(dprop.getSystemHome().equals(""))){
vmargs=CommonNames.D_SYSTEM_HOME+dprop.getSystemHome();
}
String procName="["+proj.getName()+"] - "+CommonNames.DERBY_SERVER+" "+CommonNames.START_DERBY_SERVER+" ("+dprop.getHost()+ ", "+dprop.getPort()+")";
ILaunch launch = DerbyUtils.launch(proj, procName ,
CommonNames.DERBY_SERVER_CLASS, args, vmargs, CommonNames.START_DERBY_SERVER);
IProcess ip=launch.getProcesses()[0];
//set a name to be seen in the Console list
ip.setAttribute(IProcess.ATTR_PROCESS_LABEL,procName);
// saves the mapping between (server) process and project
//servers.put(launch.getProcesses()[0], proj);
servers.put(ip, proj);
// register a listener to listen, when this process is finished
DebugPlugin.getDefault().addDebugEventListener(listener);
//Add resource listener
IWorkspace workspace = ResourcesPlugin.getWorkspace();
workspace.addResourceChangeListener(rlistener);
setRunning(proj, Boolean.TRUE);
Shell shell = new Shell();
MessageDialog.openInformation(
shell,
CommonNames.PLUGIN_NAME,
Messages.D_NS_ATTEMPT_STARTED+dprop.getPort()+".");
}
private void finishLaunchWithError(ILaunch launch) {
try {
launch.terminate();
ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager();
launchManager.removeLaunch(launch);
} catch (Throwable x) {
Log.log(x);
}
}
public static void runIJ(IFile currentScript, IProject currentProject) throws CoreException {
String launchType="";
String args="";
//the above some times throws wrong 'create=true|false' errors
String vmargs="";
DerbyProperties dprop=new DerbyProperties(currentProject);
if((dprop.getSystemHome()!=null)&& !(dprop.getSystemHome().equals(""))){
vmargs+=CommonNames.D_SYSTEM_HOME+dprop.getSystemHome();
}
if(currentScript!=null){
launchType=CommonNames.SQL_SCRIPT;
//Preferable to use the full String with quotes to take care of spaces
//in file names
args="\""+currentScript.getLocation().toOSString()+"\"";
}else{
launchType=CommonNames.IJ;
args="";
}
ILaunch launch=launch(currentProject,launchType,CommonNames.IJ_CLASS,args, vmargs, CommonNames.IJ);
IProcess ip=launch.getProcesses()[0];
String procName="["+currentProject.getName()+"] - "+CommonNames.IJ+" "+args;
ip.setAttribute(IProcess.ATTR_PROCESS_LABEL,procName);
}
@Test
public void testLaunchWithLaunchConfigurationWithIncompleteArgsThrowsIllegalArgumentException()
throws CoreException {
ILaunchConfiguration configuration = mockILaunchConfiguration();
Map<String, String> incompleteRequiredArguments = ImmutableMap.of();
when(
configuration.getAttribute(
PipelineConfigurationAttr.ALL_ARGUMENT_VALUES.toString(),
ImmutableMap.<String, String>of())).thenReturn(incompleteRequiredArguments);
Set<PipelineOptionsProperty> properties =
ImmutableSet.of(requiredProperty("foo"), requiredProperty("bar-baz"));
when(
pipelineOptionsHierarchy.getRequiredOptionsByType(
"com.google.cloud.dataflow.sdk.options.BlockingDataflowPipelineOptions"))
.thenReturn(
ImmutableMap.of(
new PipelineOptionsType(
"MyOptions", Collections.<PipelineOptionsType>emptySet(), properties),
properties));
String mode = "run";
ILaunch launch = mock(ILaunch.class);
try {
dataflowDelegate.launch(configuration, mode, launch, monitor);
fail();
} catch (IllegalArgumentException ex) {
assertTrue(ex.getMessage().contains("Dataflow Pipeline Configuration is not valid"));
}
}
protected boolean allTargetsTerminated() {
ILaunch[] launches = DebugPlugin.getDefault().getLaunchManager().getLaunches();
for (ILaunch launch : launches) {
for (IDebugTarget target : launch.getDebugTargets()) {
if (!target.isTerminated())
return false;
}
}
return true;
}
@Test(expected = CoreException.class)
public void failsIfAlreadyLaunched() throws CoreException {
IModule module1 = appEngineStandardProject1.getModule();
serverToReturn = mock(IServer.class);
ILaunch launch = mock(ILaunch.class);
when(serverToReturn.getServerState()).thenReturn(IServer.STATE_STARTED);
when(serverToReturn.getLaunch()).thenReturn(launch);
when(launch.getLaunchMode()).thenReturn(ILaunchManager.DEBUG_MODE);
handler.launch(new IModule[] {module1}, ILaunchManager.DEBUG_MODE);
}