Example usage for java.io BufferedReader read

List of usage examples for java.io BufferedReader read

Introduction

In this page you can find the example usage for java.io BufferedReader read.

Prototype

public int read(java.nio.CharBuffer target) throws IOException 

Source Link

Document

Attempts to read characters into the specified character buffer.

Usage

From source file:net.BiggerOnTheInside.Binder.engine.JSONManager.java

private static String readUrl(String urlString) throws Exception {
    BufferedReader reader = null;
    try {/*from   w  ww .j av a  2 s  . c  om*/
        URL url = new URL(urlString);
        reader = new BufferedReader(new InputStreamReader(url.openStream()));
        StringBuffer buffer = new StringBuffer();
        int read;
        char[] chars = new char[1024];

        while ((read = reader.read(chars)) != -1)
            buffer.append(chars, 0, read);

        return buffer.toString();
    } finally {
        if (reader != null)
            reader.close();
    }
}

From source file:de.adorsys.oauth.authdispatcher.FixedServletUtils.java

/**
 * Creates a new HTTP request from the specified HTTP servlet request.
 *
 * @param sr              The servlet request. Must not be
 *                        {@code null}./*w ww  .  j  ava 2 s.  com*/
 * @param maxEntityLength The maximum entity length to accept, -1 for
 *                        no limit.
 *
 * @return The HTTP request.
 *
 * @throws IllegalArgumentException The the servlet request method is
 *                                  not GET, POST, PUT or DELETE or the
 *                                  content type header value couldn't
 *                                  be parsed.
 * @throws IOException              For a POST or PUT body that
 *                                  couldn't be read due to an I/O
 *                                  exception.
 */
public static HTTPRequest createHTTPRequest(final HttpServletRequest sr, final long maxEntityLength)
        throws IOException {

    HTTPRequest.Method method = HTTPRequest.Method.valueOf(sr.getMethod().toUpperCase());

    String urlString = reconstructRequestURLString(sr);

    URL url;

    try {
        url = new URL(urlString);

    } catch (MalformedURLException e) {

        throw new IllegalArgumentException("Invalid request URL: " + e.getMessage() + ": " + urlString, e);
    }

    HTTPRequest request = new HTTPRequest(method, url);

    try {
        request.setContentType(sr.getContentType());

    } catch (ParseException e) {

        throw new IllegalArgumentException("Invalid Content-Type header value: " + e.getMessage(), e);
    }

    Enumeration<String> headerNames = sr.getHeaderNames();

    while (headerNames.hasMoreElements()) {
        final String headerName = headerNames.nextElement();
        request.setHeader(headerName, sr.getHeader(headerName));
    }

    if (method.equals(HTTPRequest.Method.GET) || method.equals(HTTPRequest.Method.DELETE)) {

        request.setQuery(sr.getQueryString());

    } else if (method.equals(HTTPRequest.Method.POST) || method.equals(HTTPRequest.Method.PUT)) {

        if (maxEntityLength > 0 && sr.getContentLength() > maxEntityLength) {
            throw new IOException("Request entity body is too large, limit is " + maxEntityLength + " chars");
        }

        Map<String, String[]> parameterMap = sr.getParameterMap();
        StringBuilder builder = new StringBuilder();

        if (!parameterMap.isEmpty()) {
            for (Entry<String, String[]> entry : parameterMap.entrySet()) {
                String key = entry.getKey();
                String[] value = entry.getValue();
                if (value.length > 0 && value[0] != null) {
                    String encoded = URLEncoder.encode(value[0], "UTF-8");
                    builder = builder.append(key).append('=').append(encoded).append('&');
                }
            }
            String queryString = StringUtils.substringBeforeLast(builder.toString(), "&");
            request.setQuery(queryString);

        } else {
            // read body
            StringBuilder body = new StringBuilder(256);

            BufferedReader reader = sr.getReader();

            char[] cbuf = new char[256];

            int readChars;

            while ((readChars = reader.read(cbuf)) != -1) {

                body.append(cbuf, 0, readChars);

                if (maxEntityLength > 0 && body.length() > maxEntityLength) {
                    throw new IOException(
                            "Request entity body is too large, limit is " + maxEntityLength + " chars");
                }
            }

            reader.close();

            request.setQuery(body.toString());
        }
    }

    return request;
}

From source file:com.voa.weixin.utils.HttpUtils.java

private static String getStreamAsString(InputStream stream, String charset) throws IOException {
    try {/*from  ww w. ja  va2  s . c o  m*/
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream, charset));
        StringWriter writer = new StringWriter();

        char[] chars = new char[1024];
        int count = 0;
        while ((count = reader.read(chars)) > 0) {
            writer.write(chars, 0, count);
        }

        return writer.toString();
    } finally {
        if (stream != null) {
            stream.close();
        }
    }
}

From source file:jshm.util.PasteBin.java

public static String post(String name, File file) throws Exception {
    BufferedReader in = null;
    StringBuilder sb = new StringBuilder();

    try {//from w w  w  .  ja va 2  s  .  c o m
        in = new BufferedReader(new FileReader(file));

        sb.append(file.getAbsolutePath());
        sb.append("\n\n");

        int charsRead = -1;
        char[] buff = new char[1024];

        while (-1 != (charsRead = in.read(buff))) {
            sb.append(buff, 0, charsRead);
        }
    } finally {
        if (null != in)
            in.close();
    }

    return post(name, sb.toString());
}

From source file:com.liusoft.dlog4j.xml.RSSFetcher.java

/**
 * ??/*from w ww  . j a  v a  2 s  .c  o  m*/
 * @param type
 * @param url
 * @return
 * @throws IOException 
 * @throws HttpException 
 * @throws SAXException 
 * @throws ParseException 
 */
private static Channel fetchChannelViaHTTP(String url) throws HttpException, IOException, SAXException {
    Digester parser = new XMLDigester();
    GetMethod get = new GetMethod(url);
    //get.setRequestHeader("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; zh-cn) Opera 8.52");
    try {
        http_client.executeMethod(get);
        if (get.getStatusCode() == HttpServletResponse.SC_OK) {
            Charset cs = null;
            Header header_cs = getResponseHeader(get, "Content-Type");
            if (header_cs == null) {
                cs = Charset.forName(get.getResponseCharSet());
            } else {
                String content_type = header_cs.getValue().toLowerCase();
                try {
                    Object[] values = content_type_parser.parse(content_type);
                    cs = Charset.forName((String) values[1]);
                } catch (ParseException e) {
                    URL o_url = new URL(url);
                    String host = o_url.getHost();
                    Iterator hosts = charsets.keySet().iterator();
                    while (hosts.hasNext()) {
                        String t_host = (String) hosts.next();
                        if (host.toLowerCase().endsWith(t_host)) {
                            cs = Charset.forName((String) charsets.get(t_host));
                            break;
                        }
                    }
                    if (cs == null)
                        cs = default_charset;

                }
            }

            BufferedReader rd = new BufferedReader(new InputStreamReader(get.getResponseBodyAsStream(), cs));

            char[] cbuf = new char[1];
            int read_idx = 1;
            do {
                rd.mark(read_idx++);
                if (rd.read(cbuf) == -1)
                    break;
                if (cbuf[0] != '<')
                    continue;
                rd.reset();
                break;
            } while (true);
            return (Channel) parser.parse(rd);
        } else {
            log.error("Fetch RSS from " + url + " failed, code=" + get.getStatusCode());
        }
    } finally {
        get.releaseConnection();
    }
    return null;
}

From source file:cn.mdict.utils.IOUtil.java

public static boolean loadStringFromStream(InputStream inputStream, String encoding, StringBuffer str) {
    boolean result = true;
    int buffer_size = 512;
    char[] char_buf = new char[buffer_size];
    BufferedReader in = null;
    try {//from ww  w  . ja  v  a  2  s .com
        in = new BufferedReader(new InputStreamReader(inputStream, encoding));
        int read_size;
        while ((read_size = in.read(char_buf)) != -1) {
            str.append(char_buf, 0, read_size);
        }
    } catch (UnsupportedEncodingException e) {
        result = false;
        e.printStackTrace();
    } catch (IOException e) {
        result = false;
        e.printStackTrace();
    } finally {
        if (in != null)
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }
    return result;
}

From source file:com.pagecrumb.proxy.util.filter.HtmlProxyTransformParser.java

private static String readFileAsString(String filePath)
/*throws java.io.IOException*/ { // No need to put exception handling since we except the file to be statically in the server
    StringBuffer fileData = new StringBuffer(1000);
    try {// ww  w.j a  v a2 s .  c om
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        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();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return fileData.toString();
}

From source file:de.adorsys.oauth.server.FixedServletUtils.java

/**
 * Creates a new HTTP request from the specified HTTP servlet request.
 *
 * @param servletRequest              The servlet request. Must not be
 *                        {@code null}.//from www . j  ava2  s .com
 * @param maxEntityLength The maximum entity length to accept, -1 for
 *                        no limit.
 *
 * @return The HTTP request.
 *
 * @throws IllegalArgumentException The the servlet request method is
 *                                  not GET, POST, PUT or DELETE or the
 *                                  content type header value couldn't
 *                                  be parsed.
 * @throws IOException              For a POST or PUT body that
 *                                  couldn't be read due to an I/O
 *                                  exception.
 */
public static HTTPRequest createHTTPRequest(final HttpServletRequest servletRequest, final long maxEntityLength)
        throws IOException {

    HTTPRequest.Method method = HTTPRequest.Method.valueOf(servletRequest.getMethod().toUpperCase());

    String urlString = reconstructRequestURLString(servletRequest);

    URL url;

    try {
        url = new URL(urlString);

    } catch (MalformedURLException e) {

        throw new IllegalArgumentException("Invalid request URL: " + e.getMessage() + ": " + urlString, e);
    }

    HTTPRequest request = new HTTPRequest(method, url);

    try {
        request.setContentType(servletRequest.getContentType());

    } catch (ParseException e) {

        throw new IllegalArgumentException("Invalid Content-Type header value: " + e.getMessage(), e);
    }

    Enumeration<String> headerNames = servletRequest.getHeaderNames();

    while (headerNames.hasMoreElements()) {
        final String headerName = headerNames.nextElement();
        request.setHeader(headerName, servletRequest.getHeader(headerName));
    }

    if (method.equals(HTTPRequest.Method.GET) || method.equals(HTTPRequest.Method.DELETE)) {

        request.setQuery(servletRequest.getQueryString());

    } else if (method.equals(HTTPRequest.Method.POST) || method.equals(HTTPRequest.Method.PUT)) {

        if (maxEntityLength > 0 && servletRequest.getContentLength() > maxEntityLength) {
            throw new IOException("Request entity body is too large, limit is " + maxEntityLength + " chars");
        }

        Map<String, String[]> parameterMap = servletRequest.getParameterMap();
        StringBuilder builder = new StringBuilder();

        if (!parameterMap.isEmpty()) {
            for (Entry<String, String[]> entry : parameterMap.entrySet()) {
                String key = entry.getKey();
                String[] value = entry.getValue();
                if (value.length > 0 && value[0] != null) {
                    String encoded = URLEncoder.encode(value[0], "UTF-8");
                    builder = builder.append(key).append('=').append(encoded).append('&');
                }
            }
            String queryString = StringUtils.substringBeforeLast(builder.toString(), "&");
            request.setQuery(queryString);

        } else {
            // read body
            StringBuilder body = new StringBuilder(256);

            BufferedReader reader = servletRequest.getReader();
            reader.reset();
            char[] cbuf = new char[256];

            int readChars;

            while ((readChars = reader.read(cbuf)) != -1) {

                body.append(cbuf, 0, readChars);

                if (maxEntityLength > 0 && body.length() > maxEntityLength) {
                    throw new IOException(
                            "Request entity body is too large, limit is " + maxEntityLength + " chars");
                }
            }

            reader.reset();
            // reader.close();

            request.setQuery(body.toString());
        }
    }

    return request;
}

From source file:com.netscape.cmsutil.util.Utils.java

public static void copyStream(BufferedReader in, OutputStreamWriter out) throws IOException {
    char[] buf = new char[4096];
    int len;/*from  w  w  w. j  a va2 s.  c  o  m*/

    while ((len = in.read(buf)) != -1) {
        out.write(buf, 0, len);
    }
}

From source file:de.jgoestl.massdatagenerator.MassDataGenerator.java

private static String readInputFile(String inputFilePath, String inputString) {
    BufferedReader br = null;
    try {/*from w  w w  . j ava 2  s . com*/
        File input = new File(inputFilePath);
        br = new BufferedReader(new FileReader(input));
        StringBuilder inputStringBuilder = new StringBuilder();
        char[] readBuffer = new char[1];
        while (br.read(readBuffer) != -1) {
            inputStringBuilder.append(readBuffer);
        }
        inputString = inputStringBuilder.toString();
    } catch (FileNotFoundException ex) {
        System.out.println("Input-File \"" + inputFilePath + "\" not found");
        try {
            System.in.read();
        } catch (IOException e) {
            Logger.getLogger(MassDataGenerator.class.getName()).log(Level.SEVERE, null, e);
        }
        System.exit(1);
    } catch (IOException ex) {
        Logger.getLogger(MassDataGenerator.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            if (br != null)
                br.close();
        } catch (IOException ex) {
            Logger.getLogger(MassDataGenerator.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return inputString;
}