org.apache.commons.exec.PumpStreamHandler Java Examples

The following examples show how to use org.apache.commons.exec.PumpStreamHandler. 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: SimpleTestServer.java    From p4ic4idea with 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 File: Ffprobe.java    From piper with 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 #3
Source File: LocalLbAdapter.java    From Baragon with 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 #4
Source File: ProcessLauncher.java    From zeppelin with 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 #5
Source File: SpringBootContractTest.java    From moneta with 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 #6
Source File: DropwizardContractTest.java    From moneta with 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 #7
Source File: SimpleTestServer.java    From p4ic4idea with 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 #8
Source File: SimpleTestServer.java    From p4ic4idea with 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 #9
Source File: SimpleTestServer.java    From p4ic4idea with 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 #10
Source File: Session.java    From poor-man-transcoder with 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 #11
Source File: BotRunner.java    From 2018-TowerDefence with 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 #12
Source File: DockerCompose.java    From football-events with 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 #13
Source File: __platform-name__Loader.java    From ldbc_graphalytics with 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 #14
Source File: JavaPythonInteropUnitTest.java    From tutorials with 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 #15
Source File: ProcessExecClient.java    From Quicksql with 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 #16
Source File: ScriptUtil.java    From open-capacity-platform with 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 #17
Source File: CommandLineExecutor.java    From Open-LaTeX-Studio with MIT License 5 votes vote down vote up
public static synchronized void executeGeneratePDF(CommandLineBuilder cmd) {
    String outputDirectory = "--output-directory=" + cmd.getOutputDirectory();
    String outputFormat = "--output-format=pdf";
    String job = cmd.getJobname() == null ? "" : "--jobname=" + cmd.getJobname().replaceAll(" ", "_");
    ByteArrayOutputStream outputStream = null;
    
    try {           
        String[] command =  new String[] {
            outputDirectory, outputFormat, job, cmd.getPathToSource()
        };
     
        CommandLine cmdLine = new CommandLine(ApplicationUtils.getPathToTEX(cmd.getLatexPath()));
        //For windows, we set handling quoting to true
        cmdLine.addArguments(command, ApplicationUtils.isWindows());
        
        outputStream = new ByteArrayOutputStream();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        EXECUTOR.setStreamHandler(streamHandler);
        
        if (cmd.getWorkingFile() != null) {
            EXECUTOR.setWorkingDirectory(cmd.getWorkingFile().getParentFile().getAbsoluteFile());
        }
        
        EXECUTOR.execute(cmdLine);      

        if (cmd.getLogger() != null) {
            cmd.getLogger().log(cmdLine.toString());
            cmd.getLogger().log(outputStream.toString());
        }
                    
    } catch (IOException e) {
        if (cmd.getLogger() != null) {
            cmd.getLogger().log("The path to the pdflatex tool is incorrect or has not been set.");
        }
    } finally {
        IOUtils.closeQuietly(outputStream);
    }
}
 
Example #18
Source File: NetworkUtils.java    From logstash with Apache License 2.0 5 votes vote down vote up
public 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());
}
 
Example #19
Source File: OsProcess.java    From selenium with Apache License 2.0 5 votes vote down vote up
public void executeAsync() {
  try {
    final OutputStream outputStream = getOutputStream();
    executeWatchdog.reset();
    executor.setWatchdog(executeWatchdog);
    streamHandler = new PumpStreamHandler(outputStream, outputStream, getInputStream());
    executor.setStreamHandler(streamHandler);
    executor.execute(cl, getMergedEnv(), handler);
  } catch (IOException e) {
    throw new WebDriverException(e);
  }
}
 
Example #20
Source File: TestServer.java    From p4ic4idea with Apache License 2.0 5 votes vote down vote up
private int innerExec(String... args)
        throws IOException {
    File p4d = P4ExtFileUtils.extractP4d(outDir, version);
    CommandLine cmdLine = createBaseCmdLine(p4d);
    for (String arg : args) {
        cmdLine.addArgument(arg);
    }
    DefaultExecutor executor = new DefaultExecutor();
    // default - log is pumped to stderr.
    PumpStreamHandler streamHandler = new PumpStreamHandler(status.out, status.log);
    executor.setStreamHandler(streamHandler);
    executor.setProcessDestroyer(processDestroyer);
    return executor.execute(cmdLine);
}
 
Example #21
Source File: __platform-name__Loader.java    From ldbc_graphalytics with Apache License 2.0 5 votes vote down vote up
public int load(String loadedInputPath) throws Exception {
	String loaderDir = platformConfig.getLoaderPath();
	commandLine = new CommandLine(Paths.get(loaderDir).toFile());

	commandLine.addArgument("--graph-name");
	commandLine.addArgument(formattedGraph.getName());
	commandLine.addArgument("--input-vertex-path");
	commandLine.addArgument(formattedGraph.getVertexFilePath());
	commandLine.addArgument("--input-edge-path");
	commandLine.addArgument(formattedGraph.getEdgeFilePath());
	commandLine.addArgument("--output-path");
	commandLine.addArgument(loadedInputPath);
	commandLine.addArgument("--directed");
	commandLine.addArgument(formattedGraph.isDirected() ? "true" : "false");
	commandLine.addArgument("--weighted");
	commandLine.addArgument(formattedGraph.hasEdgeProperties() ? "true" : "false");


	String commandString = StringUtils.toString(commandLine.toStrings(), " ");
	LOG.info(String.format("Execute graph loader 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 #22
Source File: __platform-name__Job.java    From ldbc_graphalytics with Apache License 2.0 5 votes vote down vote up
/**
 * Executes the platform job with the pre-defined parameters.
 *
 * @return the exit code
 * @throws IOException if the platform failed to run
 */
public int execute() throws Exception {
	String executableDir = platformConfig.getExecutablePath();
	commandLine = new CommandLine(Paths.get(executableDir).toFile());

	// List of benchmark parameters.
	String jobId = getJobId();
	String logDir = getLogPath();

	// List of dataset parameters.
	String inputPath = getInputPath();
	String outputPath = getOutputPath();

	// List of platform parameters.
	int numMachines = platformConfig.getNumMachines();
	int numThreads = platformConfig.getNumThreads();
	String homeDir = platformConfig.getHomePath();

	appendBenchmarkParameters(jobId, logDir);
	appendAlgorithmParameters();
	appendDatasetParameters(inputPath, outputPath);
	appendPlatformConfigurations(homeDir, numMachines, numThreads);

	String commandString = StringUtils.toString(commandLine.toStrings(), " ");
	LOG.info(String.format("Execute benchmark job 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 #23
Source File: NetworkUtils.java    From elasticsearch with 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());
}
 
Example #24
Source File: AbstractTestRestApi.java    From zeppelin with 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 #25
Source File: IngestionUtils.java    From Explorer with Apache License 2.0 5 votes vote down vote up
public static DefaultExecuteResultHandler executeBash(String command) throws IOException {
    CommandLine cmdLine = CommandLine.parse("bash");
    cmdLine.addArgument("-c", false);
    cmdLine.addArgument(command, false);

    DefaultExecutor executor = new DefaultExecutor();
    ByteArrayOutputStream outputStreamAgentStart = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(outputStreamAgentStart));
    DefaultExecuteResultHandler handler = new DefaultExecuteResultHandler();
    executor.execute(cmdLine, handler);

    return handler;
}
 
Example #26
Source File: CommonsExecOsCommandOperations.java    From spring-data-dev-tools with Apache License 2.0 5 votes vote down vote up
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 #27
Source File: JStormUtils.java    From jstorm with Apache License 2.0 5 votes vote down vote up
/**
 * If it is backend, please set resultHandler, such as DefaultExecuteResultHandler
 * If it is frontend, ByteArrayOutputStream.toString will return the calling result
 * <p>
 * This function will ignore whether the command is successfully executed or not
 *
 * @param command       command to be executed
 * @param environment   env vars
 * @param workDir       working directory
 * @param resultHandler exec result handler
 * @return output stream
 * @throws IOException
 */
@Deprecated
public static ByteArrayOutputStream launchProcess(
        String command, final Map environment, final String workDir,
        ExecuteResultHandler resultHandler) throws IOException {

    String[] cmdlist = command.split(" ");

    CommandLine cmd = new CommandLine(cmdlist[0]);
    for (String cmdItem : cmdlist) {
        if (!StringUtils.isBlank(cmdItem)) {
            cmd.addArgument(cmdItem);
        }
    }

    DefaultExecutor executor = new DefaultExecutor();

    executor.setExitValue(0);
    if (!StringUtils.isBlank(workDir)) {
        executor.setWorkingDirectory(new File(workDir));
    }

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    PumpStreamHandler streamHandler = new PumpStreamHandler(out, out);
    executor.setStreamHandler(streamHandler);

    try {
        if (resultHandler == null) {
            executor.execute(cmd, environment);
        } else {
            executor.execute(cmd, environment, resultHandler);
        }
    } catch (ExecuteException ignored) {
    }

    return out;

}
 
Example #28
Source File: ExecutorFactory.java    From genie with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new {@link Executor} implementation instance.
 *
 * @param detached Whether the streams for processes run on this executor should be detached (ignored) or not
 * @return A {@link Executor} instance
 */
public Executor newInstance(final boolean detached) {
    final Executor executor = new DefaultExecutor();
    if (detached) {
        executor.setStreamHandler(new PumpStreamHandler(null, null));
    }
    return executor;
}
 
Example #29
Source File: ScrcpyVideoRecorder.java    From agent with 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 #30
Source File: LinuxUtil.java    From SikuliX1 with 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;
}