Java Code Examples for org.apache.commons.exec.PumpStreamHandler

The following examples show how to use org.apache.commons.exec.PumpStreamHandler. These examples are extracted from open source projects. 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 Project: p4ic4idea   Source File: SimpleTestServer.java    License: Apache License 2.0 7 votes vote down vote up
public int getVersion() throws Exception {
	ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
	CommandLine cmdLine = new CommandLine(p4d);
	cmdLine.addArgument("-V");
	DefaultExecutor executor = new DefaultExecutor();
	PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
	executor.setStreamHandler(streamHandler);
	executor.execute(cmdLine);

	int version = 0;
	for (String line : outputStream.toString().split("\\n")) {
		if (line.startsWith("Rev. P4D")) {
			Pattern p = Pattern.compile("\\d{4}\\.\\d{1}");
			Matcher m = p.matcher(line);
			while (m.find()) {
				String found = m.group();
				found = found.replace(".", ""); // strip "."
				version = Integer.parseInt(found);
			}
		}
	}
	logger.info("P4D Version: " + version);
	return version;
}
 
Example 2
Source Project: open-capacity-platform   Source File: ScriptUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 日志文件输出方式
 *
 * 优点:支持将目标数据实时输出到指定日志文件中去
 * 缺点:
 *      标准输出和错误输出优先级固定,可能和脚本中顺序不一致
 *      Java无法实时获取
 *
 * @param command
 * @param scriptFile
 * @param logFile
 * @param params
 * @return
 * @throws IOException
 */
public static int execToFile(String command, String scriptFile, String logFile, String... params) throws IOException {
    // 标准输出:print (null if watchdog timeout)
    // 错误输出:logging + 异常 (still exists if watchdog timeout)
    // 标准输入
    try (FileOutputStream fileOutputStream = new FileOutputStream(logFile, true)) {
        PumpStreamHandler streamHandler = new PumpStreamHandler(fileOutputStream, fileOutputStream, null);

        // command
        CommandLine commandline = new CommandLine(command);
        commandline.addArgument(scriptFile);
        if (params!=null && params.length>0) {
            commandline.addArguments(params);
        }

        // exec
        DefaultExecutor exec = new DefaultExecutor();
        exec.setExitValues(null);
        exec.setStreamHandler(streamHandler);
        int exitValue = exec.execute(commandline);  // exit code: 0=success, 1=error
        return exitValue;
    }
}
 
Example 3
Source Project: Quicksql   Source File: ProcessExecClient.java    License: MIT License 6 votes vote down vote up
/**
 * Start a new process to execute.
 *
 * @return log or result output stream
 */
public OutputStream exec() {
    CommandLine commandLine = CommandLine.parse(submit());
    commandLine.addArguments(arguments());
    LOGGER.debug("CommandLine is " + commandLine.toString());

    DefaultExecutor executor = new DefaultExecutor();
    executor.setStreamHandler(new PumpStreamHandler(System.out));
    try {
        executor.execute(commandLine);
    } catch (Exception ex) {
        ex.printStackTrace();
        LOGGER.error("Process executing failed!! Caused by: " + ex.getMessage());
        throw new RuntimeException(ex);
    }

    return System.out;
}
 
Example 4
Source Project: football-events   Source File: DockerCompose.java    License: MIT License 6 votes vote down vote up
private String execProcess(String command) {
    logger.debug(command);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    CommandLine commandline = CommandLine.parse(command);
    DefaultExecutor exec = new DefaultExecutor();
    exec.setStreamHandler(new PumpStreamHandler(outputStream));
    int exitCode;

    try {
        exitCode = exec.execute(commandline);
    } catch (IOException e) {
        throw new RuntimeException("Unable to execute " + command + ": " + outputStream, e);
    }
    if (exitCode != 0) {
        throw new RuntimeException(command + " exited with code " + exitCode + ", " + outputStream);
    }
    String output = outputStream.toString();
    logger.debug(System.lineSeparator() + output);
    return output;
}
 
Example 5
Source Project: 2018-TowerDefence   Source File: BotRunner.java    License: MIT License 6 votes vote down vote up
protected String RunSimpleCommandLineCommand(String line, int expectedExitValue) throws IOException, TimeoutException {
    CommandLine cmdLine = CommandLine.parse(line);
    DefaultExecutor executor = new DefaultExecutor();
    File bot = new File(this.getBotDirectory());
    executor.setWorkingDirectory(bot);
    executor.setExitValue(expectedExitValue);

    ExecuteWatchdog watchdog = new ExecuteWatchdog(this.timeoutInMilliseconds);
    executor.setWatchdog(watchdog);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    executor.setStreamHandler(streamHandler);

    try {
        executor.execute(cmdLine);
    } catch (IOException e) {
        if (watchdog.killedProcess()) {
            throw new TimeoutException("Bot process timed out after " + this.timeoutInMilliseconds + "ms of inactivity");
        } else {
            throw e;
        }
    }

    return outputStream.toString();
}
 
Example 6
Source Project: piper   Source File: Ffprobe.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Map<String,Object> handle(TaskExecution aTask) throws Exception {
  CommandLine cmd = new CommandLine ("ffprobe");
  cmd.addArgument("-v")
     .addArgument("quiet")
     .addArgument("-print_format")
     .addArgument("json")
     .addArgument("-show_error")
     .addArgument("-show_format")
     .addArgument("-show_streams")
     .addArgument(aTask.getRequiredString("input"));
  log.debug("{}",cmd);
  DefaultExecutor exec = new DefaultExecutor();
  File tempFile = File.createTempFile("log", null);
  try (PrintStream stream = new PrintStream(tempFile);) {
    exec.setStreamHandler(new PumpStreamHandler(stream));
    exec.execute(cmd);
    return parse(FileUtils.readFileToString(tempFile));
  }
  catch (ExecuteException e) {
    throw new ExecuteException(e.getMessage(),e.getExitValue(), new RuntimeException(FileUtils.readFileToString(tempFile)));
  }
  finally {
    FileUtils.deleteQuietly(tempFile);
  }
}
 
Example 7
Source Project: moneta   Source File: DropwizardContractTest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUpBeforeClass() throws Exception {
	System.out.println("Java Temp Dir: " +System.getProperty("java.io.tmpdir"));
	
	executor = new DefaultExecutor();
	resultHandler = new DefaultExecuteResultHandler();
	String javaHome = System.getProperty("java.home");
	String userDir = System.getProperty("user.dir");
	
	executor.setStreamHandler(new PumpStreamHandler(System.out));
	watchdog = new ExecuteWatchdog(10000);
	executor.setWatchdog(watchdog);
	executor.execute(new CommandLine(javaHome + SystemUtils.FILE_SEPARATOR 
			+ "bin"+ SystemUtils.FILE_SEPARATOR+"java.exe").addArgument("-version"));
	executor.execute(new CommandLine(javaHome + SystemUtils.FILE_SEPARATOR 
			+ "bin"+ SystemUtils.FILE_SEPARATOR+"java.exe")
		.addArgument("-jar")
		.addArgument(userDir + "/../moneta-dropwizard/target/moneta-dropwizard-" + ContractTestSuite.getProjectVersion() + ".jar")
		.addArgument("server")
		.addArgument("src/main/resources/dropwizard/moneta-dropwizard.yaml"), resultHandler);
	Thread.sleep(3000);
	System.out.println("Test sequence starting....");
}
 
Example 8
Source Project: moneta   Source File: SpringBootContractTest.java    License: Apache License 2.0 6 votes vote down vote up
public void run() {
	try {
	executor = new DaemonExecutor();
	resultHandler = new DefaultExecuteResultHandler();
	String javaHome = System.getProperty("java.home");
	String userDir = System.getProperty("user.dir");
	
	executor.setStreamHandler(new PumpStreamHandler(System.out));
	watchdog = new ExecuteWatchdog(15000);
	executor.setWatchdog(watchdog);
	executor.execute(new CommandLine(javaHome + SystemUtils.FILE_SEPARATOR 
			+ "bin"+ SystemUtils.FILE_SEPARATOR+"java.exe").addArgument("-version"));
	executor.execute(new CommandLine(javaHome + SystemUtils.FILE_SEPARATOR 
			+ "bin"+ SystemUtils.FILE_SEPARATOR+"java.exe")
		.addArgument("-jar")
		.addArgument(userDir + "/../moneta-springboot/target/moneta-springboot-" + ContractTestSuite.getProjectVersion() + ".jar"));
	
	}
	catch (Exception e) {
		e.printStackTrace();
	}
	
}
 
Example 9
Source Project: zeppelin   Source File: ProcessLauncher.java    License: Apache License 2.0 6 votes vote down vote up
public void launch() {
  DefaultExecutor executor = new DefaultExecutor();
  executor.setStreamHandler(new PumpStreamHandler(processOutput));
  this.watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
  executor.setWatchdog(watchdog);
  try {
    executor.execute(commandLine, envs, this);
    transition(State.LAUNCHED);
    LOGGER.info("Process is launched: {}", commandLine);
  } catch (IOException e) {
    this.processOutput.stopCatchLaunchOutput();
    LOGGER.error("Fail to launch process: " + commandLine, e);
    transition(State.TERMINATED);
    errorMessage = e.getMessage();
  }
}
 
Example 10
Source Project: p4ic4idea   Source File: SimpleTestServer.java    License: Apache License 2.0 6 votes vote down vote up
public int getVersion() throws Exception {
	ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
	CommandLine cmdLine = new CommandLine(p4d);
	cmdLine.addArgument("-V");
	DefaultExecutor executor = new DefaultExecutor();
	PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
	executor.setStreamHandler(streamHandler);
	executor.execute(cmdLine);

	int version = 0;
	for (String line : outputStream.toString().split("\\n")) {
		if (line.startsWith("Rev. P4D")) {
			Pattern p = Pattern.compile("\\d{4}\\.\\d{1}");
			Matcher m = p.matcher(line);
			while (m.find()) {
				String found = m.group();
				found = found.replace(".", ""); // strip "."
				version = Integer.parseInt(found);
			}
		}
	}
	logger.info("P4D Version: " + version);
	return version;
}
 
Example 11
Source Project: p4ic4idea   Source File: SimpleTestServer.java    License: Apache License 2.0 6 votes vote down vote up
public int getVersion() throws Exception {
	ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
	CommandLine cmdLine = new CommandLine(p4d);
	cmdLine.addArgument("-V");
	DefaultExecutor executor = new DefaultExecutor();
	PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
	executor.setStreamHandler(streamHandler);
	executor.execute(cmdLine);

	int version = 0;
	for (String line : outputStream.toString().split("\\n")) {
		if (line.startsWith("Rev. P4D")) {
			Pattern p = Pattern.compile("\\d{4}\\.\\d{1}");
			Matcher m = p.matcher(line);
			while (m.find()) {
				String found = m.group();
				found = found.replace(".", ""); // strip "."
				version = Integer.parseInt(found);
			}
		}
	}
	logger.info("P4D Version: " + version);
	return version;
}
 
Example 12
Source Project: p4ic4idea   Source File: SimpleTestServer.java    License: Apache License 2.0 6 votes vote down vote up
public int getVersion() throws Exception {
	ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
	CommandLine cmdLine = new CommandLine(p4d);
	cmdLine.addArgument("-V");
	DefaultExecutor executor = new DefaultExecutor();
	PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
	executor.setStreamHandler(streamHandler);
	executor.execute(cmdLine);

	int version = 0;
	for (String line : outputStream.toString().split("\\n")) {
		if (line.startsWith("Rev. P4D")) {
			Pattern p = Pattern.compile("\\d{4}\\.\\d{1}");
			Matcher m = p.matcher(line);
			while (m.find()) {
				String found = m.group();
				found = found.replace(".", ""); // strip "."
				version = Integer.parseInt(found);
			}
		}
	}
	logger.info("P4D Version: " + version);
	return version;
}
 
Example 13
Source Project: poor-man-transcoder   Source File: Session.java    License: GNU General Public License v2.0 6 votes vote down vote up
protected void startTranscode()
{
	try 
	{	
		logger.info("Starting transcode");
		
		notifyObservers(SessionEvent.PRESTART, null);
		
		this.outstream = new TranscodeSessionOutputStream(this);
		this.resultHandler = new TranscodeSessionResultHandler(this.watchdog, this);
		
		this.executor.setWorkingDirectory(new File(this.workingDirectoryPath));
		this.executor.setStreamHandler(new PumpStreamHandler(this.outstream));
		this.executor.setProcessDestroyer(new TranscodeSessionDestroyer(this));
		this.executor.setWatchdog(this.watchdog);
		this.executor.setExitValue(0);
		
		
		this.executor.execute(this.cmdLine, this.resultHandler);
	} 
	catch (Exception e) 
	{
		logger.info("Error starting process " + e.getMessage());
	}
}
 
Example 14
Source Project: ldbc_graphalytics   Source File: __platform-name__Loader.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 15
Source Project: tutorials   Source File: JavaPythonInteropUnitTest.java    License: MIT License 6 votes vote down vote up
@Test
public void givenPythonScript_whenPythonProcessExecuted_thenSuccess() throws ExecuteException, IOException {
    String line = "python " + resolvePythonScriptPath("hello.py");
    CommandLine cmdLine = CommandLine.parse(line);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);

    DefaultExecutor executor = new DefaultExecutor();
    executor.setStreamHandler(streamHandler);

    int exitCode = executor.execute(cmdLine);
    assertEquals("No errors should be detected", 0, exitCode);
    assertEquals("Should contain script output: ", "Hello Baeldung Readers!!", outputStream.toString()
        .trim());
}
 
Example 16
Source Project: Baragon   Source File: LocalLbAdapter.java    License: Apache License 2.0 6 votes vote down vote up
private int executeWithTimeout(CommandLine command, int timeout) throws LbAdapterExecuteException, IOException {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  DefaultExecutor executor = new DefaultExecutor();
  executor.setStreamHandler(new PumpStreamHandler(baos));
  DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

  // Start async and do our own time limiting instead of using a watchdog to avoid https://issues.apache.org/jira/browse/EXEC-62
  try {
    long start = System.currentTimeMillis();
    executor.execute(command, resultHandler);
    while (System.currentTimeMillis() - start < timeout && !resultHandler.hasResult()) {
      Thread.sleep(50);
    }
    if (resultHandler.hasResult()) {
      if (resultHandler.getException() != null) {
        throw resultHandler.getException();
      }
      return resultHandler.getExitValue();
    } else {
      CompletableFuture.runAsync(() -> executor.getWatchdog().destroyProcess(), destroyProcessExecutor);
      throw new LbAdapterExecuteException(baos.toString(Charsets.UTF_8.name()), command.toString());
    }
  } catch (ExecuteException|InterruptedException e) {
    throw new LbAdapterExecuteException(baos.toString(Charsets.UTF_8.name()), e, command.toString());
  }
}
 
Example 17
Source Project: agent   Source File: ScrcpyVideoRecorder.java    License: MIT License 5 votes vote down vote up
public synchronized void start() {
    if (isRecording) {
        return;
    }

    countDownLatch = new CountDownLatch(1);

    try {
        videoName = UUIDUtil.getUUID() + ".mp4";
        startCmd = String.format("scrcpy -s %s -Nr %s -b%sM -p %d",
                mobileId,
                videoName,
                App.getProperty("androidRecordVideoBitRate"),
                PortProvider.getScrcpyRecordVideoPort());
        log.info("[{}]start record video, cmd: {}", mobileId, startCmd);
        Terminal.executeAsync(startCmd, new PumpStreamHandler(new LogOutputStream() {
            @Override
            protected void processLine(String line, int i) {
                log.info("[{}]scrcpy: {}", mobileId, line);
                if (line.contains("Recording complete")) {
                    countDownLatch.countDown();
                }
            }
        }));
        isRecording = true;
    } catch (IOException e) {
        isRecording = false;
        throw new RuntimeException(e);
    }
}
 
Example 18
Source Project: SikuliX1   Source File: LinuxUtil.java    License: MIT License 5 votes vote down vote up
@Override
public App get(App app) {
  int pid;
  if (app == null) {
    return app;
  }
  pid = app.getPID();
  if (!app.isClosing() && pid < 0) {
    if (app.getNameGiven() != null && !app.getNameGiven().isEmpty()) {
      pid = findWindowPID(app.getNameGiven(), 0);
      app.setPID(pid);
    }
    return app;
  }
  if (app.isClosing() && pid > -1) {
    DefaultExecutor executor = new DefaultExecutor();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(outputStream));
    CommandLine command = CommandLine.parse("ps -p " + pid);
    try {
      executor.execute(command);
      app.setPID(pid);
    } catch (Exception e) {
      if (outputStream.toString().split("\\n").length == 1) {
        app.setPID(-1);
        app.setWindow("");
      } else {
        Debug.log(3, "[error] LinuxUtil::executeCommand: %s (%s)", command, e.getMessage());
        logCommandSysout(command.toString(), outputStream);
      }
    }
  }
  return app;
}
 
Example 19
Source Project: super-cloudops   Source File: LineUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Execution shell commands
 * 
 * @param line
 * @param timeout
 * @param charset
 * @return
 */
public static String execAsString(String line, long timeout, String charset) {
	// Standard output
	ByteArrayOutputStream out = new ByteArrayOutputStream();
	// Error output
	ByteArrayOutputStream err = new ByteArrayOutputStream();
	CommandLine commandline = CommandLine.parse(line);
	DefaultExecutor exec = new DefaultExecutor();
	exec.setExitValues(null);
	// Timeout
	ExecuteWatchdog watch = new ExecuteWatchdog(timeout);
	exec.setWatchdog(watch);
	PumpStreamHandler handler = new PumpStreamHandler(out, err);
	exec.setStreamHandler(handler);
	try {
		exec.execute(commandline);
		// Different operating systems should pay attention to coding,
		// otherwise the results will be scrambled.
		String error = err.toString(charset);
		if (isNotBlank(error)) {
			throw new IllegalStateException(error.toString());
		}
		return out.toString(charset);
	} catch (IOException e) {
		throw new IllegalStateException(e);
	}
}
 
Example 20
Source Project: jbpm-work-items   Source File: ExecWorkItemHandler.java    License: Apache License 2.0 5 votes vote down vote up
public void executeWorkItem(WorkItem workItem,
                            WorkItemManager manager) {

    try {

        RequiredParameterValidator.validate(this.getClass(),
                                            workItem);

        String command = (String) workItem.getParameter("Command");
        List<String> arguments = (List<String>) workItem.getParameter("Arguments");

        Map<String, Object> results = new HashMap<>();

        CommandLine commandLine = CommandLine.parse(command);
        if (arguments != null && arguments.size() > 0) {
            commandLine.addArguments(arguments.toArray(new String[0]),
                                     true);
        }

        parsedCommandStr = commandLine.toString();

        DefaultExecutor executor = new DefaultExecutor();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        executor.setStreamHandler(streamHandler);
        executor.execute(commandLine);

        results.put(RESULT,
                    outputStream.toString());

        outputStream.close();

        manager.completeWorkItem(workItem.getId(),
                                 results);
    } catch (Throwable t) {
        handleException(t);
    }
}
 
Example 21
Source Project: vespa   Source File: ProcessExecutor.java    License: Apache License 2.0 5 votes vote down vote up
private static PumpStreamHandler createStreamHandler(ByteArrayOutputStream processOut,
                                                     ByteArrayOutputStream processErr,
                                                     String input) {
    if (input != null) {
        InputStream processInput = new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8));
        return new PumpStreamHandler(processOut, processErr, processInput);
    } else {
        return new PumpStreamHandler(processOut, processErr);
    }
}
 
Example 22
/**
 * Executes the given bash script with a one sec time limit and returns it's first output line
 * from STDOUT.
 * @param cmd Bash script, executed with bash -c "{script}".
 * @param substitutionMap A <String, File> map for substituting the paths in the commands. use '${FILE}' for full
 * compatibility.
 * @return The first line of the script's output in an Optional wrapper.
 */
public Optional<String> quickReturnFirstLine(String cmd, @Nullable Map<String, File> substitutionMap) {
    ec = build(DEFAULT_TIMEOUT);
    try {
        OneLineReader olr = new OneLineReader();
        ec.setStreamHandler(new PumpStreamHandler(olr));
        ec.execute(buildScriptCommandLine(cmd, substitutionMap), environment);
        return olr.getLine();
    } catch (IOException e) {
        return Optional.absent();
    }
}
 
Example 23
/**
 * Returns the full output.
 * @param cmd Bash script, executed with bash -c "{script}".
 * @param substitutionMap A <String, File> map for substituting the paths in the commands. use '${FILE}' for full
 * compatibility.
 * @param timeOut The timeOut in Milliseconds.
 * @return The script's output in an Optional wrapper.
 */
public Optional<String> quickReturnOutput(String cmd, @Nullable Map<String, File> substitutionMap, double timeOut) {
    ec = build(new Double(timeOut).longValue());
    try {
        AllLineReader olr = new AllLineReader();
        ec.setStreamHandler(new PumpStreamHandler(olr));
        ec.execute(buildScriptCommandLine(cmd, substitutionMap), environment);
        return Optional.of(olr.getOutput());
    } catch (IOException e) {
        return Optional.absent();
    }
}
 
Example 24
/**
 * Returns the full output.
 * @param cmd Bash script, executed with bash -c "{script}".
 * @param substitutionMap A <String, File> map for substituting the paths in the commands. use '${FILE}' for full
 * compatibility.
 * @param logToConsole If true the execution log will appear on console log.
 * @return The script's output in an Optional wrapper.
 */
public Optional<String> waitReturnOutput(String cmd, @Nullable Map<String, File> substitutionMap, boolean logToConsole) {
    ec = build();
    try {
        AllLineReader olr = new AllLineReader(logToConsole);
        ec.setStreamHandler(new PumpStreamHandler(olr));
        ec.execute(buildScriptCommandLine(cmd, substitutionMap), environment);
        return Optional.of(olr.getOutput());
    } catch (IOException e) {
        return Optional.absent();
    }
}
 
Example 25
/**
 * Job {@link IProgressMonitor} compatible version of the standard
 * {@link #waitReturnOutput(String, Map, boolean) waitReturnOutput} method.
 * @param cmd Bash script, executed with bash -c "{script}".
 * @param substitutionMap A <String, File> map for substituting the paths in the commands. use '${FILE}' for full
 * compatibility.
 * @param logToConsole If true the execution log will appear on console log.
 * @param monitor The progress monitor that can be incremented.
 * @param taskCount The number of separate jobs.
 * @return The process return value as a String wrapped in an @link {@link Optional}.
 */
public Optional<String> progressableWaitReturnOutput(String cmd, @Nullable Map<String, File> substitutionMap,
        boolean logToConsole, IProgressMonitor monitor, int taskCount) {
    ec = build();
    try {
        AllLineReader olr = new ProgressableAllLineReader(logToConsole, monitor, taskCount);
        ec.setStreamHandler(new PumpStreamHandler(olr));
        ec.execute(buildScriptCommandLine(cmd, substitutionMap), environment);
        return Optional.of(olr.getOutput());
    } catch (IOException e) {
        return Optional.absent();
    }
}
 
Example 26
Source Project: exec-maven-plugin   Source File: ExecMojo.java    License: Apache License 2.0 5 votes vote down vote up
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 );
}
 
Example 27
Source Project: exec-maven-plugin   Source File: ExecMojo.java    License: Apache License 2.0 5 votes vote down vote up
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 );
}
 
Example 28
private Future<CommandResult> executeCommand(String command, File executionDirectory, boolean silent)
		throws IOException {

	StringWriter writer = new StringWriter();
	DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

	try (WriterOutputStream outputStream = new WriterOutputStream(writer)) {

		String outerCommand = "/bin/bash -lc";

		CommandLine outer = CommandLine.parse(outerCommand);
		outer.addArgument(command, false);

		DefaultExecutor executor = new DefaultExecutor();
		executor.setWorkingDirectory(executionDirectory);
		executor.setStreamHandler(new PumpStreamHandler(silent ? outputStream : System.out, null));
		executor.execute(outer, ENVIRONMENT, resultHandler);

		resultHandler.waitFor();

	} catch (InterruptedException e) {
		throw new IllegalStateException(e);
	}

	return new AsyncResult<CommandResult>(
			new CommandResult(resultHandler.getExitValue(), writer.toString(), resultHandler.getException()));
}
 
Example 29
Source Project: zeppelin   Source File: AbstractTestRestApi.java    License: Apache License 2.0 5 votes vote down vote up
public static void ps() {
  DefaultExecutor executor = new DefaultExecutor();
  executor.setStreamHandler(new PumpStreamHandler(System.out, System.err));

  CommandLine cmd = CommandLine.parse("ps");
  cmd.addArgument("aux", false);

  try {
    executor.execute(cmd);
  } catch (IOException e) {
    LOG.error(e.getMessage(), e);
  }
}
 
Example 30
Source Project: elasticsearch   Source File: NetworkUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static String runCommand(CommandLine commandline) throws IOException {
    DefaultExecutor exec = new DefaultExecutor();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    exec.setStreamHandler(streamHandler);
    exec.execute(commandline);
    return outputStream.toString(Charset.defaultCharset().name());
}