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

The following examples show how to use org.apache.commons.exec.DefaultExecutor. 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: javafx-maven-plugin   Source File: JavaFXJLinkMojo.java    License: Apache License 2.0 6 votes vote down vote up
private boolean isJLinkVersion13orHigher(String jlinkExePath) {
    CommandLine versionCommandLine = new CommandLine(jlinkExePath)
            .addArgument("--version");

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int resultCode = -1;

    try {
        resultCode = executeCommandLine(new DefaultExecutor(), versionCommandLine, null, baos, System.err);
    } catch (IOException e) {
        if (getLog().isDebugEnabled()) {
            getLog().error("Error getting JLink version", e);
        }
    }

    if (resultCode != 0) {
        getLog().error("Unable to get JLink version");
        getLog().error("Result of " + versionCommandLine + " execution is: '" + resultCode + "'");
        return false;
    }

    String versionStr = new String(baos.toByteArray());
    return JLINK_VERSION_PATTERN.matcher(versionStr).lookingAt();
}
 
Example 3
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 4
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 5
Source Project: TrackRay   Source File: Crawlergo.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public Object start() {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    WebsocketOutputStream outputStream = new WebsocketOutputStream(byteArrayOutputStream,getSession());
    String url = param.get("url").toString();
    int maxtab = Integer.parseInt(param.get("maxtab").toString());
    String mode = param.get("mode").toString();
    String proxy = param.get("proxy").toString();
    crawlergoInner.executor();
    crawlergoInner.addUrl(url);
    CrawlergoInner.GlobalOption option = crawlergoInner.option();
    option.maxCrawledCount(maxtab);
    option.filterMode(mode);
    if (StringUtils.isNotEmpty(proxy)){
        option.pushProxy(proxy);
    }else {
        option.pushProxy("");
    }
    CommandLine commandLine = crawlergoInner.buildCommandLine();
    crawlergoInner.setOutputStream(outputStream);
    crawlergoInner.setSync(false);
    DefaultExecutor run = crawlergoInner.run(commandLine);
    return "";
}
 
Example 6
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 7
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 8
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 9
Source Project: vespa   Source File: ProcessExecutor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Executes the given command synchronously.
 *
 * @param command The command to execute.
 * @param processInput Input provided to the process.
 * @return The result of the execution, or empty if the process does not terminate within the timeout set for this executor.
 * @throws IOException if the process execution failed.
 */
public Optional<ProcessResult> execute(String command, String processInput) throws IOException {
    ByteArrayOutputStream processErr = new ByteArrayOutputStream();
    ByteArrayOutputStream processOut = new ByteArrayOutputStream();

    DefaultExecutor executor = new DefaultExecutor();
    executor.setStreamHandler(createStreamHandler(processOut, processErr, processInput));
    ExecuteWatchdog watchDog = new ExecuteWatchdog(TimeUnit.SECONDS.toMillis(timeoutSeconds));
    executor.setWatchdog(watchDog);
    executor.setExitValues(successExitCodes);

    int exitCode;
    try {
        exitCode = executor.execute(CommandLine.parse(command));
    } catch (ExecuteException e) {
        exitCode = e.getExitValue();
    }
    return (watchDog.killedProcess()) ?
            Optional.empty() : Optional.of(new ProcessResult(exitCode, processOut.toString(), processErr.toString()));
}
 
Example 10
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 11
Source Project: cppcheclipse   Source File: AbstractCppcheckCommand.java    License: Apache License 2.0 6 votes vote down vote up
public AbstractCppcheckCommand(IConsole console, String[] defaultArguments,
		long timeout, String binaryPath) {

	this.binaryPath = binaryPath;
	this.console = console;
	this.defaultArguments = defaultArguments;
	
	executor = new DefaultExecutor();

	// all modes of operation returns 0 when no error occured,
	executor.setExitValue(0);

	watchdog = new ExecuteWatchdog(timeout);
	executor.setWatchdog(watchdog);

	out = new ByteArrayOutputStream();
	err = new ByteArrayOutputStream();

	processStdOut = new LineFilterOutputStream(new TeeOutputStream(out,
			console.getConsoleOutputStream(false)), DEFAULT_CHARSET);
	processStdErr = new LineFilterOutputStream(new TeeOutputStream(err,
			console.getConsoleOutputStream(true)), DEFAULT_CHARSET);
	
}
 
Example 12
Source Project: trainbenchmark   Source File: GeneratorRunner.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public static int run(final GeneratorConfig gc, final ExecutionConfig ec) throws IOException, InterruptedException {
	final File configFile = File.createTempFile("trainbenchmark-generator-", ".conf");
	final String configPath = configFile.getAbsolutePath();
	gc.saveToFile(configPath);

	final String projectName = String.format("trainbenchmark-generator-%s", gc.getProjectName());
	final String jarPath = String.format("../%s/build/libs/%s-1.0.0-SNAPSHOT-fat.jar", projectName, projectName);
	final String javaCommand = String.format("java -Xms%s -Xmx%s -server -jar %s %s", ec.getXms(), ec.getXmx(),
			jarPath, configPath);

	final CommandLine cmdLine = CommandLine.parse(javaCommand);
	final DefaultExecutor executor = new DefaultExecutor();
	try {
		final int exitValue = executor.execute(cmdLine);
		System.out.println();
		return exitValue;
	} catch (final ExecuteException e) {
		e.printStackTrace(System.out);
		return e.getExitValue();
	}
}
 
Example 13
Source Project: zeppelin   Source File: SubmarineShellInterpreter.java    License: Apache License 2.0 6 votes vote down vote up
public void createSecureConfiguration() throws InterpreterException {
  Properties properties = getProperties();
  CommandLine cmdLine = CommandLine.parse(shell);
  cmdLine.addArgument("-c", false);
  String kinitCommand = String.format("kinit -k -t %s %s",
      properties.getProperty(SUBMARINE_HADOOP_KEYTAB),
      properties.getProperty(SUBMARINE_HADOOP_PRINCIPAL));
  cmdLine.addArgument(kinitCommand, false);
  DefaultExecutor executor = new DefaultExecutor();
  try {
    executor.execute(cmdLine);
  } catch (Exception e) {
    LOGGER.error("Unable to run kinit for zeppelin user " + kinitCommand, e);
    throw new InterpreterException(e);
  }
}
 
Example 14
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 15
Source Project: zeppelin   Source File: ShellInterpreter.java    License: Apache License 2.0 6 votes vote down vote up
public void createSecureConfiguration() throws InterpreterException {
  Properties properties = getProperties();
  CommandLine cmdLine = CommandLine.parse(shell);
  cmdLine.addArgument("-c", false);
  String kinitCommand = String.format("kinit -k -t %s %s",
      properties.getProperty("zeppelin.shell.keytab.location"),
      properties.getProperty("zeppelin.shell.principal"));
  cmdLine.addArgument(kinitCommand, false);
  DefaultExecutor executor = new DefaultExecutor();
  try {
    executor.execute(cmdLine);
  } catch (Exception e) {
    LOGGER.error("Unable to run kinit for zeppelin user " + kinitCommand, e);
    throw new InterpreterException(e);
  }
}
 
Example 16
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 17
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 18
Source Project: p4ic4idea   Source File: SimpleTestServer.java    License: Apache License 2.0 6 votes vote down vote up
protected void exec(String[] args, boolean block, HashMap<String, String> environment) throws Exception {
	CommandLine cmdLine = new CommandLine(p4d);
	cmdLine.addArgument("-C0");
	cmdLine.addArgument("-r");
	cmdLine.addArgument(formatPath(p4root.getAbsolutePath()));
	for (String arg : args) {
		cmdLine.addArgument(arg);
	}

	logger.debug("EXEC: " + cmdLine.toString());

	DefaultExecutor executor = new DefaultExecutor();
	if (block) {
		executor.execute(cmdLine, environment);
	} else {
		DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
		executor.execute(cmdLine, environment, resultHandler);
	}
}
 
Example 19
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 20
Source Project: p4ic4idea   Source File: SimpleTestServer.java    License: Apache License 2.0 6 votes vote down vote up
protected void exec(String[] args, boolean block, HashMap<String, String> environment) throws Exception {
	CommandLine cmdLine = new CommandLine(p4d);
	cmdLine.addArgument("-C0");
	cmdLine.addArgument("-r");
	cmdLine.addArgument(formatPath(p4root.getAbsolutePath()));
	for (String arg : args) {
		cmdLine.addArgument(arg);
	}

	logger.debug("EXEC: " + cmdLine.toString());

	DefaultExecutor executor = new DefaultExecutor();
	if (block) {
		executor.execute(cmdLine, environment);
	} else {
		DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
		executor.execute(cmdLine, environment, resultHandler);
	}
}
 
Example 21
Source Project: p4ic4idea   Source File: TestServer.java    License: Apache License 2.0 6 votes vote down vote up
protected void exec(String[] args, boolean block, HashMap<String, String> environment) throws Exception {
    File p4d = P4ExtFileUtils.extractP4d(outDir, version);
    CommandLine cmdLine = new CommandLine(p4d);
    cmdLine.addArgument("-C0");
    cmdLine.addArgument("-r");
    cmdLine.addArgument(outDir.getAbsolutePath());
    for (String arg : args) {
        cmdLine.addArgument(arg);
    }

    DefaultExecutor executor = new DefaultExecutor();
    if (block) {
        executor.execute(cmdLine, environment);
    } else {
        DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
        executor.execute(cmdLine, environment, resultHandler);
    }
}
 
Example 22
Source Project: poor-man-transcoder   Source File: Session.java    License: GNU General Public License v2.0 6 votes vote down vote up
private Session(Builder builder) 
{
	Session.id++;
	
	this.config = builder.config;
	this.source = builder.input;
	this.cmdLine = builder.cmdLine;	
	this.cleanUpOnExit = builder.cleanUpOnExit;
	this.setOutputs(builder.outputs);
	this.executor = new DefaultExecutor();
	
	// set this locally not globally -|
	this.workingDirectoryPath = (builder.workingDirectoryPath == null || builder.workingDirectoryPath == "")?Globals.getEnv(Globals.Vars.WORKING_DIRECTORY):builder.workingDirectoryPath;
	
	this.executonTimeout = ExecuteWatchdog.INFINITE_TIMEOUT;
	this.watchdog = new ExecuteWatchdog(executonTimeout);
	this.observers = new ArrayList<ISessionObserver>();
	
	
	logger.info("Command :" + this.cmdLine.toString());
}
 
Example 23
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 24
Source Project: s3-bucket-loader   Source File: Worker.java    License: Apache License 2.0 6 votes vote down vote up
private void runInitOrDestroyCommand(String mode, Properties props) throws Exception {
	// Initialization command and environment vars
	String initCmd 		= 	props.getProperty("worker."+mode+".cmd");
	String initCmdEnv 	= 	props.getProperty("worker."+mode+".cmd.env");
	
	if (initCmd != null) {
		
		Map<String,String> env = null;
		if (initCmdEnv != null) {
			env = Splitter.on(",").withKeyValueSeparator("=").split(initCmdEnv);
		}
		
		// execute it!
		logger.debug("Running "+mode+" command: " + initCmd);
		CommandLine cmdLine = CommandLine.parse(initCmd);
		DefaultExecutor executor = new DefaultExecutor();
		executor.execute(cmdLine, env);
		
	}
}
 
Example 25
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 26
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 27
Source Project: CQL   Source File: ProcPragma.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void execute() {
	try {
		for (String cmd : cmds) {
			CommandLine cmdLine = CommandLine.parse(cmd);
			DefaultExecutor executor = new DefaultExecutor();
			executor.setStreamHandler(new ProcHandler(cmd));
			executor.execute(cmdLine);
		}
	} catch (IOException e) {
		throw new RuntimeException(e);
	}
}
 
Example 28
private static CompletableFuture<AbstractSpan<?>> asyncProcessHasTransactionContext() throws Exception {
    final CompletableFuture<AbstractSpan<?>> future = new CompletableFuture<>();
    DefaultExecuteResultHandler handler = new DefaultExecuteResultHandler() {

        // note: calling super is required otherwise process termination is not detected and waits forever

        @Override
        public void onProcessComplete(int exitValue) {
            super.onProcessComplete(exitValue);
            if (exitValue == 0) {
                future.complete(tracer.getActive());
            } else {
                future.completeExceptionally(new IllegalStateException("Exit value is not 0: " + exitValue));
            }
        }

        @Override
        public void onProcessFailed(ExecuteException e) {
            super.onProcessFailed(e);
            future.completeExceptionally(e);
        }
    };

    new DefaultExecutor().execute(new CommandLine(getJavaBinaryPath()).addArgument("-version"), handler);
    handler.waitFor();

    assertThat(future.isCompletedExceptionally())
        .describedAs("async process should have properly executed")
        .isFalse();

    return future;
}
 
Example 29
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 30
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);
	}
}