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:controllers.ServerController.java

public void uploadFile(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    String UPLOAD_DIRECTORY = "/opt/ppd";
    int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB
    int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
    int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB

    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(MEMORY_THRESHOLD);
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(MAX_REQUEST_SIZE);

    File uploadDir = new File(UPLOAD_DIRECTORY);
    if (!uploadDir.exists())
        uploadDir.mkdir();//from w  w w.j  a  va 2s.co  m

    try {
        // parses the request's content to extract file data
        @SuppressWarnings("unchecked")
        List<FileItem> formItems = upload.parseRequest(request);
        if (formItems != null && formItems.size() > 0) {
            // iterates over form's fields
            for (FileItem item : formItems) {
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    String filePath = UPLOAD_DIRECTORY + File.separator + fileName;
                    File storeFile = new File(filePath);
                    item.write(storeFile);
                    PrintWriter out = response.getWriter();
                    Runtime runtime = Runtime.getRuntime();
                    Process process = runtime.exec("/opt/script.sh " + fileName);
                    out.write("uplad success");
                    out.close();
                }
            }
        }
    } catch (Exception ex) {
        PrintWriter out = response.getWriter();
        out.write("There was an error: " + ex.getMessage().toString());
        out.close();
    }

}

From source file:oscar.util.OscarStatusAction.java

private String getOscarSQLMasterStatus() {
    String output = "$ show master status\\G\n";

    String dbUser = OscarProperties.getInstance().getProperty("db_username");
    String dbPass = OscarProperties.getInstance().getProperty("db_password");

    String[] cmd = { "/bin/sh", "-c",
            "mysql -u" + dbUser + " -p" + dbPass + " --vertical -e \"show master status\"" };

    Runtime r = Runtime.getRuntime();
    try {/*from   ww w . ja va 2s.c om*/
        Process p = r.exec(cmd);
        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 getOscarSQLSlaveStatus() {
    String output = "$ show slave status\\G\n";

    String dbUser = OscarProperties.getInstance().getProperty("db_username");
    String dbPass = OscarProperties.getInstance().getProperty("db_password");

    String[] cmd = { "/bin/sh", "-c",
            "mysql -u" + dbUser + " -p" + dbPass + " --vertical -e \"show slave status\"" };

    Runtime r = Runtime.getRuntime();
    try {/*from  www.j av a2s .  c o  m*/
        Process p = r.exec(cmd);
        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:hu.bme.mit.trainbenchmark.generator.sql.SQLGenerator.java

public void compact() throws IOException, InterruptedException {
    MySQLProcess.stopSQLProcess();/*from www  .  jav a 2s .  c  o m*/
    MySQLProcess.startSQLProcess();

    final Runtime rt = Runtime.getRuntime();
    final String[] commandLoad = { "/bin/bash", "-c", "mysql -u " + USER + " < " + sqlRawPath };
    final Process processLoad = rt.exec(commandLoad);
    processLoad.waitFor();

    final String[] commandDump = { "/bin/bash", "-c",
            "mysqldump -u " + USER + " --databases trainbenchmark --skip-dump-date > " + sqlDumpPath };
    final Process processDump = rt.exec(commandDump);
    processDump.waitFor();
}

From source file:com.eucalyptus.blockstorage.HttpReader.java

private void getResponseToFile() {
    byte[] bytes = new byte[StorageProperties.TRANSFER_CHUNK_SIZE];
    FileOutputStream fileOutputStream = null;
    BufferedOutputStream bufferedOut = null;
    try {//from   w w w . ja  va 2 s.  co  m
        File outFile = null;
        File outFileUncompressed = null;
        if (compressed) {
            String outFileNameUncompressed = tempPath + File.pathSeparator + file.getName()
                    + Hashes.getRandom(16);
            outFileUncompressed = new File(outFileNameUncompressed);
            outFile = new File(outFileNameUncompressed + ".gz");
        } else {
            outFile = file;
        }

        httpClient.executeMethod(method);

        // GZIPInputStream has a bug thats corrupting snapshot file system. Mounting the block device failed with unknown file system error
        /*InputStream httpIn = null;
        if(compressed) {
           httpIn = new GZIPInputStream(method.getResponseBodyAsStream());
        }
        else {
           httpIn = method.getResponseBodyAsStream();            
        }*/

        InputStream httpIn = method.getResponseBodyAsStream();
        int bytesRead;
        fileOutputStream = new FileOutputStream(outFile);
        // fileOutputStream = new FileOutputStream(file);
        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:com.alfaariss.oa.authentication.password.digest.HtPasswdMD5Digest.java

/**
 * DD Instead of realm, the "salt" is given
 * @see IDigest#digest(java.lang.String, java.lang.String, java.lang.String)
 *///from   ww w . j  av a2  s .  c om
public byte[] digest(String password, String salt, String username) throws OAException {
    byte[] result = null;
    Runtime r = Runtime.getRuntime();
    Process p = null;
    String[] saCommand = null;
    try {
        saCommand = resolveCommand(_sCommand, salt, password);
        p = r.exec(saCommand);

        BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));

        int exitCode = p.waitFor();
        if (exitCode == 0) {
            result = in.readLine().getBytes();
            _systemLogger.debug("Result openssl: " + new String(result));
        }
    } catch (IOException e) {
        _systemLogger.error("IO Error executing command: " + resolveCommand(saCommand), e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    } catch (InterruptedException e) {
        _systemLogger.error("Error executing command: " + resolveCommand(saCommand), e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }

    return result;
}

From source file:oscar.util.OscarStatusAction.java

private String hl7Status() {

    String output = "";
    if (OscarProperties.getInstance().getProperty("HL7_COMPLETED_DIR") != null) {

        String hl7Dir = OscarProperties.getInstance().getProperty("HL7_COMPLETED_DIR");
        output += "$ ls -ltr " + hl7Dir + " \n";

        String[] cmd = { "/bin/sh", "-c", "ls -ltr " + hl7Dir };

        Runtime r = Runtime.getRuntime();
        try {//from  w  w  w .j a  v a  2s .co m
            Process p = r.exec(cmd);
            InputStream in = p.getInputStream();
            InputStreamReader isr = new InputStreamReader(in);
            BufferedReader br = new BufferedReader(isr);
            String line;

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

        } catch (IOException e) {
            output += "[An error has been encountered.]\n";
            output += "[" + e.getMessage() + "]\n";
        }
    } else {
        output += "Property for HL7_COMPLETED_DIR is not definied.";
    }

    return output;
}

From source file:oscar.util.OscarStatusAction.java

private String documentStorage() {
    String output = "";

    if (OscarProperties.getInstance().getProperty("DOCUMENT_DIR") != null) {
        String docDir = OscarProperties.getInstance().getProperty("DOCUMENT_DIR");

        output += "$ ls -R " + docDir + " | wc \n";
        String bashCmd = "ls -R " + docDir + " | wc";

        String[] cmd = { "/bin/sh", "-c", bashCmd };

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

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

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

    } else {
        output += "Property for DOCUMENT_DIR is not definied.";
    }
    return output;
}

From source file:org.rifidi.edge.adapter.opticon.OpticonSensor.java

public void setSerialPort(String serialPortID) {
    String cmd = "ls -al /dev/Opticon";

    if (serialPortID.equalsIgnoreCase("/dev/Opticon")) {
        File f = new File("/dev/Opticon");
        if (f.exists()) {
            Runtime run = Runtime.getRuntime();
            Process pr = null;/*from w  w w. j av  a  2s. c  o  m*/
            try {
                pr = run.exec(cmd);
            } catch (IOException e) {
                logger.error(e.getMessage());
            }
            try {
                pr.waitFor();

            } catch (Exception e) {
                e.printStackTrace();
            }
            BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
            String dev = "";
            try {
                dev = buf.readLine();
            } catch (IOException e) {
                this.serialPortID = serialPortID;
                return;
            }
            char no = dev.charAt(dev.length() - 1);
            this.serialPortID = "/dev/ttyUSB" + no;

            logger.info("Comm port that the Opticon is being connected to: " + this.serialPortID);

            // logger.info("AbstractSSS()  hope to see tty: "
            // + this.serialPortID);
            return;
        }
    }
    this.serialPortID = serialPortID;
}

From source file:org.sipfoundry.sipxconfig.admin.monitoring.RRDToolGraphUpdater.java

private void executeCommand(MRTGTarget target, String intervalExt, String[] command) throws Exception {
    int exitValue = 0;
    List<String> results = new ArrayList<String>();
    Runtime rt = Runtime.getRuntime();
    Process p = rt.exec(command);

    StreamGobbler outGobbler = new StreamGobbler(p.getInputStream());
    StreamGobbler errGobbler = new StreamGobbler(p.getErrorStream());
    outGobbler.start();/*from  www. ja  va 2s  .  c o m*/
    errGobbler.start();
    try {
        exitValue = p.waitFor();
    } catch (InterruptedException e) {
        exitValue = m_successExitCode + 100;
        m_lastErrors += TOOL_ERROR;
        m_lastErrors += MonitoringUtil.NEW_LINE + e.getMessage();
    } catch (Throwable e) {
        exitValue = m_successExitCode + 200;
        m_lastErrors += TOOL_ERROR;
        m_lastErrors += e.getMessage();
    }

    List<String> outlines = outGobbler.getOutputLines();
    for (int i = 0; i < outlines.size(); i++) {
        StringTokenizer st = new StringTokenizer(outlines.get(i), "=");
        if (st.hasMoreTokens()) {
            st.nextToken();
            if (st.hasMoreTokens()) {
                // this is line we expect, save result
                results.add(outlines.get(i));
            }
        }
    }

    List<String> errlines = errGobbler.getOutputLines();

    for (int i = 0; i < errlines.size(); i++) {
        m_lastErrors += MonitoringUtil.NEW_LINE + errlines.get(i);
    }

    if (results.size() > 0) {
        writePrintInfo(target, intervalExt, results);
    }

    if (exitValue != m_successExitCode) {
        throw new GraphCreationException(m_lastErrors);
    }
}