Example usage for java.io InputStreamReader close

List of usage examples for java.io InputStreamReader close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:eu.musesproject.server.policyrulesselector.PolicySelector.java

private String getJSONDevicePolicy(int requestId, Decision decision, String action, Asset asset) {
    String errorBuildingPolicy = "<errorBuildingPolicy/>";
    String jsonDevicePolicy = null;
    BufferedReader br = null;/*from w  w  w .  j ava2s .c o m*/
    InputStream in = null;
    InputStreamReader is = null;
    String policyContent = null;
    try {
        policyContent = getPolicyDTHeader();
        policyContent += getActionSection(decision, action, requestId, asset);
        policyContent += getPolicyDTBottom();
        JSONObject xmlJSONObj = XML.toJSONObject(policyContent);
        jsonDevicePolicy = xmlJSONObj.toString();
    } catch (JSONException je) {
        logger.error("JSONException:" + je.getCause());
    } catch (Exception e) {
        jsonDevicePolicy = errorBuildingPolicy;
    } finally {
        try {
            if (br != null) {
                br.close();
            }
        } catch (IOException e) {
            logger.error("IOException:" + e.getCause());

        }
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            logger.error("IOException:" + e.getCause());

        }
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException e) {
            logger.error("IOException:" + e.getCause());

        }
    }

    return jsonDevicePolicy;
}

From source file:com.example.mahmoud.asynctask_and_network.NetWork.java

public String callURL(String myStringURL) {
    StringBuilder sb = new StringBuilder();
    // String sb="";
    // to convert String to URL
    URL url = null;/* ww w  .j av  a  2s  . c o m*/
    //to open Connection with URL
    URLConnection urlConn = null;

    //to get InputStrem From Connection 
    InputStreamReader in = null;
    // to connect inputStrem with bufferedReader
    BufferedReader bufferedReader = null;

    try {
        //1  convert String to URL
        url = new URL(myStringURL);
        //2  Open Connection
        urlConn = url.openConnection();
        //3 check if there are newtork found or not 

        if (urlConn != null && urlConn.getInputStream() != null) {
            // 4 if there are connectio found make connection opent for just 1 minute
            urlConn.setReadTimeout(60 * 1000);
            // 5 get inputStrem from connection with the default charset for URL
            in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());
            // 6 connect inputStrem with bufferedReader
            bufferedReader = new BufferedReader(in);
            // 7  Read Data from bufferReader while that we not arrived to final char (-1)
            String cp;
            /*    while ((cp = bufferedReader.readLine()) != null) {
             sb.append( cp);
             //    sb.a
             //sb+=""+((char) cp);
             }*/
            int x;
            while ((x = in.read()) != -1) {
                sb.append((char) x);
            }
            bufferedReader.close();
        }

        in.close();
    } catch (Exception e) {

    }

    return sb.toString();

}

From source file:com.portfolio.data.attachment.ConvertCSV.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {
        try {/*from  w  w w .ja  va  2  s .c o  m*/
            request.getInputStream().close();
            response.setStatus(417);
            response.getWriter().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return;
    }

    initialize(request);
    response.setContentType("application/json");

    JSONObject data = new JSONObject();
    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> iter = items.iterator();

        List<String[]> meta = new ArrayList<String[]>();
        List<List<String[]>> linesData = new ArrayList<List<String[]>>();

        while (iter.hasNext()) {
            FileItem item = iter.next();
            if (item.isFormField()) {
                // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
            } else {
                // Process form file field (input type="file").
                String fieldname = item.getFieldName();
                if ("uploadfile".equals(fieldname)) // name="uploadfile"
                {
                    InputStreamReader isr = new InputStreamReader(item.getInputStream());
                    CSVReader reader = new CSVReader(isr, ';');
                    String[] headerLine;
                    String[] dataLine;

                    headerLine = reader.readNext();
                    if (headerLine == null)
                        break;

                    dataLine = reader.readNext();
                    if (dataLine == null)
                        break;

                    for (int i = 0; i < headerLine.length; ++i) {
                        data.put(headerLine[i], dataLine[i]);
                    }

                    headerLine = reader.readNext();
                    if (headerLine == null)
                        break;

                    JSONArray lines = new JSONArray();
                    while ((dataLine = reader.readNext()) != null) {
                        JSONObject lineInfo = new JSONObject();
                        for (int i = 0; i < headerLine.length; ++i) {
                            lineInfo.put(headerLine[i], dataLine[i]);
                        }
                        lines.put(lineInfo);
                    }

                    data.put("lines", lines);

                    isr.close();
                }
            }
        }
    } catch (Exception e) {

    }

    PrintWriter out = null;
    try {
        out = response.getWriter();
        out.print(data);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (out != null) {
            out.flush();
            out.close();
        }
    }

}

From source file:com.prey.net.PreyRestHttpClient.java

public StringBuilder getStringHttpResponse(HttpResponse httpResponse) throws Exception {

    HttpEntity httpEntity = null;/*from   ww w . j a  v a  2s. c o m*/
    InputStream is = null;
    InputStreamReader input = null;
    BufferedReader reader = null;
    StringBuilder sb = null;
    try {
        httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();
        input = new InputStreamReader(is, "iso-8859-1");
        reader = new BufferedReader(input, 8);
        sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }

        sb.toString().trim();
    } catch (IllegalStateException e) {

    } catch (Exception e) {
        PreyLogger.e("Buffer Error, Error converting result " + e.toString(), e);
    } finally {
        try {
            if (is != null)
                is.close();
        } catch (IOException e) {
        }
        try {
            if (reader != null)
                reader.close();
        } catch (IOException e) {
        }
        try {
            if (input != null)
                input.close();
        } catch (IOException e) {
        }
    }
    return sb;
}

From source file:nmtysh.android.test.speedtest.SpeedTestActivity.java

private void runHttpClient() {
    final String url = urlEdit.getText().toString();
    if (url == null || (!url.startsWith("http://") && !url.startsWith("https://"))) {
        list.add("URL error!");
        adapter.notifyDataSetChanged();/*  w  w w .  ja v  a  2s  .  c o m*/
        return;
    }
    task = new AsyncTask<Void, Integer, Void>() {
        long startTime;
        ProgressDialog progress;

        // ??
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            progress = new ProgressDialog(SpeedTestActivity.this);
            progress.setMessage(getString(R.string.progress_message));
            progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progress.setIndeterminate(false);
            progress.setCancelable(true);
            progress.setOnCancelListener(new OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    task.cancel(true);
                }
            });
            progress.setMax(10);
            progress.setProgress(0);
            progress.show();

            startTime = System.currentTimeMillis();
        }

        // ???
        @Override
        protected Void doInBackground(Void... params) {
            // 10?????
            for (int i = 0; i < 10; i++) {
                HttpClient client = new DefaultHttpClient();
                InputStreamReader in = null;
                // BufferedReader br = null;
                try {
                    HttpGet get = new HttpGet(url);
                    HttpResponse response = client.execute(get);
                    if (response.getStatusLine().getStatusCode() < 400) {
                        in = new InputStreamReader(response.getEntity().getContent());
                        // br = new BufferedReader(in);
                        // while (br.readLine() != null) {
                        long len = 0;
                        while (in.read() != -1) {
                            len++;
                        }
                        Log.i("HttpClient", len + " Bytes");
                    }
                } catch (IOException e) {
                } finally {
                    /*
                     * if (br != null) { try { br.close(); } catch
                     * (IOException e) { } br = null; }
                     */
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                        }
                        in = null;
                    }
                    // ?
                    client.getConnectionManager().shutdown();
                    client = null;
                }
                publishProgress(i + 1);
                // Dos????????
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                }
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            if (progress == null) {
                return;
            }
            progress.setProgress(values[0]);
        }

        // 
        @Override
        protected void onPostExecute(Void result) {
            long endTime = System.currentTimeMillis();

            // 
            progress.cancel();
            progress = null;

            list.add("HttpClient:" + url + " " + (endTime - startTime) + "msec/10" + " "
                    + (endTime - startTime) / 10 + "msec");
            adapter.notifyDataSetChanged();
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
            progress.dismiss();
            progress = null;
        }
    }.execute();
}

From source file:com.netease.dagger.BrowserEmulator.java

/**
 * The method for reading TXT file//from   ww w.ja v a2s . c o  m
 * 
 * @param filepath
 */
public void readTextFile(String filePath) {
    try {
        String encoding = "GBK";
        File file = new File(filePath);
        if (file.isFile() && file.exists()) {
            InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);
            BufferedReader bufferedReader = new BufferedReader(read);
            String lineTxt = null;
            while ((lineTxt = bufferedReader.readLine()) != null) {
                System.out.println(lineTxt);
            }
            read.close();
        } else {
            System.out.println("?");
        }
    } catch (Exception e) {
        System.out.println("?");
        e.printStackTrace();
    }
}

From source file:com.impetus.ankush.agent.utils.AgentRestClient.java

/**
 * Method sendNodeInfo./*from ww  w . jav a2  s .  c o m*/
 * 
 * @param urlPath
 *            String
 * @param input
 *            String
 * @return String
 * @throws IOException
 */
private String sendRequest(String urlPath, String input, String method, String accept, String contentType) {
    HttpURLConnection conn = null;
    OutputStream os = null;
    BufferedReader br = null;
    InputStreamReader isr = null;

    try {
        LOGGER.info("URL Path : " + urlPath);
        URL url = new URL(urlPath);

        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod(method);
        conn.setRequestProperty("Accept", accept);
        conn.setRequestProperty("Content-type", contentType);

        if (input != null && !input.isEmpty()) {
            os = conn.getOutputStream();
            os.write(input.getBytes());
            os.flush();
        }

        LOGGER.info("Response Code :" + conn.getResponseCode());

        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
        }
        isr = new InputStreamReader(conn.getInputStream());
        br = new BufferedReader(isr);

        String buffer = "";
        StringBuilder output = new StringBuilder();
        while ((buffer = br.readLine()) != null) {
            output.append(buffer);
        }
        return output.toString();
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        return null;
    } finally {
        try {
            if (isr != null) {
                isr.close();
            }

            if (br != null) {
                br.close();
            }
        } catch (Exception e) {
            LOGGER.error("Unable to close buffer stream while sending request", e);
        }
        if (conn != null) {
            conn.disconnect();
        }

        if (os != null) {
            IOUtils.closeQuietly(os);
        }
    }
}

From source file:com.nartex.FileManager.java

private void loadLanguageFile() {

    // we load langCode var passed into URL if present
    // else, we use default configuration var
    if (language == null) {
        String lang = "";
        if (params.get("langCode") != null)
            lang = this.params.get("langCode");
        else// w  w  w  .ja va 2  s.  com
            lang = config.getProperty("culture");
        BufferedReader br = null;
        InputStreamReader isr = null;
        String text;
        StringBuffer contents = new StringBuffer();
        try {
            isr = new InputStreamReader(
                    new FileInputStream(this.fileManagerRoot + "/scripts/languages/" + lang + ".js"), "UTF-8");
            br = new BufferedReader(isr);
            while ((text = br.readLine()) != null)
                contents.append(text);
            language = new JSONObject(contents.toString());
        } catch (Exception e) {
            this.error("Fatal error: Language file not found.");
        } finally {
            try {
                if (br != null)
                    br.close();
            } catch (Exception e2) {
            }
            try {
                if (isr != null)
                    isr.close();
            } catch (Exception e2) {
            }
        }
    }
}

From source file:com.prey.PreyPhone.java

public long totalMemory() {
    String line = "";
    File file = null;/*www .j  av  a2  s .com*/
    FileInputStream fi = null;
    InputStreamReader ir = null;
    BufferedReader br = null;
    long totalMemory = 0;
    try {
        file = new File("/proc/meminfo");
        fi = new FileInputStream(file);
        ir = new InputStreamReader(fi);
        br = new BufferedReader(ir);
        while ((line = br.readLine()) != null) {
            if (line.indexOf("MemTotal") >= 0) {
                line = line.replace("MemTotal", "");
                line = line.replace(":", "");
                line = line.replace("kB", "");
                line = line.trim();
                break;
            }
        }
        totalMemory = Long.parseLong(line) / 1024;
    } catch (Exception e) {
    } finally {
        try {
            br.close();
        } catch (Exception e) {
        }
        try {
            ir.close();
        } catch (Exception e) {
        }
        try {
            fi.close();
        } catch (Exception e) {
        }
    }
    return totalMemory;
}

From source file:com.nartex.RichFileManager.java

@Override
public void loadLanguageFile() {

    // we load langCode var passed into URL if present
    // else, we use default configuration var
    if (language == null || reload) {
        String lang = "";
        if (params.get("langCode") != null)
            lang = this.params.get("langCode");
        else/*  w  w  w.  j  a v a  2s . c o  m*/
            lang = config.getProperty("culture");
        BufferedReader br = null;
        InputStreamReader isr = null;
        String text;
        StringBuffer contents = new StringBuffer();
        try {
            isr = new InputStreamReader(new FileInputStream(
                    this.fileManagerRoot.resolve("scripts/languages/").resolve(lang + ".json").toString()),
                    "UTF-8");
            br = new BufferedReader(isr);
            while ((text = br.readLine()) != null)
                contents.append(text);
            language = new JSONObject(contents.toString());
        } catch (Exception e) {
            this.error("Fatal error: Language file not found.");
        } finally {
            try {
                if (br != null)
                    br.close();
            } catch (Exception e2) {
            }
            try {
                if (isr != null)
                    isr.close();
            } catch (Exception e2) {
            }
        }
    }
}