Java Code Examples for com.intellij.execution.process.ProcessOutput#getExitCode()

The following examples show how to use com.intellij.execution.process.ProcessOutput#getExitCode() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WindowsDefenderChecker.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
private static Collection<String> getWindowsDefenderProperty(final String propertyName) {
  try {
    ProcessOutput output = ExecUtil.execAndGetOutput(new GeneralCommandLine("powershell", "-inputformat", "none", "-outputformat", "text", "-NonInteractive", "-Command",
                                                                            "Get-MpPreference | select -ExpandProperty \"" + propertyName + "\""), POWERSHELL_COMMAND_TIMEOUT_MS);
    if (output.getExitCode() == 0) {
      return output.getStdoutLines();
    }
    else {
      LOG.warn("Windows Defender " + propertyName + " check exited with status " + output.getExitCode() + ": " + StringUtil.first(output.getStderr(), MAX_POWERSHELL_STDERR_LENGTH, false));
    }
  }
  catch (ExecutionException e) {
    LOG.warn("Windows Defender " + propertyName + " check failed", e);
  }
  return null;
}
 
Example 2
Source File: SystemInfopageDocSource.java    From BashSupport with Apache License 2.0 6 votes vote down vote up
String callTextToHtml(final String infoPageData) throws IOException {
    if (txt2htmlExecutable == null) {
        //cheap fallback
        return "<html><body><pre>" + infoPageData + "</pre></body></html>";
    }

    ProcessBuilder processBuilder = new ProcessBuilder(txt2htmlExecutable, "--infile", "-");

    CapturingProcessHandler processHandler = new MyCapturingProcessHandler(processBuilder.start(), infoPageData, txt2htmlExecutable + " --inifile -");

    ProcessOutput output = processHandler.runProcess(TIMEOUT_IN_MILLISECONDS);
    if (output.getExitCode() != 0) {
        return null;
    }

    return output.getStdout();
}
 
Example 3
Source File: NoSqlConfigurable.java    From nosql4idea with Apache License 2.0 6 votes vote down vote up
private void testPath(final DatabaseVendor databaseVendor) {
    ProcessOutput processOutput;
    try {
        processOutput = ProgressManager.getInstance().runProcessWithProgressSynchronously(new ThrowableComputable<ProcessOutput, Exception>() {
            @Override
            public ProcessOutput compute() throws Exception {
                return checkShellPath(databaseVendor, getShellPath());
            }
        }, "Testing " + databaseVendor.name + " CLI Executable...", true, NoSqlConfigurable.this.project);
    } catch (ProcessCanceledException pce) {
        return;
    } catch (Exception e) {
        Messages.showErrorDialog(mainPanel, e.getMessage(), "Something wrong happened");
        return;
    }
    if (processOutput != null && processOutput.getExitCode() == 0) {
        Messages.showInfoMessage(mainPanel, processOutput.getStdout(), databaseVendor.name + " CLI Path Checked");
    }
}
 
Example 4
Source File: NoSqlConfigurable.java    From nosql4idea with Apache License 2.0 5 votes vote down vote up
public ProcessOutput checkShellPath(DatabaseVendor databaseVendor, String shellPath) throws ExecutionException, TimeoutException {
    if (isBlank(shellPath)) {
        return null;
    }

    GeneralCommandLine commandLine = new GeneralCommandLine();
    commandLine.setExePath(shellPath);
    if (testParameter != null) {
        commandLine.addParameter(testParameter);
    }
    CapturingProcessHandler handler = new CapturingProcessHandler(commandLine.createProcess(), CharsetToolkit.getDefaultSystemCharset());
    ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
    ProcessOutput result = indicator == null ?
            handler.runProcess(TIMEOUT_MS) :
            handler.runProcessWithProgressIndicator(indicator);
    if (result.isTimeout()) {
        throw new TimeoutException("Couldn't check " + databaseVendor.name + " CLI executable - stopped by timeout.");
    } else if (result.isCancelled()) {
        throw new ProcessCanceledException();
    } else if (result.getExitCode() != 0 || !result.getStderr().isEmpty()) {
        throw new ExecutionException(String.format("Errors while executing %s. exitCode=%s errors: %s",
                commandLine.toString(),
                result.getExitCode(),
                result.getStderr()));
    }
    return result;
}
 
Example 5
Source File: WindowsDefenderChecker.java    From consulo with Apache License 2.0 5 votes vote down vote up
public boolean runExcludePathsCommand(Project project, Collection<Path> paths) {
  try {
    final ProcessOutput output = ExecUtil.sudoAndGetOutput(
            new GeneralCommandLine("powershell", "-Command", "Add-MpPreference", "-ExclusionPath", StringUtil.join(paths, (path) -> StringUtil.wrapWithDoubleQuote(path.toString()), ",")), "");
    return output.getExitCode() == 0;
  }
  catch (IOException | ExecutionException e) {
    UIUtil.invokeLaterIfNeeded(() -> Messages.showErrorDialog(project, DiagnosticBundle.message("virus.scanning.fix.failed", e.getMessage()), DiagnosticBundle.message("virus.scanning.fix.title")));
  }
  return false;
}
 
Example 6
Source File: WindowsDefenderChecker.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static Boolean isWindowsDefenderActive() {
  try {
    ProcessOutput output = ExecUtil.execAndGetOutput(new GeneralCommandLine("wmic", "/Namespace:\\\\root\\SecurityCenter2", "Path", "AntivirusProduct", "Get", "displayName,productState"), WMIC_COMMAND_TIMEOUT_MS);
    if (output.getExitCode() == 0) {
      return parseWindowsDefenderProductState(output);
    }
    else {
      LOG.warn("wmic Windows Defender check exited with status " + output.getExitCode() + ": " + StringUtil.first(output.getStderr(), MAX_POWERSHELL_STDERR_LENGTH, false));
    }
  }
  catch (ExecutionException e) {
    LOG.warn("wmic Windows Defender check failed", e);
  }
  return null;
}
 
Example 7
Source File: ExecutableValidator.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected static boolean doCheckExecutable(@Nonnull String executable, @Nonnull List<String> processParameters) {
  try {
    GeneralCommandLine commandLine = new GeneralCommandLine();
    commandLine.setExePath(executable);
    commandLine.addParameters(processParameters);
    commandLine.setCharset(CharsetToolkit.getDefaultSystemCharset());
    CapturingProcessHandler handler = new CapturingProcessHandler(commandLine);
    ProcessOutput result = handler.runProcess(TIMEOUT_MS);
    boolean timeout = result.isTimeout();
    int exitCode = result.getExitCode();
    String stderr = result.getStderr();
    if (timeout) {
      LOG.warn("Validation of " + executable + " failed with a timeout");
    }
    if (exitCode != 0) {
      LOG.warn("Validation of " + executable + " failed with a non-zero exit code: " + exitCode);
    }
    if (!stderr.isEmpty()) {
      LOG.warn("Validation of " + executable + " failed with a non-empty error output: " + stderr);
    }
    return !timeout && exitCode == 0 && stderr.isEmpty();
  }
  catch (Throwable t) {
    LOG.warn(t);
    return false;
  }
}
 
Example 8
Source File: Executor.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected static String run(List<String> params) {
  final ProcessBuilder builder = new ProcessBuilder().command(params);
  builder.directory(ourCurrentDir());
  builder.redirectErrorStream(true);
  Process clientProcess;
  try {
    clientProcess = builder.start();
  }
  catch (IOException e) {
    throw new RuntimeException(e);
  }

  CapturingProcessHandler handler = new CapturingProcessHandler(clientProcess, CharsetToolkit.getDefaultSystemCharset(), StringUtil.join(params, " "));
  ProcessOutput result = handler.runProcess(30*1000);
  if (result.isTimeout()) {
    throw new RuntimeException("Timeout waiting for the command execution. Command: " + StringUtil.join(params, " "));
  }

  if (result.getExitCode() != 0) {
    log("{" + result.getExitCode() + "}");
  }
  String stdout = result.getStdout().trim();
  if (!StringUtil.isEmptyOrSpaces(stdout)) {
    log(stdout.trim());
  }
  return stdout;
}
 
Example 9
Source File: BuildifierUtil.java    From buck with Apache License 2.0 5 votes vote down vote up
/**
 * Reformats the given {@link String} using the given {@code buildifier} executable.
 *
 * <p>Note: this method only returns a non-empty {@link Optional} if reformatting results in a
 * change to the text.
 */
public static Optional<String> reformatText(String buildifierExecutable, String text) {
  try {
    GeneralCommandLine commandLine =
        new GeneralCommandLine()
            .withExePath(buildifierExecutable)
            .withParameters("-buildifier_disable=label", "-mode=print_if_changed")
            .withParentEnvironmentType(GeneralCommandLine.ParentEnvironmentType.CONSOLE);
    CapturingProcessHandler capturingProcessHandler = new CapturingProcessHandler(commandLine);
    byte[] textBytes = text.getBytes(CharsetToolkit.UTF8_CHARSET);
    capturingProcessHandler.getProcessInput().write(textBytes);
    capturingProcessHandler.getProcessInput().flush();
    capturingProcessHandler.getProcessInput().close();
    ProcessOutput processOutput = capturingProcessHandler.runProcess();
    if (!processOutput.isExitCodeSet() || processOutput.getExitCode() != 0) {
      LOGGER.debug(
          "Reformatting with buildifier failed [exit code="
              + processOutput.getExitCode()
              + "] stderr: "
              + processOutput.getStderr());
      return Optional.empty(); // failed to format text
    }
    String stdout = processOutput.getStdout();
    if ("".equals(stdout)) {
      LOGGER.debug("No change to original text");
      return Optional.empty(); // no change to original text
    }
    return Optional.of(stdout);
  } catch (IOException | ExecutionException e) {
    LOGGER.warn("Failed to reformat text using buildifier [" + buildifierExecutable + "]", e);
    return Optional.empty();
  }
}
 
Example 10
Source File: SassLintRunner.java    From sass-lint-plugin with MIT License 5 votes vote down vote up
@NotNull
public static String runVersion(@NotNull SassLintSettings settings) throws ExecutionException {
    if (!new File(settings.executablePath).exists()) {
        LOG.warn("Calling version with invalid sasslint exe " + settings.executablePath);
        return "";
    }
    ProcessOutput out = version(settings);
    if (out.getExitCode() == 0) {
        return out.getStdout().trim();
    }
    return "";
}
 
Example 11
Source File: ESLintRunner.java    From eslint-plugin with MIT License 5 votes vote down vote up
@NotNull
public static String runVersion(@NotNull ESLintSettings settings) throws ExecutionException {
    if (!new File(settings.eslintExecutablePath).exists()) {
        LOG.warn("Calling version with invalid eslint exe " + settings.eslintExecutablePath);
        return "";
    }
    ProcessOutput out = version(settings);
    if (out.getExitCode() == 0) {
        return out.getStdout().trim();
    }
    return "";
}
 
Example 12
Source File: SystemInfopageDocSource.java    From BashSupport with Apache License 2.0 5 votes vote down vote up
String loadPlainTextInfoPage(String commandName) throws IOException {
    ProcessBuilder processBuilder = new ProcessBuilder(infoExecutable, "-o", "-", commandName);

    CapturingProcessHandler processHandler = new CapturingProcessHandler(processBuilder.start(), Charset.forName(CHARSET_NAME), infoExecutable + " -o - " + commandName);
    ProcessOutput output = processHandler.runProcess(TIMEOUT_IN_MILLISECONDS);

    if (output.getExitCode() != 0) {
        return null;
    }

    return output.getStdout();
}
 
Example 13
Source File: SystemInfopageDocSource.java    From BashSupport with Apache License 2.0 5 votes vote down vote up
boolean infoFileExists(String commandName) throws IOException {
    //info -w locates an info file, exit status == 1 means that there is no info file 
    ProcessBuilder processBuilder = new ProcessBuilder(infoExecutable, "-w", commandName);

    CapturingProcessHandler processHandler = new CapturingProcessHandler(processBuilder.start(), Charset.forName(CHARSET_NAME), infoExecutable + " -w " + commandName);
    ProcessOutput output = processHandler.runProcess(TIMEOUT_IN_MILLISECONDS);

    return output.getExitCode() == 0 && !output.getStdout().isEmpty();
}
 
Example 14
Source File: LoginSsoCallbackHandler.java    From p4ic4idea with Apache License 2.0 5 votes vote down vote up
@Override
public Status getSSOCredentials(StringBuffer credBuffer, String ssoKey, String userName) {
    try {
        GeneralCommandLine cmd = createCommandLine();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Running login sso command `" + cmd.getCommandLineString() + "`");
        }
        ProcessOutput output = (new CapturingProcessHandler(cmd)).runProcess(lockWaitTimeoutMillis);
        if (output.getExitCode() != 0) {
            LOG.info("failed with exit code " + output.getExitCode());
            LOG.info("stdout: " + output.getStdout());
            LOG.info("stderr: " + output.getStderr());
            //final ExecutionException ex = new ExecutionException("Exit code " + output.getExitCode());

            LoginFailureMessage.send().singleSignOnExecutionFailed(
                    new LoginFailureMessage.SingleSignOnExecutionFailureEvent(
                            config, loginSsoCmd,
                            output.getExitCode(), output.getStdout(), output.getStderr()
                    ));

            return Status.FAIL;
        }
        credBuffer.append(output.getStdout());
        return Status.PASS;
    } catch (ExecutionException e) {
        LOG.warn("Failed to run single sign in command [" + loginSsoCmd + "]", e);
        LoginFailureMessage.send().singleSignOnExecutionFailed(
                new LoginFailureMessage.SingleSignOnExecutionFailureEvent(
                        config, loginSsoCmd,
                        -1, "", e.getLocalizedMessage()
                ));
        return Status.FAIL;
    }
}
 
Example 15
Source File: VueRunner.java    From vue-for-idea with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@NotNull
public static String runVersion(@NotNull VueSettings settings) throws ExecutionException {
    if (!new File(settings.vueExePath).exists()) {
        handleError("Calling version with invalid vue exe " + settings.vueExePath,new RuntimeException());
        return "";
    }
    ProcessOutput out = version(settings);
    if (out.getExitCode() == 0) {
        return out.getStdout().trim();
    }
    return "";
}
 
Example 16
Source File: VueRunner.java    From vue-for-idea with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static List<String> listTemplate(@NotNull VueSettings settings) throws ExecutionException {
    ProcessOutput out = template(settings);
    ArrayList<String> list=new ArrayList<>();
    if (out.getExitCode() == 0) {
        list.addAll(out.getStdoutLines());
    }else{
        UsageTrigger.trigger(out.getStderr());
    }
    return list;
}
 
Example 17
Source File: HaxeSdkUtil.java    From intellij-haxe with Apache License 2.0 4 votes vote down vote up
@Nullable
public static HaxeSdkData testHaxeSdk(String path) {
  final String exePath = getCompilerPathByFolderPath(path);

  if (exePath == null) {
    return null;
  }

  final GeneralCommandLine command = new GeneralCommandLine();
  command.setExePath(exePath);
  command.addParameter("-help");
  command.setWorkDirectory(path);

  try {
    final ProcessOutput output = new CapturingProcessHandler(
      command.createProcess(),
      Charset.defaultCharset(),
      command.getCommandLineString()).runProcess();

    if (output.getExitCode() != 0) {
      LOG.error("Haxe compiler exited with invalid exit code: " + output.getExitCode());
      return null;
    }

    final String outputString = output.getStderr();

    String haxeVersion = "NA";
    final Matcher matcher = VERSION_MATCHER.matcher(outputString);
    if (matcher.find()) {
      haxeVersion = matcher.group(1);
    }
    final HaxeSdkData haxeSdkData = new HaxeSdkData(path, haxeVersion);
    haxeSdkData.setHaxelibPath(getHaxelibPathByFolderPath(path));
    haxeSdkData.setNekoBinPath(suggestNekoBinPath(path));
    return haxeSdkData;
  }
  catch (ExecutionException e) {
    LOG.info("Exception while executing the process:", e);
    return null;
  }
}
 
Example 18
Source File: WslDistributionDescriptor.java    From consulo with Apache License 2.0 4 votes vote down vote up
/**
 * @see #getMntRoot()
 */
@Nonnull
private String computeMntRoot() {
  String windowsCurrentDirectory = System.getProperty("user.dir");

  if (StringUtil.isEmpty(windowsCurrentDirectory) || windowsCurrentDirectory.length() < 3) {
    LOG.warn("Could not obtain current directory from user.dir (or path is too short): " + windowsCurrentDirectory);
    return WSLDistribution.DEFAULT_WSL_MNT_ROOT;
  }

  WSLDistribution distribution = WSLUtil.getDistributionById(getId());
  if (distribution == null) {
    return WSLDistribution.DEFAULT_WSL_MNT_ROOT;
  }
  ProcessOutput pwdOutput;
  try {
    pwdOutput = distribution.executeOnWsl(-1, "pwd");
  }
  catch (ExecutionException e) {
    LOG.warn("Error reading pwd output for " + getId(), e);
    return WSLDistribution.DEFAULT_WSL_MNT_ROOT;
  }

  if (pwdOutput.getExitCode() != 0) {
    LOG.info("Non-zero exit code while fetching pwd: " +
             "[id=" + getId() + "; " +
             "[exitCode=" + pwdOutput.getExitCode() + "; " +
             "[stderr=" + pwdOutput.getStderr() + "; " +
             "[stdout=" + pwdOutput.getStdout() + "]");
    return WSLDistribution.DEFAULT_WSL_MNT_ROOT;
  }

  List<String> pwdOutputLines = pwdOutput.getStdoutLines();

  if (pwdOutputLines.size() != 1) {
    LOG.warn("One line response expected from `pwd`: " +
             "[id=" + getId() + "; " +
             "exitCode=" + pwdOutput.getExitCode() + "; " +
             "stderr=" + pwdOutput.getStderr() + "; " +
             "stdout=" + pwdOutput.getStdout() + "]");
    return WSLDistribution.DEFAULT_WSL_MNT_ROOT;
  }

  String wslCurrentDirectory = pwdOutputLines.get(0).trim();

  String currentPathSuffix = WSLDistribution.convertWindowsPath(windowsCurrentDirectory);
  if (StringUtil.endsWithIgnoreCase(wslCurrentDirectory, currentPathSuffix)) {
    return StringUtil.trimEnd(wslCurrentDirectory, currentPathSuffix, true);
  }
  LOG.warn("Wsl current directory does not ends with windows converted suffix: " + "[pwd=" + wslCurrentDirectory + "; " + "suffix=" + currentPathSuffix + "]");
  return WSLDistribution.DEFAULT_WSL_MNT_ROOT;
}