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:com.norconex.importer.parser.impl.xfdl.XFDLParser.java

private void parse(BufferedReader reader, Writer out, ImporterMetadata metadata)
        throws IOException, ParserConfigurationException, SAXException {
    reader.mark(MAGIC_BASE64.length);//  w w  w.  j  av  a 2 s  .c om
    char[] signature = new char[MAGIC_BASE64.length];
    int num = reader.read(signature);
    reader.reset();
    if (num == -1) {
        return;
    }

    //--- Create XML DOM ---
    DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document dom = null;
    if (Arrays.equals(signature, MAGIC_BASE64)) {
        // skip first line
        reader.readLine();

        // un-encode first
        byte[] compressedContent = Base64.decodeBase64(IOUtils.toString(reader));
        // deal with compression
        InputStream is = new GZIPInputStream(new ByteArrayInputStream(compressedContent));

        dom = docBuilder.parse(is);
        IOUtils.closeQuietly(is);
    } else {
        dom = docBuilder.parse(new InputSource(reader));
    }
    parseXML(dom, out, metadata);
}

From source file:org.ut.biolab.medsavant.server.ontology.OBOParser.java

private OntologyTerm parseNextTerm(BufferedReader reader) throws IOException {

    String line;//w ww . j  a v  a2s.  c  o m
    String id = null, name = null, description = null;
    List<String> altIDs = new ArrayList<String>();
    List<String> parentIDs = new ArrayList<String>();
    while ((line = reader.readLine()) != null) {
        if (line.startsWith("[")) {
            // We've hit the next term (or typedef).  Rewind to the beginning of the line.
            reader.reset();
            break;
        } else {
            lineNum++;
            if (line.length() > 0 && line.charAt(0) != '!') {
                int colonPos = line.indexOf(":");
                if (colonPos > 0) {
                    String key = line.substring(0, colonPos);
                    String value = line.substring(colonPos + 1);
                    int commentPos = indexOf(value, '!');
                    if (commentPos > 0) {
                        value = value.substring(0, commentPos);
                    }
                    value = value.trim();
                    if (key.equals("id")) {
                        id = value;
                    } else if (key.equals("alt_id")) {
                        altIDs.add(value);
                    } else if (key.equals("name")) {
                        name = value;
                    } else if (key.equals("def")) {
                        // Def consists of a quote-delimited string followed by some (ignored) reference material.
                        int quotePos = indexOf(value, '\"');
                        if (quotePos >= 0) {
                            value = value.substring(quotePos + 1);
                            quotePos = indexOf(value, '\"');
                            if (quotePos >= 0) {
                                value = value.substring(0, quotePos);
                                description = value.replace("\\", "");
                            }
                        }
                    } else if (key.equals("is_a")) {
                        parentIDs.add(value);
                    } else if (key.equals("is_obsolete") && value.equals("true")) {
                        return null;
                    }
                }
            }
            reader.mark(10); // So we can rewind if the line is the next [Term].
        }
    }
    return new OntologyTerm(ontology, id, name, description, altIDs.toArray(new String[0]),
            parentIDs.toArray(new String[0]));
}

From source file:uk.ac.sanger.cgp.dbcon.sqllibs.SqlLibraries.java

/**
 * Takes in a string and looks to see if it is an XML definition file
 *///from  w ww  . ja  va2  s  . c  om
private LibraryParser detectAndCreateParser(Reader reader) throws SqlLibraryRuntimeException {

    LibraryParser parser = null;

    try {
        BufferedReader br = new BufferedReader(reader);
        if (!br.markSupported()) {
            throw new SqlLibraryRuntimeException("Reader does not support marking - aborting");
        }

        br.mark(50);
        char[] xmlDefArray = new char[6];
        br.read(xmlDefArray, 0, 6);
        br.reset();

        String xmlDef = new String(xmlDefArray);

        if (xmlDef.matches("^.*<\\?xml.*")) {
            if (log.isInfoEnabled())
                log.info("Detected .xml sql library");
            parser = new XMLLibraryParser();
        } else {
            if (log.isInfoEnabled())
                log.info("Detected .sqllib sql library");
            parser = new SqlLibLibraryParser();
        }
    } catch (IOException e) {
        throw new SqlLibraryRuntimeException("Error occured whilst testing the InputStream for XML syntax", e);
    }

    return parser;
}

From source file:com.thinkbiganalytics.discovery.parsers.csv.CSVAutoDetect.java

private List<LineStats> generateStats(BufferedReader br, Character separatorChar) throws IOException {
    List<LineStats> lineStats = new Vector<>();
    String line;//from  w  ww. j  a  v  a2  s.co  m
    int rows = 0;
    br.mark(32765);
    while ((line = br.readLine()) != null && rows < 100) {
        LineStats stats = new LineStats(line, separatorChar);
        rows++;
        lineStats.add(stats);
    }
    br.reset();
    return lineStats;
}

From source file:org.uva.itast.blended.omr.PageTemplate.java

/**
 * Mtodo que lee las marcas de un objeto BufferedReader y las almacena en un objeto tipo Campo
 * @param in/*from  w  w w  . ja v  a2  s  . co  m*/
 * @throws IOException 
 */
public void leerMarcas(BufferedReader in) throws IOException {

    String line;

    in.mark(20); //marcamos para recordar la posicin anterior donde termino la lectura de in
    while ((line = in.readLine()) != null && !line.equals("")) {
        if (line.startsWith("[Page")) //etiqueta de principio de pgina   
        {
            if (logger.isDebugEnabled()) {
                logger.debug("leerMarcas(BufferedReader) - Pgina siguiente"); //$NON-NLS-1$
            }
            in.reset();
            return;
        } else //lectura de fields de una lnea
        {
            Field campo;
            try {
                campo = new Field(line);
                fields.put(campo.getName(), campo);
                marcas.add(campo.getName()); //almacenamos en el array marcas[] la clave
            } catch (IllegalArgumentException e) // bad field especification
            {
                logger.warn("Field ignored.", e);
            }

        }
        in.mark(20); // mark position for next page
    }

}

From source file:org.tellervo.desktop.io.TridasDoc.java

/**
 * Quickly check to see if it's an XML document
 * @param r/*from www.j a v  a 2 s .  c o  m*/
 * @throws IOException
 */
private void quickVerify(BufferedReader r) throws IOException {
    r.mark(4096);

    String firstLine = r.readLine();
    if (firstLine == null || !firstLine.startsWith("<?xml"))
        throw new WrongFiletypeException();

    r.reset();
}

From source file:net.dv8tion.jda.core.requests.Response.java

protected Response(final okhttp3.Response response, final int code, final String message, final long retryAfter,
        final Set<String> cfRays) {
    this.rawResponse = response;
    this.code = code;
    this.message = message;
    this.exception = null;
    this.retryAfter = retryAfter;
    this.cfRays = cfRays;

    if (response == null || response.body().contentLength() == 0) {
        this.object = null;
        return;//from   w ww .jav  a  2s. c  o  m
    }

    InputStream body = null;
    BufferedReader reader = null;
    try {
        body = Requester.getBody(response);
        // this doesn't add overhead as org.json would do that itself otherwise
        reader = new BufferedReader(new InputStreamReader(body));
        char begin; // not sure if I really like this... but we somehow have to get if this is an object or an array
        int mark = 1;
        do {
            reader.mark(mark++);
            begin = (char) reader.read();
        } while (Character.isWhitespace(begin));

        reader.reset();

        if (begin == '{')
            this.object = new JSONObject(new JSONTokener(reader));
        else if (begin == '[')
            this.object = new JSONArray(new JSONTokener(reader));
        else
            this.object = reader.lines().collect(Collectors.joining());
    } catch (final Exception e) {
        throw new RuntimeException("An error occurred while parsing the response for a RestAction", e);
    } finally {
        try {
            body.close();
            reader.close();
        } catch (NullPointerException | IOException ignored) {
        }
    }
}

From source file:com.mirth.connect.plugins.datatypes.delimited.DelimitedReader.java

/**
 * Look ahead one character in the stream, return it, but don't consume it.
 * // w ww . jav  a2  s .c  o  m
 * @param in
 *            The input stream (it's a BufferedReader, because operations on it require
 *            in.mark()).
 * @return The next character in the stream, or -1 if end of stream reached.
 * @throws IOException
 */
public int peekChar(BufferedReader in) throws IOException {
    in.mark(1);
    int ch = getNonIgnoredChar(in, true);
    in.reset();
    return ch;
}

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

private void parseSection(BufferedReader in, String sectionName) throws IOException, ParseException {
    SectionHandler handler = getSectionHandler(sectionName);
    if (handler == null) {
        return;/*  w w  w  . j av  a2  s . com*/
    }
    handler.startSection(sectionName);
    in.mark(READ_AHEAD_LIMIT);
    String line = in.readLine();
    while (line != null) {
        if (getSectionName(line) != null) {
            // found start of a new section
            in.reset();
            break;
        }
        boolean shouldBreak = !handler.handleLine(line);
        if (shouldBreak) {
            // handler reported that his section is over
            break;
        }
        in.mark(READ_AHEAD_LIMIT);
        line = in.readLine();
    }
    handler.endSection();
}