Java Code Examples for com.intellij.execution.process.OSProcessHandler

The following are top voted examples for showing how to use com.intellij.execution.process.OSProcessHandler. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: react-native-console   File: RunnerUtil.java   Source Code and License 6 votes vote down vote up
public static final ConsoleView showHelperProcessRunContent(String header, OSProcessHandler runHandler, Project project, Executor defaultExecutor) {
        ProcessTerminatedListener.attach(runHandler);

        ConsoleViewImpl consoleView = new ConsoleViewImpl(project, true);
        DefaultActionGroup toolbarActions = new DefaultActionGroup();

        JPanel panel = new JPanel((LayoutManager) new BorderLayout());
        panel.add((Component) consoleView.getComponent(), "Center");
        ActionToolbar toolbar = ActionManager.getInstance().createActionToolbar("unknown", (ActionGroup) toolbarActions, false);
        toolbar.setTargetComponent(consoleView.getComponent());
        panel.add((Component) toolbar.getComponent(), "West");

        RunContentDescriptor runDescriptor = new RunContentDescriptor((ExecutionConsole) consoleView,
                (ProcessHandler) runHandler, (JComponent) panel, header, AllIcons.RunConfigurations.Application);
        AnAction[]
                consoleActions = consoleView.createConsoleActions();
        toolbarActions.addAll((AnAction[]) Arrays.copyOf(consoleActions, consoleActions.length));
        toolbarActions.add((AnAction) new StopProcessAction("Stop process", "Stop process", (ProcessHandler) runHandler));
        toolbarActions.add((AnAction) new CloseAction(defaultExecutor, runDescriptor, project));

        consoleView.attachToProcess((ProcessHandler) runHandler);
//        ExecutionManager.getInstance(environment.getProject()).getContentManager().showRunContent(environment.getExecutor(), runDescriptor);
        showConsole(project, defaultExecutor, runDescriptor);
        return (ConsoleView) consoleView;
    }
 
Example 2
Project: intellij-ce-playground   File: JavadocGeneratorRunProfile.java   Source Code and License 6 votes vote down vote up
@NotNull
protected OSProcessHandler startProcess() throws ExecutionException {
  final OSProcessHandler handler = JavaCommandLineStateUtil.startProcess(createCommandLine());
  ProcessTerminatedListener.attach(handler, myProject, JavadocBundle.message("javadoc.generate.exited"));
  handler.addProcessListener(new ProcessAdapter() {
    public void processTerminated(ProcessEvent event) {
      if (myConfiguration.OPEN_IN_BROWSER) {
        File url = new File(myConfiguration.OUTPUT_DIRECTORY, INDEX_HTML);
        if (url.exists() && event.getExitCode() == 0) {
          BrowserUtil.browse(url);
        }
      }
    }
  });
  return handler;
}
 
Example 3
Project: intellij-ce-playground   File: NativeFileWatcherImpl.java   Source Code and License 6 votes vote down vote up
private void shutdownProcess() {
  final OSProcessHandler processHandler = myProcessHandler;
  if (processHandler != null) {
    if (!processHandler.isProcessTerminated()) {
      boolean forceQuite = true;
      try {
        writeLine(EXIT_COMMAND);
        forceQuite = !processHandler.waitFor(500);
        if (forceQuite) {
          LOG.warn("File watcher is still alive. Doing a force quit.");
        }
      }
      catch (IOException ignore) { }
      if (forceQuite) {
        processHandler.destroyProcess();
      }
    }

    myProcessHandler = null;
  }
}
 
Example 4
Project: intellij-ocaml   File: OCamlTopLevelConsoleView.java   Source Code and License 6 votes vote down vote up
public OCamlTopLevelConsoleView(@NotNull final Project project, @NotNull final ContentManager contentManager, final Sdk topLevelSdk) throws ExecutionException {
    super(project, contentManager);
    myConsoleNumber = ++ourLastConsoleNumber;

    final GeneralCommandLine cmd = createCommandLine(topLevelSdk);
    myConsoleView = TextConsoleBuilderFactory.getInstance().createBuilder(project).getConsole();
    myProcessHandler = new OSProcessHandler(cmd.createProcess(), cmd.getCommandLineString());
    myConsoleView.attachToProcess(myProcessHandler);
    ProcessTerminatedListener.attach(myProcessHandler);

    setLayout(new BoxLayout(this, BoxLayout.X_AXIS));

    final DefaultActionGroup group = new DefaultActionGroup();
    group.add(getOCamlToolWindowOpenCloseAction(true, false));
    group.addAll(myConsoleView.createConsoleActions());
    group.add(getOCamlToolWindowSettingsAction());
    group.add(getOCamlToolWindowOpenCloseAction(false, true));
    final JComponent toolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, group, false).getComponent();
    toolbar.setMaximumSize(new Dimension(toolbar.getPreferredSize().width, Integer.MAX_VALUE));

    add(toolbar);
    add(myConsoleView.getComponent());

    myConsoleView.getComponent().requestFocus();
    myProcessHandler.startNotify();
}
 
Example 5
Project: Dynatrace-AppMon-IntelliJ-IDEA-Integration-Plugin   File: DynatraceRunConfigurationExtension.java   Source Code and License 6 votes vote down vote up
@Override
public void attachToProcess(@NotNull final RunConfigurationBase configuration, @NotNull final ProcessHandler handler, @Nullable RunnerSettings runnerSettings) {
    super.attachToProcess(configuration, handler, runnerSettings);
    if (!(runnerSettings instanceof DynatraceRunnerSettings)) {
        return;
    }
    if (!(handler instanceof OSProcessHandler)) {
        return;
    }

    DynatraceConfigurableStorage executionSettings = DynatraceConfigurableStorage.getOrCreateStorage(configuration);
    handler.putCopyableUserData(PROFILE_KEY, executionSettings.getSystemProfile());

    OSProcessHandler procHandler = (OSProcessHandler) handler;
    handler.addProcessListener(new DynatraceProcessListener(executionSettings.getSystemProfile(), configuration.getProject()));

    if(!(configuration instanceof JavaTestConfigurationBase)) {
        return;
    }

    Matcher matcher = TRID_EXTRACTOR.matcher(procHandler.getCommandLine());
    if (!matcher.find()) {
        return;
    }
    handler.putCopyableUserData(TRID_KEY, matcher.group(1));
}
 
Example 6
Project: intellij-pants-plugin   File: OSSPantsTestExamplesIntegrationTest.java   Source Code and License 6 votes vote down vote up
public void testJUnitTests() throws Throwable {
  doImport("intellij-integration/tests/java/org/pantsbuild/testprojects");

  assertFirstSourcePartyModules("intellij-integration_tests_java_org_pantsbuild_testprojects_testprojects");

  PantsExecuteTaskResult result = pantsCompileModule("intellij-integration_tests_java_org_pantsbuild_testprojects_testprojects");
  assertPantsCompileExecutesAndSucceeds(result);
  assertTrue(result.output.isPresent());
  assertTrue(result.output.get().contains("compile intellij-integration/tests/java/org/pantsbuild/testprojects:testprojects"));
  assertSuccessfulTest(
    "intellij-integration_tests_java_org_pantsbuild_testprojects_testprojects", "org.pantsbuild.testprojects.JUnitIntegrationTest");
  final OSProcessHandler processHandler = runJUnitTest(
    "intellij-integration_tests_java_org_pantsbuild_testprojects_testprojects",
    "org.pantsbuild.testprojects.JUnitIntegrationTest",
    "-DPANTS_FAIL_TEST=true"
  );
  assertTrue("Tests should fail!", processHandler.getProcess().exitValue() != 0);
}
 
Example 7
Project: defrac-plugin-intellij   File: SwitchToXCodeAction.java   Source Code and License 6 votes vote down vote up
@Override
public void actionPerformed(@NotNull final AnActionEvent event) {
  final VirtualFile project = getXCodeProject(event);

  if(project == null) {
    return;
  }

  final GeneralCommandLine commandLine =
      new GeneralCommandLine("open", FileUtil.toSystemDependentName(project.getPath()));

  try {
    final ProcessHandler processHandler =
        new OSProcessHandler(commandLine);
    processHandler.startNotify();
    processHandler.waitFor();
  } catch(ExecutionException e) {
    e.printStackTrace();
  }
}
 
Example 8
Project: tools-idea   File: JavadocConfiguration.java   Source Code and License 6 votes vote down vote up
@NotNull
protected OSProcessHandler startProcess() throws ExecutionException {
  final OSProcessHandler handler = JavaCommandLineStateUtil.startProcess(createCommandLine());
  ProcessTerminatedListener.attach(handler, myProject, JavadocBundle.message("javadoc.generate.exited"));
  handler.addProcessListener(new ProcessAdapter() {
    public void processTerminated(ProcessEvent event) {
      if (OPEN_IN_BROWSER) {
        File url = new File(OUTPUT_DIRECTORY, INDEX_HTML);
        if (url.exists() && event.getExitCode() == 0) {
          BrowserUtil.browse(url);
        }
      }
    }
  });
  return handler;
}
 
Example 9
Project: tools-idea   File: FileWatcher.java   Source Code and License 6 votes vote down vote up
private void shutdownProcess() {
  final OSProcessHandler processHandler = myProcessHandler;
  if (processHandler != null) {
    if (!processHandler.isProcessTerminated()) {
      boolean forceQuite = true;
      try {
        writeLine(EXIT_COMMAND);
        forceQuite = !processHandler.waitFor(500);
        if (forceQuite) {
          LOG.warn("File watcher is still alive. Doing a force quit.");
        }
      }
      catch (IOException ignore) { }
      if (forceQuite) {
        processHandler.destroyProcess();
      }
    }

    myProcessHandler = null;
  }
}
 
Example 10
Project: tools-idea   File: ExecutionHelper.java   Source Code and License 6 votes vote down vote up
/** @deprecated use lookup by user data (to remove in IDEA 13) */
public static Collection<RunContentDescriptor> findRunningConsoleByCmdLine(final Project project,
                                                                           @NotNull final NotNullFunction<String, Boolean> cmdLineMatcher) {
  return findRunningConsole(project, new NotNullFunction<RunContentDescriptor, Boolean>() {
    @NotNull
    @Override
    public Boolean fun(RunContentDescriptor selectedContent) {
      final ProcessHandler processHandler = selectedContent.getProcessHandler();
      if (processHandler instanceof OSProcessHandler && !processHandler.isProcessTerminated()) {
        final String commandLine = ((OSProcessHandler)processHandler).getCommandLine();
        return cmdLineMatcher.fun(commandLine);
      }
      return false;
    }
  });
}
 
Example 11
Project: tools-idea   File: SvnCommand.java   Source Code and License 6 votes vote down vote up
public void start() {
  synchronized (myLock) {
    checkNotStarted();

    try {
      myProcess = myCommandLine.createProcess();
      if (LOG.isDebugEnabled()) {
        LOG.debug(myCommandLine.toString());
      }
      myHandler = new OSProcessHandler(myProcess, myCommandLine.getCommandLineString());
      startHandlingStreams();
    } catch (Throwable t) {
      myListeners.getMulticaster().startFailed(t);
    }
  }
}
 
Example 12
Project: buck   File: TestExecutionState.java   Source Code and License 6 votes vote down vote up
private void schedulePostExecutionActions(final OSProcessHandler result, final String title) {
  final ProgressManager manager = ProgressManager.getInstance();
  ApplicationManager.getApplication()
      .invokeLater(
          () -> {
            manager.run(
                new Task.Backgroundable(mProject, title, true) {
                  public void run(@NotNull final ProgressIndicator indicator) {
                    try {
                      result.waitFor();
                    } finally {
                      indicator.cancel();
                    }
                    if (!BuckToolWindowFactory.isRunToolWindowVisible(mProject)) {
                      BuckToolWindowFactory.showRunToolWindow(mProject);
                    }
                  }
                });
          });
}
 
Example 13
Project: consulo-javaee   File: TomcatStartupPolicy.java   Source Code and License 6 votes vote down vote up
private ExecutableObject createScriptExecutable()
{
	return new ColoredCommandLineExecutableObject(new String[]{
			myCatalinaScriptFile.getAbsolutePath(),
			myScriptCommand
	}, null)
	{
		@Override
		public OSProcessHandler createProcessHandler(String workingDirectory, Map<String, String> envVariables) throws ExecutionException
		{
			List<String> customJavaOptions = getCustomJavaOptions();
			if(!customJavaOptions.isEmpty())
			{
				envVariables = new HashMap<>(envVariables);
				String javaOptions = StringUtil.notNullize(envVariables.get(JAVA_VM_ENV_VARIABLE)) + " " + StringUtil.join(customJavaOptions, " ");
				envVariables.put(JAVA_VM_ENV_VARIABLE, javaOptions);
			}
			return super.createProcessHandler(workingDirectory, envVariables);
		}
	};
}
 
Example 14
Project: consulo-javaee   File: ColoredCommandLineExecutableObject.java   Source Code and License 6 votes vote down vote up
@Override
public OSProcessHandler createProcessHandler(String workingDirectory, Map<String, String> envVariables) throws ExecutionException
{
	GeneralCommandLine commandLine = createCommandLine(myParameters, envVariables);
	if(workingDirectory == null && myParameters.length > 0)
	{
		File parentFile = new File(myParameters[0]).getParentFile();
		if(parentFile != null)
		{
			workingDirectory = parentFile.getAbsolutePath();
		}
	}
	commandLine.withWorkDirectory(workingDirectory);
	commandLine.withEnvironment(CLASSPATH_VAR_NAME, "");
	commandLine.withEnvironment(envVariables);
	return createProcessHandler(commandLine);
}
 
Example 15
Project: consulo-javaee   File: ScriptExecutableObject.java   Source Code and License 6 votes vote down vote up
public OSProcessHandler createProcessHandler(String workingDirectory, Map<String,String> envVariables) throws ExecutionException {
  final File executableFile;
  try {
    executableFile = createNewExecutableFile();
    FileOutputStream outputStream = new FileOutputStream(executableFile);
    try {
      FileUtil.copy(new ByteArrayInputStream(getScript().getBytes()), outputStream);
    }
    finally {
      outputStream.close();
    }
  }
  catch (IOException e) {
    throw new ExecutionException(J2EEBundle.message("message.text.error.while.creating.temp.file", e.getLocalizedMessage()));
  }
  final File toDelete = myDirectoryForScript == null ? executableFile.getParentFile() : executableFile;
  toDelete.deleteOnExit();

  OSProcessHandler result = createExecutable(executableFile).createProcessHandler(workingDirectory, envVariables);
  result.addProcessListener(new ProcessAdapter() {
    public void processTerminated(ProcessEvent event) {
      FileUtil.delete(toDelete);
    }
  });
  return result;
}
 
Example 16
Project: consulo   File: NativeFileWatcherImpl.java   Source Code and License 6 votes vote down vote up
private void shutdownProcess() {
  final OSProcessHandler processHandler = myProcessHandler;
  if (processHandler != null) {
    if (!processHandler.isProcessTerminated()) {
      boolean killProcess = true;
      try {
        writeLine(EXIT_COMMAND);
        killProcess = !processHandler.waitFor(500);
        if (killProcess) {
          LOG.warn("File watcher is still alive. Doing a force quit.");
        }
      }
      catch (IOException ignore) {
      }
      if (killProcess) {
        processHandler.destroyProcess();
      }
    }

    myProcessHandler = null;
  }
}
 
Example 17
Project: consulo-java   File: BaseJavaApplicationCommandLineState.java   Source Code and License 6 votes vote down vote up
@NotNull
@Override
protected OSProcessHandler startProcess() throws ExecutionException
{
	OSProcessHandler handler;
	if(SystemInfo.isWindows)
	{
		handler = super.startProcess();
	}
	else
	{
		handler = KillableColoredProcessHandler.create(createCommandLine());
		ProcessTerminatedListener.attach(handler);
	}

	RunnerSettings runnerSettings = getRunnerSettings();
	JavaRunConfigurationExtensionManager.getInstance().attachExtensionsToProcess(getConfiguration(), handler, runnerSettings);
	return handler;
}
 
Example 18
Project: consulo-java   File: JavadocGeneratorRunProfile.java   Source Code and License 6 votes vote down vote up
@NotNull
protected OSProcessHandler startProcess() throws ExecutionException
{
	final OSProcessHandler handler = JavaCommandLineStateUtil.startProcess(createCommandLine());
	ProcessTerminatedListener.attach(handler, myProject, JavadocBundle.message("javadoc.generate.exited"));
	handler.addProcessListener(new ProcessAdapter()
	{
		public void processTerminated(ProcessEvent event)
		{
			if(myConfiguration.OPEN_IN_BROWSER)
			{
				File url = new File(myConfiguration.OUTPUT_DIRECTORY, INDEX_HTML);
				if(url.exists() && event.getExitCode() == 0)
				{
					BrowserUtil.browse(url);
				}
			}
		}
	});
	return handler;
}
 
Example 19
Project: react-native-console   File: RNUtil.java   Source Code and License 5 votes vote down vote up
private static void processCommandline(final Project project, GeneralCommandLine commandLine) throws ExecutionException {
        final OSProcessHandler processHandler = new OSProcessHandler(commandLine);
        ProcessTerminatedListener.attach(processHandler);
//        processHandler.startNotify();// Don't call this, the command content will not be shown

        ApplicationManager.getApplication().invokeLater(new Runnable() {
            @Override
            public void run() {
                processConsole(project, processHandler);
            }
        });
    }
 
Example 20
Project: react-native-console   File: FreeRunConfiguration.java   Source Code and License 5 votes vote down vote up
@NotNull
@Override
protected ProcessHandler startProcess() throws ExecutionException {
    // here just run one command: python freeline.py
    GeneralCommandLine commandLine = new GeneralCommandLine();
    ExecutionEnvironment environment = getEnvironment();
    commandLine.setWorkDirectory(environment.getProject().getBasePath());
    commandLine.setExePath("npm");
    commandLine.addParameters("list");
    return new OSProcessHandler(commandLine);
}
 
Example 21
Project: Goal-Intellij-Plugin   File: GoalDebugConfiguration.java   Source Code and License 5 votes vote down vote up
@Nullable
@Override
public RunProfileState getState(@NotNull Executor executor, @NotNull ExecutionEnvironment environment) throws ExecutionException {


    final CommandLineState state = new CommandLineState(environment) {
        @NotNull
        @Override
        protected ProcessHandler startProcess() throws ExecutionException {
            GoalRuntime runtime = GoalRuntime.instance;
            System.out.println("runtime is created");

            final GeneralCommandLine line = new GeneralCommandLine();
            line.setRedirectErrorStream(true);
            line.setExePath("java");
            line.addParameters("-cp","-debug", runtime.getRuntimePath().toString(),
                    "goal.tools.Run",
                    GoalDebugConfiguration.this.runFilePath);

            System.out.println("command: " + line.getCommandLineString());


            final Process process = line.createProcess();
            return new OSProcessHandler(process, line.getCommandLineString());
        }


    };

    return state;
}
 
Example 22
Project: Goal-Intellij-Plugin   File: GoalRunConfiguration.java   Source Code and License 5 votes vote down vote up
@Nullable
@Override
public RunProfileState getState(@NotNull Executor executor,
                                @NotNull ExecutionEnvironment environment)
        throws ExecutionException {
    final CommandLineState state = new CommandLineState(environment) {
        @NotNull
        @Override
        protected ProcessHandler startProcess() throws ExecutionException {
            final GoalRuntime runtime = GoalRuntime.getInstance();

            //TODO: MAke sure that the preferences are used when running goal.
            //final Path preferences = GoalRunConfiguration.this.writePreferences();

            final GeneralCommandLine line = new GeneralCommandLine();
            line.setRedirectErrorStream(true);
            line.setExePath("java");
            line.addParameters(
                    "-cp", runtime.getRuntimePath().toString(),
                    "goal.tools.Run",
                    //preferences.toString(),
                    GoalRunConfiguration.this.runFilePath
            );
            System.out.println("command: " + line.getCommandLineString());


            final Process process = line.createProcess();

            return new OSProcessHandler(process, line.getCommandLineString());
        }
    };

    return state;
}
 
Example 23
Project: lua-for-idea   File: LuaCommandLineState.java   Source Code and License 5 votes vote down vote up
@NotNull
@Override
protected ProcessHandler startProcess() throws ExecutionException {
    GeneralCommandLine commandLine = generateCommandLine();

    OSProcessHandler osProcessHandler =
            new LuaProcessHandler(commandLine.createProcess(), commandLine.getCommandLineString());
    ProcessTerminatedListener.attach(osProcessHandler, runConfiguration.getProject());

    return osProcessHandler;
}
 
Example 24
Project: livingdoc-intellij   File: RunProfileStateLivingDoc.java   Source Code and License 5 votes vote down vote up
/**
 * {@link ProcessListenerLivingDoc#startNotified(ProcessEvent)} is the listener method for <code>osProcessHandler.startNotify()</code>
 */
@NotNull
@Override
protected OSProcessHandler startProcess() throws ExecutionException {

    OSProcessHandler osProcessHandler = super.startProcess();
    osProcessHandler.addProcessListener(new ProcessListenerLivingDoc(runConfiguration));
    osProcessHandler.startNotify(); //  start capturing the process output
    return osProcessHandler;
}
 
Example 25
Project: intellij-ce-playground   File: BaseJavaApplicationCommandLineState.java   Source Code and License 5 votes vote down vote up
@NotNull
@Override
protected OSProcessHandler startProcess() throws ExecutionException {
  OSProcessHandler handler = new KillableColoredProcessHandler(createCommandLine());
  ProcessTerminatedListener.attach(handler);
  JavaRunConfigurationExtensionManager.getInstance().attachExtensionsToProcess(getConfiguration(), handler, getRunnerSettings());
  return handler;
}
 
Example 26
Project: intellij-ce-playground   File: JavaScratchConfiguration.java   Source Code and License 5 votes vote down vote up
@Override
public RunProfileState getState(@NotNull Executor executor, @NotNull ExecutionEnvironment env) throws ExecutionException {
  final JavaCommandLineState state = new JavaApplicationCommandLineState<JavaScratchConfiguration>(this, env) {
    @Override
    protected void setupJavaParameters(JavaParameters params) throws ExecutionException {
      super.setupJavaParameters(params);
      final File scrachesOutput = JavaScratchCompilationSupport.getScratchOutputDirectory(getProject());
      if (scrachesOutput != null) {
        params.getClassPath().add(scrachesOutput);
      }
    }

    @NotNull
    @Override
    protected OSProcessHandler startProcess() throws ExecutionException {
      final OSProcessHandler handler = super.startProcess();
      if (getRunnerSettings() instanceof DebuggingRunnerData) {
        final VirtualFile vFile = getConfiguration().getScratchVirtualFile();
        if (vFile != null) {
          DebuggerManager.getInstance(getProject()).addDebugProcessListener(handler, new DebugProcessAdapter() {
            @Override
            public void processAttached(DebugProcess process) {
              if (vFile.isValid()) {
                process.appendPositionManager(new JavaScratchPositionManager((DebugProcessImpl)process, vFile));
              }
              process.removeDebugProcessListener(this);
            }
          });
        }
      }
      return handler;
    }
  };
  state.setConsoleBuilder(TextConsoleBuilderFactory.getInstance().createBuilder(getProject(), getConfigurationModule().getSearchScope()));
  return state;
}
 
Example 27
Project: intellij-ce-playground   File: BuildManager.java   Source Code and License 5 votes vote down vote up
private void cancelPreloadedBuilds(final String projectPath) {
  runCommand(new Runnable() {
    @Override
    public void run() {
      Pair<RequestFuture<PreloadedProcessMessageHandler>, OSProcessHandler> pair = takePreloadedProcess(projectPath);
      if (pair != null) {
        final RequestFuture<PreloadedProcessMessageHandler> future = pair.first;
        final OSProcessHandler processHandler = pair.second;
        myMessageDispatcher.cancelSession(future.getRequestID());
        // waiting for preloaded process from project's task queue guarantees no build is started for this project
        // until this one gracefully exits and closes all its storages
        getProjectData(projectPath).taskQueue.submit(new Runnable() {
          @Override
          public void run() {
            Throwable error = null;
            try {
              while (!processHandler.waitFor()) {
                LOG.info("processHandler.waitFor() returned false for session " + future.getRequestID() + ", continue waiting");
              }
            }
            catch (Throwable e) {
              error = e;
            }
            finally {
              notifySessionTerminationIfNeeded(future.getRequestID(), error);
            }
          }
        });
      }
    }
  });
}
 
Example 28
Project: intellij-ce-playground   File: BuildManager.java   Source Code and License 5 votes vote down vote up
@Nullable
private Pair<RequestFuture<PreloadedProcessMessageHandler>, OSProcessHandler> takePreloadedProcess(String projectPath) {
  Pair<RequestFuture<PreloadedProcessMessageHandler>, OSProcessHandler> result;
  final Future<Pair<RequestFuture<PreloadedProcessMessageHandler>, OSProcessHandler>> preloadProgress = myPreloadedBuilds.remove(projectPath);
  try {
    result = preloadProgress != null ? preloadProgress.get() : null;
  }
  catch (Throwable e) {
    LOG.info(e);
    result = null;
  }
  return result != null && !result.first.isDone()? result : null;
}
 
Example 29
Project: intellij-ce-playground   File: BuildManager.java   Source Code and License 5 votes vote down vote up
private Future<Pair<RequestFuture<PreloadedProcessMessageHandler>, OSProcessHandler>> launchPreloadedBuildProcess(final Project project, SequentialTaskExecutor projectTaskQueue) throws Exception {
  ensureListening();

  // launching build process from projectTaskQueue ensures that no other build process for this project is currently running
  return projectTaskQueue.submit(new Callable<Pair<RequestFuture<PreloadedProcessMessageHandler>, OSProcessHandler>>() {
    public Pair<RequestFuture<PreloadedProcessMessageHandler>, OSProcessHandler> call() throws Exception {
      if (project.isDisposed()) {
        return null;
      }
      final RequestFuture<PreloadedProcessMessageHandler> future = new RequestFuture<PreloadedProcessMessageHandler>(new PreloadedProcessMessageHandler(), UUID.randomUUID(), new CancelBuildSessionAction<PreloadedProcessMessageHandler>());
      try {
        myMessageDispatcher.registerBuildMessageHandler(future, null);
        final OSProcessHandler processHandler = launchBuildProcess(project, myListenPort, future.getRequestID(), true);
        final StringBuffer errors = new StringBuffer();
        processHandler.addProcessListener(new StdOutputCollector(errors));
        STDERR_OUTPUT.set(processHandler, errors);

        processHandler.startNotify();
        return Pair.create(future, processHandler);
      }
      catch (Throwable e) {
        handleProcessExecutionFailure(future.getRequestID(), e);
        throw e instanceof Exception? (Exception)e : new RuntimeException(e);
      }
    }
  });
}
 
Example 30
Project: intellij-ce-playground   File: SimpleJavaParameters.java   Source Code and License 5 votes vote down vote up
public OSProcessHandler createOSProcessHandler() throws ExecutionException {
  final Sdk sdk = getJdk();
  assert sdk != null : "SDK should be defined";
  final String exePath = ((JavaSdkType)sdk.getSdkType()).getVMExecutablePath(sdk);
  final GeneralCommandLine commandLine = JdkUtil.setupJVMCommandLine(exePath, this, myUseDynamicClasspath);
  final OSProcessHandler processHandler = new OSProcessHandler(commandLine);
  ProcessTerminatedListener.attach(processHandler);
  return processHandler;
}
 
Example 31
Project: intellij-ce-playground   File: ConsoleViewRunningState.java   Source Code and License 5 votes vote down vote up
private static OutputStreamWriter createOutputStreamWriter(OutputStream processInput, ProcessHandler processHandler) {
  Charset charset = null;
  if (processHandler instanceof OSProcessHandler) {
    charset = ((OSProcessHandler)processHandler).getCharset();
  }
  if (charset == null) {
    charset = EncodingManager.getInstance().getDefaultCharset();
  }
  return new OutputStreamWriter(processInput, charset);
}
 
Example 32
Project: intellij-ce-playground   File: Tool.java   Source Code and License 5 votes vote down vote up
public void execute(AnActionEvent event, DataContext dataContext, long executionId, @Nullable final ProcessListener processListener) {
  final Project project = CommonDataKeys.PROJECT.getData(dataContext);
  if (project == null) {
    return;
  }

  FileDocumentManager.getInstance().saveAllDocuments();
  try {
    if (isUseConsole()) {
      ExecutionEnvironment environment = ExecutionEnvironmentBuilder.create(project,
                                                                            DefaultRunExecutor.getRunExecutorInstance(),
                                                                            new ToolRunProfile(this, dataContext)).build();
      environment.setExecutionId(executionId);
      environment.getRunner().execute(environment, new ProgramRunner.Callback() {
        @Override
        public void processStarted(RunContentDescriptor descriptor) {
          ProcessHandler processHandler = descriptor.getProcessHandler();
          if (processHandler != null && processListener != null) {
            processHandler.addProcessListener(processListener);
          }
        }
      });
    }
    else {
      GeneralCommandLine commandLine = createCommandLine(dataContext);
      if (commandLine == null) {
        return;
      }
      OSProcessHandler handler = new OSProcessHandler(commandLine.createProcess(), commandLine.getCommandLineString());
      handler.addProcessListener(new ToolProcessAdapter(project, synchronizeAfterExecution(), getName()));
      if (processListener != null) {
        handler.addProcessListener(processListener);
      }
      handler.startNotify();
    }
  }
  catch (ExecutionException ex) {
    ExecutionErrorDialog.show(ex, ToolsBundle.message("tools.process.start.error"), project);
  }
}
 
Example 33
Project: intellij-ce-playground   File: AndroidRunDdmsAction.java   Source Code and License 5 votes vote down vote up
private static void doLaunchDdms(GeneralCommandLine commandLine, final Project project, final boolean adbServiceWasEnabled) {
  try {
    ourProcessHandler = new OSProcessHandler(commandLine.createProcess(), "");
    ourProcessHandler.startNotify();
    ourProcessHandler.waitFor();
  }
  catch (ExecutionException e) {
    LOG.info(e);
  }
  finally {
    ourProcessHandler = null;

    if (adbServiceWasEnabled) {
      ApplicationManager.getApplication().invokeLater(new Runnable() {
        @Override
        public void run() {
          if (project.isDisposed()) {
            return;
          }
          AndroidEnableAdbServiceAction.setAdbServiceEnabled(project, true);

          // trigger creation of new bridge
          File adb = AndroidSdkUtils.getAdb(project);
          if (adb != null) {
            AdbService.getInstance().getDebugBridge(adb);
          }
        }
      });
    }
  }
}
 
Example 34
Project: intellij-ce-playground   File: MavenExternalExecutor.java   Source Code and License 5 votes vote down vote up
public boolean execute(final ProgressIndicator indicator) {
  displayProgress();

  try {
    if (myParameterCreationError != null) {
      throw myParameterCreationError;
    }

    myProcessHandler =
      new OSProcessHandler(CommandLineBuilder.createFromJavaParameters(myJavaParameters)) {
        @Override
        public void notifyTextAvailable(String text, Key outputType) {
          // todo move this logic to ConsoleAdapter class
          if (!myConsole.isSuppressed(text)) {
            super.notifyTextAvailable(text, outputType);
          }
          updateProgress(indicator, text);
        }
      };

    myConsole.attachToProcess(myProcessHandler);
  }
  catch (ExecutionException e) {
    myConsole.systemMessage(MavenServerConsole.LEVEL_FATAL, RunnerBundle.message("external.startup.failed", e.getMessage()), null);
    return false;
  }

  start();
  readProcessOutput();
  stop();

  return printExitSummary();
}
 
Example 35
Project: intellij-ce-playground   File: OutputParser.java   Source Code and License 5 votes vote down vote up
public OutputParser(Project project,
                    OSProcessHandler processHandler,
                    AntBuildMessageView errorsView,
                    ProgressIndicator progress,
                    String buildName) {
  myProject = project;
  myProcessHandler = processHandler;
  myMessageView = errorsView;
  myProgress = new WeakReference<ProgressIndicator>(progress);
  myBuildName = buildName;
  myMessageView.setParsingThread(this);
}
 
Example 36
Project: intellij-ce-playground   File: OutputParser2.java   Source Code and License 5 votes vote down vote up
private OutputParser2(Project project,
                      OSProcessHandler processHandler,
                      AntBuildMessageView errorsView,
                      ProgressIndicator progress,
                      String buildName) {
  super(project, processHandler, errorsView, progress, buildName);
}
 
Example 37
Project: intellij-ce-playground   File: GitTextHandler.java   Source Code and License 5 votes vote down vote up
@Nullable
@Override
protected Process startProcess() throws ExecutionException {
  synchronized (myProcessStateLock) {
    if (myIsDestroyed) {
      return null;
    }
    final ProcessHandler processHandler = createProcess(myCommandLine);
    myHandler = (OSProcessHandler)processHandler;
    return myHandler.getProcess();
  }
}
 
Example 38
Project: intellij-ce-playground   File: MvcRunConfiguration.java   Source Code and License 5 votes vote down vote up
@NotNull
@Override
protected OSProcessHandler startProcess() throws ExecutionException {
  OSProcessHandler handler = super.startProcess();
  handler.setShouldDestroyProcessRecursively(true);
  final RunnerSettings runnerSettings = getRunnerSettings();
  JavaRunConfigurationExtensionManager.getInstance().attachExtensionsToProcess(MvcRunConfiguration.this, handler, runnerSettings);
  return handler;
}
 
Example 39
Project: intellij-ce-playground   File: XsltCommandLineState.java   Source Code and License 5 votes vote down vote up
@Override
@NotNull
protected OSProcessHandler startProcess() throws ExecutionException {
    final OSProcessHandler osProcessHandler = createJavaParameters().createOSProcessHandler();
    osProcessHandler.putUserData(STATE, this);

    osProcessHandler.addProcessListener(new MyProcessAdapter());

    final List<XsltRunnerExtension> extensions = XsltRunnerExtension.getExtensions(myXsltRunConfiguration, myIsDebugger);
    for (XsltRunnerExtension extension : extensions) {
        osProcessHandler.addProcessListener(extension.createProcessListener(myXsltRunConfiguration.getProject(), myExtensionData));
    }
    return osProcessHandler;
}
 
Example 40
Project: Buck-IntelliJ-Plugin   File: BuckCommandHandler.java   Source Code and License 5 votes vote down vote up
/**
 * Start the buck process.
 */
@Nullable
protected Process startProcess() throws ExecutionException {
  synchronized (mProcessStateLock) {
    final ProcessHandler processHandler = createProcess(mCommandLine);
    mHandler = (OSProcessHandler) processHandler;
    return mHandler.getProcess();
  }
}