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

The following examples show how to use org.apache.commons.exec.DefaultExecutor#setStreamHandler() . 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 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 2
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 3
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 4
Source File: ProcessExecutor.java    From vespa with 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 5
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 6
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 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: LineUtils.java    From super-cloudops with 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 9
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;
}
 
Example 10
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 11
Source File: ExecWorkItemHandler.java    From jbpm-work-items with 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 12
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 13
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 14
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 15
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 16
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 17
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 18
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);
    }

}
 
Example 19
Source File: SounderControl.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
private void play(@Nullable SoundFile sound) {
   PlayState currentState = state.get();
   if (currentState == null) {
      return;
   }

   long currentTimestamp = System.nanoTime();
   if (currentState.endTimestamp > Long.MIN_VALUE && currentTimestamp >= currentState.endTimestamp) {
      log.trace("play duration expired, stopping sounder");

      stop();
      return;
   }

   if (currentState.repeats < 0) {
      log.trace("play repeats exceeded, stopping sounder");

      stop();
      return;
   }

   if (sound == null) {
       stop();
       return;
   }

   DefaultExecutor executor = new DefaultExecutor();
   executor.setExitValue(0);

   ExecuteWatchdog watchdog = new ExecuteWatchdog(PLAYTONES_TIMEOUT_IN_MS);
   executor.setWatchdog(watchdog);
   
   Queue<CommandLine> queue;
         
   // Figure out the version we need to play
   switch (sound.getVersion()) {
       case IH200:
           queue = playerV2(sound);
           ByteArrayInputStream is = new ByteArrayInputStream(currentState.content.getBytes(StandardCharsets.US_ASCII));
           executor.setStreamHandler(new PumpStreamHandler(null,null,is));
           break;
       case IH300:
       case IH304:
           queue = playerV3(sound);
           break;
       default:
           log.error("No Player Found");
           stop();
           return;
   }
   try {
       currentState.repeats--;
       playing.set(true);
       if (sound != null) {
          source.set(sound.getMode().toString());
       }

       this.commands.clear();
       this.commands.addAll(queue);
       log.warn("Debug: queue {}, commands {}", queue, commands);
       log.warn("Debug: playing {}", commands.peek());
       executor.execute(commands.poll(), this);
    } catch (IOException ex) {
       stop();
    }      
}
 
Example 20
Source File: PhantomJS.java    From java-phantomjs-wrapper with MIT License 4 votes vote down vote up
/**
 * Execute a script with environment settings, options and a list of arguments.
 *
 * @param script
 *            path of script to execute
 * @param executionEnvironment
 *            the environment to use for script execution
 * @param options
 *            options to execute
 * @param arguments
 *            list of arguments
 * @return the exit code of the script
 * @throws IOException
 *             if cmd execution fails
 */
public static PhantomJSExecutionResponse exec(final InputStream script, final Map<String, String> executionEnvironment, final PhantomJSOptions options, final CommandLineArgument... arguments) throws IOException {
    if (!PhantomJSSetup.isInitialized()) {
        throw new IllegalStateException("Unable to find and execute PhantomJS binaries");
    }

    if (script == null) {
        throw new IllegalArgumentException("Script is a required argument");
    }

    // the path where the script will be copied to
    final String renderId = getRenderId();
    final Path scriptPath = PhantomJSConstants.TEMP_SCRIPT_DIR.resolve(PhantomJSConstants.SCRIPT_PREFIX + renderId);

    // create the parent directory
    Files.createDirectories(PhantomJSConstants.TEMP_SCRIPT_DIR);

    // copy the script to the path
    Files.copy(script, scriptPath);

    // start building the phantomjs binary call
    final CommandLine cmd = new CommandLine(PhantomJSSetup.getPhantomJsBinary());
    final Map<String, Object> args = new HashMap<>();
    cmd.setSubstitutionMap(args);

    // add options to the phantomjs call
    if (options != null) {
        options.apply(cmd, args);
    }

    // then script
    args.put("_script_path", scriptPath.toFile());
    cmd.addArgument("${_script_path}");

    // then any additional arguments
    if (arguments != null) {
        for (final CommandLineArgument arg : arguments) {
            if (arg != null) {
                arg.apply(cmd, args);
            }
        }
    }

    logger.info("Running command: [{}]", cmd);

    final InfoLoggerOutputStream stdOutLogger = new InfoLoggerOutputStream();
    final ErrorLoggerOutputStream stdErrLogger = new ErrorLoggerOutputStream();

    final DefaultExecutor de = new DefaultExecutor();
    de.setStreamHandler(new PumpStreamHandler(stdOutLogger, stdErrLogger));

    int code;
    try {
        if(executionEnvironment != null && !executionEnvironment.isEmpty()) {
            code = de.execute(cmd, executionEnvironment);
        } else {
            code = de.execute(cmd);
        }
    } catch (final ExecuteException exe) {
        code = exe.getExitValue();
    }

    // remove the script after running it
    Files.deleteIfExists(scriptPath);

    logger.info("Execution Completed");

    return new PhantomJSExecutionResponse(code, stdOutLogger.getMessageContents(), stdErrLogger.getMessageContents());
}