Example usage for java.io BufferedReader reset

List of usage examples for java.io BufferedReader reset

Introduction

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

Prototype

public void reset() throws IOException 

Source Link

Document

Resets the stream to the most recent mark.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    InputStream is = new FileInputStream("c:/test.txt");

    InputStreamReader isr = new InputStreamReader(is);

    BufferedReader br = new BufferedReader(isr);

    System.out.println((char) br.read());
    System.out.println((char) br.read());

    br.mark(26);/*  w  ww .java2 s . co  m*/
    System.out.println("mark() invoked");
    System.out.println((char) br.read());
    System.out.println((char) br.read());

    br.reset();
    System.out.println("reset() invoked");
    System.out.println((char) br.read());
    System.out.println((char) br.read());

}

From source file:Main.java

public static void main(String[] args) throws Exception {

    String s = "from java2s.com";

    StringReader sr = new StringReader(s);

    BufferedReader br = new BufferedReader(sr);

    // reads and prints BufferedReader
    System.out.println((char) br.read());
    System.out.println((char) br.read());

    // mark invoked at this position
    br.mark(0);/*w ww  . j  av a2s  .  c  o  m*/
    System.out.println("mark() invoked");
    System.out.println((char) br.read());
    System.out.println((char) br.read());

    // reset() repositioned the stream to the mark
    br.reset();
    System.out.println("reset() invoked");
    System.out.println((char) br.read());
    System.out.println((char) br.read());

}

From source file:org.bitbucket.mlopatkin.android.liblogcat.file.FileDataSourceFactory.java

private static DataSource createLogFileSource(File file, String checkLine, BufferedReader in)
        throws IOException, UnrecognizedFormatException {
    LogfileDataSource source = LogfileDataSource.createLogfileDataSourceWithStrategy(file, checkLine);
    in.reset();
    source.parse(in);/*from  w ww  .j av a2  s .c  om*/
    return source;
}

From source file:org.apache.hyracks.maven.license.LicenseUtil.java

private static void trim(Writer out, BufferedReader reader, boolean unpad, boolean wrap) throws IOException {
    Pair<Integer, Integer> result = null;
    if (unpad || wrap) {
        result = analyze(reader);/* w  w w  .ja v  a 2s  .co  m*/
        reader.reset();
    }
    doTrim(out, reader, unpad ? result.getLeft() : 0,
            wrap && (result.getRight() > wrapThreshold) ? wrapLength : Integer.MAX_VALUE);
}

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 w  w w  . ja  va 2  s  . c o m*/
 * @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.liusoft.dlog4j.xml.RSSFetcher.java

/**
 * ??//from ww w . j av  a2 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:Main.java

public static String findObject(BufferedReader br, String type) throws IOException {
    String prefix = "-----BEGIN ";
    String suffix = (type == null) ? "-----" : type + "-----";

    while (true) {
        br.mark(1024);/*w ww. j a va 2 s  . c  om*/

        String line = br.readLine();

        if (null == line) {
            return null;
        }

        if (!line.startsWith(prefix)) {
            continue;
        }

        if (!line.endsWith(suffix)) {
            continue;
        }

        br.reset();

        return line.substring(prefix.length(), line.length() - 5);
    }
}

From source file:net.sourceforge.users.dragomerlin.vcs2icsCalendarConverter.ConvertSingleFile.java

private static String readPossibleMultiline(String fieldContent, BufferedReader inStream) throws IOException {
    char[] buf = new char[1];
    boolean multilineFound = false;
    do {//from w w  w.  j  a va 2s .c o m
        inStream.mark(1);
        int res = inStream.read(buf);
        if (res == -1) {
            throw new IOException("Error while reading multiline: EOF.");
        }

        if (buf[0] == ' ') {
            multilineFound = true;
            String line = inStream.readLine();
            fieldContent += line;
        } else {
            multilineFound = false;
        }
    } while (multilineFound);
    inStream.reset();
    return fieldContent;
}

From source file:nz.net.orcon.kanban.controllers.ResourceController.java

@PreAuthorize("hasPermission(#boardId, 'BOARD', 'ADMIN')")
@RequestMapping(value = "/{resourceId}", method = RequestMethod.POST)
public @ResponseBody void createResource(@PathVariable String boardId, @PathVariable String resourceId,
        HttpServletRequest request) throws Exception {

    logger.info("Saving Resource " + boardId + "/" + resourceId);
    BufferedReader reader = request.getReader();
    reader.reset();
    StringBuilder valueBuilder = new StringBuilder();

    while (true) {
        String newValue = reader.readLine();
        if (newValue != null) {
            valueBuilder.append(newValue);
            valueBuilder.append("\n");
        } else {/*from  ww  w  . j  ava 2  s  .  c  om*/
            break;
        }
    }

    String value = valueBuilder.toString();

    logger.info("Resource Text: " + value);

    ObjectContentManager ocm = ocmFactory.getOcm();

    try {

        listTools.ensurePresence(String.format(URI.BOARD_URI, boardId), "resources", ocm.getSession());

        Node node = ocm.getSession().getNode(String.format(URI.RESOURCE_URI, boardId, ""));
        Node addNode = node.addNode(resourceId);

        addNode.setProperty("resource", value);
        addNode.setProperty("name", resourceId);
        ocm.getSession().save();
    } finally {
        ocm.logout();
    }

    logger.info("Resource Saved " + resourceId);
}

From source file:net.sourceforge.vulcan.web.ParameterParsingHttpServletRequestWrapper.java

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override//from   ww w  . j a  v  a  2s . co m
public Map getParameterMap() {
    if (parameterMap != null) {
        return parameterMap;
    }

    parameterMap = new HashMap<String, String>(super.getParameterMap());
    parameterMultiMap = new MultiHashMap();

    for (Enumeration e = super.getParameterNames(); e.hasMoreElements();) {
        String name = (String) e.nextElement();
        for (String v : super.getParameterValues(name)) {
            parameterMultiMap.put(name, v);
        }
    }

    if (!StringUtils.equals(getContentType(), "application/x-www-form-urlencoded")) {
        return parameterMultiMap;
    }

    String encoding = getCharacterEncoding();

    if (StringUtils.isBlank(encoding)) {
        encoding = "UTF-8";
    }

    try {
        BufferedReader reader = getReader();
        reader.mark(8192);
        String formData = IOUtils.toString(reader);
        reader.reset();

        for (String kvp : formData.split("&")) {
            String[] kv = kvp.split("=");
            String key = URLDecoder.decode(kv[0], encoding);
            String value = kv.length > 1 ? URLDecoder.decode(kv[1], encoding) : StringUtils.EMPTY;
            parameterMultiMap.put(key, value);
            if (!parameterMap.containsKey(key)) {
                parameterMap.put(key, value);
            }
        }
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }

    return parameterMap;
}