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

The following examples show how to use org.apache.commons.exec.DefaultExecutor#setExitValue() . 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: AbstractCppcheckCommand.java    From cppcheclipse with 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 3
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 4
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 5
Source File: SounderControl.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
@Override
public void onProcessComplete(int exitValue) {
 log.trace("Playing complete with exit {}", exitValue);

 // For v2, we handle repeats
 if ((currentSound != null) && (currentSound.getVersion() == Model.IH200)) {
  play(currentSound);
  return;
 }
 DefaultExecutor executor = new DefaultExecutor();
 executor.setExitValue(0);

 log.trace("Executor Ready {}", exitValue);
 log.trace("Debug Next: playing {}", commands.peek());
 CommandLine next;
 int delay;

 // See if the file should be played continuously - if so, it will have "continuous" in it's name
 //  (which is part of the command here).  In the future, we may want have a better way to
 //  signal this, perhaps an endless repeat, but that would be too involved at this point
 //  since we are close to a release...
 if (commands.peek().toString().contains("continuous")) {
       // If playing has been stopped, remove from queue
       if (!playing.get()) {
          next = commands.poll();
       } else {
          next = commands.peek();
       }
    delay = 10; // Just a short delay when playing a sound continuously
 } else {
    next = commands.poll();
    delay = 500; // Normal half second delay
 }
 // Play unless next sound is null
 if (next == null)  {
  play(null);
 } else {
  scheduler.schedule(() -> { 
   try {
	   executor.execute(next, this);
   } catch (Exception e) {
          log.error("Could not play next file", e);
   }
  },
  delay,
  TimeUnit.MILLISECONDS);
 }
}
 
Example 6
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 7
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);
    }

}