Example usage for org.apache.commons.exec Executor setExitValue

List of usage examples for org.apache.commons.exec Executor setExitValue

Introduction

In this page you can find the example usage for org.apache.commons.exec Executor setExitValue.

Prototype

void setExitValue(final int value);

Source Link

Document

Define the exitValue of the process to be considered successful.

Usage

From source file:com.jivesoftware.os.jive.utils.shell.utils.Invoke.java

public static int invoke(File home, String[] command, final InputStream writeToProcess,
        final ConcurrentLinkedQueue<String> response) throws Exception {
    Executor executor = new DefaultExecutor();
    executor.setExitValue(0);
    if (home != null) {
        executor.setWorkingDirectory(home);
    }//from ww  w . j a  va  2 s  .  c  om

    //give all the processes 120s to return that they started successfully
    ExecuteWatchdog watchdog = new ExecuteWatchdog(120000);
    executor.setWatchdog(watchdog);

    LogOutputStream outputStream = new LogOutputStream(20000) {
        @Override
        protected void processLine(final String line, final int level) {
            response.add(line);
        }
    };

    LogOutputStream errorStream = new LogOutputStream(40000) {
        @Override
        protected void processLine(final String line, final int level) {
            response.add(line);
        }
    };

    PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream, errorStream, writeToProcess);
    executor.setStreamHandler(pumpStreamHandler);
    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());

    CommandLine commandLine = new CommandLine(command[0]);
    for (int i = 1; i < command.length; i++) {
        commandLine.addArgument(command[i]);
    }
    try {
        //executor.execute(commandLine, handler);
        return executor.execute(commandLine);
        //handler.waitFor(20000);
    } catch (Exception x) {
        x.printStackTrace();
        return 1;
    }
}

From source file:eu.forgestore.ws.util.Utils.java

public static int executeSystemCommand(String cmdStr) {

    CommandLine cmdLine = CommandLine.parse(cmdStr);
    final Executor executor = new DefaultExecutor();
    // create the executor and consider the exitValue '0' as success
    executor.setExitValue(0);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(out);
    executor.setStreamHandler(streamHandler);

    int exitValue = -1;
    try {/*from  w  w w  . j  a  va  2s  .  c  om*/
        exitValue = executor.execute(cmdLine);

    } catch (ExecuteException e) {

        e.printStackTrace();
    } catch (IOException e) {

        e.printStackTrace();
    }

    return exitValue;

}

From source file:com.github.genium_framework.appium.support.command.CommandManager.java

/**
 * Execute a command on the operating system using Apache Commons Exec. This
 * function runs asynchronously and dumps both stderr and stdout streams to
 * a temp file.//from w w w .  j  a  va2s. co  m
 *
 * @param commandLine The command to be executed.
 * @param outputStreamHandler An output stream to dump the process stderr
 * and stdout to it.
 */
public static void executeCommandUsingApacheExec(CommandLine commandLine, OutputStream outputStreamHandler) {
    try {
        DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStreamHandler);

        Executor process = new DefaultExecutor();
        process.setExitValue(0);
        process.setStreamHandler(streamHandler);
        process.execute(commandLine, resultHandler);
    } catch (Exception ex) {
        LOGGER.log(Level.SEVERE, "An exception was thrown.", ex);
    }
}

From source file:com.bptselenium.jenkins.BPTSeleniumJenkins.RunCommand.java

public static void runCommand(String command, TaskListener listener, Run<?, ?> build) {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    CommandLine cmdLine = CommandLine.parse(command);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
    Executor executor = new DefaultExecutor();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    executor.setStreamHandler(streamHandler);
    executor.setExitValue(10);
    executor.setWatchdog(watchdog);/*w  ww  . j  av  a 2 s.  c o m*/
    try {
        executor.execute(cmdLine);
    } catch (ExecuteException ee) {
        //getting a non-standard execution value, set build result to unstable
        Result result = Result.UNSTABLE;
        if (build.getResult() == null) {
            build.setResult(result);
        } else if (build.getResult().isBetterThan(result)) {
            build.setResult(result.combine(build.getResult()));
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        listener.getLogger().println(outputStream.toString());
    }
}

From source file:com.muk.ext.process.ProcessExecutor.java

public int runCommandLine(CommandLine cmdLine, long maxWaitTimeInMillis) throws IOException {
    ExecuteWatchdog processWatchDog = new ExecuteWatchdog(maxWaitTimeInMillis);
    Executor executor = new DefaultExecutor();

    executor.setExitValue(0);
    executor.setWatchdog(processWatchDog);

    int result = 1;
    result = executor.execute(cmdLine);/*from  w  w  w  .  j ava2  s.co m*/

    return result;
}

From source file:edu.emory.cci.aiw.neo4jetl.Neo4jHome.java

private void controlServer(String command) throws IOException, InterruptedException, CommandFailedException {
    LOGGER.debug("Executing neo4j command {}...", command);
    CommandLine serverControlCommand = new CommandLine(new File(this.home, SERVER_CONTROL_COMMAND));
    serverControlCommand.addArgument("${command}");
    Map<String, String> map = new HashMap<>();
    map.put("command", command);
    serverControlCommand.setSubstitutionMap(map);

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000);
    Executor executor = new DefaultExecutor();
    executor.setExitValue(1);
    executor.setWatchdog(watchdog);// www  .  jav  a2s.c  o  m
    executor.execute(serverControlCommand, resultHandler);
    LOGGER.debug("Neo4j command {} is completed, checking exit value...", command);
    resultHandler.waitFor();
    int exitValue = resultHandler.getExitValue();
    if (exitValue != 0) {
        ExecuteException exception = resultHandler.getException();
        throw new CommandFailedException(exitValue, "Neo4j command '" + command + "' failed", exception);
    }
    LOGGER.debug("Neo4j command {} was successful", command);
}

From source file:com.taobao.ad.es.common.job.executor.ShellHttpJobExecutor.java

@Override
public JobResult execute(JobData jobData) throws IOException {
    JobResult jobResult = JobResult.succcessResult();
    CommandLine cmdLine = CommandLine.parse(jobData.getData().get(JobData.JOBDATA_DATA_JOBCOMMAND));
    Executor executor = new DefaultExecutor();
    ExecuteWatchdog watchdog = new ExecuteWatchdog(1200000);
    executor.setExitValue(0);
    executor.setWatchdog(watchdog);//from   w w  w.  j  av a  2 s .c om
    int exitValue = -1;
    try {
        exitValue = executor.execute(cmdLine);
    } catch (ExecuteException e) {
        exitValue = e.getExitValue();
    }
    if (exitValue != 0) {
        jobResult = JobResult.errorResult(JobResult.RESULTCODE_OTHER_ERR,
                "Shell?");
        jobResult.setResultCode(exitValue);
        return jobResult;
    }
    jobResult.setResultCode(exitValue);
    return jobResult;
}

From source file:com.github.mjeanroy.maven.plugins.node.commands.CommandExecutor.java

/**
 * Execute command line and return the result status.
 *
 * @param workingDirectory Working directory (i.e where the command line is executed).
 * @param command Command, containing executable path with arguments.
 * @param logger Logger to use to log command output.
 * @return Command result object./*from  w w w  .j ava  2s .c om*/
 */
public CommandResult execute(File workingDirectory, Command command, Log logger) {
    CommandLine commandLine = new CommandLine(command.getExecutable());
    for (String argument : command.getArguments()) {
        commandLine.addArgument(argument);
    }

    try {
        Executor executor = new DefaultExecutor();
        executor.setWorkingDirectory(workingDirectory);
        executor.setExitValue(0);

        // Define custom output stream
        LogStreamHandler stream = new LogStreamHandler(logger);
        PumpStreamHandler handler = new PumpStreamHandler(stream);
        executor.setStreamHandler(handler);

        int status = executor.execute(commandLine);
        return new CommandResult(status);
    } catch (ExecuteException ex) {
        return new CommandResult(ex.getExitValue());
    } catch (IOException ex) {
        throw new CommandException(ex);
    }
}

From source file:de.simu.decomap.messaging.resultprocessor.impl.helper.RulesExecutor.java

/**
 * Executing a predefined Rule//from  w ww . jav  a  2  s.  co m
 * @param ruleType RuleType
 * @param arg args for Rule
 * @return Success
 */
public boolean executePredefinedRule(byte ruleType, String arg) {
    logger.info("[IPTABLES] -> executing predefined command...");

    // use apache's commons-exec for executing command!
    CommandLine cmdLine = new CommandLine(command);

    // get the predefined rule-parameters
    String[] ruleParams = Rules.getPredefindedRuleParameters(ruleType, arg);

    if (ruleParams != null) {

        // add rule-parameters to CommanLine-Object
        for (int i = 0; i < ruleParams.length; i++) {
            cmdLine.addArgument(ruleParams[i]);
        }

        // execute command
        DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
        ExecuteWatchdog watchdog = new ExecuteWatchdog(mTimeout);
        Executor executor = new DefaultExecutor();
        executor.setExitValue(1);
        executor.setWatchdog(watchdog);
        try {
            executor.execute(cmdLine, resultHandler);
        } catch (ExecuteException e) {
            logger.warn("[IPTABLES] -> error while executing predefined command: execute-exception occured!");
            return false;
        } catch (IOException e) {
            logger.warn("[IPTABLES] -> error while executing predefined command: io-exception occured!");
            return false;
        }

        try {
            // some time later the result handler callback was invoked so we
            // can safely request the exit value
            resultHandler.waitFor();
            int exitCode = resultHandler.getExitValue();
            logger.info("[IPTABLES] -> command " + ruleType + " executed, exit-code is: " + exitCode);

            switch (exitCode) {
            case EXIT_CODE_SUCCESS:
                return true;
            case EXIT_CODE_ERROR:
                return false;
            default:
                return false;
            }

        } catch (InterruptedException e) {
            logger.warn(
                    "[IPTABLES] -> error while executing predefined command: interrupted-exception occured!");
            return false;
        }

    } else {
        logger.warn("[IPTABLES] -> error while excuting predefined command: rule-parameters-list is null!");
        return false;
    }
}

From source file:de.esukom.decoit.ifmapclient.iptables.RulesExecutor.java

public boolean executePredefinedRule(byte ruleType, String[] arg) {
    IfMapClient.LOGGER.info("[IPTABLES] -> executing predefined command...");

    // use apache's commons-exec for executing command!
    CommandLine cmdLine = new CommandLine(command);

    // get the predefined rule-parameters
    String[] ruleParams = Rules.getPredefindedRuleParameters(ruleType, arg);

    if (ruleParams != null) {

        // add rule-parameters to CommanLine-Object
        for (int i = 0; i < ruleParams.length; i++) {
            cmdLine.addArgument(ruleParams[i]);
        }/*from w w  w.j  a  v  a2  s .  c o m*/

        // execute command
        DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
        ExecuteWatchdog watchdog = new ExecuteWatchdog(mTimeout);
        Executor executor = new DefaultExecutor();
        executor.setExitValue(1);
        executor.setWatchdog(watchdog);
        try {
            executor.execute(cmdLine, resultHandler);
        } catch (ExecuteException e) {
            IfMapClient.LOGGER.warning(
                    "[IPTABLES] -> error while executing predefined command: execute-exception occured!");
            return false;
        } catch (IOException e) {
            IfMapClient.LOGGER
                    .warning("[IPTABLES] -> error while executing predefined command: io-exception occured!");
            return false;
        }

        try {
            // some time later the result handler callback was invoked so we
            // can safely request the exit value
            resultHandler.waitFor();
            int exitCode = resultHandler.getExitValue();
            IfMapClient.LOGGER.warning("[IPTABLES] -> command executed, exit-code is: " + exitCode);

            switch (exitCode) {
            case EXIT_CODE_SUCCESS:
                return true;
            case EXIT_CODE_ERROR:
                return false;
            default:
                return false;
            }

        } catch (InterruptedException e) {
            IfMapClient.LOGGER.warning(
                    "[IPTABLES] -> error while executing predefined command: interrupted-exception occured!");
            return false;
        }

    } else {
        IfMapClient.LOGGER.warning(
                "[IPTABLES] -> error while excuting predefined command: rule-parameters-list is null!");
        return false;
    }
}