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:edu.ucla.stat.SOCR.chart.ChartTree_dynamic.java

/**
 * Creates the tree node and its subnods
 * /*from  ww  w.  ja v a 2  s .  c om*/
 * @return A populated tree node.
 */
private MutableTreeNode createChartsNode(String name) {
    //System.out.println("adding-"+name+"-");

    BufferedReader rder = startReaderBuffer();

    DefaultMutableTreeNode node_root = new DefaultMutableTreeNode(name);
    String line, className, chartName;
    StringBuffer sb = new StringBuffer();

    while ((line = readLine(rder)) != null) {
        if (line.toLowerCase().equalsIgnoreCase("[" + name + "]")) {
            while ((line = readLine(rder)) != null) {

                if (line.toLowerCase().startsWith("item")) {
                    line = line.substring(line.indexOf("=") + 1);
                    StringTokenizer tk = new StringTokenizer(line, "=,; ");

                    chartName = tk.nextToken().trim();
                    className = tk.nextToken().trim();
                    //   System.out.println("className =["+className+"]");
                    DefaultMutableTreeNode n = new DefaultMutableTreeNode(
                            new DemoDescription(className, chartName));
                    node_root.add(n);
                } //item

                else if (line.toLowerCase().startsWith("subcategory")) {
                    line = line.substring(line.indexOf("=") + 1);
                    try {
                        rder.mark(100);
                        node_root.add(createChartsNode(line.trim()));
                        rder.reset();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } //subCategory

                else if (line.toLowerCase().startsWith("[")) {
                    //System.out.println("end of "+name);
                    return node_root;
                }

            }
        }

    }
    return node_root;
}

From source file:org.geoserver.catalog.SLDHandler.java

/**
 * Helper method for finding which style handler/version to use from the actual content.
 *//*from w w  w .  j a  v a2 s .c  o m*/
Object[] getVersionAndReader(Object input) throws IOException {
    //need to determine version of sld from actual content
    BufferedReader reader = null;

    if (input instanceof InputStream) {
        reader = RequestUtils.getBufferedXMLReader((InputStream) input, XML_LOOKAHEAD);
    } else {
        reader = RequestUtils.getBufferedXMLReader(toReader(input), XML_LOOKAHEAD);
    }

    if (!reader.ready()) {
        return null;
    }

    String version;
    try {
        //create stream parser
        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setValidating(false);

        //parse root element
        XmlPullParser parser = factory.newPullParser();
        parser.setInput(reader);
        parser.nextTag();

        version = null;
        for (int i = 0; i < parser.getAttributeCount(); i++) {
            if ("version".equals(parser.getAttributeName(i))) {
                version = parser.getAttributeValue(i);
            }
        }

        parser.setInput(null);
    } catch (XmlPullParserException e) {
        throw (IOException) new IOException("Error parsing content").initCause(e);
    }

    //reset input stream
    reader.reset();

    if (version == null) {
        LOGGER.warning("Could not determine SLD version from content. Assuming 1.0.0");
        version = "1.0.0";
    }

    return new Object[] { new Version(version), reader };
}

From source file:org.fhcrc.cpl.toolbox.filehandler.TabLoader.java

/**
 * Look at first 5 lines of the file and infer col names, data types.
 * Most useful if maps are being returned, otherwise use inferColumnInfo(reader, clazz) to
 * use properties of a bean instead./* ww w .  j av  a2  s  .c o  m*/
 *
 * @param reader
 * @throws IOException
 */
private void inferColumnInfo(BufferedReader reader) throws IOException {
    reader.mark(4096 * _scanAheadLineCount);

    String[] lines = new String[_scanAheadLineCount + Math.max(_skipLines, 0)];
    int i;
    for (i = 0; i < lines.length;) {
        String line = reader.readLine();
        if (null == line)
            break;
        if (line.length() == 0 || line.charAt(0) == '#')
            continue;
        lines[i++] = line;
    }
    int nLines = i;
    reader.reset();
    if (nLines == 0) {
        _columns = new ColumnDescriptor[0];
        return;
    }

    int nCols = 0;
    String[][] lineFields = new String[nLines][];
    for (i = 0; i < nLines; i++) {
        lineFields[i] = parseLine(lines[i]);
        nCols = Math.max(nCols, lineFields[i].length);
    }

    ColumnDescriptor[] colDescs = new ColumnDescriptor[nCols];
    for (i = 0; i < nCols; i++)
        colDescs[i] = new ColumnDescriptor();

    //Try to infer types
    int inferStartLine = _skipLines == -1 ? 1 : _skipLines;
    for (int f = 0; f < nCols; f++) {
        int classIndex = -1;
        for (int line = inferStartLine; line < nLines; line++) {
            if (f >= lineFields[line].length)
                continue;
            String field = lineFields[line][f];
            if ("".equals(field))
                continue;

            for (int c = Math.max(classIndex, 0); c < convertClasses.length; c++) {
                //noinspection EmptyCatchBlock
                try {
                    Object o = ConvertUtils.convert(field, convertClasses[c]);
                    //We found a type that works. If it is more general than
                    //what we had before, we must use it.
                    if (o != null && c > classIndex)
                        classIndex = c;
                    break;
                } catch (Exception x) {
                }
            }
        }
        colDescs[f].clazz = classIndex == -1 ? String.class : convertClasses[classIndex];
    }

    //If first line is compatible type for all fields, AND all fields not Strings (dhmay adding 20100502)
    // then there is no header row
    if (_skipLines == -1) {
        boolean firstLineCompat = true;
        boolean allStrings = true;
        String[] fields = lineFields[0];
        for (int f = 0; f < nCols; f++) {
            if ("".equals(fields[f]))
                continue;
            if (colDescs[f].clazz.equals(Integer.TYPE) || colDescs[f].clazz.equals(Double.TYPE)
                    || colDescs[f].clazz.equals(Float.TYPE))
                allStrings = false;
            try {
                Object o = ConvertUtils.convert(fields[f], colDescs[f].clazz);
                if (null == o) {
                    firstLineCompat = false;
                    break;
                }
            } catch (Exception x) {
                firstLineCompat = false;
                break;
            }
        }
        if (firstLineCompat && !allStrings)
            _skipLines = 0;
        else
            _skipLines = 1;
    }

    if (_skipLines > 0) {
        String[] headers = lineFields[_skipLines - 1];
        for (int f = 0; f < nCols; f++)
            colDescs[f].name = (f >= headers.length || "".equals(headers[f])) ? "column" + f : headers[f];
    } else {
        for (int f = 0; f < colDescs.length; f++) {
            ColumnDescriptor colDesc = colDescs[f];
            colDesc.name = "column" + f;
        }
    }

    _columns = colDescs;
}

From source file:org.apache.jmeter.services.FileServer.java

private BufferedReader getReader(String alias, boolean recycle, boolean firstLineIsNames) throws IOException {
    FileEntry fileEntry = files.get(alias);
    if (fileEntry != null) {
        BufferedReader reader;
        if (fileEntry.inputOutputObject == null) {
            reader = createBufferedReader(fileEntry);
            fileEntry.inputOutputObject = reader;
            if (firstLineIsNames) {
                // read first line and forget
                reader.readLine();//  w  ww .  j a v  a2 s. c  o  m
            }
        } else if (!(fileEntry.inputOutputObject instanceof Reader)) {
            throw new IOException("File " + alias + " already in use");
        } else {
            reader = (BufferedReader) fileEntry.inputOutputObject;
            if (recycle) { // need to check if we are at EOF already
                reader.mark(1);
                int peek = reader.read();
                if (peek == -1) { // already at EOF
                    reader.close();
                    reader = createBufferedReader(fileEntry);
                    fileEntry.inputOutputObject = reader;
                    if (firstLineIsNames) {
                        // read first line and forget
                        reader.readLine();
                    }
                } else { // OK, we still have some data, restore it
                    reader.reset();
                }
            }
        }
        return reader;
    } else {
        throw new IOException("File never reserved: " + alias);
    }
}

From source file:ffx.xray.CIFFilter.java

/**
 * {@inheritDoc}/*  w w  w  .jav  a2  s  .  co  m*/
 */
@Override
public double getResolution(File cifFile, Crystal crystal) {
    double res = Double.POSITIVE_INFINITY;

    try {
        BufferedReader br = new BufferedReader(new FileReader(cifFile));

        String str;
        int ncol = 0;
        boolean inhkl = false;
        while ((str = br.readLine()) != null) {
            String strarray[] = str.split("\\s+");

            if (strarray[0].startsWith("_refln.")) {
                inhkl = true;
                br.mark(0);
                String cifarray[] = strarray[0].split("\\.+");
                switch (Header.toHeader(cifarray[1])) {
                case index_h:
                    h = ncol;
                    break;
                case index_k:
                    k = ncol;
                    break;
                case index_l:
                    l = ncol;
                    break;
                }

                ncol++;
            } else if (inhkl) {
                if (h < 0 || k < 0 || l < 0) {
                    String message = "Fatal error in CIF file - no H K L indexes?\n";
                    logger.log(Level.SEVERE, message);
                    return -1.0;
                }
                break;
            }
        }

        // go back to where the reflections start
        br.reset();
        HKL hkl = new HKL();
        while ((str = br.readLine()) != null) {
            // reached end, break
            if (str.trim().startsWith("#END")) {
                break;
            } else if (str.trim().startsWith("data")) {
                break;
            } else if (str.trim().startsWith("#")) {
                continue;
            }

            String strarray[] = str.trim().split("\\s+");
            // some files split data on to multiple lines
            while (strarray.length < ncol) {
                str = str + " " + br.readLine();
                strarray = str.trim().split("\\s+");
            }

            int ih = Integer.parseInt(strarray[h]);
            int ik = Integer.parseInt(strarray[k]);
            int il = Integer.parseInt(strarray[l]);

            hkl.h(ih);
            hkl.k(ik);
            hkl.l(il);
            res = Math.min(res, Crystal.res(crystal, hkl));
        }
    } catch (IOException ioe) {
        System.out.println("IO Exception: " + ioe.getMessage());
        return -1.0;
    }

    return res;
}

From source file:ffx.xray.parsers.CIFFilter.java

/**
 * {@inheritDoc}//from  w  ww  .  ja  v  a2 s  .c om
 */
@Override
public double getResolution(File cifFile, Crystal crystal) {

    double resolution = Double.POSITIVE_INFINITY;

    try {
        BufferedReader br = new BufferedReader(new FileReader(cifFile));
        String string;
        int nCol = 0;
        boolean inHKL = false;
        while ((string = br.readLine()) != null) {
            String strArray[] = string.split("\\s+");
            if (strArray[0].startsWith("_refln.")) {
                inHKL = true;
                br.mark(0);
                String cifArray[] = strArray[0].split("\\.+");
                switch (Header.toHeader(cifArray[1])) {
                case index_h:
                    h = nCol;
                    break;
                case index_k:
                    k = nCol;
                    break;
                case index_l:
                    l = nCol;
                    break;
                }
                nCol++;
            } else if (inHKL) {
                if (h < 0 || k < 0 || l < 0) {
                    String message = " Fatal error in CIF file - no H K L indexes?\n";
                    logger.log(Level.SEVERE, message);
                    return -1.0;
                }
                break;
            }
        }

        // Go back to where the reflections start.
        br.reset();
        HKL hkl = new HKL();
        while ((string = br.readLine()) != null) {

            // Reached end, break.
            if (string.trim().startsWith("#END")) {
                break;
            } else if (string.trim().startsWith("data")) {
                break;
            } else if (string.trim().startsWith("#")) {
                continue;
            }

            // Some files split data on to multiple lines.
            String strArray[] = string.trim().split("\\s+");
            while (strArray.length < nCol) {
                string = string + " " + br.readLine();
                strArray = string.trim().split("\\s+");
            }

            int ih = Integer.parseInt(strArray[h]);
            int ik = Integer.parseInt(strArray[k]);
            int il = Integer.parseInt(strArray[l]);

            hkl.h(ih);
            hkl.k(ik);
            hkl.l(il);
            resolution = min(resolution, Crystal.res(crystal, hkl));
        }
    } catch (IOException e) {
        String message = " CIF IO Exception.";
        logger.log(Level.WARNING, message, e);
        return -1.0;
    }
    return resolution;
}

From source file:org.geoserver.ows.Dispatcher.java

/**
 * Reads the following parameters from an OWS XML request body:
 * * request/* www . j  av  a 2s  .c o m*/
 * * namespace
 * * service
 * * version
 * * outputFormat
 * Resets the input reader after reading
 *
 * @param input {@link BufferedReader} containing a valid OWS XML request body
 * @return a {@link Map} containing the parsed parameters.
 * @throws Exception if there was an error reading the input.
 */
public static Map readOpPost(BufferedReader input) throws Exception {
    //create stream parser
    XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(false);

    //parse root element
    XmlPullParser parser = factory.newPullParser();
    parser.setInput(input);
    parser.nextTag();

    Map map = new HashMap();
    map.put("request", parser.getName());
    map.put("namespace", parser.getNamespace());

    for (int i = 0; i < parser.getAttributeCount(); i++) {
        String attName = parser.getAttributeName(i);

        if ("service".equals(attName)) {
            map.put("service", parser.getAttributeValue(i));
        }

        if ("version".equals(parser.getAttributeName(i))) {
            map.put("version", parser.getAttributeValue(i));
        }

        if ("outputFormat".equals(attName)) {
            map.put("outputFormat", parser.getAttributeValue(i));
        }
    }

    //close parser + release resources
    parser.setInput(null);

    //reset the input stream
    input.reset();

    return map;
}

From source file:net.gaast.giggity.Schedule.java

public void loadSchedule(String url_, Fetcher.Source source) throws IOException {
    url = url_;/*from   w w  w  . ja v  a  2  s.co m*/

    id = null;
    title = null;

    allItems = new TreeMap<String, Schedule.Item>();
    tents = new LinkedList<Schedule.Line>();
    trackMap = null; /* Only assign if we have track info. */
    languages = new HashSet<>();

    firstTime = null;
    lastTime = null;

    dayList = null;
    curDay = null;
    curDayEnd = null;
    dayChange = new Date();
    dayChange.setHours(6);

    fullyLoaded = false;
    showHidden = false;

    icon = null;
    links = null;

    String head;
    Fetcher f = null;
    BufferedReader in;

    try {
        f = app.fetch(url, source);
        f.setProgressHandler(progressHandler);
        in = f.getReader();
        char[] headc = new char[detectHeaderSize];

        /* Read the first KByte (but keep it buffered) to try to detect the format. */
        in.mark(detectHeaderSize);
        in.read(headc, 0, detectHeaderSize);
        in.reset();

        head = new String(headc).toLowerCase();
    } catch (Exception e) {
        if (f != null)
            f.cancel();

        Log.e("Schedule.loadSchedule", "Exception while downloading schedule: " + e);
        e.printStackTrace();
        throw new LoadException("Network I/O problem: " + e);
    }

    /* Yeah, I know this is ugly, and actually reasonably fragile. For now it
     * just seems somewhat more efficient than doing something smarter, and
     * I want to avoid doing XML-specific stuff here already. */
    try {
        if (head.contains("<icalendar") && head.contains("<vcalendar")) {
            loadXcal(in);
        } else if (head.contains("<schedule") && head.contains("<conference")) {
            loadPentabarf(in);
        } else if (head.contains("<schedule") && head.contains("<line")) {
            loadDeox(in);
        } else if (head.contains("begin:vcalendar")) {
            loadIcal(in);
        } else {
            Log.d("head", head);
            throw new LoadException(app.getString(R.string.format_unknown));
        }
    } catch (LoadException e) {
        f.cancel();
        throw e;
    }

    Log.d("load", "Schedule has " + languages.size() + " languages");

    f.keep();

    if (title == null)
        if (id != null)
            title = id;
        else
            title = url;

    if (id == null)
        id = hashify(url);

    if (allItems.size() == 0) {
        throw new LoadException(app.getString(R.string.schedule_empty));
    }

    db = app.getDb();
    db.setSchedule(this, url, f.getSource() == Fetcher.Source.ONLINE);
    String md_json = db.getMetadata();
    if (md_json != null) {
        addMetadata(md_json);
    }

    /* From now, changes should be marked to go back into the db. */
    fullyLoaded = true;
}

From source file:org.opendatakit.utilities.LocalizationUtils.java

private static synchronized void loadTranslations(String appName, String tableId) throws IOException {
    if (savedAppName != null && !savedAppName.equals(appName)) {
        clearTranslations();/*from  www.  j a va 2s.c o  m*/
    }
    savedAppName = appName;
    TypeReference<HashMap<String, Object>> ref = new TypeReference<HashMap<String, Object>>() {
    };
    if (commonDefinitions == null) {
        File commonFile = new File(ODKFileUtils.getCommonDefinitionsFile(appName));
        if (commonFile.exists() && commonFile.isFile()) {
            InputStream stream = null;
            BufferedReader reader = null;
            String value;
            try {
                stream = new FileInputStream(commonFile);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8));
                } else {
                    reader = new BufferedReader(new InputStreamReader(stream, Charsets.UTF_8));
                }
                int ch = reader.read();
                while (ch != -1 && ch != '{') {
                    ch = reader.read();
                }

                StringBuilder b = new StringBuilder();
                b.append((char) ch);
                ch = reader.read();
                while (ch != -1) {
                    b.append((char) ch);
                    ch = reader.read();
                }
                reader.close();
                stream.close();
                value = b.toString().trim();
                if (value.endsWith(";")) {
                    value = value.substring(0, value.length() - 1).trim();
                }

            } finally {
                if (reader != null) {
                    reader.close();
                } else if (stream != null) {
                    stream.close();
                }
            }

            try {
                commonDefinitions = ODKFileUtils.mapper.readValue(value, ref);
            } catch (IOException e) {
                WebLogger.getLogger(appName).printStackTrace(e);
                throw new IllegalStateException("Unable to read commonDefinitions.js file");
            }
        }
    }

    if (tableId != null) {
        File tableFile = new File(ODKFileUtils.getTableSpecificDefinitionsFile(appName, tableId));
        if (!tableFile.exists()) {
            tableSpecificDefinitionsMap.remove(tableId);
        } else {
            // assume it is current if it exists
            if (tableSpecificDefinitionsMap.containsKey(tableId)) {
                return;
            }
            InputStream stream = null;
            BufferedReader reader = null;
            try {
                stream = new FileInputStream(tableFile);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8));
                } else {
                    reader = new BufferedReader(new InputStreamReader(stream, Charsets.UTF_8));
                }
                reader.mark(1);
                int ch = reader.read();
                while (ch != -1 && ch != '{') {
                    reader.mark(1);
                    ch = reader.read();
                }
                reader.reset();
                Map<String, Object> tableSpecificTranslations = ODKFileUtils.mapper.readValue(reader, ref);
                if (tableSpecificTranslations != null) {
                    tableSpecificDefinitionsMap.put(tableId, tableSpecificTranslations);
                }
            } finally {
                if (reader != null) {
                    reader.close();
                } else if (stream != null) {
                    stream.close();
                }
            }
        }
    }
}

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

/**
 * Reads from file and splits input into strings according to the delimiter,
 * taking note of quoted strings.//from ww  w . ja  va2  s . c  om
 * <p>
 * Handles DOS (CRLF), Unix (LF), and Mac (CR) line-endings equally.
 * <p>
 * A blank line - or a quoted blank line - both return an array containing
 * a single empty String.
 * @param infile
 *            input file - must support mark(1)
 * @param delim
 *            delimiter (e.g. comma)
 * @return array of strings, will be empty if there is no data, i.e. if the input is at EOF.
 * @throws IOException
 *             also for unexpected quote characters
 */
public static String[] csvReadFile(BufferedReader infile, char delim) throws IOException {
    int ch;
    ParserState state = ParserState.INITIAL;
    List<String> list = new ArrayList<>();
    CharArrayWriter baos = new CharArrayWriter(200);
    boolean push = false;
    while (-1 != (ch = infile.read())) {
        push = false;
        switch (state) {
        case INITIAL:
            if (ch == QUOTING_CHAR) {
                state = ParserState.QUOTED;
            } else if (isDelimOrEOL(delim, ch)) {
                push = true;
            } else {
                baos.write(ch);
                state = ParserState.PLAIN;
            }
            break;
        case PLAIN:
            if (ch == QUOTING_CHAR) {
                baos.write(ch);
                throw new IOException("Cannot have quote-char in plain field:[" + baos.toString() + "]");
            } else if (isDelimOrEOL(delim, ch)) {
                push = true;
                state = ParserState.INITIAL;
            } else {
                baos.write(ch);
            }
            break;
        case QUOTED:
            if (ch == QUOTING_CHAR) {
                state = ParserState.EMBEDDEDQUOTE;
            } else {
                baos.write(ch);
            }
            break;
        case EMBEDDEDQUOTE:
            if (ch == QUOTING_CHAR) {
                baos.write(QUOTING_CHAR); // doubled quote => quote
                state = ParserState.QUOTED;
            } else if (isDelimOrEOL(delim, ch)) {
                push = true;
                state = ParserState.INITIAL;
            } else {
                baos.write(QUOTING_CHAR);
                throw new IOException(
                        "Cannot have single quote-char in quoted field:[" + baos.toString() + "]");
            }
            break;
        default:
            throw new IllegalStateException("Unexpected state " + state);
        } // switch(state)
        if (push) {
            if (ch == '\r') {// Remove following \n if present
                infile.mark(1);
                if (infile.read() != '\n') {
                    infile.reset(); // did not find \n, put the character
                                    // back
                }
            }
            String s = baos.toString();
            list.add(s);
            baos.reset();
        }
        if ((ch == '\n' || ch == '\r') && state != ParserState.QUOTED) {
            break;
        }
    } // while not EOF
    if (ch == -1) {// EOF (or end of string) so collect any remaining data
        if (state == ParserState.QUOTED) {
            throw new IOException("Missing trailing quote-char in quoted field:[\"" + baos.toString() + "]");
        }
        // Do we have some data, or a trailing empty field?
        if (baos.size() > 0 // we have some data
                || push // we've started a field
                || state == ParserState.EMBEDDEDQUOTE // Just seen ""
        ) {
            list.add(baos.toString());
        }
    }
    return list.toArray(new String[list.size()]);
}