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:edu.buffalo.fusim.ReadSimulator.java

public void run(String artBinPath, File fusionFile, String outputPrefix, int readLength, int meanFragSize,
        int readCoverage, boolean pairedEnd) {
    // Example art call:
    //   art_illumina -i fusion.txt -o testsim -l 75 -f 10 -p -m 400 -s 10 
    CommandLine cmdLine = new CommandLine(artBinPath);

    // the filename of input DNA reference
    cmdLine.addArgument("-i");
    cmdLine.addArgument("${file}");
    // the prefix of output files
    cmdLine.addArgument("-o");
    cmdLine.addArgument("${outputPrefix}");
    // the length of reads to be simulated
    cmdLine.addArgument("-l");
    cmdLine.addArgument("" + readLength);
    // the fold of read coverage to be simulated
    cmdLine.addArgument("-f");
    cmdLine.addArgument("" + readCoverage);
    if (pairedEnd) {
        // indicate a paired-end read simulation
        cmdLine.addArgument("-p");
        // the mean size of DNA fragments for paired-end simulations
        cmdLine.addArgument("-m");
        cmdLine.addArgument("" + meanFragSize);
        // the standard deviation of DNA fragment size for paired-end simulations.
        cmdLine.addArgument("-s");
        cmdLine.addArgument("10");
    }//from  ww  w  . j  a  v  a2s.c  om
    // quite - turn off end of run summary
    cmdLine.addArgument("-q");

    Map map = new HashMap();
    map.put("file", fusionFile);
    map.put("outputPrefix", outputPrefix);
    cmdLine.setSubstitutionMap(map);

    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);
    // Timeout after 5 minutes
    ExecuteWatchdog watchdog = new ExecuteWatchdog(300000);
    executor.setWatchdog(watchdog);

    try {
        int exitValue = executor.execute(cmdLine);
    } catch (Exception e) {
        logger.fatal("Failed to execute ART for simulating Illumina reads: " + e.getMessage());
    }
}

From source file:it.sonarlint.cli.tools.CommandExecutor.java

public int execute(String[] args, @Nullable Path workingDir, Map<String, String> addEnv) throws IOException {
    if (!Files.isExecutable(file)) {
        Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
        perms.add(PosixFilePermission.OWNER_READ);
        perms.add(PosixFilePermission.OWNER_EXECUTE);
        Files.setPosixFilePermissions(file, perms);
    }/* w w w. jav  a2s .c o m*/

    ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT);
    CommandLine cmd = new CommandLine(file.toFile());
    cmd.addArguments(args);
    DefaultExecutor exec = new DefaultExecutor();
    exec.setWatchdog(watchdog);
    exec.setStreamHandler(createStreamHandler());
    exec.setExitValues(null);
    if (workingDir != null) {
        exec.setWorkingDirectory(workingDir.toFile());
    }
    in.close();
    LOG.info("Executing: {}", cmd.toString());
    Map<String, String> env = new HashMap<>(System.getenv());
    env.putAll(addEnv);
    return exec.execute(cmd, env);
}

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

/**
 * Executing a predefined Rule//from www.j av 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:com.sonar.scanner.api.it.tools.CommandExecutor.java

public int execute(String[] args, Map<String, String> env, @Nullable Path workingDir) throws IOException {
    if (!Files.isExecutable(file)) {
        Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
        perms.add(PosixFilePermission.OWNER_READ);
        perms.add(PosixFilePermission.OWNER_EXECUTE);
        Files.setPosixFilePermissions(file, perms);
    }//  ww w .ja v  a 2  s .c om

    watchdog = new ExecuteWatchdog(TIMEOUT);
    CommandLine cmd = new CommandLine(file.toFile());
    cmd.addArguments(args, false);
    DefaultExecutor exec = new DefaultExecutor();
    exec.setWatchdog(watchdog);
    exec.setStreamHandler(createStreamHandler());
    exec.setExitValues(null);
    if (workingDir != null) {
        exec.setWorkingDirectory(workingDir.toFile());
    }
    in.close();
    LOG.info("Executing: {}", cmd.toString());
    return exec.execute(cmd, env);
}

From source file:com.vmware.bdd.usermgmt.job.CfgUserMgmtOnMgmtVMExecutor.java

private void execCommand(CommandLine cmdLine) {
    DefaultExecutor executor = new DefaultExecutor();

    executor.setStreamHandler(new PumpStreamHandler(new ExecOutputLogger(LOGGER, false), //output logger
            new ExecOutputLogger(LOGGER, true)) //error logger
    );/*w  ww .ja v  a2s.com*/

    executor.setWatchdog(new ExecuteWatchdog(1000l * TIMEOUT));

    try {
        int exitVal = executor.execute(cmdLine);
        if (exitVal != 0) {
            throw new UserMgmtExecException("CFG_LDAP_FAIL", null);
        }
    } catch (IOException e) {
        throw new UserMgmtExecException("CFG_LDAP_FAIL", e);
    }
}

From source file:its.tools.CommandExecutor.java

public void execute(String[] args, @Nullable Path workingDir) throws IOException {
    if (!Files.isExecutable(file)) {
        Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
        perms.add(PosixFilePermission.OWNER_READ);
        perms.add(PosixFilePermission.OWNER_EXECUTE);
        Files.setPosixFilePermissions(file, perms);
    }//from www. ja v a2s  .  c  o  m

    watchdog = new ExecuteWatchdog(TIMEOUT);
    CommandLine cmd = new CommandLine(file.toFile());
    cmd.addArguments(args);
    DefaultExecutor exec = new DefaultExecutor();
    exec.setWatchdog(watchdog);
    exec.setStreamHandler(createStreamHandler());
    exec.setExitValues(null);
    if (workingDir != null) {
        exec.setWorkingDirectory(workingDir.toFile());
    }
    in.close();
    LOG.info("Executing: {}", cmd.toString());
    exec.execute(cmd, new ResultHander());
}

From source file:io.gatling.mojo.Fork.java

public void run() throws Exception {

    if (propagateSystemProperties) {
        for (Entry<Object, Object> systemProp : System.getProperties().entrySet()) {
            String name = systemProp.getKey().toString();
            String value = systemProp.getValue().toString();
            if (isPropagatableProperty(name)) {
                String escapedValue = StringUtils.escape(value);
                String safeValue = escapedValue.contains(" ") ? '"' + escapedValue + '"' : escapedValue;
                this.jvmArgs.add("-D" + name + "=" + safeValue);
            }/*from  ww w.  j  a v a2 s .co  m*/
        }
    }

    this.jvmArgs.add("-jar");
    this.jvmArgs
            .add(MojoUtils.createBooterJar(classpath, MainWithArgsInFile.class.getName()).getCanonicalPath());

    List<String> command = buildCommand();

    Executor exec = new DefaultExecutor();
    exec.setStreamHandler(new PumpStreamHandler(System.out, System.err, System.in));
    exec.setProcessDestroyer(new ShutdownHookProcessDestroyer());

    CommandLine cl = new CommandLine(javaExecutable);
    for (String arg : command) {
        cl.addArgument(arg, false);
    }

    int exitValue = exec.execute(cl);
    if (exitValue != 0) {
        throw new MojoFailureException("command line returned non-zero value:" + exitValue);
    }
}

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);/*  w  w  w  .ja va 2 s.  c  om*/
    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.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);
    }//from  w  ww.  j  a  v  a  2s. 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:eu.creatingfuture.propeller.blocklyprop.propeller.PropellerLoad.java

protected boolean loadIntoRam(String executable, File ramFile, String comPort) {
    try {//ww  w  .j av  a  2 s  . c  om
        Map map = new HashMap();
        map.put("ramFile", ramFile);

        CommandLine cmdLine = new CommandLine(executable);
        cmdLine.addArgument("-r");
        if (comPort != null) {
            cmdLine.addArgument("-p").addArgument(comPort);
        }
        cmdLine.addArgument("${ramFile}");

        cmdLine.setSubstitutionMap(map);
        DefaultExecutor executor = new DefaultExecutor();
        //executor.setExitValues(new int[]{451, 301});

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

        try {
            exitValue = executor.execute(cmdLine);
        } catch (ExecuteException ee) {
            exitValue = ee.getExitValue();
            logger.log(Level.SEVERE, "Unexpected exit value: {0}", exitValue);
            success = false;
            return false;
        } finally {
            output = outputStream.toString();
        }

        success = true;
        return true;
    } catch (IOException ioe) {
        logger.log(Level.SEVERE, null, ioe);
        success = false;
        return false;
    }
}