Java 类org.apache.commons.exec.Executor 实例源码

项目:guetzliconverter    文件:ProcessExecutor.java   
@Override
public Long call() throws Exception {
    Executor executor = new DefaultExecutor();
    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
    ExecuteWatchdog watchDog = new ExecuteWatchdog(watchdogTimeout);
    executor.setWatchdog(watchDog);
    executor.setStreamHandler(new PumpStreamHandler(new MyLogOutputStream(handler, true), new MyLogOutputStream(handler, false)));
    Long exitValue;
    try {
        exitValue = new Long(executor.execute(commandline));
    } catch (ExecuteException e) {
        exitValue = new Long(e.getExitValue());
    }
    if (watchDog.killedProcess()) {
        exitValue = WATCHDOG_EXIST_VALUE;
    }
    return exitValue;
}
项目:commons-sandbox    文件:Tests.java   
public static void main(String[] args) throws Exception {
    String cmd = "/tmp/test.sh";
    CommandLine cmdLine = CommandLine.parse("/bin/bash " + cmd);

    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    ByteArrayOutputStream stderr = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(stdout, stderr);

    psh.setStopTimeout(TIMEOUT_FIVE_MINUTES);

    ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT_TEN_MINUTES); // timeout in milliseconds

    Executor executor = new DefaultExecutor();
    executor.setExitValue(0);
    executor.setStreamHandler(psh);
    executor.setWatchdog(watchdog);

    int exitValue = executor.execute(cmdLine, Collections.emptyMap());
    System.out.println(exitValue);
}
项目:h2spec-maven-plugin    文件:H2SpecTestSuite.java   
public static List<Failure> runH2Spec(File targetDirectory, int port, final int timeout, final int maxHeaderLength, final Set<String> excludeSpecs) throws IOException {
    File reportsDirectory = new File(targetDirectory, "reports");
    if (!reportsDirectory.exists()) {
        reportsDirectory.mkdir();
    }

    File junitFile = new File(reportsDirectory, "TEST-h2spec.xml");
    File h2spec = getH2SpecFile(targetDirectory);

    Executor exec = new DefaultExecutor();
    PumpStreamHandler psh = new PumpStreamHandler(System.out, System.err, System.in);
    exec.setStreamHandler(psh);
    exec.setExitValues(new int[]{0, 1});

    psh.start();
    if (exec.execute(buildCommandLine(h2spec, port, junitFile, timeout, maxHeaderLength)) != 0) {
        return parseReports(reportsDirectory, excludeSpecs);
    }
    psh.stop();

    return Collections.emptyList();
}
项目:reactor    文件:DockerClient.java   
/**
 * Runs docker command asynchronously.
 *
 * @param arguments command line arguments
 * @param out       stdout will be written in to this file
 *
 * @return a handle used to stop the command process
 *
 * @throws IOException when command has error
 */
public ExecuteWatchdog dockerAsync(final List<Object> arguments, OutputStream out) throws IOException {
    CommandLine cmdLine = new CommandLine(DOCKER);
    arguments.forEach((arg) -> {
        cmdLine.addArgument(arg + "");
    });
    LOG.debug("[{} {}]", cmdLine.getExecutable(), StringUtils.join(cmdLine.getArguments(), " "));
    List<String> output = new ArrayList<>();
    ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
    Executor executor = new DefaultExecutor();
    executor.setWatchdog(watchdog);
    PrintWriter writer = new PrintWriter(out);
    ESH esh = new ESH(writer);
    executor.setStreamHandler(esh);
    executor.execute(cmdLine, new DefaultExecuteResultHandler());
    return watchdog;
}
项目:gradle-mobile-plugin    文件:ExecUtil.java   
public static ExecResult setupSudoCredentials(String password) {
    ExecCommand execCommand = new ExecCommand("sudo");
    execCommand.addArgument("--validate", false);
    execCommand.addArgument("--stdin", false);
    Executor executor = new DefaultExecutor();
    executor.setWorkingDirectory(execCommand.getWorkingDirectory());
    executor.setExitValues(execCommand.getExitValues());
    ExecOutputStream execOutputStream = new ExecOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(execOutputStream, execOutputStream, new ExecInputStream(password)));
    try {
        executor.execute(execCommand);
    } catch (IOException e) {
        return new ExecResult(execOutputStream.getOutput(), e);
    }
    return new ExecResult(execOutputStream.getOutput());
}
项目:gradle-mobile-plugin    文件:ExecUtil.java   
@Deprecated
public static ExecResult execCommand(CommandLine commandLine, File workDir, int[] exitValues, boolean routeToCapture, boolean routeToStdout) {
    Executor executor = new DefaultExecutor();
    if (workDir != null) {
        executor.setWorkingDirectory(workDir);
    }
    if (exitValues != null) {
        executor.setExitValues(exitValues);
    }
    ExecOutputStream execOutputStream = new ExecOutputStream(routeToCapture, routeToStdout);
    PumpStreamHandler streamHandler = new PumpStreamHandler(execOutputStream);
    executor.setStreamHandler(streamHandler);
    try {
        executor.execute(commandLine);
    } catch (IOException e) {
        return new ExecResult(false, execOutputStream.getOutput(), e);
    }
    return new ExecResult(true, execOutputStream.getOutput(), null);
}
项目:project-build-plugin    文件:EngineControl.java   
private void waitForEngineStart(Executor executor) throws Exception
{
  int i = 0;
  while (!engineStarted.get())
  {
    Thread.sleep(1_000);
    i++;
    if (!executor.getWatchdog().isWatching())
    {
      throw new RuntimeException("Engine start failed unexpected.");
    }
    if (i > context.timeoutInSeconds)
    {
      throw new TimeoutException("Timeout while starting engine " + context.timeoutInSeconds + " [s].\n"
              + "Check the engine log for details or increase the timeout property '"+StartTestEngineMojo.IVY_ENGINE_START_TIMEOUT_SECONDS+"'");
    }
  }
  context.log.info("Engine started after " + i + " [s]");
}
项目:project-build-plugin    文件:EngineControl.java   
/**
 * Run a short living engine command where we expect a process failure as the engine invokes <code>System.exit(-1)</code>.
 * @param statusCmd 
 * @return the output of the engine command.
 */
private String executeSynch(CommandLine statusCmd)
{
  String engineOutput = null;
  ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream, System.err);
  Executor executor = createEngineExecutor();
  executor.setStreamHandler(streamHandler);
  executor.setExitValue(-1);
  try
  {
    executor.execute(statusCmd);
  }
  catch (IOException ex)
  { // expected!
  }
  finally
  {
    engineOutput = outputStream.toString();
    IOUtils.closeQuietly(outputStream);
  }
  return engineOutput;
}
项目:project-build-plugin    文件:TestStartEngine.java   
@Test
public void canStartEngine() throws Exception
{
  StartTestEngineMojo mojo = rule.getMojo();
  assertThat(getProperty(EngineControl.Property.TEST_ENGINE_URL)).isNull();
  assertThat(getProperty(EngineControl.Property.TEST_ENGINE_LOG)).isNull();

  Executor startedProcess = null;
  try
  {
    startedProcess = mojo.startEngine();
    assertThat(getProperty(EngineControl.Property.TEST_ENGINE_URL)).startsWith("http://");
    assertThat(new File(getProperty(EngineControl.Property.TEST_ENGINE_LOG))).exists();
  }
  finally
  {
    kill(startedProcess);
  }
}
项目:project-build-plugin    文件:TestStartEngine.java   
@Test
public void testKillEngineOnVmExit() throws Exception
{
  StartTestEngineMojo mojo = rule.getMojo();
  Executor startedProcess = null;
  try
  {
    startedProcess = mojo.startEngine();
    assertThat(startedProcess.getProcessDestroyer()).isInstanceOf(ShutdownHookProcessDestroyer.class);
    ShutdownHookProcessDestroyer jvmShutdownHoock = (ShutdownHookProcessDestroyer) startedProcess.getProcessDestroyer();
    assertThat(jvmShutdownHoock.size())
      .as("One started engine process must be killed on VM end.")
      .isEqualTo(1);
  }
  finally
  {
    kill(startedProcess);
  }
}
项目:yagga    文件:CommandExecutorTest.java   
@Test
public void shouldExecuteCommand() throws IOException {
    // given
    Executor executor = mock(Executor.class);
    when(executor.getWorkingDirectory()).thenReturn(Paths.get("/my/repo").toFile());
    CommandOutput output = new CommandOutput(executor.getWorkingDirectory().getName())
            .addOutputLine(new CommandOutputLine("First line."))
            .addOutputLine(new CommandOutputLine("Second line."));
    CommandExecutor commandExecutor = new CommandExecutor(mock(Command.class), executor, () -> output);

    // when
    CommandOutput expectedOutput = commandExecutor.execute();

    // then
    verify(executor).execute(any(CommandLine.class));
    assertThat(expectedOutput.getRepositoryName()).isEqualTo("repo");
    assertThat(expectedOutput.getOutputLines().stream().map(CommandOutputLine::getLine).collect(toList()))
            .containsExactly("First line.", "Second line.");
}
项目:movingcode    文件:PythonCLIProbe.java   
public static boolean testExecutable() {
    CommandLine commandLine = CommandLine.parse(PythonCLIProcessor.pythonExecutable + " --version");

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    Executor executor = new DefaultExecutor();

    // put a watchdog with a timeout
    ExecuteWatchdog watchdog = new ExecuteWatchdog(new Long(timeout_seconds) * 1000);
    executor.setWatchdog(watchdog);

    try {
        executor.execute(commandLine, resultHandler);
        resultHandler.waitFor();
        int exitVal = resultHandler.getExitValue();
        if (exitVal != 0) {
            return false;
        }
        return true;
    }
    catch (Exception e) {
        return false;
    }
}
项目:movingcode    文件:RCLIProbe.java   
private static boolean testExecutable() {
    CommandLine commandLine = CommandLine.parse(RCLIProcessor.rExecutable + " " + VERSION_CALL);

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    Executor executor = new DefaultExecutor();

    // put a watchdog with a timeout
    ExecuteWatchdog watchdog = new ExecuteWatchdog(new Long(TIMEOUT_SECONDS) * 1000);
    executor.setWatchdog(watchdog);

    try {
        executor.execute(commandLine, resultHandler);
        resultHandler.waitFor();
        int exitVal = resultHandler.getExitValue();
        if (exitVal != 0) {
            return false;
        }
            return true;
    }
    catch (Exception e) {
        return false;
    }
}
项目:event-store-maven-plugin    文件:EventStoreDownloadMojo.java   
private static void applyFileMode(final File file, final FileMode fileMode)
        throws MojoExecutionException {

    if (OS.isFamilyUnix() || OS.isFamilyMac()) {
        final String smode = fileMode.toChmodStringFull();
        final CommandLine cmdLine = new CommandLine("chmod");
        cmdLine.addArgument(smode);
        cmdLine.addArgument(file.getAbsolutePath());
        final Executor executor = new DefaultExecutor();
        try {
            final int result = executor.execute(cmdLine);
            if (result != 0) {
                throw new MojoExecutionException("Error # " + result + " while trying to set mode \""
                        + smode + "\" for file: " + file.getAbsolutePath());
            }
        } catch (final IOException ex) {
            throw new MojoExecutionException("Error while trying to set mode \"" + smode + "\" for file: "
                    + file.getAbsolutePath(), ex);
        }
    } else {
        file.setReadable(fileMode.isUr() || fileMode.isGr() || fileMode.isOr());
        file.setWritable(fileMode.isUw() || fileMode.isGw() || fileMode.isOw());
        file.setExecutable(fileMode.isUx() || fileMode.isGx() || fileMode.isOx());
    }
}
项目:adb4j    文件:CmdExecutor.java   
private CmdResultHandler runAsync(String command, CmdResultHandler resultHandler, boolean shouldClone) throws IOException, IOException, IOException, IOException {
        CmdResultHandler handler = shouldClone ? resultHandler.clone() : resultHandler;

        PumpStreamHandler streamHandler = handler.getStreamHandler(this);
        Executor executor = new DefaultExecutor();
        executor.setStreamHandler(streamHandler);

//        String[] arguments = CommandLine.parse(command).toStrings();
//        CommandLine cmdLine = new CommandLine(arguments[0]);
//        for (int i = 1; i < arguments.length; i++) {
//            cmdLine.addArgument(command, true);
//        }
        CommandLine cmdLine = CommandLine.parse(command);
        executor.execute(cmdLine, getEnvironment(), handler.delegate);

        return handler;
    }
项目:Edge-Node    文件:AlchemyEngine.java   
public static void learn(String path, String factsForLearningFile,
        String rulesDefinitionFile, String learnedWeightsFile)
        throws Exception {
    CommandLine cmdLine = new CommandLine(path + "/learnwts");
    cmdLine.addArgument("-i");
    cmdLine.addArgument(factsForLearningFile);
    cmdLine.addArgument("-o");
    cmdLine.addArgument(rulesDefinitionFile);
    cmdLine.addArgument("-t");
    cmdLine.addArgument(learnedWeightsFile);
    cmdLine.addArgument("-g -multipleDatabases");

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000);
    Executor executor = new DefaultExecutor();
    executor.setExitValue(1);
    executor.setWatchdog(watchdog);
    executor.execute(cmdLine, resultHandler);
    resultHandler.waitFor();
}
项目:pack200-maven-plugin    文件:AbstractPluginMojo.java   
/**
 * Executes command.
 *
 * @throws IOException Execution of subprocess failed or the subprocess returned a exit value indicating a failure
 *                     {@code Executor.setExitValue(int)}.
 * @see AbstractPluginMojo#command
 * @see AbstractPluginMojo#executor
 */
private void executeCommand() throws IOException, MojoExecutionException {
    if (debug) {
        getLog().info("Executable: " + command.getExecutable());
        getLog().info("Arguments: " + StringUtils.join(command.getArguments(), " "));
    }

    int processExitValue = executor.execute(command);
    if (debug) {
        getLog().info(String.format("Process returned %d (0x%01X)", processExitValue, processExitValue));
    }

    if (processExitValue == Executor.INVALID_EXITVALUE) {
        throw new MojoExecutionException("An error occurred during the execution of the program.");
    }
}
项目:CliDispatcher    文件:ProcessExecutor.java   
public Long call() throws Exception {
    logger.debug("Started");
    Executor executor = new DefaultExecutor();
    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
    ExecuteWatchdog watchDog = new ExecuteWatchdog(watchdogTimeout);
    executor.setWatchdog(watchDog);
    executor.setStreamHandler(new PumpStreamHandler(new MyLogOutputStream(handler, true),new MyLogOutputStream(handler, false)));
    Long exitValue;
    try {
        logger.debug("Successfully completed");
        exitValue =  new Long(executor.execute(commandline));

    } catch (ExecuteException e) {
        logger.debug("Execute exception");
        exitValue =  new Long(e.getExitValue());
    }
    if(watchDog.killedProcess()){
        logger.debug("Killed by watchdog");
        exitValue =WATCHDOG_EXIT_VALUE;
    }

    return exitValue;
}
项目:ldbc_graphalytics    文件:__platform-name__Loader.java   
public int unload(String loadedInputPath) throws Exception {
    String unloaderDir = platformConfig.getUnloaderPath();
    commandLine = new CommandLine(Paths.get(unloaderDir).toFile());

    commandLine.addArgument("--graph-name");
    commandLine.addArgument(formattedGraph.getName());

    commandLine.addArgument("--output-path");
    commandLine.addArgument(loadedInputPath);

    String commandString = StringUtils.toString(commandLine.toStrings(), " ");
    LOG.info(String.format("Execute graph unloader with command-line: [%s]", commandString));

    Executor executor = new DefaultExecutor();
    executor.setStreamHandler(new PumpStreamHandler(System.out, System.err));
    executor.setExitValue(0);

    return executor.execute(commandLine);
}
项目:ABRAID-MP    文件:CommonsExecProcessRunnerTest.java   
@Test
public void runCallsExecuteWithCorrectCommand() throws Exception {
    // Arrange
    Executor mockExecutor = mock(Executor.class);
    File executable = testFolder.newFile("file1");
    String[] executionArguments = new String[]{"arg1", "arg2", "${arg3}"};
    File script = testFolder.newFile("file2");
    HashMap<String, File> fileArguments = new HashMap<>();
    fileArguments.put("arg3", script);
    ProcessRunner target = new CommonsExecProcessRunner(mockExecutor, testFolder.getRoot(), executable,
            executionArguments, fileArguments, 10);
    String expectation = "[" + executable + ", arg1, arg2, " + script + "]";

    // Act
    target.run(mock(ProcessHandler.class));

    // Assert
    ArgumentCaptor<CommandLine> commandLineCaptor = captorForClass(CommandLine.class);
    verify(mockExecutor).execute(commandLineCaptor.capture(), any(ExecuteResultHandler.class));
    assertThat(commandLineCaptor.getValue().toString()).isEqualTo(expectation);
}
项目:ABRAID-MP    文件:CommonsExecProcessRunnerTest.java   
@Test
public void runWrapsInnerExceptionInErrorCase() throws Exception {
    // Arrange
    Executor mockExecutor = mock(Executor.class);
    ExecuteException expectedCause = new ExecuteException("foo", -1);
    doThrow(expectedCause).when(mockExecutor).execute(any(CommandLine.class), any(ExecuteResultHandler.class));

    ProcessRunner target = new CommonsExecProcessRunner(mockExecutor, testFolder.getRoot(), new File("exe"),
            new String[0], new HashMap<String, File>(), 10);

    // Act
    catchException(target).run(mock(ProcessHandler.class));
    Exception result = caughtException();

    // Assert
    assertThat(result).isInstanceOf(ProcessException.class);
    assertThat(result.getCause()).isEqualTo(expectedCause);
}
项目:ABRAID-MP    文件:CommonsExecProcessRunnerTest.java   
@Test
public void runCanNotBeCalledMoreThanOnce() throws Exception {
    // Arrange
    Executor mockExecutor = mock(Executor.class);
    ProcessRunner target = new CommonsExecProcessRunner(mockExecutor, testFolder.getRoot(), new File("exe"),
            new String[0], new HashMap<String, File>(), 10);

    // Act
    catchException(target).run(mock(ProcessHandler.class)); // Once
    Exception firstRunException = caughtException();

    catchException(target).run(mock(ProcessHandler.class)); //Twice
    Exception secondRunException = caughtException();

    // Assert
    assertThat(firstRunException).isNull();
    assertThat(secondRunException).isInstanceOf(ProcessException.class);
}
项目:ridire-cpi    文件:AsyncSketchCreator.java   
private void compactLines(List<File> tableFile, File finalTable)
        throws ExecuteException, IOException {
    Executor executor = new DefaultExecutor();
    File tempTabTot = File.createTempFile("ridireTABTOT", ".tbl");
    File tempSh = File.createTempFile("ridireSH", ".sh");
    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append("export LC_ALL=C\n");
    stringBuffer.append("cat " + StringUtils.join(tableFile, " ") + " > "
            + tempTabTot.getAbsolutePath() + "\n");
    stringBuffer
            .append("awk '{a[$2]+= $1; s+=$1}END{for(i in a){print a[i],i;}; print s \"\t\"}' "
                    + tempTabTot.getAbsolutePath()
                    + " | sort -k1nr -k2 > "
                    + finalTable.getAbsolutePath());
    FileUtils.writeStringToFile(tempSh, stringBuffer.toString());
    tempSh.setExecutable(true);
    CommandLine commandLine = new CommandLine(tempSh.getAbsolutePath());
    executor.execute(commandLine);
    FileUtils.deleteQuietly(tempTabTot);
    FileUtils.deleteQuietly(tempSh);
}
项目:ridire-cpi    文件:AsyncSketchCreator.java   
private void executeCQPQuery(File queryFile, boolean inverse)
        throws ExecuteException, IOException {
    Executor executor = new DefaultExecutor();
    File tempSh = File.createTempFile("ridireSH", ".sh");
    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append("export LC_ALL=C\n");
    String corpusName = this.cqpCorpusName;
    if (inverse) {
        corpusName += "INV";
    }
    stringBuffer.append(this.cqpExecutable + " -f "
            + queryFile.getAbsolutePath() + " -D " + corpusName + " -r "
            + this.cqpRegistry + "\n");
    FileUtils.writeStringToFile(tempSh, stringBuffer.toString());
    tempSh.setExecutable(true);
    CommandLine commandLine = new CommandLine(tempSh.getAbsolutePath());
    executor.execute(commandLine);
    FileUtils.deleteQuietly(tempSh);
}
项目:ridire-cpi    文件:CWBConcordancer.java   
private void executeCQPQuery(File queryFile, boolean inverse)
        throws ExecuteException, IOException {
    Executor executor = new DefaultExecutor();
    File tempSh = File.createTempFile("ridireSH", ".sh");
    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append("LC_ALL=C && ");
    String corpusName = this.cqpCorpusName;
    if (inverse) {
        corpusName += "INV";
    }
    stringBuffer.append(this.cqpExecutable + " -f "
            + queryFile.getAbsolutePath() + " -D " + corpusName + " -r "
            + this.cqpRegistry + "\n");
    FileUtils.writeStringToFile(tempSh, stringBuffer.toString());
    tempSh.setExecutable(true);
    CommandLine commandLine = new CommandLine(tempSh.getAbsolutePath());
    executor.execute(commandLine);
    FileUtils.deleteQuietly(tempSh);
}
项目:ridire-cpi    文件:CWBConcordancer.java   
private Integer getCQPQueryResultsSize(File queryFile)
        throws ExecuteException, IOException {
    Executor executor = new DefaultExecutor();
    File tempSh = File.createTempFile("ridireSH", ".sh");
    File tempSize = File.createTempFile("ridireSZ", ".size");
    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append("export LC_ALL=C\n");
    stringBuffer.append(this.cqpExecutable + " -f "
            + queryFile.getAbsolutePath() + " -D " + this.cqpCorpusName
            + " -r " + this.cqpRegistry + " > "
            + tempSize.getAbsolutePath() + "\n");
    FileUtils.writeStringToFile(tempSh, stringBuffer.toString());
    tempSh.setExecutable(true);
    CommandLine commandLine = new CommandLine(tempSh.getAbsolutePath());
    executor.execute(commandLine);
    Integer size = 0;
    List<String> lines = FileUtils.readLines(tempSize);
    if (lines.size() > 0) {
        size = Integer.parseInt(lines.get(0).trim());
    }
    FileUtils.deleteQuietly(tempSh);
    FileUtils.deleteQuietly(tempSize);
    return size;
}
项目:coala-eclipse    文件:ExternalUtils.java   
/**
 * Get details of all bears that are available on the user's system.
 * 
 * @return JSONArray containing details of bears.
 */
public static JSONArray getAvailableBears() throws ExecuteException, IOException {
  CommandLine cmdLine = new CommandLine("coala");
  cmdLine.addArgument("--json");
  cmdLine.addArgument("-B");
  final ByteArrayOutputStream stdout = new ByteArrayOutputStream();
  PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(stdout, null);
  Executor executor = new DefaultExecutor();
  executor.setStreamHandler(pumpStreamHandler);
  executor.execute(cmdLine);
  JSONArray bearList = new JSONObject(stdout.toString()).getJSONArray("bears");
  return bearList;
}
项目:reactor    文件:DockerClient.java   
/**
 * Runs docker command synchronously.
 *
 * @param arguments command line arguments
 *
 * @return command stdout
 *
 * @throws IOException when command has error
 */
public List<String> docker(final List<Object> arguments) throws IOException {
    CommandLine cmdLine = new CommandLine(DOCKER);
    arguments.forEach((arg) -> {
        cmdLine.addArgument(arg + "");
    });
    LOG.debug("[{} {}]", cmdLine.getExecutable(), StringUtils.join(cmdLine.getArguments(), " "));
    List<String> output = new ArrayList<>();
    Executor executor = new DefaultExecutor();
    executor.setStreamHandler(new ESH(output));
    if (executor.execute(cmdLine) != 0) {
        throw new IOException(cmdLine + " failed");
    }
    return output;
}
项目:zeppelin-mongodb-interpreter    文件:MongoDbInterpreter.java   
private void stopProcess(String paragraphId) {
  if (runningProcesses.containsKey(paragraphId)) {
    final Executor executor = runningProcesses.get(paragraphId);
    final ExecuteWatchdog watchdog = executor.getWatchdog();
    watchdog.destroyProcess();
  }
}
项目:gradle-mobile-plugin    文件:ExecUtil.java   
public static ExecResult executeCommand(ExecCommand execCommand, ExecOutputStream execOutputStream) {
    Executor executor = new DefaultExecutor();
    executor.setWorkingDirectory(execCommand.getWorkingDirectory());
    executor.setExitValues(execCommand.getExitValues());
    executor.setStreamHandler(new PumpStreamHandler(execOutputStream));
    try {
        executor.execute(execCommand);
    } catch (IOException e) {
        return new ExecResult(execOutputStream.getOutput(), e);
    }
    return new ExecResult(execOutputStream.getOutput());
}
项目:gradle-mobile-plugin    文件:ExecUtil.java   
public static ExecResult executeCommandWithPipe(ExecCommand execCommand, ExecOutputStream execOutputStream, String pipeValue) {
    Executor executor = new DefaultExecutor();
    executor.setWorkingDirectory(execCommand.getWorkingDirectory());
    executor.setExitValues(execCommand.getExitValues());
    executor.setStreamHandler(new PumpStreamHandler(execOutputStream, execOutputStream, new ExecInputStream(pipeValue)));
    try {
        executor.execute(execCommand);
    } catch (IOException e) {
        return new ExecResult(execOutputStream.getOutput(), e);
    }
    return new ExecResult(execOutputStream.getOutput());
}
项目:gradle-mobile-plugin    文件:ExecUtil.java   
public static ExecResult resetSudoCredentials() {
    ExecCommand execCommand = new ExecCommand("sudo");
    execCommand.addArgument("--remove-timestamp", false);
    Executor executor = new DefaultExecutor();
    executor.setWorkingDirectory(execCommand.getWorkingDirectory());
    executor.setExitValues(execCommand.getExitValues());
    ExecOutputStream execOutputStream = new ExecOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(execOutputStream));
    try {
        executor.execute(execCommand);
    } catch (IOException e) {
        return new ExecResult(execOutputStream.getOutput(), e);
    }
    return new ExecResult(execOutputStream.getOutput());
}
项目:exec-maven-plugin    文件:ExecMojo.java   
private void fillSuccessCodes( Executor exec )
{
    if ( successCodes != null && successCodes.length > 0 )
    {
        exec.setExitValues( successCodes );
    }
}
项目:exec-maven-plugin    文件:ExecMojo.java   
protected int executeCommandLine( Executor exec, CommandLine commandLine, Map<String, String> enviro,
                                  OutputStream out, OutputStream err )
                                      throws ExecuteException, IOException
{
    // note: don't use BufferedOutputStream here since it delays the outputs MEXEC-138
    PumpStreamHandler psh = new PumpStreamHandler( out, err, System.in );
    return executeCommandLine( exec, commandLine, enviro, psh );
}
项目:exec-maven-plugin    文件:ExecMojo.java   
protected int executeCommandLine( Executor exec, CommandLine commandLine, Map<String, String> enviro,
                                  FileOutputStream outputFile )
                                      throws ExecuteException, IOException
{
    BufferedOutputStream bos = new BufferedOutputStream( outputFile );
    PumpStreamHandler psh = new PumpStreamHandler( bos );
    return executeCommandLine( exec, commandLine, enviro, psh );
}
项目:exec-maven-plugin    文件:ExecMojoTest.java   
protected int executeCommandLine( Executor exec, CommandLine commandLine, Map enviro, OutputStream out,
                                  OutputStream err )
                                      throws IOException, ExecuteException
{
    commandLines.add( commandLine );
    if ( failureMsg != null )
    {
        throw new ExecuteException( failureMsg, executeResult );
    }
    return executeResult;
}
项目:project-build-plugin    文件:EngineControl.java   
public Executor start() throws Exception
{
  CommandLine startCmd = toEngineCommand(Command.start);
  context.log.info("Start Axon.ivy Engine in folder: " + context.engineDirectory);

  Executor executor = createEngineExecutor();
  executor.setStreamHandler(createEngineLogStreamForwarder(logLine -> findStartEngineUrl(logLine)));
  executor.setWatchdog(new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT)); 
  executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
  executor.execute(startCmd, asynchExecutionHandler());
  waitForEngineStart(executor);
  return executor;
}
项目:project-build-plugin    文件:StartTestEngineMojo.java   
Executor startEngine() throws Exception
{
  EngineVmOptions vmOptions = new EngineVmOptions(maxmem, additionalClasspath, additionalVmOptions);
  EngineControl engineControl = new EngineControl(new EngineMojoContext(
          identifyAndGetEngineDirectory(), project, getLog(), engineLogFile, vmOptions, startTimeoutInSeconds));
  return engineControl.start();
}
项目:project-build-plugin    文件:TestStartEngine.java   
@Test @Ignore
public void engineStartCanFailFast() throws Exception
{
  StartTestEngineMojo mojo = rule.getMojo();
  File engineDir = installUpToDateEngineRule.getMojo().getRawEngineDirectory();
  File configDir = new File(engineDir, "configuration");
  File tmpConfigDir = new File(engineDir, "config.bkp");
  configDir.renameTo(tmpConfigDir);

  StopWatch stopWatch = new StopWatch();
  stopWatch.start();
  Executor startedProcess = null;
  try
  {
    startedProcess = mojo.startEngine();
    fail("Engine start should fail as no configuration directory exists.");
  }
  catch (RuntimeException ex)
  {
    stopWatch.stop();
    long seconds = TimeUnit.SECONDS.convert(stopWatch.getTime(), TimeUnit.MILLISECONDS);
    assertThat(seconds)
      .describedAs("engine start should fail early if engine config is incomplete")
      .isLessThanOrEqualTo(20);
  }
  finally
  {
    kill(startedProcess);
    FileUtils.deleteDirectory(configDir);
    tmpConfigDir.renameTo(configDir);
  }
}
项目:project-build-plugin    文件:TestStartEngine.java   
private static void kill(Executor startedProcess)
{
  if (startedProcess != null)
  {
    startedProcess.getWatchdog().destroyProcess();
  }
}