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.microsoft.tfs.util.NewlineUtils.java

/**
 * <p>/*from  w w  w.j  ava 2 s  .  c  o m*/
 * Replaces newlines read from the given {@link Reader} with the
 * <code>replacement</code> argument and writes the results to the given
 * {@link Writer}.
 * </p>
 * <p>
 * This method internally wraps the given reader in a {@link BufferedReader}
 * (so it can mark and rewind the stream to read multi-character EOL
 * sequences), so the caller may omit its own buffering layer. The
 * {@link Writer} is not automatically buffered.
 * </p>
 *
 * @see #replaceNewlines(String, String, boolean)
 *
 * @param reader
 *        The input {@link Reader} to read characters from. If the input is
 *        <code>null</code>, the method returns immediately (no characters
 *        are written to the {@link Writer}).
 * @param writer
 *        The output {@link Writer} where characters and converted newlines
 *        are written (must not be <code>null</code>)
 * @param replacement
 *        The replacement <code>String</code> for newlines (must not be
 *        <code>null</code>)
 * @param groupNewlines
 *        controls the behavior of this method when there are consecutive
 *        newlines in the input (see the Javadoc for the method that takes
 *        String input for details)
 * @throws IOException
 *         if an error occurred reading from the {@link Reader}, writing to
 *         the {@link Writer}. These errors may include the discovery of
 *         invalid character sequences in the input.
 */
public static void replaceNewlines(final Reader reader, final Writer writer, final String replacement,
        final boolean groupNewlines) throws IOException {
    if (reader == null) {
        return;
    }

    Check.notNull(writer, "output"); //$NON-NLS-1$
    Check.notNull(replacement, "replacement"); //$NON-NLS-1$

    final BufferedReader bufferedReader = new BufferedReader(reader);

    boolean inNewlineGroup = false;

    int currentCharacter;
    while ((currentCharacter = bufferedReader.read()) != -1) {
        final boolean isNewlineCharacter = isNewlineCharacter((char) currentCharacter);

        /*
         * Move the index past the second character of the Windows newline
         * sequence (CRLF), if applicable.
         */
        if (currentCharacter == CARRIAGE_RETURN) {
            /*
             * Set a mark so we can rewind after peeking.
             */
            bufferedReader.mark(BUFFERED_READER_MARK_READ_AHEAD_CHARACTERS);

            final int nextCharacter = bufferedReader.read();

            if (nextCharacter == LINE_FEED) {
                /*
                 * Is a line feed, set this as the current character for
                 * evaluation this iteration.
                 */
                currentCharacter = nextCharacter;
            } else {
                /*
                 * Not a line feed or end of stream.
                 */
                bufferedReader.reset();
            }
        }

        if (isNewlineCharacter) {
            if (groupNewlines) {
                /*
                 * Just record that we've entered a newline group - we'll
                 * apply the replacement string to the result after we've
                 * exited the group.
                 */
                inNewlineGroup = true;
            } else {
                /*
                 * Not in grouping mode - each distinct newline character
                 * gets its own replacement.
                 */
                writer.write(replacement);
            }
        } else {
            if (groupNewlines && inNewlineGroup) {
                /*
                 * Exiting a newline group - apply the replacement to the
                 * result.
                 */
                writer.write(replacement);
                inNewlineGroup = false;
            }
            writer.write(currentCharacter);
        }
    }

    if (inNewlineGroup) {
        /*
         * The input string terminated while we were in a newline group, so
         * be sure to add in the replacement character for this group
         * (without this check, newline groups at the end of strings would
         * be ignored).
         */
        writer.write(replacement);
        inNewlineGroup = false;
    }
}

From source file:massbank.CallCgi.java

public void run() {
    String progName = "CallCgi";
    String msg = "";

    HttpClient client = new HttpClient();
    // ^CAEgl(msec)Zbg
    client.setTimeout(m_timeout * 1000);
    PostMethod method = new PostMethod(this.m_url);
    String strParam = "";
    if (m_params != null && m_params.size() > 0) {
        for (Enumeration keys = m_params.keys(); keys.hasMoreElements();) {
            String key = (String) keys.nextElement();
            if (!key.equals("inst_grp") && !key.equals("inst") && !key.equals("ms")
                    && !key.equals("inst_grp_adv") && !key.equals("inst_adv") && !key.equals("ms_adv")) {
                // L?[InstrumentType,MSTypeO??Stringp??[^
                String val = (String) m_params.get(key);
                strParam += key + "=" + val + "&";
                method.addParameter(key, val);
            } else {
                // L?[InstrumentType,MSType??Stringzp??[^
                String[] vals = (String[]) m_params.get(key);
                for (int i = 0; i < vals.length; i++) {
                    strParam += key + "=" + vals[i] + "&";
                    method.addParameter(key, vals[i]);
                }// w ww  .  ja va  2 s.c o  m
            }
        }
        strParam = strParam.substring(0, strParam.length() - 1);
    }

    try {
        // ?s
        int statusCode = client.executeMethod(method);
        // Xe?[^XR?[h`FbN
        if (statusCode != HttpStatus.SC_OK) {
            // G?[
            msg = method.getStatusLine().toString() + "\n" + "URL  : " + this.m_url;
            msg += "\nPARAM : " + strParam;
            MassBankLog.ErrorLog(progName, msg, m_context);
            return;
        }
        // X|X
        //         this.result = method.getResponseBodyAsString();

        /**
         * modification start
         * Use method.getResponseBodyAsStream() rather 
         * than method.getResponseBodyAsString() (marked as deprecated) for updated HttpClient library.
         * Prevents logging of message:
         * "Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended."
         */

        String charset = method.getResponseCharSet();
        InputStream is = method.getResponseBodyAsStream();
        StringBuilder sb = new StringBuilder();
        String line = "";
        if (is != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, charset));
            while ((line = reader.readLine()) != null) {
                reader.mark(2000);
                String forward = reader.readLine();
                if ((line.equals("") || line.equals("\n") || line.equals("OK")) && forward == null)
                    sb.append(line); // append last line to StringBuilder
                else if (forward != null)
                    sb.append(line).append("\n"); // append current line with explicit line break
                else
                    sb.append(line);

                reader.reset();
            }
            reader.close();
            is.close();

            //            this.result = sb.toString().trim();
            this.result = sb.toString(); // trim() deleted. because the last [\t] and [\n] are removed.
            if (this.result.endsWith("\n")) // remove trailing line break
            {
                int pos = this.result.lastIndexOf("\n");
                this.result = this.result.substring(0, pos);
            }
        } else {
            this.result = "";
        }

        /**
         * modification end
         */
    } catch (Exception e) {
        // G?[
        msg = e.toString() + "\n" + "URL  : " + this.m_url;
        msg += "\nPARAM : " + strParam;
        MassBankLog.ErrorLog(progName, msg, m_context);
    } finally {
        // RlNV
        method.releaseConnection();
    }
}

From source file:org.alfresco.repo.search.impl.lucene.analysis.VerbatimMLAnalayser.java

@Override
public TokenStream tokenStream(String fieldName, Reader reader) {
    // We use read ahead to get the language info - if this does not exist we need to restart
    // an use the default - there foer we need mark and restore.

    if (!(reader instanceof BufferedReader)) {
        BufferedReader breader = new BufferedReader(reader);
        try {//  w  w  w.j  av  a2s  . c  om
            if (!breader.markSupported()) {
                throw new AnalysisException(
                        "Multilingual tokenisation requires a reader that supports marks and reset");
            }
            breader.mark(100);
            StringBuilder builder = new StringBuilder();
            if (breader.read() == '\u0000') {
                String language = "";
                String country = "";
                String varient = "";
                char c;
                int count = 0;
                while ((c = (char) breader.read()) != '\u0000') {
                    if (count++ > 99) {
                        breader.reset();
                        return getAnalyser().tokenStream(fieldName, breader);
                    }
                    if (c == '_') {
                        if (language.length() == 0) {
                            language = builder.toString();
                        } else if (country.length() == 0) {
                            country = builder.toString();
                        } else if (varient.length() == 0) {
                            varient = builder.toString();
                        } else {
                            breader.reset();
                            return getAnalyser().tokenStream(fieldName, breader);
                        }
                        builder = new StringBuilder();
                    } else {
                        builder.append(c);
                    }
                }
                if (builder.length() > 0) {
                    if (language.length() == 0) {
                        language = builder.toString();
                    } else if (country.length() == 0) {
                        country = builder.toString();
                    } else if (varient.length() == 0) {
                        varient = builder.toString();
                    } else {
                        breader.reset();
                        return getAnalyser().tokenStream(fieldName, breader);
                    }
                }
                Locale locale = new Locale(language, country, varient);
                // leave the reader where it is ....
                return new MLTokenDuplicator(getAnalyser().tokenStream(fieldName, breader), locale, breader,
                        mlAnalaysisMode);
            } else {
                breader.reset();
                return getAnalyser().tokenStream(fieldName, breader);
            }
        } catch (IOException io) {
            try {
                breader.reset();
            } catch (IOException e) {
                throw new AnalysisException("Failed to reset buffered reader - token stream will be invalid",
                        e);
            }
            return getAnalyser().tokenStream(fieldName, breader);
        }

    } else {
        throw new AnalysisException("Multilingual tokenisation requires a buffered reader");
    }
}

From source file:edu.lternet.pasta.gatekeeper.GatekeeperFilter.java

/**
 * dumpBody outputs the contents of the request message body to the
 * designated logger.  Note that the use of this method will render the
 * request object inoperable for and subsequent calls.
 * //w  ww.  j  a v a 2 s  .  c o m
 * @param req 
 *          the HttpServletRequest object.
 * @param contentLength 
 *          the content length that was specified in the 
 *          request headers, possibly null
 */
private void dumpBody(HttpServletRequest req, Integer contentLength) {

    if (contentLength != null) {

        try {
            BufferedReader br = req.getReader();
            String line = null;

            logger.info("Request message body:\n");

            if (br.markSupported()) {

                br.mark(contentLength + 1);

                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                }

                br.reset();

            }

            br.close();

        } catch (IOException e) {
            logger.error("dumpBody: " + e);
            e.printStackTrace();
        }

    }

}

From source file:org.lockss.util.CXSerializer.java

/**
 * <p>Deserializes an object from a reader, determining on the fly
 * if the incoming object is in Castor or XStream format.</p>
 * @param reader    A reader instance.//  w  w w  .  ja v  a2 s.c om
 * @param wasCastor A mutable boolean. After the method executes,
 *                  its value will be true if the input was in
 *                  Castor format, false otherwise.
 * @return An Object reference whose field were populated from the
 *         data found in the XML file.
 * @throws SerializationException   if input or output fails.
 * @throws InterruptedIOException   if input or output is
 *                                  interrupted.
 */
public Object deserialize(Reader reader, MutableBoolean wasCastor)
        throws SerializationException, InterruptedIOException {
    // Constants
    final String recognizeCastor = "<?xml";

    // Make rewinding possible
    BufferedReader bufReader = new BufferedReader(reader);

    // Peek at beginning of input
    char[] buffer = new char[recognizeCastor.length()];
    try {
        bufReader.mark(recognizeCastor.length() + 1);
        if (StreamUtil.readChars(bufReader, buffer, buffer.length) != buffer.length) {
            throw failDeserialize(
                    new SerializationException("Could not peek at first " + buffer.length + " bytes"));
        }
        bufReader.reset();
    } catch (IOException exc) {
        throw failDeserialize(exc);
    }

    // Guess format and deserialize
    ObjectSerializer deserializer;
    if (recognizeCastor.equals(new String(buffer))) {
        deserializer = castor;
        wasCastor.setValue(true);
    } else {
        deserializer = xstream;
        wasCastor.setValue(false);
    }
    return deserializer.deserialize(bufReader);
}

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

/**
 * Look ahead n characters in the stream, return them, but don't consume them.
 * /* w w w. j  a va  2 s  .c om*/
 * @param in
 *            The input stream (it's a BufferedReader, because operations on it require
 *            in.mark()).
 * @param n
 *            The number of characters to read.
 * @return A string containing the next n characters without consuming them. Returns an empty
 *         string if no characters are read.
 * @throws IOException
 */
public String peekChars(BufferedReader in, int n) throws IOException {
    // Mark with a little extra (64 characters) in case the code skips over
    // some ignored characters (e.g. \r's)
    // Beyond 64 ignored characters may cause a problem on reset().
    in.mark(n + 64);
    StringBuilder result = new StringBuilder();
    while (n > 0) {

        int ch = getNonIgnoredChar(in, false);

        if (ch == -1) {
            break;
        }

        result.append((char) ch);
        n--;
    }
    in.reset();
    return result.toString();
}

From source file:org.apache.jmeter.save.CSVSaveService.java

/**
 * Read Samples from a file; handles quoted strings.
 * //  w  ww .  ja  v  a 2s .  co  m
 * @param filename
 *            input file
 * @param visualizer
 *            where to send the results
 * @param resultCollector
 *            the parent collector
 * @throws IOException
 *             when the file referenced by <code>filename</code> can't be
 *             read correctly
 */
public static void processSamples(String filename, Visualizer visualizer, ResultCollector resultCollector)
        throws IOException {
    BufferedReader dataReader = null;
    final boolean errorsOnly = resultCollector.isErrorLogging();
    final boolean successOnly = resultCollector.isSuccessOnlyLogging();
    try {
        dataReader = new BufferedReader(
                new InputStreamReader(new FileInputStream(filename), SaveService.getFileEncoding("UTF-8")));
        dataReader.mark(400);// Enough to read the header column names
        // Get the first line, and see if it is the header
        String line = dataReader.readLine();
        if (line == null) {
            throw new IOException(filename + ": unable to read header line");
        }
        long lineNumber = 1;
        SampleSaveConfiguration saveConfig = CSVSaveService.getSampleSaveConfiguration(line, filename);
        if (saveConfig == null) {// not a valid header
            log.info(filename + " does not appear to have a valid header. Using default configuration.");
            saveConfig = (SampleSaveConfiguration) resultCollector.getSaveConfig().clone(); // may change the format later
            dataReader.reset(); // restart from beginning
            lineNumber = 0;
        }
        String[] parts;
        final char delim = saveConfig.getDelimiter().charAt(0);
        // TODO: does it matter that an empty line will terminate the loop?
        // CSV output files should never contain empty lines, so probably
        // not
        // If so, then need to check whether the reader is at EOF
        while ((parts = csvReadFile(dataReader, delim)).length != 0) {
            lineNumber++;
            SampleEvent event = CSVSaveService.makeResultFromDelimitedString(parts, saveConfig, lineNumber);
            if (event != null) {
                final SampleResult result = event.getResult();
                if (ResultCollector.isSampleWanted(result.isSuccessful(), errorsOnly, successOnly)) {
                    visualizer.add(result);
                }
            }
        }
    } finally {
        JOrphanUtils.closeQuietly(dataReader);
    }
}

From source file:org.apache.any23.mime.TikaMIMETypeDetector.java

/**
 * Extracts a sample data from the input stream, from the current
 * mark to the first <i>breakChar</i> char.
 *
 * @param is the input stream to sample.
 * @param breakChar the char to break to sample.
 * @return the sample string.//from  w w w .  java2s .  c  o m
 * @throws IOException if an error occurs during sampling.
 */
private static StringBuilder extractDataSample(InputStream is, char breakChar, char[] insideBlockCharacters,
        char[] lineCommentChars, char[] outsideBlockCharacters, char[] switchBlockCharacters)
        throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    // TODO: Make this configurable
    final int MAX_SIZE = 1024 * 2;
    int c;
    boolean insideBlock = false;
    int read = 0;
    br.mark(MAX_SIZE);
    try {
        while ((c = br.read()) != -1) {
            read++;
            if (sb.length() > MAX_SIZE) {
                break;
            }

            if (!insideBlock) {
                for (char nextLineCommentChar : lineCommentChars) {
                    // if we hit a comment character that signals the rest of the line is a comment 
                    // then we do not want to extract any of the rest of the line, including the 
                    // comment character for our sample, so we read to the end of the line and then 
                    // continue the loop without appending anything
                    if (c == nextLineCommentChar) {
                        br.readLine();
                        continue;
                    }
                }
            }

            for (char nextInsideChar : insideBlockCharacters) {
                if (c == nextInsideChar)
                    insideBlock = true;
            }

            for (char nextOutsideChar : outsideBlockCharacters) {
                if (c == nextOutsideChar)
                    insideBlock = false;
            }

            for (char nextSwitchChar : switchBlockCharacters) {
                if (c == nextSwitchChar)
                    insideBlock = !insideBlock;
            }
            sb.append((char) c);
            if (!insideBlock && breakChar == c) {
                break;
            }
        }
    } finally {
        is.reset();
        br.reset();
    }
    return sb;
}

From source file:tufts.vue.action.ActionUtil.java

private static LWMap unmarshallMap(final java.net.URL url, Mapping mapping, String charsetEncoding,
        boolean allowOldFormat, String savingVersion, MapUnmarshalHandler mapHandler)
        //throws IOException, org.exolab.castor.mapping.MappingException, org.exolab.castor.xml.ValidationException
        throws IOException {
    LWMap map = null;//from w  w  w .j  a  va 2s  .  c om

    Log.info("unmarshalling: " + url + "; charset=" + charsetEncoding);

    // TODO: now that we support opening maps via HTTP URL's, it's a bit obscene to
    // open the URL twice just to support old maps where we might need to detect the
    // encoding, then re-open the file with the proper encoding.  We could
    // presumably have the MapReader keep an underlying buffered raw InputStream,
    // then create Reader's on top of that with different encodings to support this
    // more smoothly.  SMF 2008-04-08
    final MapReader mapReader = getMapReaderForURL(url, charsetEncoding, true);

    final BufferedReader reader = mapReader.reader;

    // Skip over comments to get to start of XML

    for (;;) {
        reader.mark(2048); // a single comment line can't be longer than this...
        String line = reader.readLine();
        if (line == null) {
            Log.error("Unexpected end-of-stream in [" + url + "]");
            throw new java.io.IOException("end of stream in " + url);
        }
        if (line.startsWith("<!--") == false) {
            // we should have just hit thie "<?xml ..." line -- done with comments
            break;
        }
        if (DEBUG.META && (DEBUG.CASTOR || DEBUG.IO))
            Log.debug("Skipping[" + line + "]");
    }

    // Reset the reader to the start of the last line read, which should be the <?xml line,
    // which is what castor needs to see at start (it can't handle ignoring comments...)
    reader.reset();

    final String sourceName = url.toString();

    try {
        Unmarshaller unmarshaller = getDefaultUnmarshaller(mapping, sourceName);

        if (mapHandler == null)
            mapHandler = new MapUnmarshalHandler(url, tufts.vue.Resource.MANAGED_UNMARSHALLING); // managed is the default

        if (DEBUG.Enabled)
            Log.debug("unmarshal handler: " + mapHandler);
        unmarshaller.setUnmarshalListener(mapHandler);

        // unmarshall the map:

        try {
            map = (LWMap) unmarshaller.unmarshal(new InputSource(reader));
            //} catch (org.exolab.castor.xml.MarshalException me) {
        } catch (org.exolab.castor.xml.MarshalException me) {
            //if (allowOldFormat && me.getMessage().endsWith("tufts.vue.Resource")) {
            //if (allowOldFormat && me.getMessage().indexOf("Unable to instantiate tufts.vue.Resource") >= 0) {
            // 2007-10-01 SMF: rev forward the special exception to check for once again in new castor version: castor-1.1.2.1-xml.jar
            // TODO: 2009-03-25: upgraded to Castor release 1.3: the below message check may no longer work...
            if (allowOldFormat && me.getMessage() != null
                    && me.getMessage().indexOf("tufts.vue.Resource can no longer be constructed") >= 0) {
                Log.warn("ActionUtil.unmarshallMap: " + me);
                Log.warn("Attempting specialized MapResource mapping for old format.");
                // NOTE: delicate recursion here: won't loop as long as we pass in a non-null mapping.
                return unmarshallMap(url, getMapping(XML_MAPPING_OLD_RESOURCES), charsetEncoding, false,
                        savingVersion, mapHandler);
            } else
                throw me;
        }

        reader.close();

        Log.info("unmarshalled: " + map);

        // The below three notify calls must be called in exact sequence (file, then version, then completed)

        mapHandler.notifyFile(map, mapReader.file);

        mapHandler.notifyVersionOfVueThatSavedMap(savingVersion);

        mapHandler.notifyUnmarshallingCompleted();

        Log.debug("completed: " + map);
    } catch (Exception e) {
        tufts.Util.printStackTrace(e, "Exception restoring map from [" + url + "]: " + e.getClass().getName());
        Log.info("map-as-is: " + Util.tags(map)); // presumably null
        map = null;
        throw new Error("Exception restoring map from [" + url + "]", e);
    }

    return map;
}

From source file:com.pironet.tda.SunJDKParser.java

/**
 * parses a loggc file stream and reads any found class histograms and adds the to the dump store
 *
 * @param loggcFileStream the stream to read
 * @param root            the root node of the dumps.
 *///www. ja  v  a  2 s  . co  m
public void parseLoggcFile(InputStream loggcFileStream, DefaultMutableTreeNode root) {
    final BufferedReader bis = new BufferedReader(new InputStreamReader(loggcFileStream));
    final List<HistogramTableModel> histograms = new Vector<>();
    try {
        while (bis.ready()) {
            bis.mark(getMarkSize());
            String nextLine = bis.readLine();
            if (nextLine.startsWith("num   #instances    #bytes  class name")) {
                bis.reset();
                histograms.add(parseNextClassHistogram(bis));
            }
        }

        // now add the found histograms to the tree.
        for (int i = histograms.size() - 1; i >= 0; i--) {
            DefaultMutableTreeNode dump = getNextDumpForHistogram(root);
            if (dump != null) {
                addHistogramToDump(dump, histograms.get(i));
            }
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        IOUtils.closeQuietly(bis);
    }
}