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

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

Introduction

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

Prototype

void execute(CommandLine command, ExecuteResultHandler handler) throws ExecuteException, IOException;

Source Link

Document

Methods for starting asynchronous execution.

Usage

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 ww  w. ja va2s . com*/
 *
 * @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.zxy.commons.exec.CmdExecutor.java

/**
 * /*from  ww  w  .j  a  va2  s  .com*/
 * 
 * @param workHome workHome
 * @param command command
 * @return ???
 * @throws InterruptedException InterruptedException
 * @throws IOException IOException
 */
public static ExecutorResult exec(String workHome, String command) throws InterruptedException, IOException {
    CommandLine cmdLine = CommandLine.parse(PRE_CMD + command);
    Executor executor = new DefaultExecutor();
    executor.setWorkingDirectory(new File(workHome));

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream, errorStream);
    executor.setStreamHandler(streamHandler);

    int code = executor.execute(cmdLine, EnvironmentUtils.getProcEnvironment());
    String successMsg = outputStream.toString(ENCODING);
    String errorMsg = errorStream.toString(ENCODING);
    return new ExecutorResult(code, successMsg, errorMsg);
}

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);//from   w w  w.  j a va  2  s .co  m
    executor.setWatchdog(watchdog);
    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.netflix.spinnaker.clouddriver.jobs.local.JobExecutorLocal.java

private JobResult<String> execute(JobRequest jobRequest) throws IOException {
    ByteArrayOutputStream stdOut = new ByteArrayOutputStream();
    ByteArrayOutputStream stdErr = new ByteArrayOutputStream();

    Executor executor = buildExecutor(new PumpStreamHandler(stdOut, stdErr, jobRequest.getInputStream()));
    int exitValue = executor.execute(jobRequest.getCommandLine(), jobRequest.getEnvironment());

    return JobResult.<String>builder()
            .result(exitValue == 0 ? JobResult.Result.SUCCESS : JobResult.Result.FAILURE)
            .killed(executor.getWatchdog().killedProcess()).output(stdOut.toString()).error(stdErr.toString())
            .build();/*from  w  ww .j  av a 2 s . c  o  m*/
}

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

/**
 * Executing a predefined Rule//  w w  w  .  j a  v  a 2s . com
 * @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  a2s.c  om*/

        // 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;
    }
}

From source file:de.torstenwalter.maven.plugins.SQLPlusMojo.java

private void runScriptWithSqlPlus(File file, Map environment)
        throws MojoExecutionException, MojoFailureException {
    checkFileIsReadable(file);/*from   w ww . ja v  a2 s.co  m*/

    CommandLine commandLine = new CommandLine(sqlplus);
    // logon only once, without this sql*plus would prompt for
    // credentials if given ones are not correct
    commandLine.addArgument("-L");
    StringTokenizer stringTokenizer = new StringTokenizer(getConnectionIdentifier());
    while (stringTokenizer.hasMoreTokens()) {
        commandLine.addArgument(stringTokenizer.nextToken());
    }
    commandLine.addArgument("@" + file.getName());
    if (arguments != null) {
        for (Object argument : arguments) {
            if (argument == null) {
                throw new MojoExecutionException("Misconfigured argument, value is null. "
                        + "Set the argument to an empty value if this is the required behaviour.");
            } else {
                commandLine.addArgument(argument.toString());
            }
        }
    }

    getLog().info("Executing command line: " + obfuscateCredentials(commandLine.toString(), getCredentials()));

    Executor exec = new DefaultExecutor();
    exec.setWorkingDirectory(file.getParentFile());
    exec.setStreamHandler(new PumpStreamHandler(System.out, System.err));
    try {
        exec.execute(commandLine, environment);
    } catch (ExecuteException e) {
        throw new MojoExecutionException("program exited with exitCode: " + e.getExitValue());
    } catch (IOException e) {
        throw new MojoExecutionException("Command execution failed.", e);
    }
}

From source file:com.tascape.qa.th.android.comm.Adb.java

public ExecuteWatchdog adbAsync(final List<Object> arguments, long timeoutMillis) throws IOException {
    CommandLine cmdLine = new CommandLine(ADB);
    if (!this.serial.isEmpty()) {
        cmdLine.addArgument("-s");
        cmdLine.addArgument(serial);// w w  w. ja  va  2s  . com
    }
    arguments.forEach((arg) -> {
        cmdLine.addArgument(arg + "");
    });
    LOG.debug("[{} {}]", cmdLine.getExecutable(), StringUtils.join(cmdLine.getArguments(), " "));
    ExecuteWatchdog watchdog = new ExecuteWatchdog(timeoutMillis);
    Executor executor = new DefaultExecutor();
    executor.setWatchdog(watchdog);
    executor.setStreamHandler(new ESH());
    executor.execute(cmdLine, new DefaultExecuteResultHandler());

    return watchdog;
}

From source file:com.github.shyiko.hmp.AbstractHadoopMojo.java

protected void executeCommand(HadoopSettings hadoopSettings, String command, String automaticResponseOnPrompt,
        boolean bindProcessDestroyerToShutdownHook) throws IOException {
    if (getLog().isDebugEnabled()) {
        getLog().debug("Executing " + command);
    }/*  w w  w .  j a  v  a2  s  . c  o m*/
    Executor executor = new DefaultExecutor();
    executor.setStreamHandler(new ExecutionStreamHandler(quiet, automaticResponseOnPrompt));
    executor.setWorkingDirectory(hadoopSettings.getHomeDirectory());
    if (bindProcessDestroyerToShutdownHook) {
        executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
    }
    executor.execute(CommandLine.parse(command), hadoopSettings.getEnvironment());
}

From source file:ch.ivyteam.ivy.maven.engine.EngineControl.java

public Executor start() throws Exception {
    CommandLine startCmd = toEngineCommand(Command.start);
    context.log.info("Start Axon.ivy Engine in folder: " + context.engineDirectory);

    Executor executor = createEngineExecutor();
    executor.setStreamHandler(createEngineLogStreamForwarder(logLine -> findStartEngineUrl(logLine)));
    executor.setWatchdog(new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT));
    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
    executor.execute(startCmd, asynchExecutionHandler());
    waitForEngineStart(executor);//from ww  w. j ava 2 s .  com
    return executor;
}