Example usage for java.lang Runtime exec

List of usage examples for java.lang Runtime exec

Introduction

In this page you can find the example usage for java.lang Runtime exec.

Prototype

public Process exec(String cmdarray[]) throws IOException 

Source Link

Document

Executes the specified command and arguments in a separate process.

Usage

From source file:org.formic.util.CommandExecutor.java

/**
 * Run the thread./* w ww  .  j a va  2s.  com*/
 */
public void run() {
    logger.info(this.toString());
    Runtime runtime = Runtime.getRuntime();
    try {
        process = runtime.exec(cmd);

        shutdownHook = new ShutdownHook();
        try {
            runtime.addShutdownHook(shutdownHook);
        } catch (IllegalStateException ignore) {
            // happens if this is called during shutdown
        }

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Thread outThread = createOutThread(out);
        outThread.start();

        ByteArrayOutputStream err = new ByteArrayOutputStream();
        Thread errThread = createErrThread(err);
        errThread.start();

        returnCode = process.waitFor();
        outThread.join(1000);
        errThread.join(1000);

        if (result == null) {
            result = out.toString();
        }
        if (error == null) {
            error = err.toString();
        }
    } catch (Exception e) {
        returnCode = 12;
        error = e.getMessage();
        e.printStackTrace();
    } finally {
        if (shutdownHook != null) {
            try {
                runtime.removeShutdownHook(shutdownHook);
            } catch (IllegalStateException ignore) {
                // happens if this is called during shutdown
            }
        }
    }
}

From source file:canreg.client.analysis.Tools.java

public static LinkedList<String> callR(String rScript, String rpath, String reportFileName)
        throws TableErrorException {
    LinkedList<String> filesCreated = new LinkedList<String>();
    Runtime rt = Runtime.getRuntime();
    ArrayList<String> commandList = new ArrayList<String>();
    commandList.add(rpath);//from w  w w  .  ja va2  s  .  co m
    commandList.add("CMD");
    commandList.add("BATCH");
    commandList.add("--vanilla");
    commandList.add("--slave");
    commandList.add(rScript);
    commandList.add(reportFileName);

    //String command = canreg.common.Tools.encapsulateIfNeeded(rpath)
    //        + " CMD BATCH --vanilla --slave "
    //        + canreg.common.Tools.encapsulateIfNeeded(rScript) + " "
    //        + canreg.common.Tools.encapsulateIfNeeded(reportFileName);
    System.out.println(commandList);
    Process pr = null;
    try {
        pr = rt.exec(commandList.toArray(new String[] {}));
        // collect the output from the R program in a stream
        // BufferedInputStream is = new BufferedInputStream(pr.getInputStream());
        pr.waitFor();
        BufferedInputStream is = new BufferedInputStream(new FileInputStream(reportFileName));
        // convert the output to a string
        String theString = convertStreamToString(is);
        Logger.getLogger(RTableBuilderGrouped.class.getName()).log(Level.INFO, "Messages from R: \n{0}",
                theString);
        // System.out.println(theString);
        // and add all to the list of files to return
        for (String fileName : theString.split("\n")) {
            if (fileName.startsWith("-outFile:")) {
                fileName = fileName.replaceFirst("-outFile:", "");
                if (new File(fileName).exists()) {
                    filesCreated.add(fileName);
                }
            }
        }
    } catch (InterruptedException ex) {
        Logger.getLogger(RTableBuilder.class.getName()).log(Level.SEVERE, null, ex);
    } catch (java.util.NoSuchElementException ex) {
        Logger.getLogger(RTableBuilder.class.getName()).log(Level.SEVERE, null, ex);
        if (pr != null) {
            BufferedInputStream errorStream = new BufferedInputStream(pr.getErrorStream());
            String errorMessage = convertStreamToString(errorStream);
            System.out.println(errorMessage);
            throw new TableErrorException("R says:\n \"" + errorMessage + "\"");
        }
    } catch (IOException ex) {
        Logger.getLogger(Tools.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        if (pr != null) {
            System.out.println(pr.exitValue());
        }
    }
    return filesCreated;
}

From source file:org.openmeetings.app.documents.GenerateThumbs.java

public HashMap<String, String> processImageWindows(String[] args) {
    HashMap<String, String> returnMap = new HashMap<String, String>();
    returnMap.put("process", "processImageWindows");
    try {/*from   ww  w .  ja  v a2s .  c o  m*/

        // Init variables
        String[] cmd;
        String executable_fileName = "";

        String runtimeFile = "interviewMerge.bat";
        executable_fileName = ScopeApplicationAdapter.batchFileDir + runtimeFile;

        cmd = new String[4];
        cmd[0] = "cmd.exe";
        cmd[1] = "/C";
        cmd[2] = "start";
        cmd[3] = executable_fileName;

        // log.debug("executable_fileName: "+executable_fileName);

        // Create the Content of the Converter Script (.bat or .sh File)

        String fileContent = "";

        for (int k = 0; k < args.length; k++) {
            if (k != 0) {
                fileContent += " ";
            }
            fileContent += args[k];
        }

        fileContent += ScopeApplicationAdapter.lineSeperator + "exit";

        File previous = new File(executable_fileName);
        if (previous.exists()) {
            previous.delete();
        }

        // execute the Script
        FileOutputStream fos = new FileOutputStream(executable_fileName);
        fos.write(fileContent.getBytes());
        fos.close();

        Runtime rt = Runtime.getRuntime();
        returnMap.put("command", cmd.toString());

        Process proc = rt.exec(cmd);

        InputStream stderr = proc.getErrorStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(stderr));
        String line = null;
        String error = "";
        while ((line = br.readLine()) != null) {
            error += line;
            // log.debug("line: "+line);
        }
        br.close();
        returnMap.put("error", error);
        int exitVal = proc.waitFor();
        returnMap.put("exitValue", "" + exitVal);
        return returnMap;
    } catch (Throwable t) {
        t.printStackTrace();
        returnMap.put("error", t.getMessage());
        returnMap.put("exitValue", "-1");
        return returnMap;
    }
}

From source file:org.squale.squalix.tools.clearcase.ClearCaseTaskTest.java

/**
 * Supprime / dmonte la vue ClearCase.//  w  w  w  .  j  a  v a2  s.c o m
 */
protected void umountView() {
    try {
        Runtime runtime = Runtime.getRuntime();
        Process processCleanView = runtime.exec(mCct.getConfiguration().getUmountViewCommand());

        /* le processus se termine correctement */
        processCleanView.waitFor();

        processCleanView = null;
        runtime = null;
    } catch (Exception e) {
        LOGGER.error(e, e);
    }
}

From source file:edu.ucsb.eucalyptus.cloud.ws.HttpReader.java

private void getResponseToFile() {
    byte[] bytes = new byte[StorageProperties.TRANSFER_CHUNK_SIZE];
    FileOutputStream fileOutputStream = null;
    BufferedOutputStream bufferedOut = null;
    try {/*  w  w w. jav  a2  s  . co m*/
        File outFile;
        File outFileUncompressed = null;
        if (compressed) {
            String outFileNameUncompressed = tempPath + File.separator + file.getName() + Hashes.getRandom(16);
            outFileUncompressed = new File(outFileNameUncompressed);
            outFile = new File(outFileNameUncompressed + ".gz");
        } else {
            outFile = file;
        }
        httpClient.executeMethod(method);
        InputStream httpIn;
        httpIn = method.getResponseBodyAsStream();
        int bytesRead;
        fileOutputStream = new FileOutputStream(outFile);
        bufferedOut = new BufferedOutputStream(fileOutputStream);
        while ((bytesRead = httpIn.read(bytes)) > 0) {
            bufferedOut.write(bytes, 0, bytesRead);
        }
        bufferedOut.close();
        if (compressed) {
            try {
                Runtime rt = Runtime.getRuntime();
                Process proc = rt.exec(new String[] { "/bin/gunzip", outFile.getAbsolutePath() });
                StreamConsumer error = new StreamConsumer(proc.getErrorStream());
                StreamConsumer output = new StreamConsumer(proc.getInputStream());
                error.start();
                output.start();
                output.join();
                error.join();
            } catch (Exception t) {
                LOG.error(t);
            }
            if ((outFileUncompressed != null) && (!outFileUncompressed.renameTo(file))) {
                LOG.error("Unable to uncompress: " + outFile.getAbsolutePath());
                return;
            }
        }
    } catch (Exception ex) {
        LOG.error(ex, ex);
    } finally {
        method.releaseConnection();
        if (bufferedOut != null) {
            try {
                bufferedOut.close();
            } catch (IOException e) {
                LOG.error(e);
            }
        }
        if (fileOutputStream != null) {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                LOG.error(e);
            }
        }
    }
}

From source file:org.squale.squalix.tools.clearcase.ClearCaseTaskTest.java

/**
 * Vrifie si la vue a bien t monte, i.e. si le fichier <code>.vws</code> existe.
 * /*from   w w w .j a  v a  2s .c  o  m*/
 * @return <code>true</code> en cas de succs, <code>
 * false</code> sinon.
 */
private boolean checkViewExistence() {
    boolean alreadyMounted = false;
    try {
        /* initialisation du runtime. */
        Runtime runtime = Runtime.getRuntime();
        Process processViewExist = runtime.exec(mCct.getConfiguration().getVerifyViewExistenceCommand());

        /* si la commande est excute avec succs. */
        if (0 == processViewExist.waitFor()) {
            alreadyMounted = true;
        }

        processViewExist = null;
        runtime = null;
    } catch (Exception e) {
        LOGGER.error(e, e);
        alreadyMounted = false;
    }
    return alreadyMounted;
}

From source file:oscar.util.OscarStatusAction.java

private String getFilesystemStatus() {
    String output = "$ df -h\n";

    Runtime r = Runtime.getRuntime();
    try {//from  w ww .ja  v a  2 s .  c om
        Process p = r.exec("df -h");
        InputStream in = p.getInputStream();
        InputStreamReader isr = new InputStreamReader(in);
        BufferedReader br = new BufferedReader(isr);
        String line;

        while ((line = br.readLine()) != null) {
            output += line + "\n";
        }

    } catch (IOException e) {
        output += "[An error has been encountered.]\n";
        output += "[" + e.getMessage() + "]\n";
    }

    return output;
}

From source file:oscar.util.OscarStatusAction.java

private String uptime() {
    String output = "$ uptime\n";

    Runtime r = Runtime.getRuntime();
    try {/*ww  w.j a  va2 s. c om*/
        Process p = r.exec("uptime");
        InputStream in = p.getInputStream();
        InputStreamReader isr = new InputStreamReader(in);
        BufferedReader br = new BufferedReader(isr);
        String line;

        while ((line = br.readLine()) != null) {
            output += line + "\n";
        }

    } catch (IOException e) {
        output += "[An error has been encountered.]\n";
        output += "[" + e.getMessage() + "]\n";
    }

    return output;
}

From source file:oscar.util.OscarStatusAction.java

private String vmstat() {
    String output = "$ vmstat\n";

    Runtime r = Runtime.getRuntime();
    try {// www  . j  a  v  a2 s .c om
        Process p = r.exec("vmstat");
        InputStream in = p.getInputStream();
        InputStreamReader isr = new InputStreamReader(in);
        BufferedReader br = new BufferedReader(isr);
        String line;

        while ((line = br.readLine()) != null) {
            output += line + "\n";
        }

    } catch (IOException e) {
        output += "[An error has been encountered.]\n";
        output += "[" + e.getMessage() + "]\n";
    }

    return output;
}

From source file:spms.client.Solver.java

public void executePDDL(javax.swing.JTextArea t, javax.swing.JButton b) { //Through this method will call planner and give it generatorFile that chosen by client and receive planner output to be sent to the server
    System.out.println("STTTTTTTTTTTTTTTTTTTTTTTTT");
    //TODO: call to planner software & send the generator file to planner

    String planner_path = "/home/yazeedalmusharraf/Desktop/gameProject/SPMS_Project/";
    int randomNum = 1 + (int) (Math.random() * 1000);
    String path = planner_path + game.getGameName() + "/plan" + randomNum + ".pddl";

    Runtime run = Runtime.getRuntime();
    try {/*  w w  w.jav  a 2 s .c o m*/

        // System.out.println(planner_path+"planner/FF-v2.3/./ff -o "+planner_path+game.getGameName()+"/domain.pddl -f "+planner_path+game.getGameName()+"/genfile.pddl");
        pddlProcces = run.exec(planner_path + "planner/FF-v2.3/./ff -o " + planner_path + game.getGameName()
                + "/domain.pddl -f " + planner_path + game.getGameName() + "/genfile.pddl");
        BufferedReader d = new BufferedReader(new InputStreamReader(pddlProcces.getInputStream()));
        FileOutputStream out = new FileOutputStream(path);

        String line;
        while ((line = d.readLine()) != null) {
            t.append(line + "\n");
            out.write(line.getBytes());
            out.write("\n".getBytes());
        }
        out.close();
        String f = t.getText().replace("\n", SysConst.ENDL);
        b.setVisible(true);
        session.send(SysConst.SEND_FINISHED_GMAE + f);

    } catch (Exception ex) {
        ex.printStackTrace();
    }

}