Java Code Examples for org.apache.commons.exec.ExecuteException#getExitValue()

The following examples show how to use org.apache.commons.exec.ExecuteException#getExitValue() . 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: 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 2
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 3
Source File: GeneratorRunner.java    From trainbenchmark with 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 4
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());
}
 
Example 5
Source File: BenchmarkRunner.java    From trainbenchmark with Eclipse Public License 1.0 4 votes vote down vote up
public static int runPerformanceBenchmark(final BenchmarkConfig bc, final ExecutionConfig ec)
		throws IOException, InterruptedException {
	final Joiner joiner = Joiner.on(", ");
	System.out.println("Running benchmark.");
	System.out.println("Workload: " + bc.getConfigBase().getWorkload());
	System.out.println("Tool: " + bc.getToolName());
	System.out.println("Model: " + bc.getConfigBase().getModelPath());
	System.out.println("Description: " + bc.getDescription());
	System.out.println("Operations: [" + joiner.join(bc.getConfigBase().getOperations()) + "]");
	System.out.println("Execution configuration: " + ec);
	System.out.println("Runs: " + bc.getConfigBase().getRuns());

	final File configFile = File.createTempFile("trainbenchmark-benchmark-", ".conf");
	final String configPath = configFile.getAbsolutePath();
	bc.saveToFile(configPath);

	final String projectName = String.format("trainbenchmark-tool-%s", bc.getProjectName());
	final String jarPath = String.format("../%s/build/libs/%s-1.0.0-SNAPSHOT-fat.jar %s", projectName, projectName,
			configPath);

	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 long timeoutInSeconds = bc.getConfigBase().getTimeout();
	final long timeoutInMilliseconds = timeoutInSeconds * 1000;
	final ExecuteWatchdog watchdog = new ExecuteWatchdog(timeoutInMilliseconds);
	final Executor executor = new DefaultExecutor();
	executor.setWatchdog(watchdog);
	executor.setStreamHandler(new PumpStreamHandler());
	try {
		final int exitValue = executor.execute(cmdLine);
		System.out.println();
		return exitValue;
	} catch (final ExecuteException e) {
		if (watchdog.killedProcess()) {
			System.out.println("Process timed out.");
		} else {
			e.printStackTrace(System.out);
		}
		return e.getExitValue();
	}
}