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:com.fdwills.external.http.SaxAsyncHttpResponseHandler.java

/**
 * Deconstructs response into given content handler
 *
 * @param entity returned HttpEntity/*w w  w . ja  v  a2  s .c  o m*/
 * @return deconstructed response
 * @throws java.io.IOException
 * @see org.apache.http.HttpEntity
 */
@Override
protected byte[] getResponseData(HttpEntity entity) throws IOException {
    if (entity != null) {
        InputStream instream = entity.getContent();
        InputStreamReader inputStreamReader = null;
        if (instream != null) {
            try {
                SAXParserFactory sfactory = SAXParserFactory.newInstance();
                SAXParser sparser = sfactory.newSAXParser();
                XMLReader rssReader = sparser.getXMLReader();
                rssReader.setContentHandler(handler);
                inputStreamReader = new InputStreamReader(instream, DEFAULT_CHARSET);
                rssReader.parse(new InputSource(inputStreamReader));
            } catch (SAXException e) {
                Log.e(LOG_TAG, "getResponseData exception", e);
            } catch (ParserConfigurationException e) {
                Log.e(LOG_TAG, "getResponseData exception", e);
            } finally {
                AsyncHttpClient.silentCloseInputStream(instream);
                if (inputStreamReader != null) {
                    try {
                        inputStreamReader.close();
                    } catch (IOException e) { /*ignore*/
                    }
                }
            }
        }
    }
    return null;
}

From source file:org.apache.hadoop.io.crypto.bee.RestClient.java

public StringBuffer getResult() throws Exception {
    InputStream is = null;/*w w w .ja  va 2  s  . c o m*/
    InputStreamReader isr = null;
    try {
        LOG.info("Try to establish connection to " + url.toString());
        if ("https".compareTo(url.getProtocol()) == 0) {
            if (this.isHttpsCertificateEnabled()) {
                is = this.httpsWithCertificate(url);
            } else {
                is = httpsIgnoreCertificate(url);
            }

        } else {
            URLConnection urlConnection = url.openConnection();
            is = urlConnection.getInputStream();
        }

        isr = new InputStreamReader(is);
        StringBuffer sb = new StringBuffer();
        int numCharsRead;
        char[] charArray = new char[1024];
        while ((numCharsRead = isr.read(charArray)) > 0) {
            sb.append(charArray, 0, numCharsRead);
        }

        return sb;

    } finally {
        if (isr != null)
            isr.close();
    }

}

From source file:com.amytech.android.library.utils.asynchttp.SaxAsyncHttpResponseHandler.java

/**
 * Deconstructs response into given content handler
 *
 * @param entity//from   ww w.j a v  a  2s.  c  o  m
 *            returned HttpEntity
 * @return deconstructed response
 * @throws java.io.IOException
 *             if there is problem assembling SAX response from stream
 * @see org.apache.http.HttpEntity
 */
@Override
protected byte[] getResponseData(HttpEntity entity) throws IOException {
    if (entity != null) {
        InputStream instream = entity.getContent();
        InputStreamReader inputStreamReader = null;
        if (instream != null) {
            try {
                SAXParserFactory sfactory = SAXParserFactory.newInstance();
                SAXParser sparser = sfactory.newSAXParser();
                XMLReader rssReader = sparser.getXMLReader();
                rssReader.setContentHandler(handler);
                inputStreamReader = new InputStreamReader(instream, DEFAULT_CHARSET);
                rssReader.parse(new InputSource(inputStreamReader));
            } catch (SAXException e) {
                Log.e(LOG_TAG, "getResponseData exception", e);
            } catch (ParserConfigurationException e) {
                Log.e(LOG_TAG, "getResponseData exception", e);
            } finally {
                AsyncHttpClient.silentCloseInputStream(instream);
                if (inputStreamReader != null) {
                    try {
                        inputStreamReader.close();
                    } catch (IOException e) { /* ignore */
                    }
                }
            }
        }
    }
    return null;
}

From source file:cn.com.loopj.android.http.SaxAsyncHttpResponseHandler.java

/**
 * Deconstructs response into given content handler
 *
 * @param entity returned HttpEntity//from   w  w  w  .ja  va2 s . c  o m
 * @return deconstructed response
 * @throws IOException if there is problem assembling SAX response from stream
 * @see HttpEntity
 */
@Override
protected byte[] getResponseData(HttpEntity entity) throws IOException {
    if (entity != null) {
        InputStream instream = entity.getContent();
        InputStreamReader inputStreamReader = null;
        if (instream != null) {
            try {
                SAXParserFactory sfactory = SAXParserFactory.newInstance();
                SAXParser sparser = sfactory.newSAXParser();
                XMLReader rssReader = sparser.getXMLReader();
                rssReader.setContentHandler(handler);
                inputStreamReader = new InputStreamReader(instream, getCharset());
                rssReader.parse(new InputSource(inputStreamReader));
            } catch (SAXException e) {
                AsyncHttpClient.log.e(LOG_TAG, "getResponseData exception", e);
            } catch (ParserConfigurationException e) {
                AsyncHttpClient.log.e(LOG_TAG, "getResponseData exception", e);
            } finally {
                AsyncHttpClient.silentCloseInputStream(instream);
                if (inputStreamReader != null) {
                    try {
                        inputStreamReader.close();
                    } catch (IOException e) {
                        /*ignore*/ }
                }
            }
        }
    }
    return null;
}

From source file:com.csipsimple.service.DownloadLibService.java

private boolean downloadFile(RemoteLibInfo updateInfo) throws IOException {
    HttpClient httpClient = new DefaultHttpClient();
    HttpClient MD5httpClient = new DefaultHttpClient();

    HttpUriRequest req, md5req;/*from  ww  w . jav  a2s. c  o  m*/
    HttpResponse response, md5response;

    URI updateURI;
    File destinationFile = null;
    File partialDestinationFile = null;

    String downloadedMD5 = null;

    String fileName = updateInfo.getFileName();
    File filePath = updateInfo.getFilePath();

    // Set the Filename to update.zip.partial
    partialDestinationFile = new File(filePath, fileName + ".part");
    destinationFile = new File(filePath, fileName + ".gz");

    if (partialDestinationFile.exists()) {
        partialDestinationFile.delete();
    }
    if (!cancellingDownload) {
        updateURI = updateInfo.getDownloadUri();

        boolean md5Available = true;

        try {
            req = new HttpGet(updateURI);
            md5req = new HttpGet(updateURI + ".md5sum");

            // Add no-cache Header, so the File gets downloaded each time
            req.addHeader("Cache-Control", "no-cache");
            md5req.addHeader("Cache-Control", "no-cache");
            //Proceed request
            md5response = MD5httpClient.execute(md5req);
            response = httpClient.execute(req);

            //Get responses codes
            int serverResponse = response.getStatusLine().getStatusCode();
            int md5serverResponse = md5response.getStatusLine().getStatusCode();

            if (md5serverResponse != HttpStatus.SC_OK) {
                md5Available = false;
            }

            if (serverResponse == HttpStatus.SC_OK) {
                if (md5Available) {
                    //Get the md5 sum and save it into a string
                    try {
                        HttpEntity temp = md5response.getEntity();
                        InputStreamReader isr = new InputStreamReader(temp.getContent());
                        BufferedReader br = new BufferedReader(isr);
                        try {
                            downloadedMD5 = br.readLine().split("  ")[0];
                        } catch (NullPointerException e) {
                            md5Available = false;
                        }
                        br.close();
                        isr.close();

                        if (temp != null) {
                            temp.consumeContent();
                        }
                    } catch (IOException e) {
                        //Nothing to do, just imagine there is a problem with download
                        md5Available = false;
                    }
                }

                // Download Update ZIP if md5sum went ok
                HttpEntity entity = response.getEntity();
                dumpFile(entity, partialDestinationFile, destinationFile);
                //Will cancel download
                if (cancellingDownload) {
                    mToastHandler
                            .sendMessage(mToastHandler.obtainMessage(0, R.string.unable_to_download_file, 0));
                    return false;
                }
                if (entity != null && !cancellingDownload) {
                    entity.consumeContent();
                } else {
                    entity = null;
                }

                if (md5Available) {
                    if (!MD5.checkMD5(downloadedMD5, destinationFile)) {
                        throw new IOException("md5_verification_failed");
                    }
                }

                return true;
            }
        } catch (IOException ex) {
            mToastHandler.sendMessage(mToastHandler.obtainMessage(0, ex.getMessage()));
        }
        if (Thread.currentThread().isInterrupted() || !Thread.currentThread().isAlive()) {
            mToastHandler.sendMessage(mToastHandler.obtainMessage(0, R.string.unable_to_download_file, 0));
            return false;
        }
    }

    mToastHandler.sendMessage(mToastHandler.obtainMessage(0, R.string.unable_to_download_file, 0));
    return false;
}

From source file:org.alfresco.repo.content.transform.TextToPdfContentTransformer.java

@Override
protected void transformInternal(ContentReader reader, ContentWriter writer, TransformationOptions options)
        throws Exception {
    PDDocument pdf = null;// w  w  w  .  j  a v  a2  s  .  c om
    InputStream is = null;
    InputStreamReader ir = null;
    OutputStream os = null;
    try {
        is = reader.getContentInputStream();
        ir = buildReader(is, reader.getEncoding(), reader.getContentUrl());

        TransformationOptionLimits limits = getLimits(reader, writer, options);
        TransformationOptionPair pageLimits = limits.getPagesPair();
        pdf = transformer.createPDFFromText(ir, pageLimits, reader.getContentUrl());

        // dump it all to the writer
        os = writer.getContentOutputStream();
        pdf.save(os);
    } finally {
        if (pdf != null) {
            try {
                pdf.close();
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
        if (ir != null) {
            try {
                ir.close();
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
        if (is != null) {
            try {
                is.close();
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
        if (os != null) {
            try {
                os.close();
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:Opm_Package.New_CommitsInterval.java

public String callURL(String myURL) {
    //System.out.println("Requested URL:" + myURL);
    StringBuilder sb = new StringBuilder();
    URLConnection urlConn = null;
    InputStreamReader in = null;
    try {//from ww  w  .  j a  v a 2  s.  co  m
        URL url = new URL(myURL);
        urlConn = url.openConnection();
        if (urlConn != null) {
            urlConn.setReadTimeout(60 * 1000);
        }
        if (urlConn != null && urlConn.getInputStream() != null) {
            in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());
            BufferedReader bufferedReader = new BufferedReader(in);
            if (bufferedReader != null) {
                int cp;
                while ((cp = bufferedReader.read()) != -1) {
                    sb.append((char) cp);
                }
                bufferedReader.close();
            }
        }
        in.close();
    } catch (Exception e) {
        throw new RuntimeException("Exception while calling URL:" + myURL, e);
    }

    return sb.toString();
}

From source file:com.ephesoft.dcma.util.FileUtils.java

/**
 * An utility method to update the properties file.
 * /*ww  w  .  j a va 2s .c  o  m*/
 * @param propertyFile File
 * @param propertyMap Map<String, String>
 * @param comments String
 * @throws IOException If any of the parameter is null or input property file is not found.
 */
public static void updateProperty(final File propertyFile, final Map<String, String> propertyMap,
        final String comments) throws IOException {
    if (null == propertyFile || null == propertyMap || propertyMap.isEmpty()) {
        throw new IOException("propertyFile/propertyMap is null or empty.");
    }
    String commentsToAdd = HASH_STRING + comments;
    FileInputStream fileInputStream = null;
    InputStreamReader inputStreamReader = null;
    BufferedReader bufferedReader = null;
    List<String> propertiesToWrite = null;
    try {
        fileInputStream = new FileInputStream(propertyFile);
        inputStreamReader = new InputStreamReader(fileInputStream);
        bufferedReader = new BufferedReader(inputStreamReader);
        propertiesToWrite = new ArrayList<String>();
        propertiesToWrite.add(commentsToAdd);
        processPropertyFile(propertyMap, bufferedReader, propertiesToWrite);
    } finally {
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException exception) {
                LOGGER.error("Exception occured while closing bufferedReader :" + exception);
            }
        }
        if (inputStreamReader != null) {
            try {
                inputStreamReader.close();
            } catch (IOException exception) {
                LOGGER.error("Exception while closing input stream :" + exception);
            }
        }
    }
    writeToPropertyFile(propertyFile, propertiesToWrite);
}

From source file:org.opendatakit.common.security.spring.Oauth2ResourceFilter.java

private Map<String, Object> getJsonResponse(String url, String accessToken) {

    Map<String, Object> nullData = new HashMap<String, Object>();

    // OK if we got here, we have a valid token.
    // Issue the request...
    URI nakedUri;/*from  w  w w  .  j  av a 2s .c o m*/
    try {
        nakedUri = new URI(url);
    } catch (URISyntaxException e2) {
        e2.printStackTrace();
        logger.error(e2.toString());
        return nullData;
    }

    List<NameValuePair> qparams = new ArrayList<NameValuePair>();
    qparams.add(new BasicNameValuePair("access_token", accessToken));
    URI uri;
    try {
        uri = new URI(nakedUri.getScheme(), nakedUri.getUserInfo(), nakedUri.getHost(), nakedUri.getPort(),
                nakedUri.getPath(), URLEncodedUtils.format(qparams, "UTF-8"), null);
    } catch (URISyntaxException e1) {
        e1.printStackTrace();
        logger.error(e1.toString());
        return nullData;
    }

    // DON'T NEED clientId on the toke request...
    // addCredentials(clientId, clientSecret, nakedUri.getHost());
    // setup request interceptor to do preemptive auth
    // ((DefaultHttpClient) client).addRequestInterceptor(getPreemptiveAuth(), 0);

    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, SERVICE_TIMEOUT_MILLISECONDS);
    HttpConnectionParams.setSoTimeout(httpParams, SOCKET_ESTABLISHMENT_TIMEOUT_MILLISECONDS);
    // support redirecting to handle http: => https: transition
    HttpClientParams.setRedirecting(httpParams, true);
    // support authenticating
    HttpClientParams.setAuthenticating(httpParams, true);

    httpParams.setParameter(ClientPNames.MAX_REDIRECTS, 1);
    httpParams.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
    // setup client
    HttpClient client = httpClientFactory.createHttpClient(httpParams);

    HttpGet httpget = new HttpGet(uri);
    logger.info(httpget.getURI().toString());

    HttpResponse response = null;
    try {
        response = client.execute(httpget, new BasicHttpContext());
        int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode != HttpStatus.SC_OK) {
            logger.error("not 200: " + statusCode);
            return nullData;
        } else {
            HttpEntity entity = response.getEntity();

            if (entity != null && entity.getContentType().getValue().toLowerCase().contains("json")) {
                BufferedReader reader = null;
                InputStreamReader isr = null;
                try {
                    reader = new BufferedReader(isr = new InputStreamReader(entity.getContent()));
                    @SuppressWarnings("unchecked")
                    Map<String, Object> userData = mapper.readValue(reader, Map.class);
                    return userData;
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            // ignore
                        }
                    }
                    if (isr != null) {
                        try {
                            isr.close();
                        } catch (IOException e) {
                            // ignore
                        }
                    }
                }
            } else {
                logger.error("unexpected body");
                return nullData;
            }
        }
    } catch (IOException e) {
        logger.error(e.toString());
        return nullData;
    } catch (Exception e) {
        logger.error(e.toString());
        return nullData;
    }
}

From source file:com.taobao.diamond.client.processor.ServerAddressProcessor.java

void reloadServerAddresses() {
    FileInputStream fis = null;//ww w.  j av  a 2 s. c o  m
    InputStreamReader reader = null;
    BufferedReader bufferedReader = null;
    try {
        File serverAddressFile = new File(
                generateLocalFilePath(this.diamondConfigure.getFilePath(), "ServerAddress"));

        if (!serverAddressFile.exists()) {
            return;
        }
        fis = new FileInputStream(serverAddressFile);
        reader = new InputStreamReader(fis);
        bufferedReader = new BufferedReader(reader);
        String address = null;
        while ((address = bufferedReader.readLine()) != null) {
            address = address.trim();
            if (StringUtils.isNotBlank(address)) {
                diamondConfigure.getDomainNameList().add(address);
            }
        }
        bufferedReader.close();
        reader.close();
        fis.close();
    } catch (Exception e) {
        log.error("", e);
    } finally {
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (Exception e) {

            }
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (Exception e) {

            }
        }
        if (fis != null) {
            try {
                fis.close();
            } catch (Exception e) {

            }
        }
    }
}