Search in sources :

Example 36 with ProcessAdapter

use of com.intellij.execution.process.ProcessAdapter in project android by JetBrains.

the class EmulatorProcessHandler method startNotify.

@Override
public void startNotify() {
    // Wait for both the stdout and stderr reader threads to finish and then indicate that the process has terminated
    addProcessListener(new ProcessAdapter() {

        @Override
        public void startNotified(final ProcessEvent event) {
            try {
                String presentableName = CommandLineUtil.extractPresentableName(myCommandLine.getCommandLineString());
                final BaseDataReader stdoutReader = new EmulatorOutputReader(myProcess.getInputStream(), ProcessOutputTypes.STDOUT, presentableName);
                final BaseDataReader stderrReader = new EmulatorOutputReader(myProcess.getErrorStream(), ProcessOutputTypes.STDERR, presentableName);
                executeTask(() -> {
                    try {
                        stderrReader.waitFor();
                        stdoutReader.waitFor();
                    } catch (InterruptedException ignore) {
                    } finally {
                        notifyProcessTerminated(0);
                    }
                });
            } finally {
                removeProcessListener(this);
            }
        }
    });
    super.startNotify();
}
Also used : ProcessAdapter(com.intellij.execution.process.ProcessAdapter) BaseDataReader(com.intellij.util.io.BaseDataReader) ProcessEvent(com.intellij.execution.process.ProcessEvent)

Example 37 with ProcessAdapter

use of com.intellij.execution.process.ProcessAdapter in project android by JetBrains.

the class UnpackOperation method untar.

/**
   * @throws IOException     when tar fails in a way that we may retry the operation
   * @throws WizardException if retry is not possible (e.g. no tar executable)
   */
@NotNull
private static File untar(final File archive, File destination, final InstallContext context, final ProgressIndicator indicator) throws IOException, WizardException {
    if (!destination.mkdirs()) {
        throw new WizardException("Cannot create temporary directory to extract files");
    }
    indicator.start();
    // 0%
    indicator.setFraction(0.0);
    try {
        GeneralCommandLine line = new GeneralCommandLine(getTarExecutablePath(), TAR_FLAGS_EXTRACT_UNPACK_VERBOSE_FILENAME_TARGETDIR, archive.getAbsolutePath(), destination.getAbsolutePath());
        CapturingAnsiEscapesAwareProcessHandler handler = new CapturingAnsiEscapesAwareProcessHandler(line);
        handler.addProcessListener(new ProcessAdapter() {

            @Override
            public void onTextAvailable(ProcessEvent event, Key outputType) {
                String string = event.getText();
                if (!StringUtil.isEmptyOrSpaces(string)) {
                    if (string.startsWith(EXTRACT_OPERATION_OUTPUT)) {
                        // Extract operation prefix
                        String fileName = string.substring(EXTRACT_OPERATION_OUTPUT.length()).trim();
                        indicator.setText(fileName);
                    } else if (ProcessOutputTypes.STDOUT.equals(outputType)) {
                        indicator.setText(string.trim());
                    } else {
                        context.print(string, ConsoleViewContentType.getConsoleViewType(outputType));
                    }
                }
            }
        });
        if (handler.runProcess().getExitCode() != 0) {
            throw new IOException("Unable to unpack archive file");
        }
        return destination;
    } catch (ExecutionException e) {
        throw new WizardException("Unable to run tar utility");
    } finally {
        // 100%
        indicator.setFraction(1.0);
        indicator.stop();
    }
}
Also used : ProcessAdapter(com.intellij.execution.process.ProcessAdapter) CapturingAnsiEscapesAwareProcessHandler(com.intellij.execution.process.CapturingAnsiEscapesAwareProcessHandler) ProcessEvent(com.intellij.execution.process.ProcessEvent) GeneralCommandLine(com.intellij.execution.configurations.GeneralCommandLine) IOException(java.io.IOException) ExecutionException(com.intellij.execution.ExecutionException) Key(com.intellij.openapi.util.Key) NotNull(org.jetbrains.annotations.NotNull)

Example 38 with ProcessAdapter

use of com.intellij.execution.process.ProcessAdapter in project android by JetBrains.

the class ConnectJavaDebuggerTask method launchDebugger.

@Override
public ProcessHandler launchDebugger(@NotNull LaunchInfo currentLaunchInfo, @NotNull final Client client, @NotNull ProcessHandlerLaunchStatus launchStatus, @NotNull ProcessHandlerConsolePrinter printer) {
    String debugPort = Integer.toString(client.getDebuggerListenPort());
    final int pid = client.getClientData().getPid();
    Logger.getInstance(ConnectJavaDebuggerTask.class).info(String.format(Locale.US, "Attempting to connect debugger to port %1$s [client %2$d]", debugPort, pid));
    // detach old process handler
    RunContentDescriptor descriptor = currentLaunchInfo.env.getContentToReuse();
    // reach here before the EDT gets around to creating the descriptor?
    assert descriptor != null : "ConnectJavaDebuggerTask expects an existing descriptor that will be reused";
    final ProcessHandler processHandler = descriptor.getProcessHandler();
    assert processHandler != null;
    // create a new process handler
    RemoteConnection connection = new RemoteConnection(true, "localhost", debugPort, false);
    final AndroidRemoteDebugProcessHandler debugProcessHandler = new AndroidRemoteDebugProcessHandler(myProject, myMonitorRemoteProcess);
    // switch the launch status and console printers to point to the new process handler
    // this is required, esp. for AndroidTestListener which holds a reference to the launch status and printers, and those should
    // be updated to point to the new process handlers, otherwise test results will not be forwarded appropriately
    launchStatus.setProcessHandler(debugProcessHandler);
    printer.setProcessHandler(debugProcessHandler);
    // detach after the launch status has been updated to point to the new process handler
    processHandler.detachProcess();
    AndroidDebugState debugState = new AndroidDebugState(myProject, debugProcessHandler, connection, currentLaunchInfo.consoleProvider);
    RunContentDescriptor debugDescriptor;
    try {
        // @formatter:off
        ExecutionEnvironment debugEnv = new ExecutionEnvironmentBuilder(currentLaunchInfo.env).executor(currentLaunchInfo.executor).runner(currentLaunchInfo.runner).contentToReuse(descriptor).build();
        debugDescriptor = DebuggerPanelsManager.getInstance(myProject).attachVirtualMachine(debugEnv, debugState, connection, false);
    // @formatter:on
    } catch (ExecutionException e) {
        processHandler.notifyTextAvailable("ExecutionException: " + e.getMessage() + '.', STDERR);
        return null;
    }
    if (debugDescriptor == null) {
        processHandler.notifyTextAvailable("Unable to connect debugger to Android application", STDERR);
        return null;
    }
    // re-run the collected text from the old process handler to the new
    // TODO: is there a race between messages received once the debugger has been connected, and these messages that are printed out?
    final AndroidProcessText oldText = AndroidProcessText.get(processHandler);
    if (oldText != null) {
        oldText.printTo(debugProcessHandler);
    }
    RunProfile runProfile = currentLaunchInfo.env.getRunProfile();
    int uniqueId = runProfile instanceof RunConfigurationBase ? ((RunConfigurationBase) runProfile).getUniqueID() : -1;
    AndroidSessionInfo value = new AndroidSessionInfo(debugProcessHandler, debugDescriptor, uniqueId, currentLaunchInfo.executor.getId(), InstantRunUtils.isInstantRunEnabled(currentLaunchInfo.env));
    debugProcessHandler.putUserData(AndroidSessionInfo.KEY, value);
    debugProcessHandler.putUserData(AndroidSessionInfo.ANDROID_DEBUG_CLIENT, client);
    debugProcessHandler.putUserData(AndroidSessionInfo.ANDROID_DEVICE_API_LEVEL, client.getDevice().getVersion());
    final String pkgName = client.getClientData().getClientDescription();
    final IDevice device = client.getDevice();
    // kill the process when the debugger is stopped
    debugProcessHandler.addProcessListener(new ProcessAdapter() {

        @Override
        public void processTerminated(ProcessEvent event) {
            debugProcessHandler.removeProcessListener(this);
            Client currentClient = device.getClient(pkgName);
            if (currentClient != null && currentClient.getClientData().getPid() != pid) {
                // a new process has been launched for the same package name, we aren't interested in killing this
                return;
            }
            Logger.getInstance(ConnectJavaDebuggerTask.class).info("Debugger terminating, so terminating process: " + pkgName);
            // Note: client.kill() doesn't work when the debugger is attached, we explicitly stop by package id..
            try {
                device.executeShellCommand("am force-stop " + pkgName, new NullOutputReceiver());
            } catch (Exception e) {
            // don't care..
            }
        }
    });
    return debugProcessHandler;
}
Also used : ExecutionEnvironment(com.intellij.execution.runners.ExecutionEnvironment) RunContentDescriptor(com.intellij.execution.ui.RunContentDescriptor) ProcessAdapter(com.intellij.execution.process.ProcessAdapter) ProcessEvent(com.intellij.execution.process.ProcessEvent) IDevice(com.android.ddmlib.IDevice) RunProfile(com.intellij.execution.configurations.RunProfile) ExecutionException(com.intellij.execution.ExecutionException) RunConfigurationBase(com.intellij.execution.configurations.RunConfigurationBase) ProcessHandler(com.intellij.execution.process.ProcessHandler) RemoteConnection(com.intellij.execution.configurations.RemoteConnection) ExecutionEnvironmentBuilder(com.intellij.execution.runners.ExecutionEnvironmentBuilder) ExecutionException(com.intellij.execution.ExecutionException) Client(com.android.ddmlib.Client) NullOutputReceiver(com.android.ddmlib.NullOutputReceiver)

Example 39 with ProcessAdapter

use of com.intellij.execution.process.ProcessAdapter in project intellij-plugins by JetBrains.

the class FlexRunner method launchAirFlexUnit.

@Nullable
protected RunContentDescriptor launchAirFlexUnit(final Project project, final RunProfileState state, final RunContentDescriptor contentToReuse, final ExecutionEnvironment env, final FlexUnitRunnerParameters params) throws ExecutionException {
    final ExecutionResult executionResult;
    final SwfPolicyFileConnection policyFileConnection = new SwfPolicyFileConnection();
    policyFileConnection.open(params.getSocketPolicyPort());
    final FlexUnitConnection flexUnitConnection = new FlexUnitConnection();
    flexUnitConnection.open(params.getPort());
    executionResult = state.execute(env.getExecutor(), this);
    if (executionResult == null) {
        flexUnitConnection.close();
        policyFileConnection.close();
        return null;
    }
    flexUnitConnection.addListener(new FlexUnitListener(executionResult.getProcessHandler()));
    executionResult.getProcessHandler().addProcessListener(new ProcessAdapter() {

        @Override
        public void processWillTerminate(ProcessEvent event, boolean willBeDestroyed) {
            flexUnitConnection.write("Finish");
        }

        @Override
        public void processTerminated(ProcessEvent event) {
            flexUnitConnection.close();
            policyFileConnection.close();
        }
    });
    final RunContentBuilder contentBuilder = new RunContentBuilder(executionResult, env);
    return contentBuilder.showRunContent(contentToReuse);
}
Also used : SwfPolicyFileConnection(com.intellij.lang.javascript.flex.flexunit.SwfPolicyFileConnection) FlexUnitConnection(com.intellij.lang.javascript.flex.flexunit.FlexUnitConnection) ProcessAdapter(com.intellij.execution.process.ProcessAdapter) ProcessEvent(com.intellij.execution.process.ProcessEvent) ExecutionResult(com.intellij.execution.ExecutionResult) DefaultExecutionResult(com.intellij.execution.DefaultExecutionResult) RunContentBuilder(com.intellij.execution.runners.RunContentBuilder) Nullable(org.jetbrains.annotations.Nullable)

Example 40 with ProcessAdapter

use of com.intellij.execution.process.ProcessAdapter in project intellij-plugins by JetBrains.

the class DartPubActionBase method doPerformPubAction.

private static void doPerformPubAction(@NotNull final Module module, @NotNull final VirtualFile pubspecYamlFile, @NotNull final GeneralCommandLine command, @NotNull final String actionTitle) {
    FileDocumentManager.getInstance().saveAllDocuments();
    try {
        if (ourInProgress.compareAndSet(false, true)) {
            command.withEnvironment(PUB_ENV_VAR_NAME, getPubEnvValue());
            final OSProcessHandler processHandler = new OSProcessHandler(command);
            processHandler.addProcessListener(new ProcessAdapter() {

                @Override
                public void processTerminated(final ProcessEvent event) {
                    ourInProgress.set(false);
                    ApplicationManager.getApplication().invokeLater(() -> {
                        if (!module.isDisposed()) {
                            DartProjectComponent.excludeBuildAndPackagesFolders(module, pubspecYamlFile);
                            // refresh later than exclude, otherwise IDE may start indexing excluded folders
                            VfsUtil.markDirtyAndRefresh(true, true, true, pubspecYamlFile.getParent());
                            if (DartSdkLibUtil.isDartSdkEnabled(module)) {
                                DartAnalysisServerService.getInstance(module.getProject()).serverReadyForRequest(module.getProject());
                            }
                        }
                    });
                }
            });
            showPubOutputConsole(module, command, processHandler, pubspecYamlFile, actionTitle);
        }
    } catch (ExecutionException e) {
        ourInProgress.set(false);
        // may be better show it in Messages tool window console?
        Notifications.Bus.notify(new Notification(GROUP_DISPLAY_ID, actionTitle, DartBundle.message("dart.pub.exception", e.getMessage()), NotificationType.ERROR));
    }
}
Also used : ProcessAdapter(com.intellij.execution.process.ProcessAdapter) ProcessEvent(com.intellij.execution.process.ProcessEvent) OSProcessHandler(com.intellij.execution.process.OSProcessHandler) ExecutionException(com.intellij.execution.ExecutionException) Notification(com.intellij.notification.Notification)

Aggregations

ProcessAdapter (com.intellij.execution.process.ProcessAdapter)62 ProcessEvent (com.intellij.execution.process.ProcessEvent)59 Key (com.intellij.openapi.util.Key)19 NotNull (org.jetbrains.annotations.NotNull)15 ProcessHandler (com.intellij.execution.process.ProcessHandler)12 OSProcessHandler (com.intellij.execution.process.OSProcessHandler)10 ExecutionEnvironment (com.intellij.execution.runners.ExecutionEnvironment)10 ExecutionException (com.intellij.execution.ExecutionException)9 IOException (java.io.IOException)8 BaseOSProcessHandler (com.intellij.execution.process.BaseOSProcessHandler)7 Nullable (org.jetbrains.annotations.Nullable)7 Project (com.intellij.openapi.project.Project)5 ExecutionEnvironmentBuilder (com.intellij.execution.runners.ExecutionEnvironmentBuilder)4 RunContentDescriptor (com.intellij.execution.ui.RunContentDescriptor)4 File (java.io.File)4 ExecutionResult (com.intellij.execution.ExecutionResult)3 GeneralCommandLine (com.intellij.execution.configurations.GeneralCommandLine)3 Disposable (com.intellij.openapi.Disposable)3 Semaphore (com.intellij.util.concurrency.Semaphore)3 RunProfile (com.intellij.execution.configurations.RunProfile)2