Java Code Examples for org.apache.commons.exec.DefaultExecutor#setWorkingDirectory()

The following examples show how to use org.apache.commons.exec.DefaultExecutor#setWorkingDirectory() . 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: 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 2
Source File: CommandExecutorService.java    From cloud-portal with MIT License 5 votes vote down vote up
public CommandResult execute(CommandLine commandLine, File workingDirectory, OutputStream outputStream) {

		CommandResult commandResult = new CommandResult();

		try {

			// create executor for command
			DefaultExecutor executor = new DefaultExecutor();

			// set working directory
			if (workingDirectory != null) {
				executor.setWorkingDirectory(workingDirectory);
			}

			// set possible exit values
			executor.setExitValues(IntStream.range(0, 255).toArray());

			// create output stream for command
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			TeeOutputStream teeOutputStream = new TeeOutputStream(outputStream, byteArrayOutputStream);
			AutoFlushingPumpStreamHandler streamHandler = new AutoFlushingPumpStreamHandler(teeOutputStream);
			executor.setStreamHandler(streamHandler);

			// execute command
			int exitValue = executor.execute(commandLine);

			// fill command result
			commandResult.setOutput(byteArrayOutputStream.toString());
			commandResult.setSuccess(exitValue == 0 ? true : false);
		}
		catch(IOException e) {
			LOG.error(e.getMessage(), e);
		}

		return commandResult;
	}
 
Example 3
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 4
Source File: KuduLocal.java    From geowave with Apache License 2.0 5 votes vote down vote up
private void executeAsyncAndWatch(final CommandLine command)
    throws ExecuteException, IOException {
  LOGGER.info("Running async: {}", command.toString());
  final ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
  final DefaultExecutor executor = new DefaultExecutor();
  executor.setWatchdog(watchdog);
  executor.setWorkingDirectory(kuduLocalDir);
  watchdogs.add(watchdog);
  // Using a result handler makes the local instance run async
  executor.execute(command, new DefaultExecuteResultHandler());
}
 
Example 5
Source File: ProcessExecutor.java    From frontend-maven-plugin with Apache License 2.0 5 votes vote down vote up
private Executor createExecutor(File workingDirectory, long timeoutInSeconds) {
    DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(workingDirectory);
    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());   // Fixes #41

    if (timeoutInSeconds > 0) {
        executor.setWatchdog(new ExecuteWatchdog(timeoutInSeconds * 1000));
    }

    return executor;
}
 
Example 6
Source File: YeomanMojo.java    From yeoman-maven-plugin with Apache License 2.0 5 votes vote down vote up
void executeCommand(String command) throws MojoExecutionException {
    try {
        if (isWindows()) {
            command = "cmd /c " + command;
        }
        CommandLine cmdLine = CommandLine.parse(command);
        DefaultExecutor executor = new DefaultExecutor();
        executor.setWorkingDirectory(yeomanProjectDirectory);
        executor.execute(cmdLine);
    } catch (IOException e) {
        throw new MojoExecutionException("Error during : " + command, e);
    }
}
 
Example 7
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 8
Source File: ProcessRunner.java    From oneops with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a process and logs the output
 */
public void executeProcess(String[] cmd, String logKey, ProcessResult result,
    Map<String, String> additionalEnvVars, File workingDir) {

  Map<String, String> env = getEnvVars(cmd, additionalEnvVars);
  logger.info(format("%s Cmd: %s, Additional Env Vars: %s", logKey,
      String.join(" ", cmd), additionalEnvVars));

  try {
    CommandLine cmdLine = new CommandLine(cmd[0]);
    // add rest of cmd string[] as arguments
    for (int i = 1; i < cmd.length; i++) {
      // needs the quote handling=false or else doesn't work
      // http://www.techques.com/question/1-5080109/How-to-execute--bin-sh-with-commons-exec?
      cmdLine.addArgument(cmd[i], false);
    }
    setTimeoutInSeconds((int)config.getChefTimeout());
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);
    executor.setWatchdog(new ExecuteWatchdog(timeoutInSeconds * 1000));
    OutputHandler outputStream = new OutputHandler(logger, logKey, result);
    ErrorHandler errorStream = new ErrorHandler(logger, logKey, result);
    executor.setStreamHandler(new PumpStreamHandler(outputStream, errorStream));
    if (workingDir != null) {
      executor.setWorkingDirectory(workingDir);
    }
    result.setResultCode(executor.execute(cmdLine, env));

    // set fault to last error if fault map is empty
    if (result.getResultCode() != 0 && result.getFaultMap().keySet().size() < 1) {
      result.getFaultMap().put("ERROR", result.getLastError());
    }

  } catch(ExecuteException ee) {
    logger.error(logKey + ee);
    result.setResultCode(ee.getExitValue());
  } catch(IOException e) {
    logger.error(e);
    result.setResultCode(1);
  }

}
 
Example 9
Source File: NPM.java    From wisdom with Apache License 2.0 4 votes vote down vote up
/**
 * Executes the current NPM using the given binary file.
 *
 * @param binary the program to run
 * @param args   the arguments
 * @return the execution exit status
 * @throws MojoExecutionException if the execution failed
 */
public int execute(File binary, String... args) throws MojoExecutionException {
    File destination = getNPMDirectory();
    if (!destination.isDirectory()) {
        throw new IllegalStateException("NPM " + this.npmName + " not installed");
    }

    CommandLine cmdLine = new CommandLine(node.getNodeExecutable());

    if (binary == null) {
        throw new IllegalStateException("Cannot execute NPM " + this.npmName + " - the given binary is 'null'.");
    }

    if (!binary.isFile()) {
        throw new IllegalStateException("Cannot execute NPM " + this.npmName + " - the given binary does not " +
                "exist: " + binary.getAbsoluteFile() + ".");
    }

    // NPM is launched using the main file.
    cmdLine.addArgument(binary.getAbsolutePath(), false);
    for (String arg : args) {
        cmdLine.addArgument(arg, this.handleQuoting);
    }

    DefaultExecutor executor = new DefaultExecutor();

    executor.setExitValue(0);

    errorStreamFromLastExecution = new LoggedOutputStream(log, true, true);
    outputStreamFromLastExecution = new LoggedOutputStream(log, false, registerOutputStream);

    PumpStreamHandler streamHandler = new PumpStreamHandler(
            outputStreamFromLastExecution,
            errorStreamFromLastExecution);

    executor.setStreamHandler(streamHandler);
    executor.setWorkingDirectory(node.getWorkDir());
    log.info("Executing " + cmdLine.toString() + " from " + executor.getWorkingDirectory().getAbsolutePath());

    try {
        return executor.execute(cmdLine, extendEnvironmentWithNodeInPath(node));
    } catch (IOException e) {
        throw new MojoExecutionException("Error during the execution of the NPM " + npmName, e);
    }

}