Example usage for java.io DataInputStream close

List of usage examples for java.io DataInputStream close

Introduction

In this page you can find the example usage for java.io DataInputStream close.

Prototype

public void close() throws IOException 

Source Link

Document

Closes this input stream and releases any system resources associated with the stream.

Usage

From source file:com.aliyun.odps.ogg.handler.datahub.DatahubHandler.java

public static int getSkipSendTimes(String fileName, OggAlarm oggAlarm) {
    File handlerInfoFile = new File(fileName);
    if (handlerInfoFile.exists() && !handlerInfoFile.isDirectory()) {
        DataInputStream in = null;
        try {//from   w  w  w  .  j a  v  a2 s .co m
            in = new DataInputStream(new FileInputStream(handlerInfoFile));
            return in.readInt();
        } catch (IOException e) {
            logger.warn("Error reading handler info file, may cause duplication ", e);
            oggAlarm.warn("Error reading handler info file, may cause duplication ", e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    logger.warn("Close handler info file failed. ", e);
                    oggAlarm.warn("Close handler info file failed. ", e);
                }
            }
        }
    }
    return 0;
}

From source file:genepi.db.DatabaseUpdater.java

public static String readFileAsStringClasspath(InputStream is, String minVersion, String maxVersion)
        throws java.io.IOException, URISyntaxException {

    DataInputStream in = new DataInputStream(is);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;//from w ww.  j av  a  2 s  .c  om
    StringBuilder builder = new StringBuilder();
    boolean reading = false;
    while ((strLine = br.readLine()) != null) {

        if (strLine.startsWith("--")) {

            String version = strLine.replace("--", "");
            reading = (compareVersion(version, minVersion) > 0 && compareVersion(version, maxVersion) <= 0);

            if (reading) {
                log.info("Loading update for version " + version);
            }

        }

        if (reading) {
            builder.append("\n");
            builder.append(strLine);
        }
    }

    in.close();

    return builder.toString();
}

From source file:genepi.db.DatabaseUpdater.java

public static String readFileAsStringFile(String filename, String minVersion, String maxVersion)
        throws java.io.IOException, URISyntaxException {

    InputStream is = new FileInputStream(filename);

    DataInputStream in = new DataInputStream(is);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;/* w w w  .  j  a v  a2s.c  om*/
    StringBuilder builder = new StringBuilder();
    boolean reading = false;
    while ((strLine = br.readLine()) != null) {

        if (strLine.startsWith("--")) {

            String version = strLine.replace("--", "").trim();
            reading = (compareVersion(version, minVersion) > 0 && compareVersion(version, maxVersion) <= 0);
            if (reading) {
                log.info("Loading update for version " + version);
            }

        }

        if (reading) {
            builder.append("\n");
            builder.append(strLine);
        }
    }

    in.close();

    return builder.toString();
}

From source file:Main.java

public static String execRootCmd(String[] cmds) {
    String result = "";
    DataOutputStream dos = null;//from ww w  . ja  va  2  s .c o  m
    DataInputStream dis = null;

    try {
        Process p = Runtime.getRuntime().exec("su");
        dos = new DataOutputStream(p.getOutputStream());
        dis = new DataInputStream(p.getInputStream());

        for (String cmd : cmds) {
            Log.i("CmdUtils", cmd);
            dos.writeBytes(cmd + "\n");
            dos.flush();
        }
        dos.writeBytes("exit\n");
        dos.flush();
        String line;
        while ((line = dis.readLine()) != null) {
            Log.d("result", line);
            result += line;
        }
        p.waitFor();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (dos != null) {
            try {
                dos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (dis != null) {
            try {
                dis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return result;
}

From source file:Main.java

public static int execRootCmdForExitCode(String[] cmds) {
    int result = -1;
    DataOutputStream dos = null;//www.j av a2  s . c o  m
    DataInputStream dis = null;

    try {
        Process p = Runtime.getRuntime().exec("su");
        dos = new DataOutputStream(p.getOutputStream());
        dis = new DataInputStream(p.getInputStream());

        for (String cmd : cmds) {
            Log.i("CmdUtils", cmd);
            dos.writeBytes(cmd + "\n");
            dos.flush();
        }
        dos.writeBytes("exit\n");
        dos.flush();
        String line;
        while ((line = dis.readLine()) != null) {
            Log.d("result", line);
        }
        p.waitFor();
        result = p.exitValue();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (dos != null) {
            try {
                dos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (dis != null) {
            try {
                dis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return result;
}

From source file:CounterApp.java

public int getCount() throws Exception {
    java.net.URL url = new java.net.URL(servletURL);
    java.net.URLConnection con = url.openConnection();
    if (sessionCookie != null) {
        con.setRequestProperty("cookie", sessionCookie);
    }/*from  ww  w  .  ja v  a 2  s .  c om*/
    con.setUseCaches(false);
    con.setDoOutput(true);
    con.setDoInput(true);
    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    DataOutputStream out = new DataOutputStream(byteOut);
    out.flush();
    byte buf[] = byteOut.toByteArray();
    con.setRequestProperty("Content-type", "application/octet-stream");
    con.setRequestProperty("Content-length", "" + buf.length);
    DataOutputStream dataOut = new DataOutputStream(con.getOutputStream());
    dataOut.write(buf);
    dataOut.flush();
    dataOut.close();
    DataInputStream in = new DataInputStream(con.getInputStream());
    int count = in.readInt();
    in.close();
    if (sessionCookie == null) {
        String cookie = con.getHeaderField("set-cookie");
        if (cookie != null) {
            sessionCookie = parseCookie(cookie);
            System.out.println("Setting session ID=" + sessionCookie);
        }
    }

    return count;
}

From source file:XmlUtils.java

public static Document parse(URL url) throws DocumentException, IOException {
    URLConnection urlConnection;//from ww  w  .  j a  v a2  s  .  c o m
    DataInputStream inStream;
    urlConnection = url.openConnection();
    ((HttpURLConnection) urlConnection).setRequestMethod("GET");

    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(false);
    urlConnection.setUseCaches(false);
    inStream = new DataInputStream(urlConnection.getInputStream());

    byte[] bytes = new byte[1024];
    int read;
    StringBuilder builder = new StringBuilder();
    while ((read = inStream.read(bytes)) >= 0) {
        String readed = new String(bytes, 0, read, "UTF-8");
        builder.append(readed);
    }
    SAXReader reader = new SAXReader();

    XmlUtils.createIgnoreErrorHandler(reader);
    //        InputSource inputSource = new InputSource(new InputStreamReader(inStream, "UTF-8"));
    //        inputSource.setEncoding("UTF-8");
    Document dom = reader.read(new StringReader(builder.toString()));
    inStream.close();
    //        new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream("retrieval.xml"), "UTF-8")
    return dom;
}

From source file:org.ctuning.openme.openme.java

public static JSONObject remote_access(JSONObject i) throws JSONException {
    /*//from  www.  j a  va2  s  . co  m
    Input:  {
      remote_server_url      - remote server URL
      (module_uoa)           - module to run
      (action)               - action to perform
                                  if =='download', prepare entry/file download through Internet
            
      (save_to_file)         - if web_action==download,
                                  save output to this file
            
      (out)                  - if 'json', treat output as json
                                  if 'json_after_text', strip everything before json
                                  if 'txt', output to stdout
            
      ...                    - all other request parameters
            
      //FGG TBD - should add support for proxy
    }
            
    Output: {
      return   - return code = 0 if successful
                                > 0 if error
                                < 0 if warning (rarely used at this moment)
      (error)  - error text, if return > 0
      (stdout) - if out='txt', output there
    }
    */

    // Prepare return object
    JSONObject r = new JSONObject();

    URL u;
    HttpURLConnection c = null;

    // Prepare request
    String x = "";
    String post = "";

    String con = "";

    x = "";
    if (i.has("out"))
        x = (String) i.get("out");
    if (x != null && x != "")
        con = x;

    String url = "";
    if (i.has("remote_server_url")) {
        url = (String) i.get("remote_server_url");
        i.remove("remote_server_url");
    }
    if (url == null || url == "") {
        r.put("return", new Integer(1));
        r.put("error", "'remote_server_url is not defined");
        return r;
    }

    String save_to_file = "";
    if (i.has("save_to_file")) {
        save_to_file = (String) i.get("save_to_file");
        i.remove("save_to_file");
    }

    // Check if data download, not json and convert it to download request
    boolean download = false;

    x = "";
    if (i.has("action")) {
        x = (String) i.get("action");
    }
    if (x == "download" || x == "show") {
        download = true;
        if (post != "")
            post += "&";
        post += "module_uoa=web&action=" + x;

        if (i.has("module_uoa"))
            i.remove("module_uoa");
        if (i.has("out"))
            i.remove("out");
        i.remove("action");
    }

    // Prepare dict to transfer through Internet
    JSONObject ii = new JSONObject();
    ii.put("dict", i);
    JSONObject rx = convert_array_to_uri(ii);
    if ((Integer) rx.get("return") > 0)
        return rx;

    if (post != "")
        post += "&";
    post += "ck_json=" + ((String) rx.get("string"));

    // Prepare URL request
    String s = "";
    try {
        u = new URL(url);
        c = (HttpURLConnection) u.openConnection();

        c.setRequestMethod("POST");
        c.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        c.setRequestProperty("Content-Length", Integer.toString(post.getBytes().length));
        c.setUseCaches(false);
        c.setDoInput(true);
        c.setDoOutput(true);

        //Send request
        DataOutputStream dos = new DataOutputStream(c.getOutputStream());
        dos.writeBytes(post);
        dos.flush();
        dos.close();
    } catch (IOException e) {
        if (c != null)
            c.disconnect();
        r.put("return", new Integer(1));
        r.put("error", "Failed sending request to remote server (" + e.getMessage() + ") ...");
        return r;
    }

    r.put("return", new Integer(0));

    // Check if download, not json!
    if (download) {
        String name = "default_download_name.dat";

        x = "";
        if (i.has("filename")) {
            x = ((String) i.get("filename"));
        }
        if (x != null && x != "") {
            File xf = new File(x);
            name = xf.getName();
        }

        if (save_to_file != null && save_to_file != "")
            name = save_to_file;

        //Reading response in binary and at the same time saving to file
        try {
            //Read response
            DataInputStream dis = new DataInputStream(c.getInputStream());
            DataOutputStream dos = new DataOutputStream(new FileOutputStream(name));

            byte[] buf = new byte[16384];

            int len;

            while ((len = dis.read(buf)) != -1)
                dos.write(buf, 0, len);

            dos.close();
            dis.close();
        } catch (Exception e) {
            if (c != null)
                c.disconnect();

            r.put("return", new Integer(1));
            r.put("error",
                    "Failed reading stream from remote server or writing to file (" + e.getMessage() + ") ...");
            return r;
        }
    } else {
        //Reading response in text
        try {
            //Read response
            InputStream is = c.getInputStream();
            BufferedReader f = new BufferedReader(new InputStreamReader(is));
            StringBuffer ss = new StringBuffer();

            while ((x = f.readLine()) != null) {
                ss.append(x);
                ss.append('\r');
            }

            f.close();
            s = ss.toString();
        } catch (Exception e) {
            if (c != null)
                c.disconnect();

            r.put("return", new Integer(1));
            r.put("error", "Failed reading stream from remote server (" + e.getMessage() + ") ...");
            return r;
        }

        if (con == "json_after_text") {
            String json_sep = "*** ### --- CM JSON SEPARATOR --- ### ***";
            int li = s.lastIndexOf(json_sep);
            if (li >= 0) {
                s = s.substring(li + json_sep.length());
                s = s.trim();
            }
        }

        if (con == "json_after_text" || con == "json")
            r = new JSONObject(s);
        else
            r.put("stdout", s);
    }

    if (c != null)
        c.disconnect();

    return r;
}

From source file:ImageTransfer.java

public Object nativeToJava(TransferData transferData) {
    if (!isSupportedType(transferData))
        return null;

    byte[] buffer = (byte[]) super.nativeToJava(transferData);
    if (buffer == null)
        return null;

    ImageData imdata;/*from  ww  w .  j  a v  a2 s.c om*/
    try {
        ByteArrayInputStream in = new ByteArrayInputStream(buffer);
        DataInputStream readIn = new DataInputStream(in);
        imdata = new ImageData(readIn);
        readIn.close();
    } catch (IOException ex) {
        return null;
    }
    return imdata;
}

From source file:org.elasticsearch.discovery.custom.DataFetcher.java

public static String fetchData(String url, ESLogger logger) {
    DataInputStream responseStream = null;
    try {/*from   w w w .  j av a2  s .c o  m*/
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setConnectTimeout(1000);
        conn.setReadTimeout(10000);
        conn.setRequestMethod("GET");
        if (conn.getResponseCode() != 200)
            throw new RuntimeException("Unable to get data for URL " + url);

        byte[] b = new byte[2048];
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        responseStream = new DataInputStream((FilterInputStream) conn.getContent());
        int c = 0;
        while ((c = responseStream.read(b, 0, b.length)) != -1)
            bos.write(b, 0, c);
        String return_ = new String(bos.toByteArray(), CharEncoding.UTF_8);
        logger.info(String.format("Calling URL API: %s returns: %s", url, return_));
        conn.disconnect();
        return return_;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        try {
            if (responseStream != null)
                responseStream.close();
        } catch (Exception e) {
            logger.warn("Failed to close response stream from priam", e);
        }
    }
}