Example usage for org.apache.commons.exec ExecuteException getExitValue

List of usage examples for org.apache.commons.exec ExecuteException getExitValue

Introduction

In this page you can find the example usage for org.apache.commons.exec ExecuteException getExitValue.

Prototype

public int getExitValue() 

Source Link

Document

Gets the exit value returned by the failed process

Usage

From source file:org.kercoin.magrit.core.build.BuildTask.java

@Override
public BuildResult call() throws Exception {
    checkRequest();//from  w  w  w  . j a  v a  2 s  . c o m
    enforceCommitFromRequestInBuildRepository();

    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    PrintStream printOut = new PrintStream(stdout);

    BuildResult buildResult = new BuildResult(this.target.getU());
    try {
        buildResult.setStartDate(new Date());

        checkout(printOut);

        int exitCode = build(stdout, printOut);
        endOfTreatment(buildResult, exitCode, true);
        return buildResult;
    } catch (ExecuteException ex) {
        endOfTreatment(buildResult, ex.getExitValue(), false);
        return buildResult;
    } finally {
        buildResult.setLog(stdout.toByteArray());
        writeToRepository(buildResult);
    }
}

From source file:org.mail.bridge.FolderMonitor.java

public synchronized void runScriptAgainstReceivedFiles(List<File> inboxFiles) {
    if (config.getInboxScript().isEmpty() || Utils.isEmpty(inboxFiles))
        return;//www. ja v  a2 s  . co m
    LOG.debug("Run script '{}' against files {}", config.getInboxScript(), inboxFiles);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        CommandLine cmd = CommandLine.parse(config.getInboxScript());
        for (File file : inboxFiles)
            cmd.addArgument(file.getName(), true);
        DefaultExecutor executor = new DefaultExecutor();
        executor.setStreamHandler(new PumpStreamHandler(out));
        executor.setWatchdog(new ExecuteWatchdog(SCRIPT_TIMEOUT));
        Map<String, String> environment = EnvironmentUtils.getProcEnvironment();
        environment.putAll(config.asEnvironmentMap());
        executor.setWorkingDirectory(new File(System.getProperty("user.dir")));
        executor.execute(cmd, environment);
        LOG.info("Script '{}' successfully finished", config.getInboxScript());
        LOG.debug("Script output:\n{}", out.toString());
    } catch (ExecuteException e) {
        LOG.error(e.getMessage(), e);
        LOG.error("\nScript '{}' output:\n{}", config.getInboxScript(), out.toString());
        int c = config.getInboxScriptStopCode();
        if (c != 0 && c == e.getExitValue())
            postMessage(new Main.StopMessage(
                    String.format("Script '%s' exited with code %d that is configured as stop code",
                            config.getInboxScript(), c)));
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
        LOG.error("\nScript '{}' output:\n{}", config.getInboxScript(), out.toString());
    }
}

From source file:org.mule.test.infrastructure.process.Controller.java

protected int doExecution(DefaultExecutor executor, CommandLine commandLine, Map<Object, Object> env) {
    try {/*from  w  w w  . ja va  2s .  co m*/
        return executor.execute(commandLine, env);
    } catch (ExecuteException e) {
        return e.getExitValue();
    } catch (Exception e) {
        throw new MuleControllerException(
                "Error executing [" + commandLine.getExecutable() + " " + commandLine.getArguments() + "]", e);
    }
}

From source file:org.mule.tooling.jubula.cliexecutor.internal.DefaultCliExecutor.java

@Override
public void runAsync(final String commandString, final Callback callback, final String... params) {
    try {/*from  w  w  w  . ja v a  2  s  . c om*/
        final DefaultExecutor executor = new DefaultExecutor();
        final CommandLine command = CommandLine.parse(commandString);
        command.addArguments(params, true);
        executor.execute(command, new ExecuteResultHandler() {

            @Override
            public void onProcessFailed(final ExecuteException returnCode) {
                callback.failure(returnCode.getExitValue());
            }

            @Override
            public void onProcessComplete(final int returnCode) {
                callback.success(returnCode);
            }
        });
    } catch (final ExecuteException e) {
        throw new RuntimeException(e);
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.mybatis.generator.ext.api.MeldMergeShellCallback.java

public static boolean exec(String command) {
    CommandLine commandLine = CommandLine.parse(command);
    DefaultExecutor executor = new DefaultExecutor();
    int exitValue = DefaultExecutor.INVALID_EXITVALUE;
    ExecuteWatchdog watchdog = new ExecuteWatchdog(2000);
    executor.setWatchdog(watchdog);// w ww . ja  va2 s .c o m
    try {
        exitValue = executor.execute(commandLine);
    } catch (ExecuteException e) {
        exitValue = e.getExitValue();
    } catch (IOException e) {
        System.err.println(e.getMessage());
    }
    System.out.println("Exit :" + exitValue);
    return (exitValue == 0);
}

From source file:org.ng200.openolympus.cerberus.executors.OpenOlympusWatchdogExecutor.java

private static String callNativeId(boolean group) throws IOException {
    OpenOlympusWatchdogExecutor.ensureUserAndGroupExists();

    final CommandLine commandLine = new CommandLine("id");
    commandLine.addArgument(group ? "-g" : "-u");
    commandLine.addArgument("olympuswatchdogchild");

    final DefaultExecutor executor = new DefaultExecutor();

    final ByteArrayOutputStream out = new ByteArrayOutputStream();

    executor.setStreamHandler(new PumpStreamHandler(out));

    executor.setWatchdog(new ExecuteWatchdog(1000));

    try {/* w w w.  j a  va 2 s. c o m*/
        executor.execute(commandLine);

        return out.toString(StandardCharsets.UTF_8.name());
    } catch (final ExecuteException e) {
        throw new ExecuteException(
                "Couldn't find user/group id of the olympuswatchdogchild user/group: does it even exist?",
                e.getExitValue(), e);
    }
}

From source file:org.ng200.openolympus.cerberus.executors.OpenOlympusWatchdogExecutor.java

private static void ensureUserAndGroupExists() throws IOException {
    if (alreadyEnsuredUserExists)
        return;//w w  w  .  ja  v  a2 s  .c om
    final CommandLine commandLine = new CommandLine("sudo");
    commandLine.addArgument("useradd");
    commandLine.addArgument("-U");
    commandLine.addArgument("-M"); // Don't create home directory
    commandLine.addArgument("-s");
    commandLine.addArgument("/bin/false");
    commandLine.addArgument("olympuswatchdogchild");

    final DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValues(new int[] { 0, /* Added user */
            9
            /* User already exists */
    });

    executor.setWatchdog(new ExecuteWatchdog(1000));

    try {
        executor.execute(commandLine);
        alreadyEnsuredUserExists = true;
    } catch (final ExecuteException e) {
        throw new ExecuteException(
                "Couldn't find user/group id of the olympuswatchdogchild user/group: does it even exist?",
                e.getExitValue(), e);
    }
}

From source file:org.openflamingo.core.cmd.TailExecuteResultHandler.java

/**
 * @see org.apache.commons.exec.ExecuteResultHandler#onProcessFailed(org.apache.commons.exec.ExecuteException)
 *//* w w w.  ja va 2s .  c o  m*/
public void onProcessFailed(ExecuteException e) {
    this.exitValue = e.getExitValue();
    this.exception = e;
    this.hasResult = true;
}

From source file:org.rhq.server.control.ControlCommand.java

protected boolean isUnixPidRunning(String pid) {

    Executor executor = new DefaultExecutor();
    executor.setWorkingDirectory(getBinDir());
    PumpStreamHandler streamHandler = new PumpStreamHandler(createNullOutputStream(), createNullOutputStream());
    executor.setStreamHandler(streamHandler);
    org.apache.commons.exec.CommandLine commandLine;
    commandLine = new org.apache.commons.exec.CommandLine("kill").addArgument("-0").addArgument(pid);

    boolean isRunning = true; // assume it is running
    try {//w  w  w .  ja va  2  s  .co m
        int code = executor.execute(commandLine);
        if (code != 0) {
            isRunning = false;
        }
    } catch (ExecuteException ee) {
        log.debug("kill -0 for pid [" + pid + "] threw exception with exit value [" + ee.getExitValue() + "]");
        if (ee.getExitValue() == 1) {
            // return code 1 means process does not exist
            isRunning = false;
        }
    } catch (IOException e) {
        log.error("Checking for running process failed. Will assume it is running. Error: " + e.getMessage());
    }

    log.debug("unix pid [" + pid + "] " + ((isRunning) ? "is" : "is NOT") + " running");
    return isRunning;
}

From source file:org.waarp.gateway.kernel.exec.ExecuteExecutor.java

public void run() throws Reply421Exception {
    // Check if the execution will be done through LocalExec daemon
    if (AbstractExecutor.useLocalExec) {
        LocalExecClient localExecClient = new LocalExecClient();
        if (localExecClient.connect()) {
            localExecClient.runOneCommand(arg, delay, futureCompletion);
            localExecClient.disconnect();
            return;
        } // else continue
    }/*from   w w w  . j  av  a2 s .  c  o  m*/
    // Execution is done internally
    File exec = new File(args[0]);
    if (exec.isAbsolute()) {
        if (!exec.canExecute()) {
            logger.error("Exec command is not executable: " + args[0]);
            throw new Reply421Exception("Pre Exec command is not executable");
        }
    }
    CommandLine commandLine = new CommandLine(args[0]);
    for (int i = 1; i < args.length; i++) {
        commandLine.addArgument(args[i]);
    }
    DefaultExecutor defaultExecutor = new DefaultExecutor();
    PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(null, null);
    defaultExecutor.setStreamHandler(pumpStreamHandler);
    int[] correctValues = { 0, 1 };
    defaultExecutor.setExitValues(correctValues);
    ExecuteWatchdog watchdog = null;
    if (delay > 0) {
        watchdog = new ExecuteWatchdog(delay);
        defaultExecutor.setWatchdog(watchdog);
    }
    int status = -1;
    try {
        status = defaultExecutor.execute(commandLine);
    } catch (ExecuteException e) {
        if (e.getExitValue() == -559038737) {
            // Cannot run immediately so retry once
            try {
                Thread.sleep(10);
            } catch (InterruptedException e1) {
            }
            try {
                status = defaultExecutor.execute(commandLine);
            } catch (ExecuteException e2) {
                try {
                    pumpStreamHandler.stop();
                } catch (IOException e1) {
                }
                logger.error("System Exception: " + e.getMessage() + "\n    Exec cannot execute command "
                        + commandLine.toString());
                throw new Reply421Exception("Cannot execute Pre command");
            } catch (IOException e2) {
                try {
                    pumpStreamHandler.stop();
                } catch (IOException e1) {
                }
                logger.error(
                        "Exception: " + e.getMessage() + "\n    Exec in error with " + commandLine.toString());
                throw new Reply421Exception("Cannot execute Pre command");
            }
            logger.info("System Exception: " + e.getMessage() + " but finally get the command executed "
                    + commandLine.toString());
        } else {
            try {
                pumpStreamHandler.stop();
            } catch (IOException e1) {
            }
            logger.error("Exception: " + e.getMessage() + "\n    Exec in error with " + commandLine.toString());
            throw new Reply421Exception("Cannot execute Pre command");
        }
    } catch (IOException e) {
        try {
            pumpStreamHandler.stop();
        } catch (IOException e1) {
        }
        logger.error("Exception: " + e.getMessage() + "\n    Exec in error with " + commandLine.toString());
        throw new Reply421Exception("Cannot execute Pre command");
    }
    try {
        pumpStreamHandler.stop();
    } catch (IOException e1) {
    }
    if (watchdog != null && watchdog.killedProcess()) {
        // kill by the watchdoc (time out)
        logger.error("Exec is in Time Out");
        status = -1;
    }
    if (status == 0) {
        futureCompletion.setSuccess();
        logger.info("Exec OK with {}", commandLine);
    } else if (status == 1) {
        logger.warn("Exec in warning with {}", commandLine);
        futureCompletion.setSuccess();
    } else {
        logger.debug("Status: " + status + (status == -1 ? " Tiemout" : "") + " Exec in error with "
                + commandLine.toString());
        throw new Reply421Exception("Pre command executed in error");
    }
}