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.quinsoft.zeidon.config.ZeidonIniPreferences.java

private void loadZeidonIni(InputStream iniFile) {
    if (iniFile == null)
        throw new ZeidonException("Could not find zeidon.ini");

    InputStreamReader reader = new InputStreamReader(iniFile);

    try {/* ww  w  .j av a2  s  . c  om*/

        iniConfObj = new HierarchicalINIConfiguration();
        iniConfObj.load(reader);
        reader.close();
    } catch (Exception e) {
        throw ZeidonException.wrapException(e).prependFilename(iniFileName);
    } finally {
        IOUtils.closeQuietly(reader);
    }
}

From source file:com.dycody.android.idealnote.utils.GeocodeHelper.java

public static List<String> autocomplete(String input) {
    String MAPS_API_KEY = BuildConfig.MAPS_API_KEY;
    if (TextUtils.isEmpty(MAPS_API_KEY)) {
        return Collections.emptyList();
    }/*  w ww  .ja v  a  2  s  . c  o m*/
    ArrayList<String> resultList = null;

    HttpURLConnection conn = null;
    InputStreamReader in = null;
    StringBuilder jsonResults = new StringBuilder();
    try {
        URL url = new URL(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON + "?key=" + MAPS_API_KEY + "&input="
                + URLEncoder.encode(input, "utf8"));
        conn = (HttpURLConnection) url.openConnection();
        in = new InputStreamReader(conn.getInputStream());
        // Load the results into a StringBuilder
        int read;
        char[] buff = new char[1024];
        while ((read = in.read(buff)) != -1) {
            jsonResults.append(buff, 0, read);
        }
    } catch (MalformedURLException e) {
        Log.e(Constants.TAG, "Error processing Places API URL");
        return null;
    } catch (IOException e) {
        Log.e(Constants.TAG, "Error connecting to Places API");
        return null;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                Log.e(Constants.TAG, "Error closing address autocompletion InputStream");
            }
        }
    }

    try {
        // Create a JSON object hierarchy from the results
        JSONObject jsonObj = new JSONObject(jsonResults.toString());
        JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");
        // Extract the Place descriptions from the results
        resultList = new ArrayList<>(predsJsonArray.length());
        for (int i = 0; i < predsJsonArray.length(); i++) {
            resultList.add(predsJsonArray.getJSONObject(i).getString("description"));
        }
    } catch (JSONException e) {
        Log.e(Constants.TAG, "Cannot process JSON results", e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
        SystemHelper.closeCloseable(in);
    }
    return resultList;
}

From source file:com.mobilis.android.nfc.activities.MagTekFragment.java

public static String ReadSettings(Context context, String file) throws IOException {
    FileInputStream fis = null;//from ww w .  j  a  v  a2 s . c o m
    InputStreamReader isr = null;
    String data = null;
    fis = context.openFileInput(file);
    isr = new InputStreamReader(fis);
    char[] inputBuffer = new char[fis.available()];
    isr.read(inputBuffer);
    data = new String(inputBuffer);
    isr.close();
    fis.close();
    return data;
}

From source file:cd.education.data.collector.android.utilities.WebUtils.java

/**
 * Common method for returning a parsed xml document given a url and the
 * http context and client objects involved in the web connection.
 *
 * @param urlString// w ww .  j a v  a 2 s . co  m
 * @param localContext
 * @param httpclient
 * @return
 */
public static DocumentFetchResult getXmlDocument(String urlString, HttpContext localContext,
        HttpClient httpclient) {
    URI u = null;
    try {
        URL url = new URL(urlString);
        u = url.toURI();
    } catch (Exception e) {
        e.printStackTrace();
        return new DocumentFetchResult(e.getLocalizedMessage()
                // + app.getString(R.string.while_accessing) + urlString);
                + ("while accessing") + urlString, 0);
    }

    if (u.getHost() == null) {
        return new DocumentFetchResult("Invalid server URL (no hostname): " + urlString, 0);
    }

    // if https then enable preemptive basic auth...
    if (u.getScheme().equals("https")) {
        enablePreemptiveBasicAuth(localContext, u.getHost());
    }

    // set up request...
    HttpGet req = WebUtils.createOpenRosaHttpGet(u);
    req.addHeader(WebUtils.ACCEPT_ENCODING_HEADER, WebUtils.GZIP_CONTENT_ENCODING);

    HttpResponse response = null;
    try {
        response = httpclient.execute(req, localContext);
        int statusCode = response.getStatusLine().getStatusCode();

        HttpEntity entity = response.getEntity();

        if (statusCode != HttpStatus.SC_OK) {
            WebUtils.discardEntityBytes(response);
            if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
                // clear the cookies -- should not be necessary?
                Collect.getInstance().getCookieStore().clear();
            }
            String webError = response.getStatusLine().getReasonPhrase() + " (" + statusCode + ")";

            return new DocumentFetchResult(u.toString() + " responded with: " + webError, statusCode);
        }

        if (entity == null) {
            String error = "No entity body returned from: " + u.toString();
            Log.e(t, error);
            return new DocumentFetchResult(error, 0);
        }

        if (!entity.getContentType().getValue().toLowerCase(Locale.ENGLISH)
                .contains(WebUtils.HTTP_CONTENT_TYPE_TEXT_XML)) {
            WebUtils.discardEntityBytes(response);
            String error = "ContentType: " + entity.getContentType().getValue() + " returned from: "
                    + u.toString()
                    + " is not text/xml.  This is often caused a network proxy.  Do you need to login to your network?";
            Log.e(t, error);
            return new DocumentFetchResult(error, 0);
        }
        // parse response
        Document doc = null;
        try {
            InputStream is = null;
            InputStreamReader isr = null;
            try {
                is = entity.getContent();
                Header contentEncoding = entity.getContentEncoding();
                if (contentEncoding != null
                        && contentEncoding.getValue().equalsIgnoreCase(WebUtils.GZIP_CONTENT_ENCODING)) {
                    is = new GZIPInputStream(is);
                }
                isr = new InputStreamReader(is, "UTF-8");
                doc = new Document();
                KXmlParser parser = new KXmlParser();
                parser.setInput(isr);
                parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
                doc.parse(parser);
                isr.close();
                isr = null;
            } finally {
                if (isr != null) {
                    try {
                        // ensure stream is consumed...
                        final long count = 1024L;
                        while (isr.skip(count) == count)
                            ;
                    } catch (Exception e) {
                        // no-op
                    }
                    try {
                        isr.close();
                    } catch (Exception e) {
                        // no-op
                    }
                }
                if (is != null) {
                    try {
                        is.close();
                    } catch (Exception e) {
                        // no-op
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            String error = "Parsing failed with " + e.getMessage() + "while accessing " + u.toString();
            Log.e(t, error);
            return new DocumentFetchResult(error, 0);
        }

        boolean isOR = false;
        Header[] fields = response.getHeaders(WebUtils.OPEN_ROSA_VERSION_HEADER);
        if (fields != null && fields.length >= 1) {
            isOR = true;
            boolean versionMatch = false;
            boolean first = true;
            StringBuilder b = new StringBuilder();
            for (Header h : fields) {
                if (WebUtils.OPEN_ROSA_VERSION.equals(h.getValue())) {
                    versionMatch = true;
                    break;
                }
                if (!first) {
                    b.append("; ");
                }
                first = false;
                b.append(h.getValue());
            }
            if (!versionMatch) {
                Log.w(t, WebUtils.OPEN_ROSA_VERSION_HEADER + " unrecognized version(s): " + b.toString());
            }
        }
        return new DocumentFetchResult(doc, isOR);
    } catch (Exception e) {
        clearHttpConnectionManager();
        e.printStackTrace();
        String cause;
        Throwable c = e;
        while (c.getCause() != null) {
            c = c.getCause();
        }
        cause = c.toString();
        String error = "Error: " + cause + " while accessing " + u.toString();

        Log.w(t, error);
        return new DocumentFetchResult(error, 0);
    }
}

From source file:com.ibm.team.build.internal.hjplugin.util.HttpUtils.java

/**
 * Perform GET request against an RTC server
 * @param serverURI The RTC server/*from  w ww .  j a  v a2s  . c  om*/
 * @param uri The relative URI for the GET. It is expected it is already encoded if necessary.
 * @param userId The userId to authenticate as
 * @param password The password to authenticate with
 * @param timeout The timeout period for the connection (in seconds)
 * @param httpContext The context from the login if cycle is being managed by the caller
 * Otherwise <code>null</code> and this call will handle the login.
 * @param listener The listener to report errors to. May be 
 * <code>null</code>
 * @return Result of the GET (JSON response)
 * @throws IOException Thrown if things go wrong
 * @throws InvalidCredentialsException
 * @throws GeneralSecurityException 
 */
public static GetResult performGet(String serverURI, String uri, String userId, String password, int timeout,
        HttpClientContext httpContext, TaskListener listener)
        throws IOException, InvalidCredentialsException, GeneralSecurityException {

    CloseableHttpClient httpClient = getClient();
    String fullURI = getFullURI(serverURI, uri);
    HttpGet request = getGET(fullURI, timeout);
    if (httpContext == null) {
        httpContext = createHttpContext();
    }

    LOGGER.finer("GET: " + request.getURI()); //$NON-NLS-1$
    CloseableHttpResponse response = httpClient.execute(request, httpContext);
    try {
        // based on the response do any authentication. If authentication requires
        // the request to be performed again (i.e. Basic auth) re-issue request
        response = authenticateIfRequired(response, httpClient, httpContext, serverURI, userId, password,
                timeout, listener);
        if (response == null) {
            // retry get
            request = getGET(fullURI, timeout);
            response = httpClient.execute(request, httpContext);
        }
        int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode == 200) {
            InputStreamReader inputStream = new InputStreamReader(response.getEntity().getContent(), UTF_8);
            try {
                String responseContent = IOUtils.toString(inputStream);
                GetResult result = new GetResult(httpContext, JSONSerializer.toJSON(responseContent));
                return result;
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    LOGGER.finer("Failed to close the result input stream for request: " + fullURI); //$NON-NLS-1$
                }
            }
        } else if (statusCode == 401) {
            // if still un-authorized, then there is a good chance the basic credentials are bad.
            throw new InvalidCredentialsException(Messages.HttpUtils_authentication_failed(userId, serverURI));

        } else {
            // capture details about the error
            LOGGER.finer(Messages.HttpUtils_GET_failed(fullURI, statusCode));
            if (listener != null) {
                listener.fatalError(Messages.HttpUtils_GET_failed(fullURI, statusCode));
            }
            throw logError(fullURI, response, Messages.HttpUtils_GET_failed(fullURI, statusCode));
        }
    } finally {
        closeResponse(response);
    }
}

From source file:Main.java

public static String httpPost(String urlStr, List<NameValuePair> params) {

    String paramsEncoded = "";
    if (params != null) {
        paramsEncoded = URLEncodedUtils.format(params, "UTF-8");
    }//from  w  w  w  .  j a va 2  s  .  c om

    String result = null;
    URL url = null;
    HttpURLConnection connection = null;
    InputStreamReader in = null;
    try {
        url = new URL(urlStr);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Charset", "utf-8");
        DataOutputStream dop = new DataOutputStream(connection.getOutputStream());
        dop.writeBytes(paramsEncoded);
        dop.flush();
        dop.close();

        in = new InputStreamReader(connection.getInputStream());
        BufferedReader bufferedReader = new BufferedReader(in);
        StringBuffer strBuffer = new StringBuffer();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            strBuffer.append(line);
        }
        result = strBuffer.toString();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
    return result;
}

From source file:com.ikon.util.MailUtils.java

/**
 * User tinyurl service as url shorter Depends on commons-httpclient:commons-httpclient:jar:3.0 because of
 * org.apache.jackrabbit:jackrabbit-webdav:jar:1.6.4
 *//*from  www.  java2 s . c o m*/
public static String getTinyUrl(String fullUrl) throws HttpException, IOException {
    HttpClient httpclient = new HttpClient();

    // Prepare a request object
    HttpMethod method = new GetMethod("http://tinyurl.com/api-create.php");
    method.setQueryString(new NameValuePair[] { new NameValuePair("url", fullUrl) });
    httpclient.executeMethod(method);
    InputStreamReader isr = new InputStreamReader(method.getResponseBodyAsStream(), "UTF-8");
    StringWriter sw = new StringWriter();
    int c;
    while ((c = isr.read()) != -1)
        sw.write(c);
    isr.close();
    method.releaseConnection();

    return sw.toString();
}

From source file:com.vmware.bdd.utils.CommonUtil.java

public static String dataFromFile(String filePath) throws IOException, FileNotFoundException {
    StringBuffer dataStringBuffer = new StringBuffer();
    FileInputStream fis = null;// ww w.j av  a  2  s. c  o  m
    InputStreamReader inputStreamReader = null;
    BufferedReader bufferedReader = null;
    try {
        fis = new FileInputStream(filePath);
        inputStreamReader = new InputStreamReader(fis, "UTF-8");
        bufferedReader = new BufferedReader(inputStreamReader);
        String line = "";
        while ((line = bufferedReader.readLine()) != null) {
            dataStringBuffer.append(line);
            dataStringBuffer.append("\n");
        }
    } finally {
        if (fis != null) {
            fis.close();
        }
        if (inputStreamReader != null) {
            inputStreamReader.close();
        }
        if (bufferedReader != null) {
            bufferedReader.close();
        }
    }
    return dataStringBuffer.toString();
}

From source file:net.oneandone.shared.artifactory.SearchByGavTest.java

/**
 * Test of search method, of class SearchByGav.
 *//*from w  w  w .  j av a  2 s .com*/
@Test
public void testSearch() throws Exception {
    final String resourceName = "/junit-4.11-storage.json";
    final InputStreamReader reader = new InputStreamReader(
            SearchByGavTest.class.getResourceAsStream(resourceName));
    ArtifactoryResults staticResults;
    try {
        staticResults = Utils.createGson().fromJson(reader, ArtifactoryResults.class);
    } finally {
        reader.close();
    }
    when(mockClient.execute(any(HttpGet.class), any(ResponseHandler.class))).thenReturn(staticResults);
    List<ArtifactoryStorage> result = sut.search(repositoryName, gav);
    assertEquals(4, result.size());
}

From source file:info.magnolia.objectfactory.configuration.ComponentConfigurationReader.java

public ComponentsDefinition readFromResource(String resourcePath) {
    final InputStreamReader reader = new InputStreamReader(getClass().getResourceAsStream(resourcePath));
    try {/*  w  ww  .  j a  v  a  2s .com*/
        return read(reader);
    } finally {
        try {
            reader.close();
        } catch (IOException e) {
            log.error("Can't close input for " + resourcePath);
        }
    }
}