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:org.apache.jmeter.save.SaveService.java

public static Object loadElement(InputStream in) throws IOException {
    // Get the InputReader to use
    InputStreamReader inputStreamReader = getInputStreamReader(in);
    // Use deprecated method, to avoid duplicating code
    Object element = JMXSAVER.fromXML(inputStreamReader);
    inputStreamReader.close();
    return element;
}

From source file:org.cryptsecure.HttpStringRequest.java

/**
 * Convert the content of a HTTP response into a string.
 * // w w w .j  a  va 2 s . c  om
 * @param response
 *            the response
 * @return the content as string
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
private static String getContentAsString(HttpResponse response) throws IOException {
    String returnString = "";
    HttpEntity httpEntity = response.getEntity();

    InputStream inputStream = httpEntity.getContent();
    InputStreamReader is = new InputStreamReader(inputStream, "ISO-8859-1"); // "UTF-8");

    if (is != null) {
        Writer writer = new StringWriter();

        char[] buffer = new char[1024];
        try {
            Reader reader = new BufferedReader(is);
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
            is.close();
        }

        returnString = writer.toString().replace("\n", "");
    }

    return returnString;
}

From source file:Main.java

public static String readAssetsByName(Context context, String name, String encoding) {
    String text = null;/*ww  w.  j  a  v a2 s .  c o  m*/
    InputStreamReader inputReader = null;
    BufferedReader bufReader = null;
    try {
        inputReader = new InputStreamReader(context.getAssets().open(name));
        bufReader = new BufferedReader(inputReader);
        String line = null;
        StringBuffer buffer = new StringBuffer();
        while ((line = bufReader.readLine()) != null) {
            buffer.append(line);
        }
        text = new String(buffer.toString().getBytes(), encoding);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (bufReader != null) {
                bufReader.close();
            }
            if (inputReader != null) {
                inputReader.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return text;
}

From source file:Main.java

public static String readRawByName(Context context, int id, String encoding) {
    String text = null;/*from  w ww .j av  a 2 s  . c om*/
    InputStreamReader inputReader = null;
    BufferedReader bufReader = null;
    try {
        inputReader = new InputStreamReader(context.getResources().openRawResource(id));
        bufReader = new BufferedReader(inputReader);
        String line = null;
        StringBuffer buffer = new StringBuffer();
        while ((line = bufReader.readLine()) != null) {
            buffer.append(line);
        }
        text = new String(buffer.toString().getBytes(), encoding);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (bufReader != null) {
                bufReader.close();
            }
            if (inputReader != null) {
                inputReader.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return text;
}

From source file:pt.webdetails.cns.notifications.sparkl.kettle.baserver.web.utils.HttpConnectionHelper.java

public static Response callHttp(String url, String user, String password)
        throws IOException, KettleStepException {

    // used for calculating the responseTime
    long startTime = System.currentTimeMillis();

    HttpClient httpclient = SlaveConnectionManager.getInstance().createHttpClient();
    HttpMethod method = new GetMethod(url);
    httpclient.getParams().setAuthenticationPreemptive(true);
    Credentials credentials = new UsernamePasswordCredentials(user, password);
    httpclient.getState().setCredentials(AuthScope.ANY, credentials);
    HostConfiguration hostConfiguration = new HostConfiguration();

    int status;//from w w w . j a  v a2s  . com
    try {
        status = httpclient.executeMethod(hostConfiguration, method);
    } catch (IllegalArgumentException ex) {
        status = -1;
    }

    Response response = new Response();
    if (status != -1) {
        String body = null;
        String encoding = "";
        Header contentTypeHeader = method.getResponseHeader("Content-Type");
        if (contentTypeHeader != null) {
            String contentType = contentTypeHeader.getValue();
            if (contentType != null && contentType.contains("charset")) {
                encoding = contentType.replaceFirst("^.*;\\s*charset\\s*=\\s*", "").replace("\"", "").trim();
            }
        }

        // get the response
        InputStreamReader inputStreamReader = null;
        if (!Const.isEmpty(encoding)) {
            inputStreamReader = new InputStreamReader(method.getResponseBodyAsStream(), encoding);
        } else {
            inputStreamReader = new InputStreamReader(method.getResponseBodyAsStream());
        }
        StringBuilder bodyBuffer = new StringBuilder();
        int c;
        while ((c = inputStreamReader.read()) != -1) {
            bodyBuffer.append((char) c);
        }
        inputStreamReader.close();
        body = bodyBuffer.toString();

        // Get response time
        long responseTime = System.currentTimeMillis() - startTime;

        response.setStatusCode(status);
        response.setResult(body);
        response.setResponseTime(responseTime);
    }
    return response;
}

From source file:org.alfresco.utilities.LdtpUtils.java

/**
 * Check if process identified by <processName> is currently running
 * /*from  www .j a v  a2 s.com*/
 * @param processName
 * @return
 */
public static boolean isProcessRunning(String processName) {
    processName = processName.toLowerCase();
    Process p = null;
    try {
        if (SystemUtils.IS_OS_MAC) {
            p = Runtime.getRuntime().exec("ps -ef");
        } else if (SystemUtils.IS_OS_WINDOWS) {
            p = Runtime.getRuntime().exec(new String[] { "cmd", "/c", "tasklist" });
        }
        InputStream inputStream = p.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader bufferReader = new BufferedReader(inputStreamReader);
        String line;
        while ((line = bufferReader.readLine()) != null) {
            if (line.toLowerCase().contains(processName))
                return true;
        }
        inputStream.close();
        inputStreamReader.close();
        bufferReader.close();
    } catch (Exception err) {
        err.printStackTrace();
    }
    return false;
}

From source file:Main.java

public static String readRawByName(Context context, int id, String encoding) {
    String text = "";
    InputStreamReader inputReader = null;
    BufferedReader bufReader = null;
    try {//from  w  w  w  .ja  v  a 2s  . com
        inputReader = new InputStreamReader(context.getResources().openRawResource(id));
        bufReader = new BufferedReader(inputReader);
        String line = null;
        StringBuffer buffer = new StringBuffer();
        while ((line = bufReader.readLine()) != null) {
            buffer.append(line);
        }
        text = new String(buffer.toString().getBytes(), encoding);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (bufReader != null) {
                bufReader.close();
                bufReader = null;
            }
            if (inputReader != null) {
                inputReader.close();
                inputReader = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return text;
}

From source file:Main.java

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

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

    String fullUrl = urlStr + "?" + paramsEncoded;

    String result = null;
    URL url = null;
    HttpURLConnection connection = null;
    InputStreamReader in = null;
    try {
        url = new URL(fullUrl);
        connection = (HttpURLConnection) url.openConnection();
        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.webarch.common.net.http.HttpService.java

/**
 * ?Http/* w  w w  .  jav a 2  s.c o m*/
 *
 * @param requestUrl    ?
 * @param requestMethod ?
 * @param outputJson    ?
 * @return 
 */
public static String doHttpRequest(String requestUrl, String requestMethod, String outputJson) {
    String result = null;
    try {
        StringBuffer buffer = new StringBuffer();
        URL url = new URL(requestUrl);
        HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
        httpUrlConn.setDoOutput(true);
        httpUrlConn.setDoInput(true);
        httpUrlConn.setUseCaches(false);

        httpUrlConn.setUseCaches(false);
        httpUrlConn.setRequestProperty("Accept-Charset", DEFAULT_CHARSET);
        httpUrlConn.setRequestProperty("Content-Type", "application/json;charset=" + DEFAULT_CHARSET);
        // ?GET/POST
        httpUrlConn.setRequestMethod(requestMethod);

        if ("GET".equalsIgnoreCase(requestMethod))
            httpUrlConn.connect();

        // ????
        if (null != outputJson) {
            OutputStream outputStream = httpUrlConn.getOutputStream();
            //??
            outputStream.write(outputJson.getBytes(DEFAULT_CHARSET));
            outputStream.close();
        }

        // ???
        InputStream inputStream = httpUrlConn.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, DEFAULT_CHARSET);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            buffer.append(str);
        }
        result = buffer.toString();
        bufferedReader.close();
        inputStreamReader.close();
        // ?
        inputStream.close();
        httpUrlConn.disconnect();
    } catch (ConnectException ce) {
        logger.error("server connection timed out.", ce);
    } catch (Exception e) {
        logger.error("http request error:", e);
    } finally {
        return result;
    }
}

From source file:com.webarch.common.net.http.HttpService.java

/**
 * ?Https//from ww  w . java  2 s  .  com
 *
 * @param requestUrl    ?
 * @param requestMethod ?
 * @param trustManagers ??
 * @param outputJson    ?
 * @return 
 */
public static String doHttpsRequest(String requestUrl, String requestMethod, TrustManager[] trustManagers,
        String outputJson) {
    String result = null;
    try {
        StringBuffer buffer = new StringBuffer();
        // SSLContext??
        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        sslContext.init(null, trustManagers, new java.security.SecureRandom());
        // SSLContextSSLSocketFactory
        SSLSocketFactory ssf = sslContext.getSocketFactory();
        URL url = new URL(requestUrl);
        HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
        httpUrlConn.setSSLSocketFactory(ssf);
        httpUrlConn.setDoOutput(true);
        httpUrlConn.setDoInput(true);
        httpUrlConn.setUseCaches(false);
        httpUrlConn.setUseCaches(false);
        httpUrlConn.setRequestProperty("Accept-Charset", DEFAULT_CHARSET);
        httpUrlConn.setRequestProperty("Content-Type", "application/json;charset=" + DEFAULT_CHARSET);
        // ?GET/POST
        httpUrlConn.setRequestMethod(requestMethod);

        if ("GET".equalsIgnoreCase(requestMethod))
            httpUrlConn.connect();

        // ????
        if (null != outputJson) {
            OutputStream outputStream = httpUrlConn.getOutputStream();
            //??
            outputStream.write(outputJson.getBytes(DEFAULT_CHARSET));
            outputStream.close();
        }

        // ???
        InputStream inputStream = httpUrlConn.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, DEFAULT_CHARSET);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            buffer.append(str);
        }
        result = buffer.toString();
        bufferedReader.close();
        inputStreamReader.close();
        // ?
        inputStream.close();
        httpUrlConn.disconnect();
    } catch (ConnectException ce) {
        logger.error("Weixin server connection timed out.", ce);
    } catch (Exception e) {
        logger.error("https request error:", e);
    } finally {
        return result;
    }
}