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

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

Introduction

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

Prototype

public int execute(final CommandLine command) throws ExecuteException, IOException 

Source Link

Usage

From source file:hoot.services.command.CommandRunnerImpl.java

@Override
public CommandResult exec(String command) throws IOException {
    logger.debug("Executing the following command: {}", command);

    try (OutputStream stdout = new ByteArrayOutputStream(); OutputStream stderr = new ByteArrayOutputStream()) {

        CommandLine cmdLine = CommandLine.parse(command);

        ExecuteStreamHandler executeStreamHandler = new PumpStreamHandler(stdout, stderr);
        DefaultExecutor executor = new DefaultExecutor();
        executor.setStreamHandler(executeStreamHandler);

        int exitValue;
        try {/*ww  w. j  ava2  s . com*/
            exitValue = executor.execute(cmdLine);
        } catch (Exception e) {
            exitValue = -1;
            logger.warn("Error executing: {}", cmdLine, e);
        }

        CommandResult commandResult = new CommandResult(cmdLine.toString(), exitValue, stdout.toString(),
                stderr.toString());

        this.stdout = stdout.toString();

        logger.debug("Finished executing: {}", commandResult);

        return commandResult;
    }
}

From source file:hoot.services.command.CommandRunnerImpl.java

@Override
public CommandResult exec(String[] command) throws IOException {
    logger.debug("Executing the following command: {}", Arrays.toString(command));

    try (OutputStream stdout = new ByteArrayOutputStream(); OutputStream stderr = new ByteArrayOutputStream()) {

        CommandLine cmdLine = new CommandLine(command[0]);
        for (int i = 1; i < command.length; i++) {
            cmdLine.addArgument(command[i], false);
        }/*from  ww w  .j  a  va  2s. co m*/

        ExecuteStreamHandler executeStreamHandler = new PumpStreamHandler(stdout, stderr);
        DefaultExecutor executor = new DefaultExecutor();
        executor.setStreamHandler(executeStreamHandler);

        int exitValue;
        try {
            exitValue = executor.execute(cmdLine);
        } catch (Exception e) {
            exitValue = -1;
            logger.warn("Error executing: {}", cmdLine, e);
        }

        CommandResult commandResult = new CommandResult(cmdLine.toString(), exitValue, stdout.toString(),
                stderr.toString());

        this.stdout = stdout.toString();

        logger.debug("Finished executing: {}", commandResult);

        return commandResult;
    }
}

From source file:com.rest4j.generator.PythonGeneratorTest.java

@Test
public void testPythonClient() throws Exception {
    gen.setStylesheet("com/rest4j/client/python.xslt");
    new File("target/python").mkdir();
    gen.setApiXmlUrl(getClass().getResource("doc-generator-graph.xml"));
    gen.setOutputDir("target/python");
    gen.addParam(new TemplateParam("common-params", "access-token"));
    gen.addParam(new TemplateParam("additional-client-code", "\t# ADDITIONAL CODE"));
    gen.generate();/*from   w w  w  .ja  v a2  s. com*/

    // let's try compiling the damn thing
    CommandLine cmdLine = CommandLine.parse("python apiclient.py");
    DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(new File("target/python"));
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
    executor.setWatchdog(watchdog);
    int exitValue = executor.execute(cmdLine);
    assertFalse(executor.isFailure(exitValue));

    String a = IOUtils.toString(new File("target/python/apiclient.py").toURI());

    // check doc comments
    assertTrue(a, a.contains("Some additional client info"));
    assertTrue(a, a.contains("Some additional python client info"));

    // check existence of Parameter Object class
    assertTrue(a, a.contains("class PatchBRequest"));

    // check additional-client-code
    assertTrue(a, a.contains("\t# ADDITIONAL CODE"));
}

From source file:com.creactiviti.piper.plugin.ffmpeg.Mediainfo.java

@Override
public Map<String, Object> handle(Task aTask) throws Exception {
    CommandLine cmd = new CommandLine("mediainfo");
    cmd.addArgument(aTask.getRequiredString("input"));
    log.debug("{}", cmd);
    DefaultExecutor exec = new DefaultExecutor();
    File tempFile = File.createTempFile("log", null);
    try (PrintStream stream = new PrintStream(tempFile);) {
        exec.setStreamHandler(new PumpStreamHandler(stream));
        exec.execute(cmd);
        return parse(FileUtils.readFileToString(tempFile));
    } catch (ExecuteException e) {
        throw new ExecuteException(e.getMessage(), e.getExitValue(),
                new RuntimeException(FileUtils.readFileToString(tempFile)));
    } finally {//w  ww .  j  ava  2  s.  c  o  m
        FileUtils.deleteQuietly(tempFile);
    }
}

From source file:drat.proteus.DratStartForm.java

private void parseAsVersionControlledRepo(String path, String command, boolean downloadPhase)
        throws IOException {
    if (!downloadPhase) {
        startDrat(path, command);// w  w w  .j a  v a2 s . c om
        return;
    }

    String projectName = null;
    boolean git = path.endsWith(".git");
    File tmpDir = new File(System.getProperty("java.io.tmpdir"));
    String tmpDirPath = tmpDir.getCanonicalPath();
    String line = null;
    if (git) {
        projectName = path.substring(path.lastIndexOf("/") + 1, path.lastIndexOf("."));
        line = "git clone --depth 1 --branch master " + path;
    } else {
        projectName = path.substring(path.lastIndexOf("/") + 1);
        line = "svn export " + path;
    }
    String clonePath = tmpDirPath + File.separator + projectName;
    File cloneDir = new File(clonePath);
    if (cloneDir.isDirectory() && cloneDir.exists()) {
        LOG.info("Git / SVN clone: [" + clonePath + "] already exists, removing it.");
        FileUtils.removeDir(cloneDir);
    }
    LOG.info("Cloning Git / SVN project: [" + projectName + "] remote repo: [" + path + "] into " + tmpDirPath);

    CommandLine cmdLine = CommandLine.parse(line);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(tmpDir);
    int exitValue = executor.execute(cmdLine);

    if (git) {
        String gitHiddenDirPath = clonePath + File.separator + ".git";
        File gitHiddenDir = new File(gitHiddenDirPath);
        LOG.info("Removing .git directory from " + gitHiddenDirPath);
        FileUtils.removeDir(gitHiddenDir);
    }

    startDrat(clonePath, command);

}

From source file:com.rest4j.generator.JavaGeneratorTest.java

@Test
public void testJavaClient() throws Exception {
    gen.setStylesheet("com/rest4j/client/java.xslt");
    new File("target/java").mkdir();
    gen.setApiXmlUrl(getClass().getResource("doc-generator-graph.xml"));
    gen.setOutputDir("target/java");
    gen.addParam(new TemplateParam("common-params", "access-token"));
    gen.addParam(new TemplateParam("additional-client-code", "// ADDITIONAL CODE"));
    gen.generate();/*from  w ww . j a v  a2s .  co  m*/

    // let's try compiling the damn thing
    CommandLine cmdLine = CommandLine.parse("mvn package");
    DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(new File("target/java"));
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
    executor.setWatchdog(watchdog);
    int exitValue = executor.execute(cmdLine);
    assertFalse(executor.isFailure(exitValue));

    // check doc comments in the file A.java
    String a = IOUtils.toString(new File("target/java/src/main/java/api/model/A.java").toURI());
    assertTrue(a, a.contains("Some additional client info"));
    assertFalse(a, a.contains("Some additional python client info"));

    // check existence of Parameter Object class
    a = IOUtils.toString(new File("target/java/src/main/java/api/model/PatchBRequest.java").toURI());
    assertTrue(a, a.contains("class PatchBRequest"));

    // check some file paths
    assertTrue(new File("target/java/src/main/java/api/util/JsonUtil.java").canRead());
    assertTrue(new File("target/java/src/main/java/api/Request.java").canRead());

    String client = IOUtils.toString(new File("target/java/src/main/java/api/Client.java").toURI());
    assertTrue(client.contains("ADDITIONAL CODE"));
}

From source file:com.creactiviti.piper.plugin.ffmpeg.Ffmpeg.java

@Override
public Object handle(Task aTask) throws Exception {
    List<String> options = aTask.getList("options", String.class);
    CommandLine cmd = new CommandLine("ffmpeg");
    options.forEach(o -> cmd.addArgument(o));
    log.debug("{}", cmd);
    DefaultExecutor exec = new DefaultExecutor();
    File tempFile = File.createTempFile("log", null);
    try (PrintStream stream = new PrintStream(tempFile);) {
        exec.setStreamHandler(new PumpStreamHandler(stream));
        int exitValue = exec.execute(cmd);
        return exitValue != 0 ? FileUtils.readFileToString(tempFile) : cmd.toString();
    } catch (ExecuteException e) {
        throw new ExecuteException(e.getMessage(), e.getExitValue(),
                new RuntimeException(FileUtils.readFileToString(tempFile)));
    } finally {/* w  w w.j a  v a 2s .  c  om*/
        FileUtils.deleteQuietly(tempFile);
    }
}

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  w ww. 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:com.creactiviti.piper.plugin.ffmpeg.Ffprobe.java

@Override
public Map<String, Object> handle(Task aTask) throws Exception {
    CommandLine cmd = new CommandLine("ffprobe");
    cmd.addArgument("-v").addArgument("quiet").addArgument("-print_format").addArgument("json")
            .addArgument("-show_error").addArgument("-show_format").addArgument("-show_streams")
            .addArgument(aTask.getRequiredString("input"));
    log.debug("{}", cmd);
    DefaultExecutor exec = new DefaultExecutor();
    File tempFile = File.createTempFile("log", null);
    try (PrintStream stream = new PrintStream(tempFile);) {
        exec.setStreamHandler(new PumpStreamHandler(stream));
        exec.execute(cmd);
        return parse(FileUtils.readFileToString(tempFile));
    } catch (ExecuteException e) {
        throw new ExecuteException(e.getMessage(), e.getExitValue(),
                new RuntimeException(FileUtils.readFileToString(tempFile)));
    } finally {/* w w w.  ja v  a2 s . c  om*/
        FileUtils.deleteQuietly(tempFile);
    }
}

From source file:de.slackspace.wfail2ban.firewall.impl.DefaultFirewallManager.java

private void deleteFirewallRule(int ruleNumber, String filterName) {
    CommandLine cmdLine = new CommandLine("cmd.exe");
    cmdLine.addArgument("/C");
    cmdLine.addArgument(System.getenv("WINDIR") + "\\system32\\netsh.exe");
    cmdLine.addArgument("advfirewall");
    cmdLine.addArgument("firewall");
    cmdLine.addArgument("delete");
    cmdLine.addArgument("rule");
    cmdLine.addArgument(createFinalRuleName(ruleNumber, filterName));
    DefaultExecutor executor = new DefaultExecutor();
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
    executor.setWatchdog(watchdog);//from   w  w  w. j  a v a 2 s .c  om
    try {
        executor.execute(cmdLine);
        if (logger.isDebugEnabled()) {
            logger.debug("Deleted firewall rule " + createFinalRuleName(ruleNumber, filterName));
        }
    } catch (ExecuteException e) {
        logger.error("Could not delete firewall rule. Error was: ", e);
    } catch (IOException e) {
        logger.error("Could not delete firewall rule. Error was: ", e);
    }
}