Example usage for org.apache.commons.exec CommandLine setSubstitutionMap

List of usage examples for org.apache.commons.exec CommandLine setSubstitutionMap

Introduction

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

Prototype

public void setSubstitutionMap(final Map<String, ?> substitutionMap) 

Source Link

Document

Set the substitutionMap to expand variables in the command line.

Usage

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

private void runJob(Master.GenerateReport job) {
    TaskEvent taskEvent = job.reportJob.taskEvent;
    CommandLine cmdLine = new CommandLine(agentConfig.getJob().getCommand());
    Map<String, Object> map = new HashMap<>();

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

    //parameters come from the task event
    for (Pair<String, String> pair : taskEvent.getParameters()) {
        cmdLine.addArgument(pair.getValue());
    }/*  ww w  . j  av  a  2 s . c om*/
    String dir = agentConfig.getJob().getLogDirectory() + "reports/" + job.reportJob.trackingId + "/";
    cmdLine.addArgument(dir);

    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;
    try {
        List<String> resultFiles = new ArrayList<>(job.results.size());
        //download all files adn
        /*int i=0;
        for (Worker.Result result : job.results) {
        String destFile = dir  + i++ + ".log";
        resultFiles.add(destFile);
        DownloadFile.downloadFile(result.metrics,destFile);
        }*/
        AtomicInteger index = new AtomicInteger();
        job.results.parallelStream().forEach(result -> {
            String destFile = dir + index.incrementAndGet() + ".log";
            resultFiles.add(destFile);
            DownloadFile.downloadFile(result.metrics, destFile);
        });
        String outPath = agentConfig.getJob().getOutPath(taskEvent.getJobName(), job.reportJob.trackingId);
        String errPath = agentConfig.getJob().getErrorPath(taskEvent.getJobName(), job.reportJob.trackingId);
        //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);
        System.out.println(cmdLine);
        int exitResult = executor.execute(cmdLine);
        ReportResult result;
        if (executor.isFailure(exitResult)) {
            result = new ReportResult(dir, job.reportJob, false);
            log.info("Report Executor Failed, result: " + job.toString());
        } else {
            result = new ReportResult(job.reportJob.getHtml(), job.reportJob, true);
            log.info("Report Executor Completed, result: " + result.toString());
        }
        for (String resultFile : resultFiles) {
            FileUtils.deleteQuietly(new File(resultFile));
        }
        getSender().tell(result, getSelf());

    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    } finally {
        IOUtils.closeQuietly(outFile);
        IOUtils.closeQuietly(errorFile);
    }

}

From source file:be.tarsos.transcoder.ffmpeg.FFMPEGExecutor.java

public String toString() {
    CommandLine cmdLine = new CommandLine(ffmpegExecutablePath);

    int fileNumber = 0;
    Map<String, File> map = new HashMap<String, File>();
    for (int i = 0; i < args.size(); i++) {
        final String arg = args.get(i);
        final Boolean isFile = argIsFile.get(i);
        if (isFile) {
            String key = "file" + fileNumber;
            map.put(key, new File(arg));
            cmdLine.addArgument("${" + key + "}", false);
            fileNumber++;//from  ww w .ja va2s  .c o  m
        } else {
            cmdLine.addArgument(arg);
        }
    }
    cmdLine.setSubstitutionMap(map);
    return cmdLine.toString();
}

From source file:be.tarsos.transcoder.ffmpeg.FFMPEGExecutor.java

/**
 * Executes the ffmpeg process with the previous given arguments.
 * //from w  w w  . ja v  a2s . c  o m
 * @return The standard output of the child process.
 * 
 * @throws IOException
 *             If the process call fails.
 */
public String execute() throws IOException {
    CommandLine cmdLine = new CommandLine(ffmpegExecutablePath);

    int fileNumber = 0;
    Map<String, File> map = new HashMap<String, File>();
    for (int i = 0; i < args.size(); i++) {
        final String arg = args.get(i);
        final Boolean isFile = argIsFile.get(i);
        if (isFile) {
            String key = "file" + fileNumber;
            map.put(key, new File(arg));
            cmdLine.addArgument("'${" + key + "}'", false);
            fileNumber++;
        } else {
            cmdLine.addArgument(arg);
        }
    }
    cmdLine.setSubstitutionMap(map);
    LOG.fine("Execute: " + cmdLine);
    DefaultExecutor executor = new DefaultExecutor();
    //5minutes wait
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000 * 5);
    executor.setWatchdog(watchdog);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(out));
    int[] exitValues = { 0, 1 };
    executor.setExitValues(exitValues);
    executor.execute(cmdLine);
    return out.toString();
}

From source file:com.muk.services.util.BarcodeServiceImpl.java

@Override
public File generateBarcode(File path, String giftCardId) {

    CommandLine cmdLine = null;

    if (System.getProperty("os.name").equals("Linux")) {
        cmdLine = new CommandLine("convert");
    } else {//from ww w .  j  av  a  2 s.  co m
        cmdLine = new CommandLine("convert.exe");
    }

    cmdLine.addArgument("-font");
    cmdLine.addArgument("Free-3-of-9-Extended-Regular");
    cmdLine.addArgument("-pointsize");
    cmdLine.addArgument("40");
    cmdLine.addArgument("-bordercolor");
    cmdLine.addArgument("white");
    cmdLine.addArgument("-border");
    cmdLine.addArgument("10x10");
    cmdLine.addArgument("label:${giftCardId}");
    cmdLine.addArgument("${outfile}");

    Map<String, Object> map = new HashMap<String, Object>();
    map.put("giftCardId", giftCardId);
    map.put("outfile", path);

    cmdLine.setSubstitutionMap(map);

    ProcessExecutor executor = new ProcessExecutor();

    try {
        if (0 == executor.runCommandLine(cmdLine, 100000)) {
            return path;
        }
    } catch (IOException ex) {
        LOG.error("Failed to execute imagemagick", ex);
    }

    return null;

}

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

private void addDefaultWindowsFirewallRule(int ruleNumber, String filterName, String ipList) {
    Map<Object, Object> map = new HashMap<Object, Object>();
    map.put("name", createFinalRuleName(ruleNumber, filterName));
    map.put("direction", "in");
    map.put("ipList", ipList);
    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("add");
    cmdLine.addArgument("rule");
    cmdLine.addArgument("name=${name}");
    cmdLine.addArgument("dir=${direction}");
    cmdLine.addArgument("action=block");
    cmdLine.addArgument("localip=any");
    cmdLine.addArgument("remoteip=${ipList}");
    cmdLine.addArgument("description=This is a generated rule from wfail2ban. Do not edit!");
    cmdLine.addArgument("profile=any");
    cmdLine.addArgument("interfacetype=any");
    cmdLine.setSubstitutionMap(map);
    DefaultExecutor executor = new DefaultExecutor();
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
    executor.setWatchdog(watchdog);//from   w  ww.j  a va2 s  .  c  om
    try {
        executor.execute(cmdLine);
        if (logger.isDebugEnabled()) {
            logger.debug("Added firewall rule " + createFinalRuleName(ruleNumber, filterName));
        }
    } catch (ExecuteException e) {
        ConsolePrinter.printError("Could not create firewall rule. Continuing with next one...");
        logger.error("", e);
    } catch (IOException e) {
        logger.error("Could not create firewall rule. Error was: ", e);
    }
}

From source file:at.ac.tuwien.ims.latex2mobiformulaconv.converter.latex2html.PandocLatexToHtmlConverter.java

@Override
public Document convert(File tex, String title) {
    logger.debug("Start convert() with file " + tex.toPath().toAbsolutePath().toString() + ", title: " + title);

    CommandLine cmdLine;
    if (execPath != null) {
        // Run the configured pandoc executable
        logger.info("Pandoc will be run from: " + execPath.toString());
        cmdLine = new CommandLine(execPath.toFile());
    } else {//w w w.ja va 2  s  .c o  m
        // Run in system PATH environment
        logger.info("Pandoc will be run within the PATH variable.");
        cmdLine = new CommandLine("pandoc");
    }

    cmdLine.addArgument("--from=latex");
    cmdLine.addArgument("--to=html5");
    cmdLine.addArgument("--asciimathml"); // With this option, pandoc does not render latex formulas

    cmdLine.addArgument("${file}");

    HashMap<String, Path> map = new HashMap<String, Path>();
    map.put("file", Paths.get(tex.toURI()));

    cmdLine.setSubstitutionMap(map);

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000); // max execution time 1 minute
    Executor executor = new DefaultExecutor();
    executor.setExitValue(1);
    executor.setWatchdog(watchdog);
    StringWriter writer = new StringWriter();
    WriterOutputStream writerOutputStream = new WriterOutputStream(writer, Charset.forName("UTF-8"));

    ExecuteStreamHandler pandocStreamHandler = new PumpStreamHandler(writerOutputStream, System.err);
    executor.setStreamHandler(pandocStreamHandler);

    logger.debug("Launching pandoc:");
    logger.debug(cmdLine.toString());

    try {
        executor.execute(cmdLine, resultHandler);
    } catch (IOException e) {
        logger.error("Pandoc's execution failed, exiting...");
        logger.error(e.getMessage(), e);
        System.exit(-1);
    }

    try {
        resultHandler.waitFor();
        int exitValue = resultHandler.getExitValue();

        logger.debug("Pandoc execution's exit value: " + exitValue);
        ExecuteException executeException = resultHandler.getException();
        if (executeException != null && executeException.getCause() != null) {

            String exceptionKlass = executeException.getCause().getClass().getCanonicalName();
            String exceptionMessage = executeException.getCause().getMessage();

            if (exceptionKlass.endsWith("IOException")
                    || exceptionMessage.contains("Cannot run program \"pandoc\"")) {
                logger.error("Pandoc could not be found! Exiting...");
                logger.debug(executeException);
                System.exit(1);
            }
            logger.debug(exceptionKlass + ": " + exceptionMessage);
        }

    } catch (InterruptedException e) {
        logger.error("pandoc conversion thread got interrupted, exiting...");
        logger.error(e.getMessage(), e);
        System.exit(1);
    }

    // add html document structure to output
    // pandoc returns no document markup (html, head, body)
    // therefore we have to use a template
    String htmlOutput = "<!DOCTYPE html>\n" + "<html>\n" + "<head>\n" +
    // set title
            "<title>" + title + "</title>\n" +
            // include css
            "<link rel=\"stylesheet\" type=\"text/css\" href=\"main.css\"></link>\n" + "</head>\n" + "<body>";
    try {
        htmlOutput += writer.getBuffer().toString();
        writer.close();

    } catch (IOException e) {
        logger.error("Error reading html result from StringBuffer...");
        logger.error(e.getMessage(), e);
        System.exit(1);
    }

    // Close tags in template
    htmlOutput += "</body>\n" + "</html>";

    // output loading as JDOM Document
    SAXBuilder sax = new SAXBuilder();
    Document document = null;
    try {
        document = sax.build(new StringReader(htmlOutput));
    } catch (JDOMException e) {
        logger.error("JDOM Parsing error");
        logger.error(e.getMessage(), e);
        System.exit(1);
    } catch (IOException e) {
        logger.error("Error reading from String...");
        logger.error(e.getMessage(), e);
        System.exit(1);
    }
    return document;
}

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());
    }/*  www . j a v  a2s  .c o  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: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 w w.  ja  v  a  2 s .c o  m*/
    // 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:edu.buffalo.fusim.BowtieAlignment.java

public void run(String bowtiePath, String index, File read1, File read2, File outFile, int threads) {
    // Example bowtie call:
    //   bowtie -t -v 2 -p 12 -m 10 -S
    CommandLine cmdLine = new CommandLine(bowtiePath);

    // print wall-clock time taken by search phases
    cmdLine.addArgument("-t");
    // eport end-to-end hits w/ <=v mismatches; ignore qualities
    cmdLine.addArgument("-v");
    cmdLine.addArgument("2");
    // number of alignment threads to launch
    cmdLine.addArgument("-p");
    cmdLine.addArgument("" + threads);
    // suppress all alignments if > <int> exist
    cmdLine.addArgument("-m");
    cmdLine.addArgument("10");
    // write hits in SAM format
    cmdLine.addArgument("-S");
    // bowtie index
    cmdLine.addArgument("${index}");
    if (read2 != null) {
        // fastq1
        cmdLine.addArgument("-1");
        cmdLine.addArgument("${read1}");
        // fastq2
        cmdLine.addArgument("-2");
        cmdLine.addArgument("${read2}");
    } else {/*  w ww  . ja  v a 2 s .co  m*/
        cmdLine.addArgument("${read1}");
    }
    // output SAM file
    cmdLine.addArgument("${outFile}");

    Map map = new HashMap();
    map.put("index", index);
    map.put("read1", read1);
    if (read2 != null) {
        map.put("read2", read2);
    }
    map.put("outFile", outFile);
    cmdLine.setSubstitutionMap(map);

    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);
    // Never timeout 
    ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
    executor.setWatchdog(watchdog);

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

From source file:eu.creatingfuture.propeller.blocklyprop.propeller.GccCompiler.java

protected boolean compileForEeprom(String executable, File sourceFile, File destinationFile) {
    try {/*from w  ww .  java2 s  .c  om*/
        List<CLib> libs = new ArrayList<>();
        libs.add(cLibs.get("simpletools"));
        libs.add(cLibs.get("simpletext"));
        libs.add(cLibs.get("simplei2c"));

        File libDirectory = new File(new File(System.getProperty("user.dir")), "/propeller-c-lib");
        Map map = new HashMap();
        map.put("sourceFile", sourceFile);
        map.put("destinationFile", destinationFile);
        CommandLine cmdLine = new CommandLine(executable);
        for (CLib lib : libs) {
            cmdLine.addArgument("-I").addArgument("${libdir" + lib.getName() + "}");
            cmdLine.addArgument("-L").addArgument("${memorymodel" + lib.getName() + "}");
            cmdLine.addArgument("-l" + lib.getName());

            map.put("libdir" + lib.getName(), new File(libDirectory, lib.getLibdir()));
            map.put("memorymodel" + lib.getName(), new File(libDirectory, lib.getMemoryModel().get("cmm")));
        }
        cmdLine.addArgument("-Os");
        cmdLine.addArgument("-mcmm");
        cmdLine.addArgument("-m32bit-doubles");
        cmdLine.addArgument("-std=c99");
        cmdLine.addArgument("-o").addArgument("${destinationFile}");
        cmdLine.addArgument("${sourceFile}");
        cmdLine.addArgument("-lm");
        for (CLib lib : libs) {
            cmdLine.addArgument("-l" + lib.getName());
        }
        cmdLine.setSubstitutionMap(map);
        DefaultExecutor executor = new DefaultExecutor();
        //  executor.setExitValues(new int[]{402, 101});

        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();
        }

        //            System.out.println("output: " + output);
        /*
         Scanner scanner = new Scanner(output);
                
                
         Pattern chipFoundPattern = Pattern.compile(".*?(EVT:505).*?");
         Pattern pattern = Pattern.compile(".*?found on (?<comport>[a-zA-Z0-9]*).$");
         while (scanner.hasNextLine()) {
         String portLine = scanner.nextLine();
         if (chipFoundPattern.matcher(portLine).matches()) {
         Matcher portMatch = pattern.matcher(portLine);
         if (portMatch.find()) {
         //   String port = portMatch.group("comport");
                
         }
         }
         }
         */
        //            System.out.println("output: " + output);
        //            System.out.println("exitValue: " + exitValue);
        success = true;
        return true;
    } catch (IOException ioe) {
        logger.log(Level.SEVERE, null, ioe);
        success = false;
        return false;
    }
}