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:it.drwolf.ridire.index.cwb.CWBConcordancer.java

@SuppressWarnings("unchecked")
public void test() {
    String query = "set AutoShow off;\nset ProgressBar off;\nset PrettyPrint off;\nset Context 5 words;\nset LeftKWICDelim '--%%%--';\nset RightKWICDelim '--%%%--';\nshow -cpos;\nA=\"e\";\ncat A 0 9 > \"/home/drwolf/ridirecleaner_tmp/res.tbl\";";
    File temp = null;/* w  w w .  j av  a2s. com*/
    try {
        temp = File.createTempFile("ridireQ", ".query");
        FileUtils.writeStringToFile(temp, query);
        Executor executor = new DefaultExecutor();
        CommandLine commandLine = new CommandLine("/usr/local/cwb-3.4.3/bin/cqp");
        commandLine.addArgument("-f").addArgument(temp.getAbsolutePath()).addArgument("-D")
                .addArgument("RIDIRE2").addArgument("-r").addArgument("/usr/local/share/cwb/registry/");
        executor.execute(commandLine);
        File resFile = new File("/home/drwolf/ridirecleaner_tmp/res.tbl");
        List<String> lines = FileUtils.readLines(resFile);
        this.resultsSimple = new ArrayList<CWBResult>();
        for (String l : lines) {
            String[] res = l.split("--%%%--");
            CWBResult item = new CWBResult(res[0], res[1], res[2], "", null, null);
            this.resultsSimple.add(item);
        }
        this.entityManager.createNativeQuery("drop table if exists pippo").executeUpdate();
        this.entityManager.createNativeQuery(
                "CREATE TABLE `pippo` (`text_id` varchar(40) DEFAULT NULL,`beginPosition` int(11) DEFAULT NULL,`endPosition` int(11) DEFAULT NULL,`refnumber` bigint(20) NOT NULL,`dist` smallint(6) NOT NULL,`word` varchar(40) NOT NULL,`lemma` varchar(40) NOT NULL, `pos` varchar(40) NOT NULL) ENGINE=MyISAM DEFAULT CHARSET=utf8")
                .executeUpdate();
        File tmpAwk = File.createTempFile("ridireAWK", ".awk");
        String awk = "BEGIN{ OFS = FS = \"\t\" } { print $3, $1, $2, NR-1, -5, $4 } { print $3, $1, $2, NR-1, -4, $5 } { print $3, $1, $2, NR-1, -3, $6 } { print $3, $1, $2, NR-1, -2, $7 } { print $3, $1, $2, NR-1, -1, $8 } { print $3, $1, $2, NR-1, 1, $9 } { print $3, $1, $2, NR-1, 2, $10 } { print $3, $1, $2, NR-1, 3, $11 } { print $3, $1, $2, NR-1, 4, $12 } { print $3, $1, $2, NR-1, 5, $13 } ";
        FileUtils.writeStringToFile(tmpAwk, awk);
        File tmpTabulate = File.createTempFile("ridireTAB", ".tab");
        String tabulate = "set AutoShow off;\nset ProgressBar off;\nset PrettyPrint off;\nset Context 5 words;\nset LeftKWICDelim '--%%%--';\nset RightKWICDelim '--%%%--';\nshow -cpos;\nA=\"e\";\ntabulate A match, matchend, match text_id, match[-5] word, match[-4] word, match[-3] word, match[-2] word, match[-1] word, matchend[1] word, matchend[2] word, matchend[3] word, matchend[4] word, matchend[5] word "
                + ">  \"| awk -f '" + tmpAwk.getAbsolutePath() + "' > '" + tmpTabulate.getAbsolutePath()
                + "'\";";
        File tempSh = File.createTempFile("ridireSH", ".sh");
        FileUtils.writeStringToFile(tempSh, tabulate);
        tempSh.setExecutable(true);
        executor = new DefaultExecutor();
        executor.setExitValue(0);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(CWBConcordancer.TIMEOUT);
        executor.setWatchdog(watchdog);
        commandLine = new CommandLine("/usr/local/cwb-3.4.3/bin/cqp");
        commandLine.addArgument("-f").addArgument(tempSh.getAbsolutePath()).addArgument("-D")
                .addArgument("RIDIRE2").addArgument("-r").addArgument("/usr/local/share/cwb/registry/");
        executor.execute(commandLine);
        FileUtils.deleteQuietly(tempSh);
        this.entityManager
                .createNativeQuery(
                        "LOAD DATA LOCAL INFILE '" + tmpTabulate.getAbsolutePath() + "' INTO TABLE " + "pippo")
                .executeUpdate();
        long n = ((Number) this.entityManager.createNativeQuery("select sum(freq) as somma from freq_forma_all")
                .getSingleResult()).longValue();
        long r1 = ((Number) this.entityManager
                .createNativeQuery("select count(*) from pippo where dist between -3 and 3").getSingleResult())
                        .longValue();
        String nativeQuery = "select pippo.word, count(pippo.word) as observed," + " (" + r1
                + " * (freq_forma_all.freq) / " + n + ") as expected, sign(COUNT(pippo.word) - (" + r1
                + " * (freq_forma_all.freq) / " + n
                + ")) * 2 * ( IF(COUNT(pippo.word) > 0, COUNT(pippo.word) * log(COUNT(pippo.word) / (" + r1
                + " * (freq_forma_all.freq) / " + n + ")), 0) + IF((" + r1 + " - COUNT(pippo.word)) > 0, (" + r1
                + " - COUNT(pippo.word)) * log((" + r1 + " - COUNT(pippo.word)) / (" + r1 + " * (" + n
                + " - (freq_forma_all.freq)) / " + n
                + ")), 0) + IF(((freq_forma_all.freq) - COUNT(pippo.word)) > 0, ((freq_forma_all.freq) - COUNT(pippo.word)) * log(((freq_forma_all.freq) - COUNT(pippo.word)) / ("
                + (n - r1) + " * (freq_forma_all.freq) / " + n + ")), 0) + IF((" + (n - r1)
                + " - ((freq_forma_all.freq) - COUNT(pippo.word))) > 0, (" + (n - r1)
                + " - ((freq_forma_all.freq) - COUNT(pippo.word))) * log((" + (n - r1)
                + " - ((freq_forma_all.freq) - COUNT(pippo.word))) / (" + (n - r1) + " * (" + n
                + " - (freq_forma_all.freq)) / " + n
                + ")), 0) ) as significance, freq_forma_all.freq, count(distinct(text_id)) as text_id_count from pippo, freq_forma_all where pippo.word = freq_forma_all.item and dist between -3 and 3 and freq_forma_all.freq >= 1 group by pippo.word having observed >= 1 order by significance desc LIMIT 0, 50 ";
        List<Object[]> res = this.entityManager.createNativeQuery(nativeQuery).getResultList();
        for (Object[] r : res) {
            System.out.println(r[0] + "\t" + r[3]);
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:gov.nasa.jpl.magicdraw.projectUsageIntegrity.graph.SSCAEProjectUsageGraph.java

public BufferedImageFile convertDOTFile(@Nonnull File pugDOT, @Nonnull DOTImageFormat dotImageFormat)
        throws IIOException, IOException, InterruptedException {
    String dotCommand = ProjectUsageIntegrityPlugin.getInstance().getDOTexecutablePath();
    if (null == dotCommand)
        return null;

    File pugTemp = pugDOT.getParentFile();
    File pugImage = new File(pugTemp.getAbsoluteFile() + File.separator + project.getID() + "."
            + DOTImageFormatName.get(dotImageFormat));
    if (pugImage.exists()) {
        pluginLog.info(String.format("%s - convertDOTFile - deleting previous image for '%s' : '%s'",
                pluginName, project.getName(), pugImage.getName()));
        pugImage.delete();//from   www .j av  a  2s  .  c o m
    }

    CommandLine cmdLine = new CommandLine(dotCommand);
    cmdLine.addArgument("-Tpng");
    cmdLine.addArgument("-o");
    cmdLine.addArgument(pugImage.getName());
    cmdLine.addArgument(pugDOT.getName());

    pluginLog.info(String.format("%s - convertDOTgraph - converting gv to image for '%s'", pluginName,
            project.getName()));

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000);

    // consider '0' exit value as success.
    Executor executor = new DefaultExecutor();
    executor.setExitValue(0);
    executor.setWatchdog(watchdog);
    executor.setWorkingDirectory(pugTemp);
    executor.execute(cmdLine, resultHandler);

    resultHandler.waitFor();

    if (!executor.isFailure(resultHandler.getExitValue())) {
        pluginLog.info(String.format("%s - convertDOTgraph - reading image for '%s' from: '%s'", pluginName,
                project.getName(), pugImage.getName()));
        BufferedImageFile imageFile = new BufferedImageFile(pugImage);

        pluginLog.info(
                String.format("%s - convertDOTgraph - got image for '%s'", pluginName, project.getName()));
        return imageFile;
    }

    return null;
}

From source file:gov.nasa.jpl.magicdraw.projectUsageIntegrity.graph.SSCAEProjectUsageGraph.java

/**
 * @param pugDOT gv file// ww  w .  j  a  va 2  s  .co  m
 * @return true if the graphviz application was opened successfully for the gv file.
 * @throws IIOException
 * @throws IOException
 * @throws InterruptedException
 */
public boolean openDOTFileWithGraphViz(@Nonnull File pugDOT)
        throws IIOException, IOException, InterruptedException {
    String graphvizApp = ProjectUsageIntegrityPlugin.getInstance().getGraphvizApplicationPath();
    if (null == graphvizApp)
        return false;

    File pugTemp = pugDOT.getParentFile();

    CommandLine cmdLine;

    switch (SSCAEProjectUsageIntegrityOptions.getCurrentPlatform()) {
    case LINUX:
        cmdLine = new CommandLine(graphvizApp);
        break;
    case MACOSX:
        cmdLine = new CommandLine("/usr/bin/open");
        cmdLine.addArgument("-a");
        cmdLine.addArgument(graphvizApp);
        break;
    case WINDOWS:
        cmdLine = new CommandLine("cmd");
        cmdLine.addArgument("/c");
        cmdLine.addArgument("start");
        cmdLine.addArgument(graphvizApp);
        break;
    default:
        return false;
    }
    cmdLine.addArgument(pugDOT.getName());

    pluginLog.info(String.format("%s - openDOTFileWithGraphViz - opening DOT file for project: '%s'",
            pluginName, project.getName()));

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000);

    // consider '0' exit value as success.
    Executor executor = new DefaultExecutor();
    executor.setExitValue(0);
    executor.setWatchdog(watchdog);
    executor.setWorkingDirectory(pugTemp);
    executor.execute(cmdLine, resultHandler);

    resultHandler.waitFor();

    if (executor.isFailure(resultHandler.getExitValue())) {
        pluginLog.error(String.format(
                "%s - openDOTFileWithGraphViz - error while opening DOT file for project '%s' from: '%s'",
                pluginName, project.getName(), pugDOT.getAbsolutePath()), resultHandler.getException());
        return false;
    }

    pluginLog.info(String.format("%s - openDOTFileWithGraphViz - opened DOT file for project '%s' from: '%s'",
            pluginName, project.getName(), pugDOT.getAbsolutePath()));
    return true;
}

From source file:net.sourceforge.seqware.pipeline.plugins.ITUtility.java

/**
 * Run an arbitrary command and check it against an expected return value
 *
 * @param line//from w  ww . ja va2s  .  co  m
 * @param expectedReturnValue
 * @param dir working directory, can be null if you don't want to change directories
 * @return
 * @throws IOException
 */
public static String runArbitraryCommand(String line, int expectedReturnValue, File dir) throws IOException {
    Log.info("Running " + line);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    CommandLine commandline = CommandLine.parse(line);
    DefaultExecutor exec = new DefaultExecutor();
    if (dir != null) {
        exec.setWorkingDirectory(dir);
    }
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    exec.setStreamHandler(streamHandler);
    exec.setExitValue(expectedReturnValue);
    try {
        int exitValue = exec.execute(commandline);
        Assert.assertTrue(
                "exit value for full jar with no params should be " + expectedReturnValue + " was " + exitValue,
                exitValue == expectedReturnValue);
        String output = outputStream.toString();
        return output;
    } catch (ExecuteException e) {
        Log.error("Execution failed with:");
        Log.error(outputStream.toString());
        throw e;
    }
}

From source file:net.spinetrak.rpitft.command.Command.java

Result execute(final Stream stream_) {
    final CommandLine commandline = CommandLine.parse(_script);
    final DefaultExecutor exec = new DefaultExecutor();
    final ExecuteWatchdog watchdog = new ExecuteWatchdog(500);
    exec.setWatchdog(watchdog);//from   www.  j  a v  a  2  s  .co m
    final PumpStreamHandler streamHandler = new PumpStreamHandler(stream_.getStream());
    exec.setStreamHandler(streamHandler);
    int result = -1;
    try {
        result = exec.execute(commandline);
    } catch (final IOException ex_) {
        //LOGGER.error(ex_.getMessage());
    }
    return new Result(stream_, result);
}

From source file:net.test.aliyun.z7.Zip7Object.java

public static int extract(final String extToosHome, final String extractFile, final String toDir)
        throws Throwable {
    String cmdLine = String.format("%s\\7z.exe x \"%s\" -aoa -y \"-o%s\"", extToosHome, extractFile, toDir);
    CommandLine commandline = CommandLine.parse(cmdLine);
    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    DefaultExecutor executor = new DefaultExecutor();
    int extValue = -1;
    try {/*from  ww  w.java 2 s . com*/
        executor.execute(commandline, resultHandler);
        resultHandler.waitFor(300 * 1000);
        extValue = resultHandler.getExitValue();
        if (extValue == 0) {
            new File(extractFile).delete();
        }
    } catch (Exception e) {
        //
    } finally {
        if (extValue != 0) {
            FileUtils.deleteDir(new File(toDir));
            return extValue;
        }
    }
    //
    Iterator<File> itFile = FileUtils.iterateFiles(new File(toDir), FileFilterUtils.fileFileFilter(),
            FileFilterUtils.directoryFileFilter());
    while (itFile.hasNext()) {
        File it = itFile.next();
        if (it.isDirectory())
            continue;
        for (String com : compression) {
            if (StringUtils.endsWithIgnoreCase(it.getName(), com)) {
                String itPath = it.getAbsolutePath();
                String subToDir = itPath.substring(0, itPath.length() - com.length());
                extract(extToosHome, itPath, subToDir);
            }
        }
    }
    return 0;
}

From source file:net.tkausl.RunMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    File plugins = pluginfolder == null ? new File(serverPath, "plugins") : new File(serverPath, pluginfolder);
    if (!plugins.exists())
        plugins.mkdirs();/* w ww . ja  v  a 2s .  co m*/

    File pluginFile = new File(plugins, fileName + ".dev");
    if (!pluginFile.exists()) {
        try {
            PrintWriter w = new PrintWriter(pluginFile);
            w.print(outputDir);
            w.close();
        } catch (FileNotFoundException ex) {
            throw new MojoExecutionException("Could not write .dev-file");
        }
    }
    Executor ex = new DefaultExecutor();
    CommandLine commandLine = CommandLine.parse("java");
    String execArgs = System.getProperty("exec.args");
    if (execArgs != null && execArgs.trim().length() > 0) {
        commandLine.addArguments(execArgs.split(" "));
    }
    commandLine.addArguments(new String[] { "-jar", serverJar });

    if (pluginfolder != null)
        commandLine.addArguments(new String[] { "--plugins", pluginfolder });

    ex.setWorkingDirectory(serverPath);
    //PumpStreamHandler psh = new PumpStreamHandler(System.out, System.err, System.in);
    //ex.setStreamHandler(psh);
    ex.setStreamHandler(new ExecuteStreamHandler() {
        private PumpStreamHandler psh = new PumpStreamHandler(System.out, System.err);
        InputStreamPumper isp;
        Thread ispt;

        public void setProcessInputStream(OutputStream os) throws IOException {
            isp = new InputStreamPumper(System.in, os);
        }

        public void setProcessErrorStream(InputStream is) throws IOException {
            psh.setProcessErrorStream(is);
        }

        public void setProcessOutputStream(InputStream is) throws IOException {
            psh.setProcessOutputStream(is);
        }

        public void start() throws IOException {
            if (isp != null) {
                ispt = new Thread(isp);
                ispt.setDaemon(true);
                ispt.start();
            }
            psh.start();
        }

        public void stop() throws IOException {
            if (ispt != null)
                ispt.interrupt();
            psh.stop();
        }
    });
    try {
        ex.execute(commandLine);
    } catch (IOException ex1) {
        throw new MojoExecutionException("Error in Execution");
    }
}

From source file:nl.tudelft.graphalytics.graphlab.AlgorithmTest.java

protected boolean executeTestScript(File scriptFile, String graphFile, String outputFile) {
    if (!scriptFile.exists()) {
        throw new IllegalArgumentException("Cannot find GraphLab Test script: " + scriptFile.getAbsolutePath());
    }//from ww  w  .  ja v  a2  s .com

    CommandLine commandLine = new CommandLine("python2");
    commandLine.addArgument(scriptFile.getAbsolutePath());
    commandLine.addArgument(graphFile);
    commandLine.addArgument(outputFile);

    // Set the executor of the command, if desired this can be changed to a custom implementation
    DefaultExecutor executor = new DefaultExecutor();

    // Set the OutputStream to enable printing the output of the algorithm
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(outputStream));

    try {
        // Execute the actual command and store the return code
        executor.execute(commandLine);
        // Print the command output
        System.out.println(outputStream.toString());
        return true;
    } catch (IOException e) {
        // Catch the exception thrown when the process exits with result != 0 or another IOException occurs
        System.out.println(outputStream.toString());
        return false;
    }
}

From source file:nl.tudelft.graphalytics.graphlab.GraphLabPlatform.java

/**
 * Execute the python script belonging to a given AlgorithmType with the given graph location and extra arguments
 * and return the Process created by the Java Runtime.
 * @param job The GraphLab job to execute
 * @return The exit code of the python subprocess
 * @throws IOException When an I/O error occurs
 *//*from ww  w.  j  a v  a2 s.c o m*/
private int executePythonJob(GraphLabJob job) throws IOException {
    LOG.entry(job);

    if (job == null) {
        LOG.warn("GraphLab job set to execute is null, skipping execution.");
        return LOG.exit(-1);
    }

    // Extract the script resource file
    File scriptFile = extractFile(job.getPythonFile());
    if (scriptFile == null) {
        return LOG.exit(-1);
    }

    // Construct the commandline execution pattern starting with the python executable
    CommandLine commandLine = new CommandLine("python2");

    // Add the arguments that are the same for all jobs
    commandLine.addArgument(scriptFile.getAbsolutePath());
    commandLine.addArgument("--target");
    commandLine.addArgument(TARGET);
    if (USE_HADOOP) {
        commandLine.addArgument("--virtual-cores");
        commandLine.addArgument(VIRTUAL_CORES, false);
        commandLine.addArgument("--heap-size");
        commandLine.addArgument(HEAP_SIZE, false);
    }

    // Add the save_graph_result parameter is true (default false, but can be set to true for automated testing)
    if (saveGraphResult) {
        commandLine.addArgument("--save-result");
    }

    // Let the job format it's arguments and add it to the commandline
    commandLine.addArguments(job.formatParametersAsStrings(), false);

    // Set the executor of the command, if desired this can be changed to a custom implementation
    DefaultExecutor executor = new DefaultExecutor();

    // Set the OutputStream to enable printing the output of the algorithm
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(outputStream));

    int result;
    try {
        // Execute the actual command and store the return code
        result = executor.execute(commandLine);
        // Print the command output
        System.out.println(outputStream.toString());
    } catch (ExecuteException e) {
        // Catch the exception thrown when the process exits with result != 0
        System.out.println(outputStream.toString());
        LOG.catching(Level.ERROR, e);
        return LOG.exit(e.getExitValue());
    }
    return LOG.exit(result);
}

From source file:npanday.plugin.partcover.AbstractPartCoverMojo.java

protected int executeCommandLine(String line) throws ExecuteException, IOException {
    CommandLine commandLine = CommandLine.parse(line);
    DefaultExecutor executor = new DefaultExecutor();
    return executor.execute(commandLine);
}