List of usage examples for java.io BufferedReader mark
public void mark(int readAheadLimit) throws IOException
From source file:com.googlecode.erca.framework.io.in.RcftParser.java
private void parseFormalContext(BufferedReader input, String desc) throws IOException { String fcName = desc.split("\\ ")[1]; FormalContext fc = RcfFactory.eINSTANCE.createFormalContext(); fc.setName(fcName);/*from w w w .ja v a 2 s . c o m*/ logger.info("Parsing formal context " + fcName); input.mark(0); String line = input.readLine(); int currentRow = 0; Map<Integer, Attribute> attrs = new HashMap<Integer, Attribute>(); while (line != null) { String tline = line.trim(); if (tline.startsWith("FormalContext")) break; else if (tline.startsWith("RelationalContext")) break; else if (tline.equals("")) break; String[] tokens = line.split("\\|"); int len = tokens.length; if (currentRow == 0) { for (int i = 2; i < len; i++) { String attrDesc = tokens[i].trim(); Attribute attr = RcaParsingUtils.attributeFromText(attrDesc); attrs.put(i, attr); fc.getAttributes().add(attr); logger.debug("Attribute " + attr.getDescription() + " created. Row: " + i); } } else { String name = tokens[1].trim(); Entity ent = ErcaFactory.eINSTANCE.createEntity(); logger.debug("Entity " + name + " created. Line: " + currentRow); ent.setName(name); fc.getEntities().add(ent); for (int i = 2; i < len; i++) { String cell = tokens[i].trim().toLowerCase(); if ("x".equals(cell)) { Attribute attr = attrs.get(i); Pair pair = RcfFactory.eINSTANCE.createPair(); pair.setSource(ent); pair.setTarget(attr); fc.getRelation().add(pair); logger.debug("Pair between " + ent.getName() + " and " + attr.getDescription() + " created. Line: " + currentRow); } } } currentRow++; input.mark(0); line = input.readLine(); } rcf.getFormalContexts().add(fc); if (line != null) input.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 ww w.ja v a 2s . com*/ } 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: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 ww. j a v a2s . co m } 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(); }
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 ww .j a v a2 s.c o m * @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 one character in the stream, return it, but don't consume it. * //from www . j a v a 2 s.co 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:com.mirth.connect.plugins.datatypes.delimited.DelimitedReader.java
/** * Get the next character from the input, and return it. * // w w w . j ava 2 s. co m * @param in * The input stream (it's a BufferedReader, because operations on it require * in.mark()). * @param rawText * Optional StringBuilder used to return a copy of the raw text read by this method. * @return The next character read from the input stream, or -1 if the end of input stream is * reached. * @throws IOException */ public int getChar(BufferedReader in, StringBuilder rawText) throws IOException { in.mark(1); int ch = getNonIgnoredChar(in, true); // If building up the raw text, and a character was successfully read, // append it to the raw text if (rawText != null && ch != -1) { rawText.append((char) ch); } return ch; }
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 v a 2 s . 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: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. * //from w ww. j ava 2s .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:com.mirth.connect.plugins.datatypes.delimited.DelimitedReader.java
/** * Look ahead n characters in the stream, return them, but don't consume them. * /*w ww. j a v a 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:com.mirth.connect.plugins.datatypes.delimited.DelimitedReader.java
/** * This low level reader gets the next non-ignored character from the input, and returns it. * //from ww w .j a va 2s. co m * @param in * The input stream (it's a BufferedReader, because operations on it require * in.mark()). * @param remark * Iff true, remarks the input stream after reading an ignored character. * @return The next non-ignored character read, or -1 if end of input stream. * @throws IOException */ private int getNonIgnoredChar(BufferedReader in, boolean remark) throws IOException { int ch; // If configured, gobble \r if (serializationProperties.isIgnoreCR()) { while (((char) (ch = in.read())) == '\r') { if (remark) { in.mark(1); } } } else { ch = in.read(); } return ch; }