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.ibm.liberty.starter.service.swagger.api.v1.ProviderEndpoint.java

private String getOutput(Process joinProc) throws IOException {
    InputStream stream = joinProc.getInputStream();

    char[] buf = new char[512];
    int charsRead;
    StringBuilder sb = new StringBuilder();
    InputStreamReader reader = null;
    try {//from  w  ww .j a  va2s.  co m
        reader = new InputStreamReader(stream);
        while ((charsRead = reader.read(buf)) > 0) {
            sb.append(buf, 0, charsRead);
        }
    } finally {
        if (reader != null) {
            reader.close();
        }
    }

    return sb.toString();
}

From source file:ape.CorruptCommand.java

/**
 * This method is used to fetch the hdfs config file
 * and then fetch the address of where hdfs blk files
 * are stored from the config file/*from   w  ww  . j  a va2  s  .c om*/
 * finally, it returns that a random hdfs blk in that address
 */
private String getCorruptAddress() throws IOException {
    String cmd = "cat $HADOOP_HOME/conf/hdfs-site.xml | grep -A1 'dfs.data.dir' | grep 'value'";
    System.out.println(cmd);
    ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd);
    pb.redirectErrorStream(true);
    Process sh = null;
    try {

        sh = pb.start();
        if (sh.waitFor() != 0) {
            System.out.println("Executing '" + cmd + "' returned a nonzero exit code.");
            System.out.println("Unable to find HDFS block files");
            Main.logger.info("Executing '" + cmd + "' returned a nonzero exit code.");
            Main.logger.info("Unable to find HDFS block files");
            return null;
        }
    } catch (IOException e) {
        System.out.println("Failed to acquire block address");
        Main.logger.info("Failed to acquire block address");
        e.printStackTrace();
        Main.logger.info(e);
        return null;

    } catch (InterruptedException e) {
        System.out.println("Caught an Interrupt while runnning");
        Main.logger.info("Caught an Interrupt while runnning");
        e.printStackTrace();
        Main.logger.info(e);
        return null;
    }

    InputStream shIn = sh.getInputStream();
    InputStreamReader isr = new InputStreamReader(shIn);
    BufferedReader br = new BufferedReader(isr);
    String line = null;
    try {
        line = br.readLine();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

    br.close();
    isr.close();
    line = line.trim();

    int end = line.indexOf("</value>");

    //parse the String and randomly select an address
    String address = line.substring(7, end);

    ArrayList<String> addresses = new ArrayList<String>();

    int idx;

    while ((idx = address.indexOf(',')) != -1) {
        addresses.add(address.substring(0, idx));
        address = address.substring(idx + 1);
    }
    addresses.add(address);

    int index = new Random().nextInt(addresses.size());

    address = addresses.get(index).concat("/current");

    if (Main.VERBOSE) {
        System.out.println("The address of the HDFS data folder is: " + address);
    }
    Main.logger.info("The address of the HDFS data folder is: " + address);

    if (datatype.equalsIgnoreCase("meta")) {
        cmd = "ls " + address + " | grep -i 'blk' |grep -i 'meta' ";
    } else {
        cmd = "ls " + address + " | grep -i 'blk' | grep -v 'meta' ";
    }

    pb = new ProcessBuilder("bash", "-c", cmd);
    pb.redirectErrorStream(true);

    sh = pb.start();

    try {
        if (sh.waitFor() != 0) {
            System.out.println("Getting address of the list of files failed");
            return null;
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
        return null;
    }

    shIn = sh.getInputStream();

    isr = new InputStreamReader(shIn);
    br = new BufferedReader(isr);

    ArrayList<String> data = new ArrayList<String>();

    while ((line = br.readLine()) != null) {
        data.add(line);
    }

    int length = data.size();
    Random rdm = new Random();

    int random = rdm.nextInt(length);

    address = address.concat("/" + data.get(random));

    if (Main.VERBOSE) {
        System.out.println("The location of the data corrupted is " + address);
    }

    // Log the corrupted block
    Main.logger.info("The location of the data corrupted is " + address);

    br.close();
    isr.close();
    shIn.close();

    return address;
}

From source file:com.nolanofra.test.lazyLoader.MainActivity.java

public String convertStreamToString(InputStream is) {
    BufferedReader reader = null;
    InputStreamReader inputStreamReader = new InputStreamReader(is);
    reader = new BufferedReader(inputStreamReader);
    //String encoding = inputStreamReader.getEncoding();

    StringBuilder sb = new StringBuilder();

    String line;/*  w w  w  . java2  s  .  c  o  m*/
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            inputStreamReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    try {

        return sb.toString();

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return "";
}

From source file:me.Aron.Heinecke.fbot.lib.Socket.java

/***
 * Performs a logout from fronter based on the DB credentials
 * @param site content/*from   ww w  . j  ava 2  s.c  o  m*/
 */
public synchronized String logout() throws ClientProtocolException, IOException {
    String url = "https://fronter.com/giessen/index.phtml?logout=1";

    //create own context which custom cookie store
    HttpClientContext context = HttpClientContext.create();
    context.setCookieStore(fbot.getDB().getCookieStore());

    //create client & request
    HttpGet request = new HttpGet(url);

    // add request header
    request.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    request.addHeader("Accept-Encoding", "gzip, deflate");
    request.addHeader("Accept-Language", "de-de,de;q=0.8,en-us;q=0.5,en;q=0.3");
    request.addHeader("Content-Type", "application/x-www-form-urlencoded");
    request.addHeader("Connection", "close");
    request.addHeader("DNT", "1");
    request.addHeader("Host", "fronter.com");
    request.addHeader("Referer", "https://fronter.com/giessen/personalframe.phtml");
    request.addHeader("User-Agent", UA);

    //execute request with local context
    HttpResponse response = client.execute(request, context);

    if (fbot.isDebug()) {
        fbot.getLogger().debug("socket", "Sending GET request to URL: " + url);
        fbot.getLogger().debug("socket", "Response code: " + response.getStatusLine().getStatusCode());
    }

    //get gzip
    InputStream input = response.getEntity().getContent();
    GZIPInputStream gzip = new GZIPInputStream(input);
    InputStreamReader isr = new InputStreamReader(gzip);
    BufferedReader rd = new BufferedReader(isr);

    //write buffer
    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
        result.append(line);
    }
    input.close();
    gzip.close();
    isr.close();
    rd.close();

    return result.toString();
}

From source file:com.android.wako.net.AsyncHttpPost.java

public boolean process() {
    try {// w  ww  .j a  v a  2  s . c  om
        //            LogUtil.d(Tag, "---process---url="+url+"?"+getParames());
        request = new HttpPost(url);
        if (Constants.isGzip) {
            request.addHeader("Accept-Encoding", "gzip");
        } else {
            request.addHeader("Accept-Encoding", "default");
        }
        request.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
        //            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();
            return true;

        } else {
            mRetStatus = ResStatus.Error_Code;
            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 (IllegalArgumentException e) {
        mRetStatus = ResStatus.Error_IllegalArgument;
        //            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) {
        mRetStatus = ResStatus.Error_Connect_Timeout;
        //            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) {
        mRetStatus = ResStatus.Error_Socket_Timeout;
        //            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) {
        mRetStatus = ResStatus.Error_Unsupport_Encoding;
        e.printStackTrace();
        //            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) {
        mRetStatus = ResStatus.Error_HttpHostConnect;
        e.printStackTrace();
        //            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) {
        mRetStatus = ResStatus.Error_Client_Protocol;
        e.printStackTrace();
        //            RequestException exception = new RequestException(
        //                    RequestException.CLIENT_PROTOL_EXCEPTION, "??");
        //            ret = ErrorUtil.errorJson("ERROR.HTTP.007", exception.getMessage());
        LogUtil.d(AsyncHttpPost.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  ClientProtocolException " + e.getMessage());
    } catch (IOException e) {
        mRetStatus = ResStatus.Error_IOException;
        //            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());
    } catch (Exception e) {
        mRetStatus = ResStatus.Error_IOException;
        e.printStackTrace();
    }
    return false;
}

From source file:ch.lom.clemens.android.bibliography.data.JSONWebConnector.java

private String connect(String strURL) throws Exception {
    URL url = new URL(strURL);
    HttpURLConnection request = (HttpURLConnection) url.openConnection();
    m_consumer.sign(request);/* w  ww.j  a va2s . c  om*/

    request.connect();

    if (request.getResponseCode() == 200) {

        String strResponse = "";
        InputStreamReader in = new InputStreamReader((InputStream) request.getContent());
        BufferedReader buff = new BufferedReader(in);

        for (String strLine = ""; strLine != null; strLine = buff.readLine()) {
            strResponse += strLine + "\n";
        }
        in.close();

        return strResponse;
    } else {
        throw new Exception(
                "Mendeley Server returned " + request.getResponseCode() + ": " + request.getResponseMessage());
    }

}

From source file:org.altlaw.hadoop.JsonReader.java

public void addSmidInJson(String src, String filename, SequenceFile.Writer output) throws Exception {
    InputStreamReader isr = new InputStreamReader(new FileInputStream(src));
    BufferedReader br = new BufferedReader(isr);
    String line;/*from   w w  w  . j a  v  a 2s  .  com*/
    StringBuffer strings = new StringBuffer();
    while ((line = br.readLine()) != null) {
        JSONObject obj = (JSONObject) JSONValue.parse(line);
        obj.put("filename", filename);
        obj.put("video_id", this.getSMID(filename));
        StringWriter out = new StringWriter();
        obj.writeJSONString(out);
        String jsonText = out.toString();
        this.appendStringToOuput(filename, jsonText, output);
    }
    br.close();
    isr.close();
}

From source file:hu.javaforum.android.soap.Transport.java

/**
 * Prints out the reply of the server when the loglevel is DEBUG.
 *
 * @param stream The stream/*from www .j ava  2  s.co  m*/
 * @return The reply stream
 * @throws IOException When IO error occurred
 */
protected final InputStream debugResponseStream(final InputStream stream) throws IOException {
    InputStream replyStream = stream;
    try {
        if (LOGGER.isDebugEnabled()) {
            InputStreamReader isr = new InputStreamReader(stream, DEFAULT_ENCODING);
            BufferedReader br = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();
            for (String line = br.readLine(); line != null; line = br.readLine()) {
                sb.append(line);
                sb.append("\n");
            }
            br.close();
            isr.close();
            stream.close();

            replyStream = new ByteArrayInputStream(sb.toString().getBytes(DEFAULT_ENCODING));
            LOGGER.debug("Response:\n{}", sb.toString());
        }
    } finally {
    }

    return replyStream;
}

From source file:com.github.dpsm.android.print.jackson.JacksonResultOperator.java

@Override
public Subscriber<? super Response> call(final Subscriber<? super T> subscriber) {
    return new Subscriber<Response>() {
        @Override/*from   w w  w.  ja  v a  2  s.  c  om*/
        public void onCompleted() {
            subscriber.onCompleted();
        }

        @Override
        public void onError(final Throwable e) {
            subscriber.onError(e);
        }

        @Override
        public void onNext(final Response response) {
            switch (response.getStatus()) {
            case HttpURLConnection.HTTP_OK:
                InputStreamReader reader = null;
                try {
                    reader = new InputStreamReader(response.getBody().in());
                    final ObjectNode rootNode = mMapper.readValue(reader, ObjectNode.class);
                    T result = mConstructor.newInstance(rootNode);
                    subscriber.onNext(result);
                } catch (Exception e) {
                    subscriber.onError(e);
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            // Nothing to do here
                        }
                    }
                }
                break;
            default:
                break;
            }
        }
    };
}

From source file:com.android.wako.net.AsyncHttpGet.java

@Override
boolean process() {
    try {/*  w ww .  j a  va 2  s.c  o m*/
        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();
        }
        if (LogUtil.IS_LOG)
            LogUtil.d(TAG, "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 (LogUtil.IS_LOG)
            LogUtil.d(TAG, "statusCode=" + statusCode);
        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) {
                if (LogUtil.IS_LOG)
                    LogUtil.d(TAG, " use GZIPInputStream  ");
                is = new GZIPInputStream(bis);
            } else {
                if (LogUtil.IS_LOG)
                    LogUtil.d(TAG, " 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();
            return true;

        } else {
            mRetStatus = ResStatus.Error_Code;
            RequestException exception = new RequestException(RequestException.IO_EXCEPTION,
                    "??,??" + statusCode);
        }

        if (LogUtil.IS_LOG)
            LogUtil.d(TAG, "AsyncHttpGet  request to url :" + url + "  finished !");

    } catch (IllegalArgumentException e) {
        mRetStatus = ResStatus.Error_IllegalArgument;
        e.printStackTrace();
        RequestException exception = new RequestException(RequestException.IO_EXCEPTION,
                Constants.ERROR_MESSAGE);
        if (LogUtil.IS_LOG)
            LogUtil.d(TAG, "AsyncHttpGet  request to url :" + url + "  onFail  " + e.getMessage());
    } catch (org.apache.http.conn.ConnectTimeoutException e) {
        mRetStatus = ResStatus.Error_Connect_Timeout;
        e.printStackTrace();
        RequestException exception = new RequestException(RequestException.SOCKET_TIMEOUT_EXCEPTION,
                Constants.ERROR_MESSAGE);
        if (LogUtil.IS_LOG)
            LogUtil.d(TAG, "AsyncHttpGet  request to url :" + url + "  onFail  " + e.getMessage());
    } catch (java.net.SocketTimeoutException e) {
        mRetStatus = ResStatus.Error_Socket_Timeout;
        e.printStackTrace();
        RequestException exception = new RequestException(RequestException.SOCKET_TIMEOUT_EXCEPTION,
                Constants.ERROR_MESSAGE);
        if (LogUtil.IS_LOG)
            LogUtil.d(TAG, "AsyncHttpGet  request to url :" + url + "  onFail  " + e.getMessage());
    } catch (UnsupportedEncodingException e) {
        mRetStatus = ResStatus.Error_Unsupport_Encoding;
        e.printStackTrace();
        RequestException exception = new RequestException(RequestException.UNSUPPORTED_ENCODEING_EXCEPTION,
                "?");
        if (LogUtil.IS_LOG)
            LogUtil.d(TAG, "AsyncHttpGet  request to url :" + url + "  UnsupportedEncodingException  "
                    + e.getMessage());
    } catch (org.apache.http.conn.HttpHostConnectException e) {
        mRetStatus = ResStatus.Error_HttpHostConnect;
        e.printStackTrace();
        RequestException exception = new RequestException(RequestException.CONNECT_EXCEPTION, "");
        if (LogUtil.IS_LOG)
            LogUtil.d(TAG,
                    "AsyncHttpGet  request to url :" + url + "  HttpHostConnectException  " + e.getMessage());
    } catch (ClientProtocolException e) {
        mRetStatus = ResStatus.Error_Client_Protocol;
        e.printStackTrace();
        RequestException exception = new RequestException(RequestException.CLIENT_PROTOL_EXCEPTION,
                "??");
        e.printStackTrace();
        if (LogUtil.IS_LOG)
            LogUtil.d(TAG,
                    "AsyncHttpGet  request to url :" + url + "  ClientProtocolException " + e.getMessage());
    } catch (IOException e) {
        mRetStatus = ResStatus.Error_IOException;
        e.printStackTrace();
        RequestException exception = new RequestException(RequestException.IO_EXCEPTION, "??");
        e.printStackTrace();
        if (LogUtil.IS_LOG)
            LogUtil.d(TAG, "AsyncHttpGet  request to url :" + url + "  IOException  " + e.getMessage());
    } catch (Exception e) {
        mRetStatus = ResStatus.Error_IOException;
        e.printStackTrace();
    }
    return false;
}