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:com.wdeanmedical.portal.service.AppService.java

public String uploadProfileImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String patientId = request.getParameter("patientId");
    InputStream is = null;/*from w ww.ja v a  2  s.  co  m*/
    FileOutputStream fos = null;
    String returnString = "";

    is = request.getInputStream();
    String filename = request.getHeader("X-File-Name");
    String filesHomePatientDirPath = Core.filesHome + Core.patientDirPath + "/" + patientId + "/";
    fos = new FileOutputStream(new File(filesHomePatientDirPath + filename));
    IOUtils.copy(is, fos);
    response.setStatus(HttpServletResponse.SC_OK);
    fos.close();
    is.close();

    String[] imageMagickArgs = { Core.imageMagickHome + "convert", filesHomePatientDirPath + filename,
            "-resize", "160x160", filesHomePatientDirPath + filename };
    Runtime runtime = Runtime.getRuntime();
    Process process = runtime.exec(imageMagickArgs);

    InputStream pis = process.getInputStream();
    InputStreamReader isr = new InputStreamReader(pis);
    BufferedReader br = new BufferedReader(isr);
    String line;
    log.info("Output of running " + Arrays.toString(imageMagickArgs) + "is: ");

    while ((line = br.readLine()) != null) {
        log.info(line);
    }
    log.info("\n" + filename + " uploaded");

    Patient patient = appDAO.findPatientById(new Integer(patientId));
    appDAO.updatePatientProfileImage(patient, filename);

    returnString = "{\"filename\":\"" + filename + "\"}";
    activityLogService.logViewPatient(patient.getId(), null, patient.getId(), "UploadProfileImage");
    return returnString;
}

From source file:ch.kostceco.tools.siardexcerpt.excerption.moduleexcerpt.impl.ExcerptCGrepModuleImpl.java

@Override
public boolean validate(File siardDatei, File outFile, String excerptString) throws ExcerptCGrepException {
    // Ausgabe -> Ersichtlich das SIARDexcerpt arbeitet
    int onWork = 41;

    boolean isValid = true;

    File fGrepExe = new File("resources" + File.separator + "grep" + File.separator + "grep.exe");
    String pathToGrepExe = fGrepExe.getAbsolutePath();
    if (!fGrepExe.exists()) {
        // grep.exe existiert nicht --> Abbruch
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C)
                + getTextResourceService().getText(ERROR_XML_C_MISSINGFILE, fGrepExe.getAbsolutePath()));
        return false;
    } else {//w  ww. j av  a2 s .co  m
        File fMsys10dll = new File("resources" + File.separator + "grep" + File.separator + "msys-1.0.dll");
        if (!fMsys10dll.exists()) {
            // msys-1.0.dll existiert nicht --> Abbruch
            getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C)
                    + getTextResourceService().getText(ERROR_XML_C_MISSINGFILE, fMsys10dll.getAbsolutePath()));
            return false;
        }
    }

    File tempOutFile = new File(outFile.getAbsolutePath() + ".tmp");
    String content = "";

    // Record aus Maintable herausholen
    try {
        if (tempOutFile.exists()) {
            Util.deleteDir(tempOutFile);
        }

        /* Nicht vergessen in "src/main/resources/config/applicationContext-services.xml" beim
         * entsprechenden Modul die property anzugeben: <property name="configurationService"
         * ref="configurationService" /> */

        String name = getConfigurationService().getMaintableName();
        String folder = getConfigurationService().getMaintableFolder();
        String cell = getConfigurationService().getMaintablePrimarykeyCell();

        File fMaintable = new File(siardDatei.getAbsolutePath() + File.separator + "content" + File.separator
                + "schema0" + File.separator + folder + File.separator + folder + ".xml");

        try {
            // grep "<c11>7561234567890</c11>" table13.xml >> output.txt
            String command = "cmd /c \"" + pathToGrepExe + " \"<" + cell + ">" + excerptString + "</" + cell
                    + ">\" " + fMaintable.getAbsolutePath() + " >> " + tempOutFile.getAbsolutePath() + "\"";
            /* Das redirect Zeichen verunmglicht eine direkte eingabe. mit dem geschachtellten Befehl
             * gehts: cmd /c\"urspruenlicher Befehl\" */

            // System.out.println( command );

            Process proc = null;
            Runtime rt = null;

            getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_OPEN, name));

            try {
                Util.switchOffConsole();
                rt = Runtime.getRuntime();
                proc = rt.exec(command.toString().split(" "));
                // .split(" ") ist notwendig wenn in einem Pfad ein Doppelleerschlag vorhanden ist!

                // Fehleroutput holen
                StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");

                // Output holen
                StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");

                // Threads starten
                errorGobbler.start();
                outputGobbler.start();

                // Warte, bis wget fertig ist
                proc.waitFor();

                Util.switchOnConsole();

            } catch (Exception e) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C)
                        + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
                return false;
            } finally {
                if (proc != null) {
                    closeQuietly(proc.getOutputStream());
                    closeQuietly(proc.getInputStream());
                    closeQuietly(proc.getErrorStream());
                }
            }

            Scanner scanner = new Scanner(tempOutFile);
            content = "";
            try {
                content = scanner.useDelimiter("\\Z").next();
            } catch (Exception e) {
                // Grep ergab kein treffer Content Null
                content = "";
            }
            scanner.close();

            getMessageService()
                    .logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_CONTENT, content));
            getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_CLOSE, name));

            if (tempOutFile.exists()) {
                Util.deleteDir(tempOutFile);
            }
            content = "";

            // Ende Grep

        } catch (Exception e) {
            getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C)
                    + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
            return false;
        }

    } catch (Exception e) {
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C)
                + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
        return false;
    }

    // Ende MainTable

    // grep der SubTables
    try {
        String name = null;
        String folder = null;
        String cell = null;

        InputStream fin = new FileInputStream(
                new File("configuration" + File.separator + "SIARDexcerpt.conf.xml"));
        SAXBuilder builder = new SAXBuilder();
        Document document = builder.build(fin);
        fin.close();

        /* read the document and for each subTable */
        Namespace ns = Namespace.getNamespace("");

        // select schema elements and loop
        List<Element> subtables = document.getRootElement().getChild("subtables", ns).getChildren("subtable",
                ns);
        for (Element subtable : subtables) {
            name = subtable.getChild("name", ns).getText();
            folder = subtable.getChild("folder", ns).getText();
            cell = subtable.getChild("foreignkeycell", ns).getText();

            // System.out.println( name + " - " + folder + " - " + cell );
            File fSubtable = new File(siardDatei.getAbsolutePath() + File.separator + "content" + File.separator
                    + "schema0" + File.separator + folder + File.separator + folder + ".xml");

            try {
                // grep "<c11>7561234567890</c11>" table13.xml >> output.txt
                String command = "cmd /c \"" + pathToGrepExe + " \"<" + cell + ">" + excerptString + "</" + cell
                        + ">\" " + fSubtable.getAbsolutePath() + " >> " + tempOutFile.getAbsolutePath() + "\"";
                /* Das redirect Zeichen verunmglicht eine direkte eingabe. mit dem geschachtellten Befehl
                 * gehts: cmd /c\"urspruenlicher Befehl\" */

                // System.out.println( command );

                Process proc = null;
                Runtime rt = null;

                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_OPEN, name));

                try {
                    Util.switchOffConsole();
                    rt = Runtime.getRuntime();
                    proc = rt.exec(command.toString().split(" "));
                    // .split(" ") ist notwendig wenn in einem Pfad ein Doppelleerschlag vorhanden ist!

                    // Fehleroutput holen
                    StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");

                    // Output holen
                    StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");

                    // Threads starten
                    errorGobbler.start();
                    outputGobbler.start();

                    // Warte, bis wget fertig ist
                    proc.waitFor();

                    Util.switchOnConsole();

                } catch (Exception e) {
                    getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C)
                            + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
                    return false;
                } finally {
                    if (proc != null) {
                        closeQuietly(proc.getOutputStream());
                        closeQuietly(proc.getInputStream());
                        closeQuietly(proc.getErrorStream());
                    }
                }

                Scanner scanner = new Scanner(tempOutFile);
                content = "";
                try {
                    content = scanner.useDelimiter("\\Z").next();
                } catch (Exception e) {
                    // Grep ergab kein treffer Content Null
                    content = "";
                }
                scanner.close();

                getMessageService()
                        .logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_CONTENT, content));
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_CLOSE, name));

                if (tempOutFile.exists()) {
                    Util.deleteDir(tempOutFile);
                }
                content = "";

                // Ende Grep

            } catch (Exception e) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C)
                        + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
                return false;
            }

            // Ende SubTables
            if (onWork == 41) {
                onWork = 2;
                System.out.print("-   ");
                System.out.print("\r");
            } else if (onWork == 11) {
                onWork = 12;
                System.out.print("\\   ");
                System.out.print("\r");
            } else if (onWork == 21) {
                onWork = 22;
                System.out.print("|   ");
                System.out.print("\r");
            } else if (onWork == 31) {
                onWork = 32;
                System.out.print("/   ");
                System.out.print("\r");
            } else {
                onWork = onWork + 1;
            }
        }
        System.out.print("   ");
        System.out.print("\r");
    } catch (Exception e) {
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C)
                + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
        return false;
    }

    return isValid;
}

From source file:algo.PlotBar.java

private void buttonOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonOkActionPerformed

    BufferedReader br;/*from w w w  . j  av a 2 s  .  co m*/
    /// For bubbles.jpg image
    switch (comboAlgo.getSelectedIndex()) {
    /// For Bubble.jpg image
    case 0:
        JOptionPane.showMessageDialog(null, "Select Algorithm", "Algorithm Selection",
                JOptionPane.INFORMATION_MESSAGE);

        //                labelExecutionOutput.setText("Bubble Sort");
        //                try {
        //                    System.out.println(comboAlgo.getSelectedItem().toString());
        //                    Runtime rt = Runtime.getRuntime();
        //                    Process pr = rt.exec(new String[]{"cmd.exe",
        //                        "/c",
        //                        "start",
        //                        "BubbleSort.exe"
        //                    });
        //
        //                } catch (IOException ex) {
        //                    Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex);
        //                }

        break;
    /// For merge.jpg
    case 1:

        labelExecutionOutput.setText("Binary Search Merge Sort");
        try {
            System.out.println(comboAlgo.getSelectedItem().toString());
            Runtime rt = Runtime.getRuntime();
            Process pr = rt.exec(new String[] { "cmd.exe", "/c", "start", "Binary_search_merge_sort.exe" });

        } catch (IOException ex) {
            Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex);
        }

        try {
            String fileName = "time_binary_search_merge_sort.txt";
            br = new BufferedReader(new FileReader(fileName));
            File file = new File(fileName);
            Thread thread;
            thread = new Thread() {
                public void run() {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    if (file.exists()) {
                        try {
                            StringBuilder sb = new StringBuilder();
                            String line = br.readLine();
                            // System.out.println(line);
                            labelExecutionTimeElapsed.setText(line.concat(" s"));
                            br.close();
                        } catch (FileNotFoundException ex) {
                            Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex);
                        } catch (IOException ex) {
                            Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex);
                        }

                    }
                }
            };
            thread.start();

        } catch (FileNotFoundException ex) {
            Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex);
        }

        break;
    /// For quick.jpg
    case 2:

        labelExecutionOutput.setText("Interpolation Merge Sort");
        try {
            System.out.println(comboAlgo.getSelectedItem().toString());
            Runtime rt = Runtime.getRuntime();
            Process pr = rt
                    .exec(new String[] { "cmd.exe", "/c", "start", "interpolation_search_merge_sort.exe" });

        } catch (IOException ex) {
            Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex);
        }

        try {
            String fileName = "time_interpolation_search_merge_sort.txt";
            br = new BufferedReader(new FileReader(fileName));
            File file = new File(fileName);
            Thread thread;
            thread = new Thread() {
                public void run() {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    if (file.exists()) {
                        try {
                            StringBuilder sb = new StringBuilder();
                            String line = br.readLine();
                            // System.out.println(line);
                            labelExecutionTimeElapsed.setText(line.concat(" s"));
                            br.close();
                        } catch (FileNotFoundException ex) {
                            Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex);
                        } catch (IOException ex) {
                            Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex);
                        }

                    }
                }
            };
            thread.start();

        } catch (FileNotFoundException ex) {
            Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex);
        }

        break;
    case 3:

        labelExecutionOutput.setText("Normal Merge Sort");
        try {
            System.out.println(comboAlgo.getSelectedItem().toString());
            Runtime rt = Runtime.getRuntime();
            Process pr = rt.exec(new String[] { "cmd.exe", "/c", "start", "normal_merge_sort.exe" });

        } catch (IOException ex) {
            Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex);
        }

        try {
            String fileName = "time_normal_merge_sort.txt";
            br = new BufferedReader(new FileReader(fileName));
            File file = new File(fileName);
            Thread thread;
            thread = new Thread() {
                public void run() {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    if (file.exists()) {
                        try {
                            StringBuilder sb = new StringBuilder();
                            String line = br.readLine();
                            // System.out.println(line);
                            labelExecutionTimeElapsed.setText(line.concat(" s"));
                            br.close();
                        } catch (FileNotFoundException ex) {
                            Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex);
                        } catch (IOException ex) {
                            Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex);
                        }

                    }
                }
            };
            thread.start();

        } catch (FileNotFoundException ex) {
            Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex);
        }

        break;

    case 4:

        labelExecutionOutput.setText("TAN Sort");
        try {
            System.out.println(comboAlgo.getSelectedItem().toString());
            Runtime rt = Runtime.getRuntime();
            Process pr = rt.exec(new String[] { "cmd.exe", "/c", "start", "TAN_SOR2.exe" });

        } catch (IOException ex) {
            Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex);
        }
        // time_tan_sor2.txt

        try {
            String fileName = "time_tan_sor2.txt";
            br = new BufferedReader(new FileReader(fileName));
            File file = new File(fileName);
            Thread thread;
            thread = new Thread() {
                public void run() {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    if (file.exists()) {
                        try {
                            StringBuilder sb = new StringBuilder();
                            String line = br.readLine();
                            // System.out.println(line);
                            labelExecutionTimeElapsed.setText(line.concat(" s"));
                            br.close();
                        } catch (FileNotFoundException ex) {
                            Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex);
                        } catch (IOException ex) {
                            Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex);
                        }

                    }
                }
            };
            thread.start();

        } catch (FileNotFoundException ex) {
            Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex);
        }

        break;
    default:
        break;
    }

}

From source file:org.kchine.rpf.PoolUtils.java

public static String currentUnixProcessID() throws Exception {

    String outputFileName = TEMP_DIR + "/echoPPID_" + System.currentTimeMillis() + ".txt";
    String[] command = new String[] { "/bin/sh", "-c", "echo $PPID > " + outputFileName };

    Runtime rt = Runtime.getRuntime();
    final Process proc = rt.exec(command);
    int exitVal = proc.waitFor();
    if (exitVal != 0)
        throw new Exception(Arrays.toString(command) + " exit code : " + exitVal);

    BufferedReader br = new BufferedReader(new FileReader(outputFileName));
    String result = br.readLine();
    br.close();/*  w w  w  .ja  v a 2s.co  m*/

    new File(outputFileName).delete();
    return result;
}

From source file:org.kchine.rpf.PoolUtils.java

public static void killLocalUnixProcess(String processId, boolean isKILLSIG) throws Exception {
    String[] command = isKILLSIG ? new String[] { "kill", "-9", processId }
            : new String[] { "kill", processId };
    Runtime rt = Runtime.getRuntime();
    final Process proc = rt.exec(command);
    final Vector<String> killPrint = new Vector<String>();
    final Vector<String> errorPrint = new Vector<String>();

    System.out.println("Kill command : " + Arrays.toString(command));

    new Thread(new Runnable() {
        public void run() {
            try {
                BufferedReader br = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
                String line = null;
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                    errorPrint.add(line);
                }/*from www  . j  av a 2s  .co  m*/
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();

    new Thread(new Runnable() {
        public void run() {
            try {
                BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
                String line = null;
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                    killPrint.add(line);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();

    int exitVal = proc.waitFor();
    if (exitVal != 0)
        throw new Exception("kill exit code : " + exitVal + "\n" + errorPrint);
}

From source file:org.kchine.rpf.PoolUtils.java

public static void killLocalWinProcess(String processId, boolean isKILLSIG) throws Exception {

    String killpath = System.getProperty("java.io.tmpdir") + "/rpf/WinTools/" + "kill.exe";
    File killFile = new File(killpath);
    if (!killFile.exists()) {
        killFile.getParentFile().mkdirs();
        InputStream is = PoolUtils.class.getResourceAsStream("/wintools/kill.exe");
        RandomAccessFile raf = new RandomAccessFile(killFile, "rw");
        raf.setLength(0);// w  w  w  . j a  va  2  s  .c  om
        int b;
        while ((b = is.read()) != -1)
            raf.write((byte) b);
        raf.close();
    }
    String[] command = new String[] { killpath, processId };
    Runtime rt = Runtime.getRuntime();
    final Process proc = rt.exec(command);

    final StringBuffer killPrint = new StringBuffer();
    final StringBuffer errorPrint = new StringBuffer();
    new Thread(new Runnable() {
        public void run() {
            try {
                InputStream is = proc.getInputStream();
                int b;
                while ((b = is.read()) != -1) {
                    killPrint.append((char) b);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();
    new Thread(new Runnable() {
        public void run() {
            try {
                InputStream is = proc.getErrorStream();
                int b;
                while ((b = is.read()) != -1) {
                    errorPrint.append((char) b);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();

    int exitVal = proc.waitFor();
    if (exitVal != 0)
        throw new Exception("kill exit code : " + exitVal + "\n" + errorPrint);
}

From source file:org.kchine.rpf.PoolUtils.java

public static Properties getAMIUserData() throws Exception {

    PoolUtils.cacheJar(new URL("http://s3.amazonaws.com/ec2metadata/ec2-metadata"),
            System.getProperty("java.io.tmpdir") + "/biocep/ec2/", PoolUtils.LOG_PRGRESS_TO_SYSTEM_OUT, false);
    String ec2_metadata = new File(System.getProperty("java.io.tmpdir") + "/biocep/ec2/" + "ec2-metadata")
            .getAbsolutePath();/*  www. j  a  v a2s.  c  om*/
    Runtime rt = Runtime.getRuntime();
    Process chmodProc = rt.exec(new String[] { "chmod", "u+x", ec2_metadata });
    int chmodExitVal = chmodProc.waitFor();
    if (chmodExitVal != 0)
        throw new Exception("chmod exit code : " + chmodExitVal);

    final Process proc = rt.exec(new String[] { ec2_metadata, "-d" });

    final StringBuffer metadataOut = new StringBuffer();
    final StringBuffer metadataError = new StringBuffer();
    new Thread(new Runnable() {
        public void run() {
            try {
                InputStream is = proc.getInputStream();
                int b;
                while ((b = is.read()) != -1) {
                    metadataOut.append((char) b);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();
    new Thread(new Runnable() {
        public void run() {
            try {
                InputStream is = proc.getErrorStream();
                int b;
                while ((b = is.read()) != -1) {
                    metadataError.append((char) b);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();

    int exitVal = proc.waitFor();
    if (exitVal != 0)
        throw new Exception("ec2-metadata exit code : " + exitVal);

    BufferedReader reader = new BufferedReader(new StringReader(metadataOut.toString()));
    String line;
    String lastLine = null;
    while ((line = reader.readLine()) != null) {
        lastLine = line;
    }
    Properties props = extractProperties(
            lastLine.substring(lastLine.indexOf("user-data:") + "user-data:".length()).trim());
    return props;

}

From source file:org.kchine.rpf.PoolUtils.java

public static String getAMIHostIp() throws Exception {

    cacheJar(new URL("http://s3.amazonaws.com/ec2metadata/ec2-metadata"),
            System.getProperty("java.io.tmpdir") + "/biocep/ec2/", PoolUtils.LOG_PRGRESS_TO_SYSTEM_OUT, false);
    String ec2_metadata = new File(System.getProperty("java.io.tmpdir") + "/biocep/ec2/" + "ec2-metadata")
            .getAbsolutePath();/*w w  w . j  a v  a  2s . c o  m*/
    Runtime rt = Runtime.getRuntime();
    Process chmodProc = rt.exec(new String[] { "chmod", "u+x", ec2_metadata });
    int chmodExitVal = chmodProc.waitFor();
    if (chmodExitVal != 0)
        throw new Exception("chmod exit code : " + chmodExitVal);

    final Process proc = rt.exec(new String[] { ec2_metadata, "-v" });

    final StringBuffer metadataOut = new StringBuffer();
    final StringBuffer metadataError = new StringBuffer();
    new Thread(new Runnable() {
        public void run() {
            try {
                InputStream is = proc.getInputStream();
                int b;
                while ((b = is.read()) != -1) {
                    metadataOut.append((char) b);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();
    new Thread(new Runnable() {
        public void run() {
            try {
                InputStream is = proc.getErrorStream();
                int b;
                while ((b = is.read()) != -1) {
                    metadataError.append((char) b);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();

    int exitVal = proc.waitFor();
    if (exitVal != 0)
        throw new Exception("ec2-metadata exit code : " + exitVal);

    BufferedReader reader = new BufferedReader(new StringReader(metadataOut.toString()));
    String line;
    String lastLine = null;
    while ((line = reader.readLine()) != null) {
        lastLine = line;
    }

    System.out.println(lastLine);

    String result = lastLine.substring(lastLine.indexOf("public-ipv4:") + "public-ipv4:".length()).trim();
    System.out.println("PUBLIC AMI IP:<" + result + ">");

    return result;

}

From source file:com.redpill_linpro.libreoffice.LibreOfficeLauncherLinuxImpl.java

@Override
public void launchLibreOffice(String cmisUrl, String repositoryId, String filePath, String webdavUrl) {
    Runtime rt = Runtime.getRuntime();
    try {/*ww w .  j  a v  a2  s .com*/
        String params;
        if (null != webdavUrl && webdavUrl.length() > 0) {
            params = LibreOfficeLauncherHelper.generateLibreOfficeWebdavOpenUrl(webdavUrl);
        } else {
            params = LibreOfficeLauncherHelper.generateLibreOfficeCmisOpenUrl(cmisUrl, repositoryId, filePath);
        }
        StringBuffer cmd = new StringBuffer();
        try {
            String[] binaryLocations = { "soffice", "/usr/bin/soffice" };

            for (int i = 0; i < binaryLocations.length; i++) {
                cmd.append((i == 0 ? "" : " || ") + binaryLocations[i] + " \"" + params + "\" ");
            }

            System.out.println("Command: sh -c " + cmd);

            rt.exec(new String[] { "sh", "-c", cmd.toString() });

            System.out.println("Process started");
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "Failed to start LibreOffice, commandline: " + cmd.toString(),
                    "Error", JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
        }

    } catch (UnsupportedEncodingException e1) {
        JOptionPane.showMessageDialog(null, "Invalid URL for LibreOffice", "Error", JOptionPane.ERROR_MESSAGE);
        e1.printStackTrace();
    }
}

From source file:org.kchine.rpf.PoolUtils.java

public static String getAMIHostName() throws Exception {

    PoolUtils.cacheJar(new URL("http://s3.amazonaws.com/ec2metadata/ec2-metadata"),
            System.getProperty("java.io.tmpdir") + "/biocep/ec2/", PoolUtils.LOG_PRGRESS_TO_SYSTEM_OUT, false);
    String ec2_metadata = new File(System.getProperty("java.io.tmpdir") + "/biocep/ec2/" + "ec2-metadata")
            .getAbsolutePath();//from   www .java2 s .  c o  m
    Runtime rt = Runtime.getRuntime();
    Process chmodProc = rt.exec(new String[] { "chmod", "u+x", ec2_metadata });
    int chmodExitVal = chmodProc.waitFor();
    if (chmodExitVal != 0)
        throw new Exception("chmod exit code : " + chmodExitVal);

    final Process proc = rt.exec(new String[] { ec2_metadata, "-p" });

    final StringBuffer metadataOut = new StringBuffer();
    final StringBuffer metadataError = new StringBuffer();
    new Thread(new Runnable() {
        public void run() {
            try {
                InputStream is = proc.getInputStream();
                int b;
                while ((b = is.read()) != -1) {
                    metadataOut.append((char) b);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();
    new Thread(new Runnable() {
        public void run() {
            try {
                InputStream is = proc.getErrorStream();
                int b;
                while ((b = is.read()) != -1) {
                    metadataError.append((char) b);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();

    int exitVal = proc.waitFor();
    if (exitVal != 0)
        throw new Exception("ec2-metadata exit code : " + exitVal);

    BufferedReader reader = new BufferedReader(new StringReader(metadataOut.toString()));
    String line;
    String lastLine = null;
    while ((line = reader.readLine()) != null) {
        lastLine = line;
    }

    System.out.println(lastLine);

    String result = lastLine.substring(lastLine.indexOf("public-hostname:") + "public-hostname:".length())
            .trim();
    System.out.println("PUBLIC AMI HOST NAME:<" + result + ">");

    return result;

}