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:cn.com.zhenshiyin.crowd.net.AsyncHttpPost.java

@Override
public void run() {
    String ret = "";
    try {//  ww  w  . j a va  2  s. c o  m
        request = new HttpPost(url);
        if (Constants.isGzip) {
            request.addHeader("Accept-Encoding", "gzip");
        } else {
            request.addHeader("Accept-Encoding", "default");
        }
        LogUtil.d(AsyncHttpPost.class.getName(), "AsyncHttpPost  request to url :" + url);

        if (parameter != null && parameter.size() > 0) {
            List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
            for (RequestParameter p : parameter) {
                list.add(new BasicNameValuePair(p.getName(), p.getValue()));
            }
            ((HttpPost) request).setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
        }
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeout);
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeout);
        HttpResponse response = httpClient.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            InputStream is = response.getEntity().getContent();
            BufferedInputStream bis = new BufferedInputStream(is);
            bis.mark(2);
            // ??
            byte[] header = new byte[2];
            int result = bis.read(header);
            // reset??
            bis.reset();
            // ?GZIP?
            int headerData = getShort(header);
            // Gzip ? ? 0x1f8b
            if (result != -1 && headerData == 0x1f8b) {
                LogUtil.d("HttpTask", " use GZIPInputStream  ");
                is = new GZIPInputStream(bis);
            } else {
                LogUtil.d("HttpTask", " not use GZIPInputStream");
                is = bis;
            }
            InputStreamReader reader = new InputStreamReader(is, "utf-8");
            char[] data = new char[100];
            int readSize;
            StringBuffer sb = new StringBuffer();
            while ((readSize = reader.read(data)) > 0) {
                sb.append(data, 0, readSize);
            }
            ret = sb.toString();
            bis.close();
            reader.close();

        } else {
            RequestException exception = new RequestException(RequestException.IO_EXCEPTION,
                    "??,??" + statusCode);
            ret = ErrorUtil.errorJson("ERROR.HTTP.001", exception.getMessage());
        }

        LogUtil.d(AsyncHttpPost.class.getName(), "AsyncHttpPost  request to url :" + url + "  finished !");
    } catch (java.lang.IllegalArgumentException e) {
        RequestException exception = new RequestException(RequestException.IO_EXCEPTION,
                Constants.ERROR_MESSAGE);
        ret = ErrorUtil.errorJson("ERROR.HTTP.002", exception.getMessage());
        LogUtil.d(AsyncHttpGet.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  onFail  " + e.getMessage());
    } catch (org.apache.http.conn.ConnectTimeoutException e) {
        RequestException exception = new RequestException(RequestException.SOCKET_TIMEOUT_EXCEPTION,
                Constants.ERROR_MESSAGE);
        ret = ErrorUtil.errorJson("ERROR.HTTP.003", exception.getMessage());
        LogUtil.d(AsyncHttpPost.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  onFail  " + e.getMessage());
    } catch (java.net.SocketTimeoutException e) {
        RequestException exception = new RequestException(RequestException.SOCKET_TIMEOUT_EXCEPTION,
                Constants.ERROR_MESSAGE);
        ret = ErrorUtil.errorJson("ERROR.HTTP.004", exception.getMessage());
        LogUtil.d(AsyncHttpPost.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  onFail  " + e.getMessage());
    } catch (UnsupportedEncodingException e) {
        RequestException exception = new RequestException(RequestException.UNSUPPORTED_ENCODEING_EXCEPTION,
                "?");
        ret = ErrorUtil.errorJson("ERROR.HTTP.005", exception.getMessage());
        LogUtil.d(AsyncHttpPost.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  UnsupportedEncodingException  " + e.getMessage());
    } catch (org.apache.http.conn.HttpHostConnectException e) {
        RequestException exception = new RequestException(RequestException.CONNECT_EXCEPTION, "");
        ret = ErrorUtil.errorJson("ERROR.HTTP.006", exception.getMessage());
        LogUtil.d(AsyncHttpPost.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  HttpHostConnectException  " + e.getMessage());
    } catch (ClientProtocolException e) {
        RequestException exception = new RequestException(RequestException.CLIENT_PROTOL_EXCEPTION,
                "??");
        ret = ErrorUtil.errorJson("ERROR.HTTP.007", exception.getMessage());
        e.printStackTrace();
        LogUtil.d(AsyncHttpPost.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  ClientProtocolException " + e.getMessage());
    } catch (IOException e) {
        RequestException exception = new RequestException(RequestException.IO_EXCEPTION, "??");
        ret = ErrorUtil.errorJson("ERROR.HTTP.008", exception.getMessage());
        e.printStackTrace();
        LogUtil.d(AsyncHttpPost.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  IOException  " + e.getMessage());
    } finally {
        if (!Constants.IS_STOP_REQUEST) {
            Message msg = new Message();
            msg.obj = ret;
            LogUtil.d("", ret);
            msg.getData().putSerializable("callback", callBack);
            resultHandler.sendMessage(msg);
        }
        //
        if (customLoadingDialog != null && customLoadingDialog.isShowing()) {
            customLoadingDialog.dismiss();
            customLoadingDialog = null;
        }
    }
    super.run();
}

From source file:org.datacleaner.cli.JobTestHelper.java

public static void testJob(final File repository, final String jobName,
        final Map<String, String[]> expectedResultSets, final String... extraCliArgs) throws Exception {
    final String jobResult = runJob(repository, jobName, extraCliArgs);

    final InputStream resultInputStream = new ByteArrayInputStream(jobResult.getBytes());
    final InputStreamReader resultInputStreamReader = new InputStreamReader(resultInputStream);
    final BufferedReader resultReader = new BufferedReader(resultInputStreamReader);

    try {//w  w  w.j av a 2 s  .c o  m
        String resultLine;

        // Read the output line by line until we see an indicator that the interesting part of the output
        // is coming up.
        //noinspection StatementWithEmptyBody
        while ((resultLine = resultReader.readLine()) != null && !resultLine.equals("SUCCESS!")) {
            // Ignore.
        }

        // Now iterate over the different expected result sets and see if they're valid.
        while ((resultLine = resultReader.readLine()) != null) {
            final String resultKey = resultLine.trim();
            if (!"".equals(resultKey)) {
                final String[] expectedResultSet = expectedResultSets.get(resultKey);

                assertNotNull(expectedResultSet);

                for (final String expectedResult : expectedResultSet) {
                    // Only check the first part of the line, because numbers at the end may differ based
                    // on the moment in time the test runs at.
                    assertThat(resultReader.readLine(), containsString(expectedResult));
                }
                expectedResultSets.remove(resultKey);
            }
        }

        assertEquals("CLI result:" + System.lineSeparator() + jobResult, 0, expectedResultSets.size());
    } finally {
        resultReader.close();
        resultInputStreamReader.close();
        resultInputStream.close();
    }
}

From source file:org.archive.util.Recorder.java

/**
 * Return a short prefix of the presumed-textual content as a String.
 * /*from www .jav a 2 s . c  o  m*/
 * @param size max length of String to return 
 * @return String prefix, or empty String (with logged exception) on any error
 */
public String getContentReplayPrefixString(int size, Charset cs) {
    try {
        InputStreamReader isr = new InputStreamReader(getContentReplayInputStream(), cs);
        char[] chars = new char[size];
        int count = isr.read(chars);
        isr.close();
        if (count > 0) {
            return new String(chars, 0, count);
        } else {
            return "";
        }
    } catch (IOException e) {
        logger.log(Level.SEVERE, "unable to get replay prefix string", e);
        return "";
    }
}

From source file:com.linkedin.databus.core.TestDbusEventBufferPersistence.java

private DbusEventBufferMult createBufferMult(DbusEventBuffer.StaticConfig config)
        throws IOException, InvalidConfigException {
    ObjectMapper mapper = new ObjectMapper();
    InputStreamReader isr = new InputStreamReader(
            IOUtils.toInputStream(TestDbusEventBufferMult._configSource1));

    PhysicalSourceConfig pConfig1 = mapper.readValue(isr, PhysicalSourceConfig.class);

    isr.close();
    isr = new InputStreamReader(IOUtils.toInputStream(TestDbusEventBufferMult._configSource2));
    PhysicalSourceConfig pConfig2 = mapper.readValue(isr, PhysicalSourceConfig.class);

    PhysicalSourceStaticConfig pStatConf1 = pConfig1.build();
    PhysicalSourceStaticConfig pStatConf2 = pConfig2.build();

    PhysicalSourceStaticConfig[] _physConfigs = new PhysicalSourceStaticConfig[] { pStatConf1, pStatConf2 };

    return new DbusEventBufferMult(_physConfigs, config, new DbusEventV2Factory());
}

From source file:com.baifendian.swordfish.execserver.utils.OsUtil.java

public static Map<?, ?> cpuinfo() {
    InputStreamReader inputs = null;
    BufferedReader buffer = null;
    Map<String, Object> map = new HashMap<>();

    try {//from   w w w  .j  av a  2s.  c o  m
        inputs = new InputStreamReader(new FileInputStream("/proc/stat"));
        buffer = new BufferedReader(inputs);
        String line = "";

        while (true) {
            line = buffer.readLine();
            if (line == null) {
                break;
            }

            if (line.startsWith("cpu")) {
                StringTokenizer tokenizer = new StringTokenizer(line);
                List<String> temp = new ArrayList<>();

                while (tokenizer.hasMoreElements()) {
                    String value = tokenizer.nextToken();
                    temp.add(value);
                }

                map.put("user", temp.get(1));
                map.put("nice", temp.get(2));
                map.put("system", temp.get(3));
                map.put("idle", temp.get(4));
                map.put("iowait", temp.get(5));
                map.put("irq", temp.get(6));
                map.put("softirq", temp.get(7));
                map.put("stealstolen", temp.get(8));
                break;
            }
        }
    } catch (Exception e) {
        logger.error("get cpu usage error", e);
    } finally {
        try {
            buffer.close();
            inputs.close();
        } catch (Exception e) {
            logger.error("get cpu usage error", e);
        }
    }

    return map;
}

From source file:mobi.jenkinsci.ci.client.JenkinsClient.java

public <T> T load(final String url, final String queryString, final Class<T> returnType,
        final HashMap<String, String> extraHeaders) throws IOException {
    final String query = url + "/api/json" + queryString;

    LOG.info("Request to Jenkins: '" + query + "'");

    final Map<String, String> headers = new HashMap<String, String>();
    if (extraHeaders != null) {
        headers.putAll(extraHeaders);/*ww w  . j  a v a  2 s  .c o  m*/
    }
    final HttpGet get = new HttpGet(query);
    for (final Entry<String, String> header : headers.entrySet()) {
        get.addHeader(header.getKey(), header.getValue());
    }
    try {
        final InputStream result = http.getInputStream(get);
        final InputStreamReader jsonReader = new InputStreamReader(result, "UTF-8");
        try {
            final T outObj = new Gson().fromJson(jsonReader, returnType);
            if (outObj instanceof JenkinsItem) {
                ((JenkinsItem) outObj).init(this);
            }
            return outObj;
        } finally {
            jsonReader.close();
        }
    } finally {
        get.releaseConnection();
    }
}

From source file:com.pipi.studio.dev.net.AsyncHttpGet.java

@Override
public void run() {
    String ret = "";
    try {/*from  ww  w . jav a  2s .  c  om*/
        if (parameter != null && parameter.size() > 0) {
            StringBuilder bulider = new StringBuilder();
            for (RequestParameter p : parameter) {
                if (bulider.length() != 0) {
                    bulider.append("&");
                }

                bulider.append(Utils.encode(p.getName()));
                bulider.append("=");
                bulider.append(Utils.encode(p.getValue()));
            }
            url += "?" + bulider.toString();
        }
        LogUtil.d(AsyncHttpGet.class.getName(), "AsyncHttpGet  request to url :" + url);
        request = new HttpGet(url);
        /*if(Constants.isGzip){
        request.addHeader("Accept-Encoding", "gzip");
          }else{
        request.addHeader("Accept-Encoding", "default");
          }*/
        //  
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeout);
        // ? 
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeout);
        HttpResponse response = httpClient.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            InputStream is = response.getEntity().getContent();
            BufferedInputStream bis = new BufferedInputStream(is);
            bis.mark(2);
            // ??
            byte[] header = new byte[2];
            int result = bis.read(header);
            // reset??
            bis.reset();
            // ?GZIP?
            int headerData = getShort(header);
            // Gzip ? ? 0x1f8b
            if (result != -1 && headerData == 0x1f8b) {
                LogUtil.d("HttpTask", " use GZIPInputStream  ");
                is = new GZIPInputStream(bis);
            } else {
                LogUtil.d("HttpTask", " not use GZIPInputStream");
                is = bis;
            }
            InputStreamReader reader = new InputStreamReader(is, "utf-8");
            char[] data = new char[100];
            int readSize;
            StringBuffer sb = new StringBuffer();
            while ((readSize = reader.read(data)) > 0) {
                sb.append(data, 0, readSize);
            }
            ret = sb.toString();
            bis.close();
            reader.close();

            //            ByteArrayOutputStream content = new ByteArrayOutputStream();
            //            response.getEntity().writeTo(content);
            //            ret = new String(content.toByteArray()).trim();
            //            content.close();
        } else {
            RequestException exception = new RequestException(RequestException.IO_EXCEPTION,
                    "??,??" + statusCode);
            ret = ErrorUtil.errorJson("ERROR.HTTP.001", exception.getMessage());
        }

        LogUtil.d(AsyncHttpGet.class.getName(), "AsyncHttpGet  request to url :" + url + "  finished !");

    } catch (java.lang.IllegalArgumentException e) {

        RequestException exception = new RequestException(RequestException.IO_EXCEPTION,
                Constants.ERROR_MESSAGE);
        ret = ErrorUtil.errorJson("ERROR.HTTP.002", exception.getMessage());
        LogUtil.d(AsyncHttpGet.class.getName(),
                "AsyncHttpGet  request to url :" + url + "  onFail  " + e.getMessage());
    } catch (org.apache.http.conn.ConnectTimeoutException e) {
        RequestException exception = new RequestException(RequestException.SOCKET_TIMEOUT_EXCEPTION,
                Constants.ERROR_MESSAGE);
        ret = ErrorUtil.errorJson("ERROR.HTTP.003", exception.getMessage());
        LogUtil.d(AsyncHttpGet.class.getName(),
                "AsyncHttpGet  request to url :" + url + "  onFail  " + e.getMessage());
    } catch (java.net.SocketTimeoutException e) {
        RequestException exception = new RequestException(RequestException.SOCKET_TIMEOUT_EXCEPTION,
                Constants.ERROR_MESSAGE);
        ret = ErrorUtil.errorJson("ERROR.HTTP.004", exception.getMessage());
        LogUtil.d(AsyncHttpGet.class.getName(),
                "AsyncHttpGet  request to url :" + url + "  onFail  " + e.getMessage());
    } catch (UnsupportedEncodingException e) {
        RequestException exception = new RequestException(RequestException.UNSUPPORTED_ENCODEING_EXCEPTION,
                "?");
        ret = ErrorUtil.errorJson("ERROR.HTTP.005", exception.getMessage());
        LogUtil.d(AsyncHttpGet.class.getName(),
                "AsyncHttpGet  request to url :" + url + "  UnsupportedEncodingException  " + e.getMessage());
    } catch (org.apache.http.conn.HttpHostConnectException e) {
        RequestException exception = new RequestException(RequestException.CONNECT_EXCEPTION,
                Constants.ERROR_MESSAGE);
        ret = ErrorUtil.errorJson("ERROR.HTTP.006", exception.getMessage());
        LogUtil.d(AsyncHttpGet.class.getName(),
                "AsyncHttpGet  request to url :" + url + "  HttpHostConnectException  " + e.getMessage());
    } catch (ClientProtocolException e) {
        RequestException exception = new RequestException(RequestException.CLIENT_PROTOL_EXCEPTION,
                "??");
        ret = ErrorUtil.errorJson("ERROR.HTTP.007", exception.getMessage());
        e.printStackTrace();
        LogUtil.d(AsyncHttpGet.class.getName(),
                "AsyncHttpGet  request to url :" + url + "  ClientProtocolException " + e.getMessage());
    } catch (IOException e) {
        RequestException exception = new RequestException(RequestException.IO_EXCEPTION, "??");
        ret = ErrorUtil.errorJson("ERROR.HTTP.008", exception.getMessage());
        e.printStackTrace();
        LogUtil.d(AsyncHttpGet.class.getName(),
                "AsyncHttpGet  request to url :" + url + "  IOException  " + e.getMessage());
    } finally {
        if (!Constants.IS_STOP_REQUEST) {
            Message msg = new Message();
            msg.obj = ret;
            LogUtil.d("result", ret);
            msg.getData().putSerializable("callback", callBack);
            resultHandler.sendMessage(msg);
        }
        //request.//
        if (customLoadingDialog != null && customLoadingDialog.isShowing()) {
            customLoadingDialog.dismiss();
            customLoadingDialog = null;
        }
    }
    super.run();
}

From source file:op.tools.SYSTools.java

/**
 * @param filePath name of file to open. The file can reside
 *                 anywhere in the classpath
 *                 http://snippets.dzone.com/posts/show/4480
 *///from ww w . java 2s  .  co m
public static String readFileAsString(String filePath) throws IOException {
    StringBuffer fileData = new StringBuffer(1000);
    FileInputStream fis = new FileInputStream(filePath);
    InputStreamReader reader = new InputStreamReader(fis, "UTF-8");
    char[] buf = new char[1024];
    int numRead = 0;
    while ((numRead = reader.read(buf)) != -1) {
        String readData = String.valueOf(buf, 0, numRead);
        fileData.append(readData);
        buf = new char[1024];
    }
    reader.close();
    fis.close();
    return fileData.toString();
}

From source file:com.murrayc.galaxyzoo.app.LoginUtils.java

public static LoginResult parseLoginResponseContent(final InputStream content) throws IOException {
    //A failure by default.
    LoginResult result = new LoginResult(false, null, null);

    final InputStreamReader streamReader = new InputStreamReader(content, Utils.STRING_ENCODING);
    final JsonReader reader = new JsonReader(streamReader);
    reader.beginObject();/*www  .ja  v a 2 s.c o m*/
    boolean success = false;
    String apiKey = null;
    String userName = null;
    String message = null;
    while (reader.hasNext()) {
        final String name = reader.nextName();
        switch (name) {
        case "success":
            success = reader.nextBoolean();
            break;
        case "api_key":
            apiKey = reader.nextString();
            break;
        case "name":
            userName = reader.nextString();
            break;
        case "message":
            message = reader.nextString();
            break;
        default:
            reader.skipValue();
        }
    }

    if (success) {
        result = new LoginResult(true, userName, apiKey);
    } else {
        Log.info("Login failed.");
        Log.info("Login failure message: " + message);
    }

    reader.endObject();
    reader.close();

    streamReader.close();

    return result;
}

From source file:com.iloomo.net.AsyncHttpPost.java

@Override
public void run() {
    String ret = "";
    try {// www .j  av  a 2  s.c  o  m
        for (int i = 0; i < HttpConstant.CONNECTION_COUNT; i++) {
            try {
                request = new HttpPost(url);
                request.addHeader("Accept-Encoding", "default");

                if (parameter != null && parameter.size() > 0) {
                    List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
                    Set<String> keys = parameter.keySet();

                    for (String key : keys) {
                        list.add(new BasicNameValuePair(key, String.valueOf(parameter.get(key))));
                    }
                    ((HttpPost) request).setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
                }
                httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeout);
                httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeout);
                HttpResponse response = httpClient.execute(request);
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == HttpStatus.SC_OK) {
                    InputStream is = response.getEntity().getContent();
                    BufferedInputStream bis = new BufferedInputStream(is);
                    bis.mark(2);
                    // ??
                    byte[] header = new byte[2];
                    int result = bis.read(header);
                    // reset??
                    bis.reset();
                    // ?GZIP?
                    int headerData = getShort(header);
                    // Gzip ? ? 0x1f8b
                    if (result != -1 && headerData == 0x1f8b) {
                        // LogUtil.d("HttpTask", " use GZIPInputStream  ");
                        is = new GZIPInputStream(bis);
                    } else {
                        // LogUtil.d("HttpTask",
                        // " not use GZIPInputStream");
                        is = bis;
                    }
                    InputStreamReader reader = new InputStreamReader(is, "utf-8");
                    char[] data = new char[100];
                    int readSize;
                    StringBuffer sb = new StringBuffer();
                    while ((readSize = reader.read(data)) > 0) {
                        sb.append(data, 0, readSize);
                    }
                    ret = sb.toString();
                    bis.close();
                    reader.close();

                } else {
                    RequestException exception = new RequestException(RequestException.IO_EXCEPTION,
                            "??,??" + statusCode);
                    ret = ErrorUtil.errorJson("999", exception.getMessage());
                }

                break;
            } catch (Exception e) {
                if (i == HttpConstant.CONNECTION_COUNT - 1) {
                    RequestException exception = new RequestException(RequestException.IO_EXCEPTION,
                            "");
                    ret = ErrorUtil.errorJson("999", exception.getMessage());
                } else {
                    Log.d("connection url", "" + i);
                    continue;
                }
            }
        }
    } catch (IllegalArgumentException e) {
        RequestException exception = new RequestException(RequestException.IO_EXCEPTION,
                HttpConstant.ERROR_MESSAGE);
        ret = ErrorUtil.errorJson("999", exception.getMessage());
    } finally {
        if (!HttpConstant.IS_STOP_REQUEST) {
            Message msg = new Message();
            msg.obj = ret;
            msg.getData().putSerializable("callback", callBack);
            resultHandler.sendMessage(msg);
        }
    }
    super.run();
}