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

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

Introduction

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

Prototype

public CommandLine(final CommandLine other) 

Source Link

Document

Copy constructor.

Usage

From source file:com.tibco.tgdb.test.lib.TGServer.java

/**
 * Initialize the TG server synchronously. This Init operation blocks until
 * it is completed.//ww w. j  av  a 2s .  c o  m
 * 
 * @param initFile
 *            TG server init config file
 * @param forceCreation
 *            Force creation. Delete all the data in the db directory first.
 * @param timeout
 *            Number of milliseconds allowed to initialize the server
 * @return the output stream of init operation 
 * @throws TGInitException
 *             Init operation fails or timeout occurs 
 */
public String init(String initFile, boolean forceCreation, long timeout) throws TGInitException {

    File initF = new File(initFile);
    if (!initF.exists())
        throw new TGInitException("TGServer - Init file '" + initFile + "' does not exist");
    try {
        this.setInit(initF);
    } catch (TGGeneralException e) {
        throw new TGInitException(e.getMessage());
    }

    //ByteArrayOutputStream output = new ByteArrayOutputStream();

    PumpStreamHandler psh = new PumpStreamHandler(new ByteArrayOutputStream());
    Executor tgExec = new DefaultExecutor();
    tgExec.setStreamHandler(psh);
    tgExec.setWorkingDirectory(new File(this.home + "/bin"));
    CommandLine tgCL = new CommandLine((new File(this.home + "/bin/" + process)).getAbsolutePath());
    if (forceCreation)
        tgCL.addArguments(new String[] { "-i", "-f", "-Y", "-c", initFile, "-l", this.initLogFileBase });
    else
        tgCL.addArguments(new String[] { "-i", "-Y", "-c", initFile, "-l", this.initLogFileBase });

    ExecuteWatchdog tgWatch = new ExecuteWatchdog(timeout);
    tgExec.setWatchdog(tgWatch);
    System.out.println("TGServer - Initializing " + StringUtils.toString(tgCL.toStrings(), " "));
    String output = "";
    try {
        tgExec.execute(tgCL);
        output = new String(Files.readAllBytes(Paths.get(this.getInitLogFile().toURI())));
    } catch (IOException ee) {
        if (tgWatch.killedProcess())
            throw new TGInitException("TGServer - Init did not complete within " + timeout + " ms");
        else {
            try {
                Thread.sleep(1000); // make sure output has time to fill up

            } catch (InterruptedException ie) {
                ;
            }
            throw new TGInitException("TGServer - Init failed: " + ee.getMessage(), output);
        }
    }
    try {
        this.setBanner(output);
    } catch (TGGeneralException tge) {
        throw new TGInitException(tge.getMessage());
    }

    if (output.contains("TGSuccess")) {
        System.out.println("TGServer - Initialized successfully");
        return output;
    } else
        throw new TGInitException("TGServer - Init failed", output);
}

From source file:com.tibco.tgdb.test.lib.TGServer.java

/**
 * Start the TG server synchronously.//w w  w  .  ja  v  a 2 s. com
 * 
 * @param timeout
 *            Number of milliseconds allowed to start the server
 * @throws TGStartException Start operation fails
 */
public void start(long timeout) throws TGStartException {

    if (this.configFile == null)
        throw new TGStartException("TGServer - Config file not set");

    if (this.logFile == null)
        this.setLogFile("tgdb_" + this.dbName);

    //this.outStream = new ByteArrayOutputStream(); // reset
    //this.errStream = new ByteArrayOutputStream(); // reset
    PumpStreamHandler psh = new PumpStreamHandler(new ByteArrayOutputStream());
    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    Executor tgExec = new DefaultExecutor();
    tgExec.setWorkingDirectory(new File(this.home + "/bin"));
    tgExec.setStreamHandler(psh);
    CommandLine tgCL = new CommandLine((new File(this.home + "/bin/" + process)).getAbsolutePath());
    tgCL.addArguments(new String[] { "-s", "-c", this.configFile.getAbsolutePath(), "-l", this.logFileBase });

    System.out.println("TGServer - Starting " + StringUtils.toString(tgCL.toStrings(), " "));
    try {
        tgExec.execute(tgCL, resultHandler);
    } catch (IOException ioe) {
        try {
            Thread.sleep(1000); // Make sure output/error fill up
        } catch (InterruptedException ie) {
            ;
        }
        throw new TGStartException(ioe.getMessage());
    }

    if (timeout > 0) {
        Calendar future = Calendar.getInstance();
        future.add(Calendar.MILLISECOND, (int) timeout);
        boolean started = false;
        boolean error = false;
        List<String> acceptedClients = new ArrayList<String>();
        String acceptedClient;
        while (!future.before(Calendar.getInstance())) {
            try {
                Thread.sleep(1000);
                BufferedReader reader = new BufferedReader(new StringReader(this.getOutput()));
                String line = reader.readLine();
                while (line != null) {
                    if (line.contains("Process pid:"))
                        this.setPid(Integer.parseInt(line.substring(line.lastIndexOf("Process pid:") + 12,
                                line.indexOf(",", line.lastIndexOf("Process pid:") + 12))));
                    if (line.contains("[Error]")) {
                        error = true;
                    }
                    if (line.contains("Accepting clients on")) {
                        started = true;
                        acceptedClient = line.substring(line.indexOf("- Accepting clients on") + 2);
                        if (!acceptedClients.contains(acceptedClient))
                            acceptedClients.add(acceptedClient);
                    }
                    line = reader.readLine();
                }
                reader.close();
                if (started)
                    break;
            } catch (Exception e) {
                throw new TGStartException("TGServer - " + e.getMessage());
            }
        }
        if (!started)
            throw new TGStartException(
                    "TGServer - Did not start on time (after " + timeout + " msec) - See log " + this.logFile);
        else {
            this.running = true;
            System.out.println("TGServer - Started successfully with pid " + this.pid + " :");
            System.out.println("\t\t- Log file: " + this.logFile);
            if (error)
                System.out.println("\t\t- With some error(s) - See log");
            for (String client : acceptedClients)
                System.out.println("\t\t- " + client);
            try {
                this.setBanner(this.getOutput());
            } catch (TGGeneralException tge) {
                throw new TGStartException(tge.getMessage());
            }
        }
    }
}

From source file:fr.fastconnect.factory.tibco.bw.maven.AbstractBWMojo.java

/**
 * This calls a TIBCO binary.//  w w w.j  a v  a 2s . c o  m
 * 
 * @param binary, the TIBCO binary file to execute
 * @param tras, the TRA files associated with the TIBCO binary
 * @param arguments, command-line arguments
 * @param workingDir, working directory from where the binary is launched
 * @param errorMsg, error message to display in case of a failure
 * @param fork, if true the chiild process will be detached from the caller
 * 
 * @throws IOException
 * @throws MojoExecutionException
 */
protected int launchTIBCOBinary(File binary, List<File> tras, ArrayList<String> arguments, File workingDir,
        String errorMsg, boolean fork, boolean synchronous) throws IOException, MojoExecutionException {
    Integer result = 0;

    if (tras == null) { // no value specified as Mojo parameter, we use the .tra in the same directory as the binary
        String traPathFileName = binary.getAbsolutePath();
        traPathFileName = FilenameUtils.removeExtension(traPathFileName);
        traPathFileName += ".tra";
        tras = new ArrayList<File>();
        tras.add(new File(traPathFileName));
    }

    HashMap<File, File> trasMap = new HashMap<File, File>();
    for (File tra : tras) {
        // copy of ".tra" file in the working directory
        File tmpTRAFile = new File(directory, tra.getName());
        trasMap.put(tra, tmpTRAFile);
        copyFile(tra, tmpTRAFile);
    }

    for (File tra : trasMap.keySet()) {
        if (trasMap.containsKey(tibcoDesignerTRAPath)
                && ((tibcoBuildEARUseDesignerTRA && tra == tibcoBuildEARTRAPath)
                        || (tibcoBuildLibraryUseDesignerTRA && tra == tibcoBuildLibraryTRAPath))) {
            if (tras.size() > 1) {
                ReplaceRegExp replaceRegExp = new ReplaceRegExp();
                replaceRegExp.setFile(trasMap.get(tra));
                replaceRegExp.setMatch("tibco.include.tra (.*/designer.tra)");
                replaceRegExp.setReplace(
                        "tibco.include.tra " + trasMap.get(tibcoDesignerTRAPath).toString().replace('\\', '/'));
                replaceRegExp.setByLine(true);

                replaceRegExp.execute();
            }
        }

        if (tra == tibcoBuildEARTRAPath || tra == tibcoDesignerTRAPath || tra == tibcoBWEngineTRAPath) { // FIXME: should check more properly
            // append user.home at the end to force the use of custom Designer5.prefs
            PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(trasMap.get(tra), true)));
            out.println("");
            out.println("java.property.user.home=" + directory.getAbsolutePath().replace("\\", "/"));
            out.close();
        }
    }

    CommandLine cmdLine = new CommandLine(binary);

    for (String argument : arguments) {
        cmdLine.addArgument(argument);
    }
    getLog().debug("launchTIBCOBinary command line : " + cmdLine.toString());
    getLog().debug("working dir : " + workingDir);

    DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(workingDir);

    if (timeOut > 0) {
        ExecuteWatchdog watchdog = new ExecuteWatchdog(timeOut * 1000);
        executor.setWatchdog(watchdog);
    }

    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());

    ByteArrayOutputStream stdOutAndErr = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(stdOutAndErr));

    if (fork) {
        CommandLauncher commandLauncher = CommandLauncherFactory.createVMLauncher();
        commandLauncher.exec(cmdLine, null, workingDir);
    } else {
        try {
            if (synchronous) {
                result = executor.execute(cmdLine);
            } else {
                executor.execute(cmdLine, new DefaultExecuteResultHandler());
            }
        } catch (ExecuteException e) {
            // TODO : grer erreurs des excutables (ventuellement parser les erreurs classiques)
            getLog().info(cmdLine.toString());
            getLog().info(stdOutAndErr.toString());
            getLog().info(result.toString());
            throw new MojoExecutionException(errorMsg, e);
        } catch (IOException e) {
            throw new MojoExecutionException(e.getMessage(), e);
        }
    }

    return result;
}

From source file:it.drwolf.ridire.index.cwb.CWBPatternSearcher.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;/*from   ww w. j  a  v  a  2 s.c  o m*/
    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(CWBPatternSearcher.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: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;/*from  w  w w  .j a v a  2 s  .  c om*/
    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  w ww .ja v a2  s . com*/
    }

    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/*from   w w  w.j  av a 2 s. com*/
 * @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.vulcan.git.ProcessInvoker.java

public InvocationResult invoke(String command, File workDir, String... args) throws IOException {
    CommandLine cmdLine = new CommandLine(executable);

    cmdLine.addArgument(command);//w  w  w  .j  a  va 2 s. c om
    cmdLine.addArgument("--noninteractive");
    cmdLine.addArguments(args, false);

    err = new ByteArrayOutputStream();

    executor.setExitValues(new int[] { 0, 1 });
    executor.setWorkingDirectory(workDir);
    executor.setStreamHandler(new MyPumpStreamHandler(out, err));

    LOG.debug("Executing " + cmdLine);

    try {
        exitCode = executor.execute(cmdLine);
        return new InvocationResult(isOutputRedirected() ? null : out.toString(), err.toString(),
                exitCode == 0);
    } catch (ExecuteException e) {
        exitCode = e.getExitValue();
        throw e;
    }

}

From source file:net.sourceforge.vulcan.git.ProcessInvokerTest.java

private InvocationResult doInvokeTest() throws ExecuteException, IOException {
    CommandLine commandLine = new CommandLine(executable);
    commandLine.addArgument("help");
    commandLine.addArgument("--noninteractive");
    commandLine.addArgument("arg 1", false);
    commandLine.addArgument("arg 2", false);

    executor.setExitValues(reflectionEq(new int[] { 0, 1 }));
    executor.setWorkingDirectory(new File("."));
    executor.setStreamHandler((ExecuteStreamHandler) notNull());

    expectLastCall().andAnswer(captureStreamHandler);
    expect(executor.execute(stringEq(commandLine))).andAnswer(executeAnswer);

    replay();/*from w w w .j  ava 2 s. c om*/

    if (outputStream != null) {
        invoker.setOutputStream(outputStream);
    }

    invoker.setExecutable(executable);
    result = invoker.invoke("help", new File("."), "arg 1", "arg 2");

    verify();

    return result;
}

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 . j av  a 2s  . c om

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