Example usage for org.apache.commons.exec DefaultExecutor DefaultExecutor

List of usage examples for org.apache.commons.exec DefaultExecutor DefaultExecutor

Introduction

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

Prototype

public DefaultExecutor() 

Source Link

Document

Default constructor creating a default PumpStreamHandler and sets the working directory of the subprocess to the current working directory.

Usage

From source file:com.github.badamowicz.maven.ojdeploy.plugin.executor.OjdeployExecutor.java

/**
 * Actually execute the ojdeploy command which has been prepared before.
 * //from   w w w  . ja va  2  s.  c om
 * @throws IOException if execution of external process failed.
 */
private void exec() throws IOException {

    FileOutputStream fos = null;
    PumpStreamHandler pStreamHandler = null;
    DefaultExecutor executor = null;
    int exitVal = -1;

    LOG.info("Start executing ojdeploy now with command:");
    LOG.info(getCmdLine());
    fos = new FileOutputStream(new File(getProps().getProperty("ojdeploy.build.log.file")));
    pStreamHandler = new PumpStreamHandler(fos);
    executor = new DefaultExecutor();
    executor.setStreamHandler(pStreamHandler);
    executor.setExitValue(Integer.valueOf(getProps().getProperty("exit.value")));
    exitVal = executor.execute(getCmdLine());
    fos.flush();
    fos.close();
    LOG.info("Finished executing ojdeploy with exit value: " + exitVal);
}

From source file:com.github.zeroxff.executor.ExtendedExecutor.java

public ExecuteResult execute() throws ExtendedExecuteException {
    this.clearOut();
    if (this.commandLine == null) {
        throw new ExtendedExecuteException("CommandLine cannot be null", Executor.INVALID_EXITVALUE);
    }/*from w w w .java  2  s .c o  m*/
    if (this.commandLine.length == 0) {
        throw new ExtendedExecuteException("CommandLine cannot be empty", Executor.INVALID_EXITVALUE);
    }
    if (this.maxExecutiontime != ExecuteWatchdog.INFINITE_TIMEOUT && this.maxExecutiontime < 1) {
        throw new ExtendedExecuteException("Max execution time must not be less than 1",
                Executor.INVALID_EXITVALUE);
    }

    try {
        // load the command line as an array of strings
        CommandLine cmdLine = new CommandLine(this.commandLine[0]);
        for (int counter = 1; counter < commandLine.length; counter++) {
            cmdLine.addArgument(this.commandLine[counter], quoteCommandlineArgs);
        }

        // load the substitution map, if defined
        if (this.substitutionMap != null) {
            cmdLine.setSubstitutionMap(this.substitutionMap);
        }

        // load the watchdog timer, it can be set to infinite time
        ExecuteWatchdog watchdog = new ExecuteWatchdog(this.maxExecutiontime);
        ExtendedResultHandler resultHandler = new ExtendedResultHandler(watchdog);

        // inizialize outputstream processors.
        OutStreamProcessor outLinee = null;
        OutStreamProcessor errLinee = null;
        PumpStreamHandler streamHandler = null;
        if (outputFilter != null && outputFilter.size() > 0) {
            outLinee = new OutStreamProcessor(outputFilter);
        } else {
            outLinee = new OutStreamProcessor();
        }
        if (this.enableAllLinesOut) {
            outLinee.enableAllLines();
        }
        if (mergeOutStreams) {
            // Using Std out for the output/error stream
            streamHandler = new PumpStreamHandler(outLinee);
        } else {
            if (errorFilter != null && errorFilter.size() > 0) {
                errLinee = new OutStreamProcessor(errorFilter);
            } else {
                errLinee = new OutStreamProcessor();
            }
            if (enableAllLinesErr) {
                errLinee.enableAllLines();
            }
            // Using Std out for the output/error stream
            streamHandler = new PumpStreamHandler(outLinee, errLinee);
        }
        DefaultExecutor executor = new DefaultExecutor();
        // set the working directory...
        // if the working directory doesn't exists, it can crash the
        // executor.
        if (workingDirecory != null) {
            executor.setWorkingDirectory(workingDirecory);
        }

        // set the accepted exit values for the command line
        // default is '0'.
        if (okExitValues != null && okExitValues.length > 0) {
            executor.setExitValues(okExitValues);
        }

        executor.setWatchdog(watchdog);
        executor.setStreamHandler(streamHandler);

        try {
            executor.execute(cmdLine, resultHandler);
            resultHandler.waitFor();
            returnCode = resultHandler.getExitValue();
            exitMode = resultHandler.getExitMode();
            switch (exitMode) {
            case ERROR_IN_EXECUTION:
                this.message = resultHandler.getException().getMessage();
                break;
            default:
                break;
            }
        } catch (ExecuteException e) {
            exitMode = ExecuteResult.EXCEPTION;
            exception = e;
            this.message = e.getMessage();
        } catch (IOException e) {
            exitMode = ExecuteResult.EXCEPTION;
            exception = e;
            this.message = e.getMessage();
        } catch (InterruptedException e) {
            exitMode = ExecuteResult.EXCEPTION;
            exception = e;
            this.message = e.getMessage();
        }

        //

        if (outLinee != null) {
            outputLines = outLinee.getLines();
            allOutputLines = outLinee.getAllLines();
        }
        if (errLinee != null) {
            errorLines = errLinee.getLines();
            allErrorLines = errLinee.getAllLines();
        }

        this.closeStreams(outLinee, errLinee);
    } catch (Exception e) {
        throw new ExtendedExecuteException(e.getMessage(), Executor.INVALID_EXITVALUE, e);
    }

    return exitMode;
}

From source file:de.akquinet.innovation.play.maven.Play2PackageMojo.java

private void packageDistribution() throws MojoExecutionException {
    String line = getPlay2().getAbsolutePath();

    CommandLine cmdLine = CommandLine.parse(line);
    cmdLine.addArgument("dist");
    DefaultExecutor executor = new DefaultExecutor();

    if (timeout > 0) {
        ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
        executor.setWatchdog(watchdog);/*from   w  w w.  j  a v  a2  s .com*/
    }

    executor.setWorkingDirectory(project.getBasedir());
    executor.setExitValue(0);
    try {
        executor.execute(cmdLine, getEnvironment());
    } catch (IOException e) {
        throw new MojoExecutionException("Error during distribution creation", e);
    }
}

From source file:com.walmart.gatling.commons.ScriptExecutor.java

private Object runJob(Object message) {
    Master.Job job = (Master.Job) message;
    TaskEvent taskEvent = (TaskEvent) job.taskEvent;

    CommandLine cmdLine = new CommandLine(agentConfig.getJob().getCommand());
    log.info("Verified Script worker received task: {}", message);
    Map<String, Object> map = new HashMap<>();

    if (StringUtils.isNotEmpty(agentConfig.getJob().getMainClass()))
        cmdLine.addArgument(agentConfig.getJob().getCpOrJar());

    map.put("path", new File(agentConfig.getJob().getJobArtifact(taskEvent.getJobName())));
    cmdLine.addArgument("${path}");

    if (!StringUtils.isEmpty(agentConfig.getJob().getMainClass())) {
        cmdLine.addArgument(agentConfig.getJob().getMainClass());
    }/*  w  ww. j a  va  2s  . co  m*/
    //parameters come from the task event
    for (Pair<String, String> pair : taskEvent.getParameters()) {
        cmdLine.addArgument(pair.getValue());
    }
    cmdLine.addArgument("-rf").addArgument(agentConfig.getJob().getResultPath(job.roleId, job.jobId));

    cmdLine.setSubstitutionMap(map);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValues(agentConfig.getJob().getExitValues());
    ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
    executor.setWatchdog(watchdog);
    executor.setWorkingDirectory(new File(agentConfig.getJob().getPath()));
    FileOutputStream outFile = null;
    FileOutputStream errorFile = null;
    String outPath = "", errPath = "";
    try {
        outPath = agentConfig.getJob().getOutPath(taskEvent.getJobName(), job.jobId);
        errPath = agentConfig.getJob().getErrorPath(taskEvent.getJobName(), job.jobId);
        //create the std and err files
        outFile = FileUtils.openOutputStream(new File(outPath));
        errorFile = FileUtils.openOutputStream(new File(errPath));

        PumpStreamHandler psh = new PumpStreamHandler(new ExecLogHandler(outFile),
                new ExecLogHandler(errorFile));
        executor.setStreamHandler(psh);
        log.info("command: {}", cmdLine);
        int exitResult = executor.execute(cmdLine);
        //executor.getWatchdog().destroyProcess().
        Worker.Result result = new Worker.Result(exitResult, agentConfig.getUrl(errPath),
                agentConfig.getUrl(outPath), null, job);
        log.info("Exit code: {}", exitResult);
        if (executor.isFailure(exitResult) || exitResult == 1) {
            log.info("Script Executor Failed, job: " + job.jobId);
            //getSender().tell(new Worker.WorkFailed(result), getSelf());
            return new Worker.WorkFailed(result);
        } else {
            result = new Worker.Result(exitResult, agentConfig.getUrl(errPath), agentConfig.getUrl(outPath),
                    agentConfig.getUrl(getMetricsPath(job)), job);
            log.info("Script Executor Completed, job: " + result);
            //getSender().tell(new Worker.WorkComplete(result), getSelf());
            return new Worker.WorkComplete(result);
        }

    } catch (IOException e) {
        log.error(e.toString());
        Worker.Result result = new Worker.Result(-1, agentConfig.getUrl(errPath), agentConfig.getUrl(outPath),
                null, job);
        log.info("Executor Encountered run time exception, result: " + result.toString());
        //getSender().tell(new Worker.WorkFailed(result), getSelf());
        return new Worker.WorkFailed(result);
    } finally {
        IOUtils.closeQuietly(outFile);
        IOUtils.closeQuietly(errorFile);
    }
}

From source file:io.vertx.config.vault.utils.VaultProcess.java

public void runAndProcess(String command, Consumer<String> processor) {
    String cli = executable.getAbsolutePath() + " " + command;
    System.out.println(">> " + cli);
    CommandLine parse = CommandLine.parse(cli);
    DefaultExecutor executor = new DefaultExecutor();
    PumpStreamHandler pump = new PumpStreamHandler(new VaultOutputStream().addExtractor(processor), System.err);

    ExecuteWatchdog watchDog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
    executor.setWatchdog(watchDog);//w w w.  j a  va2s .c o  m
    executor.setStreamHandler(pump);
    try {
        executor.execute(parse);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

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

public List<String> adb(final List<Object> arguments) throws IOException {
    CommandLine cmdLine = new CommandLine(ADB);
    if (!this.serial.isEmpty()) {
        cmdLine.addArgument("-s");
        cmdLine.addArgument(serial);//from  ww  w.j  av a 2  s  .  co m
    }
    arguments.forEach((arg) -> {
        cmdLine.addArgument(arg + "");
    });
    LOG.debug("[{} {}]", cmdLine.getExecutable(), StringUtils.join(cmdLine.getArguments(), " "));
    List<String> output = new ArrayList<>();
    Executor executor = new DefaultExecutor();
    executor.setStreamHandler(new ESH(output));
    if (executor.execute(cmdLine) != 0) {
        throw new IOException(cmdLine + " failed");
    }
    return output;
}

From source file:net.openbyte.gui.WorkFrame.java

private void menuItem2ActionPerformed(ActionEvent e) {
    if (this.api == ModificationAPI.BUKKIT) {
        showBukkitIncompatibleFeature();
        return;/*from   w ww  . j av a 2 s  .c  om*/
    }
    System.out.println("Starting server...");
    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
        @Override
        protected Void doInBackground() throws Exception {
            GradleConnector.newConnector().forProjectDirectory(workDirectory).connect().newBuild()
                    .forTasks("runServer").run();
            return null;
        }
    };
    if (this.api == ModificationAPI.MCP) {
        worker = new SwingWorker<Void, Void>() {
            @Override
            protected Void doInBackground() throws Exception {
                if (System.getProperty("os.name").startsWith("Windows")) {
                    Runtime.getRuntime().exec("cmd /c startserver.bat", null, workDirectory);
                    return null;
                }
                try {
                    CommandLine startServer = CommandLine.parse("python "
                            + new File(new File(workDirectory, "runtime"), "startserver.py").getAbsolutePath()
                            + " $@");
                    CommandLine authServer = CommandLine.parse("chmod 755 "
                            + new File(new File(workDirectory, "runtime"), "startserver.py").getAbsolutePath());
                    DefaultExecutor executor = new DefaultExecutor();
                    executor.setWorkingDirectory(workDirectory);
                    executor.execute(authServer);
                    executor.execute(startServer);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        };
    }
    worker.execute();
}

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);//from  w w  w  .j  av  a 2  s  .  c  om
    }
    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:net.hasor.maven.ExecMojo.java

/**
 * priority in the execute method will be to use System properties arguments over the pom specification.
 *
 * @throws MojoExecutionException if a failure happens
 *//*from w  ww  .  j a  v a  2 s. c om*/
public void execute() throws MojoExecutionException {
    if (isSkip()) {
        getLog().info("skipping execute as per configuraion");
        return;
    }
    if (basedir == null) {
        throw new IllegalStateException("basedir is null. Should not be possible.");
    }
    try {
        handleWorkingDirectory();
        String argsProp = getSystemProperty("exec.args");
        List<String> commandArguments = new ArrayList<String>();
        if (hasCommandlineArgs()) {
            handleCommandLineArgs(commandArguments);
        } else if (!StringUtils.isEmpty(argsProp)) {
            handleSystemPropertyArguments(argsProp, commandArguments);
        } else {
            if (arguments != null) {
                handleArguments(commandArguments);
            }
        }
        Map<String, String> enviro = handleSystemEnvVariables();
        CommandLine commandLine = getExecutablePath(enviro, workingDirectory);
        String[] args = commandArguments.toArray(new String[commandArguments.size()]);
        commandLine.addArguments(args, false);
        Executor exec = new DefaultExecutor();
        exec.setWorkingDirectory(workingDirectory);
        fillSuccessCodes(exec);
        getLog().debug("Executing command line: " + commandLine);
        try {
            int resultCode;
            if (outputFile != null) {
                if (!outputFile.getParentFile().exists() && !outputFile.getParentFile().mkdirs()) {
                    getLog().warn(
                            "Could not create non existing parent directories for log file: " + outputFile);
                }
                FileOutputStream outputStream = null;
                try {
                    outputStream = new FileOutputStream(outputFile);
                    resultCode = executeCommandLine(exec, commandLine, enviro, outputStream);
                } finally {
                    IOUtil.close(outputStream);
                }
            } else {
                resultCode = executeCommandLine(exec, commandLine, enviro, System.out, System.err);
            }
            if (isResultCodeAFailure(resultCode)) {
                throw new MojoExecutionException(
                        "Result of " + commandLine + " execution is: '" + resultCode + "'.");
            }
        } catch (ExecuteException e) {
            throw new MojoExecutionException("Command execution failed.", e);
        } catch (IOException e) {
            throw new MojoExecutionException("Command execution failed.", e);
        }
        registerSourceRoots();
    } catch (IOException e) {
        throw new MojoExecutionException("I/O Error", e);
    }
}

From source file:com.sohu.dc.jobkeeper.ActiveMasterManager.java

private void startPrepare() {
    String shellPath = ActiveMasterManager.class.getClassLoader().getResource("").getPath().replace("classes/",
            "");//from   www .j  a v  a  2  s .  c o  m
    DefaultExecutor executor = new DefaultExecutor();
    CommandLine cmd = new CommandLine(shellPath + "prepare.sh");
    try {
        executor.execute(cmd);
    } catch (ExecuteException e) {
        LOG.debug("prepare.sh exec faild \n" + e);
    } catch (IOException e) {
        LOG.debug("prepare.sh exec faild \n" + e);
    }

}