Example usage for org.apache.commons.exec DefaultExecuteResultHandler getException

List of usage examples for org.apache.commons.exec DefaultExecuteResultHandler getException

Introduction

In this page you can find the example usage for org.apache.commons.exec DefaultExecuteResultHandler getException.

Prototype

public ExecuteException getException() 

Source Link

Document

Get the exception causing the process execution to fail.

Usage

From source file:gov.nasa.jpl.magicdraw.projectUsageIntegrity.graph.SSCAEProjectUsageGraph.java

/**
 * @param pugDOT gv file/*w ww  .ja  va  2s  . c  o  m*/
 * @return true if the graphviz application was opened successfully for the gv file.
 * @throws IIOException
 * @throws IOException
 * @throws InterruptedException
 */
public boolean openDOTFileWithGraphViz(@Nonnull File pugDOT)
        throws IIOException, IOException, InterruptedException {
    String graphvizApp = ProjectUsageIntegrityPlugin.getInstance().getGraphvizApplicationPath();
    if (null == graphvizApp)
        return false;

    File pugTemp = pugDOT.getParentFile();

    CommandLine cmdLine;

    switch (SSCAEProjectUsageIntegrityOptions.getCurrentPlatform()) {
    case LINUX:
        cmdLine = new CommandLine(graphvizApp);
        break;
    case MACOSX:
        cmdLine = new CommandLine("/usr/bin/open");
        cmdLine.addArgument("-a");
        cmdLine.addArgument(graphvizApp);
        break;
    case WINDOWS:
        cmdLine = new CommandLine("cmd");
        cmdLine.addArgument("/c");
        cmdLine.addArgument("start");
        cmdLine.addArgument(graphvizApp);
        break;
    default:
        return false;
    }
    cmdLine.addArgument(pugDOT.getName());

    pluginLog.info(String.format("%s - openDOTFileWithGraphViz - opening DOT file for project: '%s'",
            pluginName, project.getName()));

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000);

    // consider '0' exit value as success.
    Executor executor = new DefaultExecutor();
    executor.setExitValue(0);
    executor.setWatchdog(watchdog);
    executor.setWorkingDirectory(pugTemp);
    executor.execute(cmdLine, resultHandler);

    resultHandler.waitFor();

    if (executor.isFailure(resultHandler.getExitValue())) {
        pluginLog.error(String.format(
                "%s - openDOTFileWithGraphViz - error while opening DOT file for project '%s' from: '%s'",
                pluginName, project.getName(), pugDOT.getAbsolutePath()), resultHandler.getException());
        return false;
    }

    pluginLog.info(String.format("%s - openDOTFileWithGraphViz - opened DOT file for project '%s' from: '%s'",
            pluginName, project.getName(), pugDOT.getAbsolutePath()));
    return true;
}

From source file:org.apache.geode.examples.replicated.ReplicatedTest.java

/**
 * Given a script file name, runs the script and return the exit code.
 * If exitCode != 0 extract and prints exception.
 * @param scriptName/*from   www  .j  a  v a 2  s  . c om*/
 * @return <code>int</code> with exitCode
 * @throws IOException
 * @throws InterruptedException
 */
private int executeScript(String scriptName) throws IOException, InterruptedException {
    final int exitCode;
    DefaultExecuteResultHandler resultHandler = shell.execute(scriptName, scriptTimeout, environment,
            testFolder.getRoot());
    processRunning = true;
    resultHandler.waitFor();

    logger.finest(String.format("Executing %s...", scriptName));
    exitCode = resultHandler.getExitValue();

    // extract and log exception if any happened
    if (exitCode != 0) {
        ExecuteException executeException = resultHandler.getException();
        logger.log(Level.SEVERE, executeException.getMessage(), executeException);
    }
    return exitCode;
}

From source file:org.fuin.esmp.EventStoreStartMojo.java

private List<String> waitForHttpServer(final DefaultExecuteResultHandler resultHandler,
        final ByteArrayOutputStream bos) throws MojoExecutionException {

    // Wait for result
    int wait = 0;
    while ((wait++ < maxWaitCycles) && !resultHandler.hasResult() && !bos.toString().contains(upMessage)) {
        sleep(sleepMs);/*from w ww.ja  va  2s  . c om*/
    }

    if (bos.toString().contains(upMessage)) {
        // Success
        return asList(bos.toString());
    }

    // Failure
    final List<String> messages = asList(bos.toString());
    logError(messages);

    // Exception
    if (resultHandler.hasResult()) {
        throw new MojoExecutionException("Error starting the server. Exit code=" + resultHandler.getExitValue(),
                resultHandler.getException());
    }
    // Timeout
    throw new MojoExecutionException("Waited too long for the server to start!");

}

From source file:org.jberet.support.io.OsCommandBatchlet.java

/**
 * {@inheritDoc}//from   ww w  .j  a v  a  2s .c  o m
 * <p>
 * This method runs the OS command.
 * If the command completes successfully, its process exit code is returned.
 * If there is exception while running the OS command, which may be
 * caused by timeout, the command being stopped, or other errors, the process
 * exit code is set as the step exit status, and the exception is thrown.
 *
 * @return the OS command process exit code
 *
 * @throws Exception upon errors
 */
@Override
public String process() throws Exception {
    final DefaultExecutor executor = new DefaultExecutor();
    final CommandLine commandLineObj;
    if (commandLine != null) {
        commandLineObj = CommandLine.parse(commandLine);
    } else {
        if (commandArray == null) {
            throw SupportMessages.MESSAGES.invalidReaderWriterProperty(null, null, "commandArray");
        } else if (commandArray.isEmpty()) {
            throw SupportMessages.MESSAGES.invalidReaderWriterProperty(null, commandArray.toString(),
                    "commandArray");
        }
        commandLineObj = new CommandLine(commandArray.get(0));
        final int len = commandArray.size();
        if (len > 1) {
            for (int i = 1; i < len; i++) {
                commandLineObj.addArgument(commandArray.get(i));
            }
        }
    }

    if (workingDir != null) {
        executor.setWorkingDirectory(workingDir);
    }
    if (streamHandler != null) {
        executor.setStreamHandler((ExecuteStreamHandler) streamHandler.newInstance());
    }

    SupportLogger.LOGGER.runCommand(commandLineObj.getExecutable(),
            Arrays.toString(commandLineObj.getArguments()), executor.getWorkingDirectory().getAbsolutePath());

    if (commandOkExitValues != null) {
        executor.setExitValues(commandOkExitValues);
    }

    watchdog = new ExecuteWatchdog(
            timeoutSeconds > 0 ? timeoutSeconds * 1000 : ExecuteWatchdog.INFINITE_TIMEOUT);
    executor.setWatchdog(watchdog);

    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
    final DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    executor.execute(commandLineObj, environment, resultHandler);
    resultHandler.waitFor();

    final ExecuteException exception = resultHandler.getException();
    if (exception != null) {
        stepContext.setExitStatus(String.valueOf(resultHandler.getExitValue()));
        if (!isStopped) {
            throw exception;
        } else {
            SupportLogger.LOGGER.warn("", exception);
        }
    }
    return String.valueOf(resultHandler.getExitValue());
}

From source file:org.openhab.io.net.exec.ExecUtil.java

/**
 * <p>/*from  w ww  .j a v  a2s. com*/
 * 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>
 * <p>
 * A possible {@link IOException} gets logged but no further processing is
 * done.
 * </p>
 * 
 * @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.setExitValue(1);
    executor.setStreamHandler(streamHandler);
    executor.setWatchdog(watchdog);

    try {
        executor.execute(cmdLine, resultHandler);
        logger.debug("executed commandLine '{}'", commandLine);
    } catch (ExecuteException e) {
        logger.error("couldn't execute commandLine '" + commandLine + "'", e);
    } catch (IOException e) {
        logger.error("couldn't execute commandLine '" + commandLine + "'", e);
    }

    // some time later the result handler callback was invoked so we
    // 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.error("Timeout occured when executing commandLine '" + commandLine + "'", e);
    }

    return retval;
}

From source file:org.springframework.data.release.io.CommonsExecOsCommandOperations.java

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();/*from  w  ww  . ja  v  a2  s.  c  o m*/

    } catch (InterruptedException e) {
        throw new IllegalStateException(e);
    }

    return new AsyncResult<CommandResult>(
            new CommandResult(resultHandler.getExitValue(), writer.toString(), resultHandler.getException()));
}

From source file:ro.cosu.vampires.client.executors.fork.ForkExecutor.java

@Override
public Result execute(Computation computation) {

    acquireResources();//from ww  w.j  a  v  a  2  s. c  om

    CommandLine commandLine = getCommandLine(computation.command());

    CollectingLogOutputStream collectingLogOutputStream = new CollectingLogOutputStream();
    PumpStreamHandler handler = new PumpStreamHandler(collectingLogOutputStream);
    executor.setStreamHandler(handler);
    executor.setWatchdog(new ExecuteWatchdog(TIMEOUT_IN_MILIS));
    executor.setWorkingDirectory(Paths.get("").toAbsolutePath().toFile());

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    LocalDateTime start = LocalDateTime.now();
    int exitCode;
    try {
        executor.execute(commandLine, resultHandler);
    } catch (IOException e) {
        LOG.error("failed to exec", resultHandler.getException());
    }

    try {
        resultHandler.waitFor();
    } catch (InterruptedException e) {
        LOG.error("failed to exec", resultHandler.getException());
    }

    exitCode = resultHandler.hasResult() ? resultHandler.getExitValue() : -1;

    //TODO take different action for failed commands so we can collect the output (stderr or java exception)

    LocalDateTime stop = LocalDateTime.now();

    long duration = Duration.between(start, stop).toMillis();

    releaseResources();
    return Result.builder().duration(duration).exitCode(exitCode).trace(getTrace(start, stop))
            .output(collectingLogOutputStream.getLines()).build();

}

From source file:sce.ProcessExecutor.java

public String executeProcess(String[] processParameters) throws JobExecutionException {
    try {/*from  ww  w.  j ava 2 s .  c  om*/
        //Command to be executed
        CommandLine command = new CommandLine(processParameters[0]);

        String[] params = new String[processParameters.length - 1];
        for (int i = 0; i < processParameters.length - 1; i++) {
            params[i] = processParameters[i + 1];
        }

        //Adding its arguments
        command.addArguments(params);

        //set timeout in seconds
        ExecuteWatchdog watchDog = new ExecuteWatchdog(
                this.timeout == 0 ? ExecuteWatchdog.INFINITE_TIMEOUT : this.timeout * 1000);
        this.watchdog = watchDog;

        //Result Handler for executing the process in a Asynch way
        DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
        //MyResultHandler resultHandler = new MyResultHandler();

        //Using Std out for the output/error stream
        //ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        //PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        //This is used to end the process when the JVM exits
        ShutdownHookProcessDestroyer processDestroyer = new ShutdownHookProcessDestroyer();

        //Our main command executor
        DefaultExecutor executor = new DefaultExecutor();

        //Setting the properties
        executor.setStreamHandler(new PumpStreamHandler(null, null));
        executor.setWatchdog(watchDog);
        //executor.setExitValue(1); // this has to be set if the java code contains System.exit(1) to avoid a FAILED status

        //Setting the working directory
        //Use of recursion along with the ls makes this a long running process
        //executor.setWorkingDirectory(new File("/home"));
        executor.setProcessDestroyer(processDestroyer);

        //if set, use the java environment variables when running the command
        if (!this.environment.equals("")) {
            Map<String, String> procEnv = EnvironmentUtils.getProcEnvironment();
            EnvironmentUtils.addVariableToEnvironment(procEnv, this.environment);
            //Executing the command
            executor.execute(command, procEnv, resultHandler);
        } else {
            //Executing the command
            executor.execute(command, resultHandler);
        }

        //The below section depends on your need
        //Anything after this will be executed only when the command completes the execution
        resultHandler.waitFor();

        /*int exitValue = resultHandler.getExitValue();
         System.out.println(exitValue);
         if (executor.isFailure(exitValue)) {
         System.out.println("Execution failed");
         } else {
         System.out.println("Execution Successful");
         }
         System.out.println(outputStream.toString());*/
        //return outputStream.toString();
        if (watchdog.killedProcess()) {
            throw new JobExecutionException("Job Interrupted", new InterruptedException());
        }
        if (executor.isFailure(resultHandler.getExitValue())) {
            ExecuteException ex = resultHandler.getException();
            throw new JobExecutionException(ex.getMessage(), ex);
        }
        return "1";
    } catch (ExecuteException ex) {
        throw new JobExecutionException(ex.getMessage(), ex);
    } catch (IOException | InterruptedException | JobExecutionException ex) {
        throw new JobExecutionException(ex.getMessage(), ex);
    }
}