Search in sources :

Example 61 with DefaultExecutor

use of org.apache.commons.exec.DefaultExecutor in project smarthome by eclipse.

the class ExecUtil method executeCommandLineAndWaitResponse.

/**
 * <p>
 * Executes <code>commandLine</code>. Sometimes (especially observed on MacOS) the commandLine isn't executed
 * properly. In that cases another exec-method is to be used. To accomplish this please use the special delimiter '
 * <code>@@</code>'. If <code>commandLine</code> contains this delimiter it is split into a String[] array and the
 * special exec-method is used.
 *
 * <p>
 * A possible {@link IOException} gets logged but no further processing is done.
 *
 * @param commandLine the command line to execute
 * @param timeout timeout for execution in milliseconds
 * @return response data from executed command line
 */
public static String executeCommandLineAndWaitResponse(String commandLine, int timeout) {
    String retval = null;
    CommandLine cmdLine = null;
    if (commandLine.contains(CMD_LINE_DELIMITER)) {
        String[] cmdArray = commandLine.split(CMD_LINE_DELIMITER);
        cmdLine = new CommandLine(cmdArray[0]);
        for (int i = 1; i < cmdArray.length; i++) {
            cmdLine.addArgument(cmdArray[i], false);
        }
    } else {
        cmdLine = CommandLine.parse(commandLine);
    }
    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
    Executor executor = new DefaultExecutor();
    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(stdout);
    executor.setExitValues(null);
    executor.setStreamHandler(streamHandler);
    executor.setWatchdog(watchdog);
    Logger logger = LoggerFactory.getLogger(ExecUtil.class);
    try {
        executor.execute(cmdLine, resultHandler);
        logger.debug("executed commandLine '{}'", commandLine);
    } catch (ExecuteException e) {
        logger.warn("couldn't execute commandLine '{}'", commandLine, e);
    } catch (IOException e) {
        logger.warn("couldn't execute commandLine '{}'", commandLine, e);
    }
    // can safely request the exit code
    try {
        resultHandler.waitFor();
        int exitCode = resultHandler.getExitValue();
        retval = StringUtils.chomp(stdout.toString());
        if (resultHandler.getException() != null) {
            logger.warn("{}", resultHandler.getException().getMessage());
        } else {
            logger.debug("exit code '{}', result '{}'", exitCode, retval);
        }
    } catch (InterruptedException e) {
        logger.warn("Timeout occurred when executing commandLine '{}'", commandLine, e);
    }
    return retval;
}
Also used : DefaultExecuteResultHandler(org.apache.commons.exec.DefaultExecuteResultHandler) DefaultExecutor(org.apache.commons.exec.DefaultExecutor) ExecuteWatchdog(org.apache.commons.exec.ExecuteWatchdog) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) Logger(org.slf4j.Logger) CommandLine(org.apache.commons.exec.CommandLine) Executor(org.apache.commons.exec.Executor) DefaultExecutor(org.apache.commons.exec.DefaultExecutor) PumpStreamHandler(org.apache.commons.exec.PumpStreamHandler) ExecuteException(org.apache.commons.exec.ExecuteException)

Example 62 with DefaultExecutor

use of org.apache.commons.exec.DefaultExecutor in project openj9 by eclipse.

the class SoftmxRASTest1 method startSecondJVM.

/**
 * Starts a JVM in a subproces
 * @param xmxVal : -Xmx value to use in the command line of the JVM to be spawned
 * @param softmxVal : -Xsoftmx value to use in the command line of the JVM to be spawned
 * @param classToRun : The class that should be run using java
 * @return : return code of the sub-process which runs the JVM
 * @throws IOException
 * @throws InterruptedException
 */
public static int startSecondJVM(long xmxVal, long softmxVal, Class<?> classToRun) throws IOException, InterruptedException {
    List<String> arguments = new ArrayList<String>();
    /* pass parent JVM options to the child JVMs. */
    List<String> inputArgs = ManagementFactory.getRuntimeMXBean().getInputArguments();
    // Include -X, but not -Xdump, arguments from parent first to allow for later overrides.
    for (String arg : inputArgs) {
        if (arg.startsWith("-X") && !arg.startsWith("-Xdump")) {
            arguments.add(arg);
        }
    }
    // We're only interested in generating javacore files: disable other dumps.
    // first disable all dump agents
    arguments.add("-Xdump:none");
    // now enable javacore files for systhrow of OutOfMemoryError
    arguments.add("-Xdump:java:events=systhrow,filter=java/lang/OutOfMemoryError");
    String classpath = System.getProperty("java.class.path");
    arguments.add("-cp");
    arguments.add(classpath);
    arguments.add("-Xmx" + xmxVal + "M");
    if (softmxVal != -1) {
        arguments.add("-Xsoftmx" + softmxVal + "M");
    }
    arguments.add("-Xmn1M");
    arguments.add(classToRun.getCanonicalName());
    StringBuilder cmdLineBuffer = new StringBuilder();
    String javaPath = System.getProperty("java.home") + "/bin/java";
    cmdLineBuffer.append(javaPath);
    for (String argument : arguments) {
        cmdLineBuffer.append(' ').append(argument);
    }
    String cmdLineStr = cmdLineBuffer.toString();
    logger.debug("Executing cmd: " + cmdLineStr);
    CommandLine cmdLine = CommandLine.parse(cmdLineStr);
    DefaultExecutor executor = new DefaultExecutor();
    PumpStreamHandler strmHndlr = new PumpStreamHandler(System.out);
    executor.setWorkingDirectory(new File("."));
    executor.setStreamHandler(strmHndlr);
    int exitValue;
    try {
        exitValue = executor.execute(cmdLine);
    } catch (ExecuteException e) {
        exitValue = -1;
    }
    return exitValue;
}
Also used : CommandLine(org.apache.commons.exec.CommandLine) PumpStreamHandler(org.apache.commons.exec.PumpStreamHandler) DefaultExecutor(org.apache.commons.exec.DefaultExecutor) ArrayList(java.util.ArrayList) ExecuteException(org.apache.commons.exec.ExecuteException) File(java.io.File)

Example 63 with DefaultExecutor

use of org.apache.commons.exec.DefaultExecutor in project openj9 by eclipse.

the class SoftmxUserScenarioTest method startSecondJVM.

/**
 * Starts a JVM in a subproces
 * @param xmxVal : -Xmx value to use in the command line of the JVM to be spawned
 * @param softmxVal : -Xsoftmx value to use in the command line of the JVM to be spawned
 * @param classToRun : The class that should be run using java
 * @return : return code of the sub-process which runs the JVM
 * @throws IOException
 * @throws InterruptedException
 */
private static int startSecondJVM(long xmxVal, long softmxVal, Class classToRun) throws IOException, InterruptedException {
    String classpath = System.getProperty("java.class.path");
    String path = System.getProperty("java.home") + "/bin/java";
    String cmdLineStr = null;
    int exitValue = -1;
    if (softmxVal == -1) {
        cmdLineStr = path + " -cp " + classpath + " -Xmx" + xmxVal + "m " + classToRun.getCanonicalName();
    } else {
        cmdLineStr = path + " -cp " + classpath + " -Xmx" + xmxVal + "m -Xsoftmx" + softmxVal + "m " + classToRun.getCanonicalName();
    }
    logger.info("Executing cmd : " + cmdLineStr);
    CommandLine cmdLine = CommandLine.parse(cmdLineStr);
    DefaultExecutor executor = new DefaultExecutor();
    try {
        exitValue = executor.execute(cmdLine);
    } catch (ExecuteException e) {
        logger.warn("Exception throw from executing the second JVM:" + e, e);
    }
    return exitValue;
}
Also used : CommandLine(org.apache.commons.exec.CommandLine) DefaultExecutor(org.apache.commons.exec.DefaultExecutor) ExecuteException(org.apache.commons.exec.ExecuteException)

Example 64 with DefaultExecutor

use of org.apache.commons.exec.DefaultExecutor in project tycho by eclipse.

the class DefaultEquinoxLauncher method execute.

@Override
public int execute(LaunchConfiguration configuration, int forkedProcessTimeoutInSeconds) throws EquinoxLaunchingException {
    String executable = configuration.getJvmExecutable();
    if (executable == null || "".equals(executable)) {
        // use the same JVM as the one used to run Maven (the "java.home" one)
        executable = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
        if (File.separatorChar == '\\') {
            executable = executable + ".exe";
        }
    }
    CommandLine cli = new CommandLine(executable);
    final boolean handleQuotes = false;
    cli.addArguments(configuration.getVMArguments(), handleQuotes);
    cli.addArguments(new String[] { "-jar", getCanonicalPath(configuration.getLauncherJar()) }, handleQuotes);
    cli.addArguments(configuration.getProgramArguments(), handleQuotes);
    log.info("Command line:\n\t" + cli.toString());
    DefaultExecutor executor = new DefaultExecutor();
    ExecuteWatchdog watchdog = null;
    if (forkedProcessTimeoutInSeconds > 0) {
        watchdog = new ExecuteWatchdog(forkedProcessTimeoutInSeconds * 1000L);
        executor.setWatchdog(watchdog);
    }
    // best effort to avoid orphaned child process
    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
    executor.setWorkingDirectory(configuration.getWorkingDirectory());
    try {
        return executor.execute(cli, getMergedEnvironment(configuration));
    } catch (ExecuteException e) {
        if (watchdog != null && watchdog.killedProcess()) {
            log.error("Timeout " + forkedProcessTimeoutInSeconds + " s exceeded. Process was killed.");
        }
        return e.getExitValue();
    } catch (IOException e) {
        throw new EquinoxLaunchingException(e);
    }
}
Also used : CommandLine(org.apache.commons.exec.CommandLine) DefaultExecutor(org.apache.commons.exec.DefaultExecutor) ExecuteWatchdog(org.apache.commons.exec.ExecuteWatchdog) ExecuteException(org.apache.commons.exec.ExecuteException) IOException(java.io.IOException) EquinoxLaunchingException(org.eclipse.sisu.equinox.launching.EquinoxLaunchingException) ShutdownHookProcessDestroyer(org.apache.commons.exec.ShutdownHookProcessDestroyer)

Example 65 with DefaultExecutor

use of org.apache.commons.exec.DefaultExecutor in project evosuite by EvoSuite.

the class ProcessLauncher method launchNewProcess.

public int launchNewProcess(File baseDir, String cmdString, int timeout) throws IOException, ProcessTimeoutException {
    DefaultExecutor executor = new DefaultExecutor();
    ExecuteWatchdog timeoutWatchdog = new ExecuteWatchdog(timeout);
    executor.setWatchdog(timeoutWatchdog);
    PumpStreamHandler streamHandler = new PumpStreamHandler(this.outAndErr, this.outAndErr, this.input);
    executor.setStreamHandler(streamHandler);
    if (baseDir != null) {
        executor.setWorkingDirectory(baseDir);
    }
    int exitValue;
    try {
        logger.debug("About to execute command " + cmdString);
        exitValue = executor.execute(CommandLine.parse(cmdString));
        if (executor.isFailure(exitValue) && timeoutWatchdog.killedProcess()) {
            // it was killed on purpose by the watchdog
            logger.debug("A timeout occured while executing a process");
            logger.debug("The command is " + cmdString);
            throw new ProcessTimeoutException("A timeout occurred while executing command " + cmdString);
        }
        return exitValue;
    } catch (ExecuteException e) {
        if (timeoutWatchdog.killedProcess()) {
            logger.debug("A timeout occured while executing a process");
            logger.debug("The command is " + cmdString);
            throw new ProcessTimeoutException("A timeout occurred while executing command " + cmdString);
        } else {
            throw e;
        }
    }
}
Also used : PumpStreamHandler(org.apache.commons.exec.PumpStreamHandler) DefaultExecutor(org.apache.commons.exec.DefaultExecutor) ExecuteWatchdog(org.apache.commons.exec.ExecuteWatchdog) ExecuteException(org.apache.commons.exec.ExecuteException)

Aggregations

DefaultExecutor (org.apache.commons.exec.DefaultExecutor)81 CommandLine (org.apache.commons.exec.CommandLine)62 PumpStreamHandler (org.apache.commons.exec.PumpStreamHandler)47 IOException (java.io.IOException)36 ExecuteWatchdog (org.apache.commons.exec.ExecuteWatchdog)33 ExecuteException (org.apache.commons.exec.ExecuteException)27 ByteArrayOutputStream (java.io.ByteArrayOutputStream)26 File (java.io.File)24 Executor (org.apache.commons.exec.Executor)11 DefaultExecuteResultHandler (org.apache.commons.exec.DefaultExecuteResultHandler)9 ShutdownHookProcessDestroyer (org.apache.commons.exec.ShutdownHookProcessDestroyer)9 HashMap (java.util.HashMap)5 Test (org.junit.Test)5 URL (java.net.URL)4 Properties (java.util.Properties)4 LogOutputStream (org.apache.commons.exec.LogOutputStream)4 InputStream (java.io.InputStream)3 PipedInputStream (java.io.PipedInputStream)3 PipedOutputStream (java.io.PipedOutputStream)3 HashSet (java.util.HashSet)3