List of usage examples for java.io PushbackInputStream PushbackInputStream
public PushbackInputStream(InputStream in, int size)
PushbackInputStream
with a pushback buffer of the specified size
, and saves its argument, the input stream in
, for later use. From source file:z.hol.net.http.entity.DeflateDecompressingEntity.java
/** * Returns the non-null InputStream that should be returned to by all requests to * {@link #getContent()}.// w w w. j a v a 2s. c om * * @return a non-null InputStream * @throws IOException if there was a problem */ @Override InputStream getDecompressingInputStream(final InputStream wrapped) throws IOException { /* * A zlib stream will have a header. * * CMF | FLG [| DICTID ] | ...compressed data | ADLER32 | * * * CMF is one byte. * * * FLG is one byte. * * * DICTID is four bytes, and only present if FLG.FDICT is set. * * Sniff the content. Does it look like a zlib stream, with a CMF, etc? c.f. RFC1950, * section 2.2. http://tools.ietf.org/html/rfc1950#page-4 * * We need to see if it looks like a proper zlib stream, or whether it is just a deflate * stream. RFC2616 calls zlib streams deflate. Confusing, isn't it? That's why some servers * implement deflate Content-Encoding using deflate streams, rather than zlib streams. * * We could start looking at the bytes, but to be honest, someone else has already read * the RFCs and implemented that for us. So we'll just use the JDK libraries and exception * handling to do this. If that proves slow, then we could potentially change this to check * the first byte - does it look like a CMF? What about the second byte - does it look like * a FLG, etc. */ /* We read a small buffer to sniff the content. */ byte[] peeked = new byte[6]; PushbackInputStream pushback = new PushbackInputStream(wrapped, peeked.length); int headerLength = pushback.read(peeked); if (headerLength == -1) { throw new IOException("Unable to read the response"); } /* We try to read the first uncompressed byte. */ byte[] dummy = new byte[1]; Inflater inf = new Inflater(); try { int n; while ((n = inf.inflate(dummy)) == 0) { if (inf.finished()) { /* Not expecting this, so fail loudly. */ throw new IOException("Unable to read the response"); } if (inf.needsDictionary()) { /* Need dictionary - then it must be zlib stream with DICTID part? */ break; } if (inf.needsInput()) { inf.setInput(peeked); } } if (n == -1) { throw new IOException("Unable to read the response"); } /* * We read something without a problem, so it's a valid zlib stream. Just need to reset * and return an unused InputStream now. */ pushback.unread(peeked, 0, headerLength); return new InflaterInputStream(pushback); } catch (DataFormatException e) { /* Presume that it's an RFC1951 deflate stream rather than RFC1950 zlib stream and try * again. */ pushback.unread(peeked, 0, headerLength); return new InflaterInputStream(pushback, new Inflater(true)); } }
From source file:de.unisb.cs.st.javaslicer.traceResult.TraceResult.java
public TraceResult(File filename) throws IOException { final MultiplexedFileReader file = new MultiplexedFileReader(filename); if (file.getStreamIds().size() < 2) throw new IOException("corrupted data"); final MultiplexInputStream readClassesStream = file.getInputStream(0); if (readClassesStream == null) throw new IOException("corrupted data"); PushbackInputStream pushBackInput = new PushbackInputStream( new BufferedInputStream(new GZIPInputStream(readClassesStream, 512), 512), 1); final DataInputStream readClassesInputStream = new DataInputStream(pushBackInput); final ArrayList<ReadClass> readClasses0 = new ArrayList<ReadClass>(); final StringCacheInput stringCache = new StringCacheInput(); int testRead; while ((testRead = pushBackInput.read()) != -1) { pushBackInput.unread(testRead);//from w ww . ja va2s . c o m readClasses0.add(ReadClass.readFrom(readClassesInputStream, stringCache)); } readClasses0.trimToSize(); Collections.sort(readClasses0); this.readClasses = readClasses0; this.instructions = getInstructionArray(readClasses0); final MultiplexInputStream threadTracersStream = file.getInputStream(1); if (threadTracersStream == null) throw new IOException("corrupted data"); pushBackInput = new PushbackInputStream( new BufferedInputStream(new GZIPInputStream(threadTracersStream, 512), 512), 1); final DataInputStream threadTracersInputStream = new DataInputStream(pushBackInput); final ArrayList<ThreadTraceResult> threadTraces0 = new ArrayList<ThreadTraceResult>(); while ((testRead = pushBackInput.read()) != -1) { pushBackInput.unread(testRead); threadTraces0.add(ThreadTraceResult.readFrom(threadTracersInputStream, this, file)); } threadTraces0.trimToSize(); Collections.sort(threadTraces0); this.threadTraces = threadTraces0; }
From source file:org.openhealthtools.openatna.syslog.protocol.ProtocolMessageFactory.java
/** * This reads up to 256 characters to read headers (excluding SDs). This limit is arbitrary. * It is imposed to reduce the risk//from w w w .j a va 2s. co m * of badly formed or malicious messages from using too many resources. * * @param in * @return * @throws SyslogException */ public SyslogMessage read(InputStream in) throws SyslogException { try { PushbackInputStream pin = new PushbackInputStream(in, 5); int priority = readPriority(pin); int facility; int severity; byte c; int spaces = 5; int count = 0; ByteBuffer buff = ByteBuffer.wrap(new byte[256]); String timestamp = null; String host = "-"; String app = "-"; String proc = "-"; String mid = "-"; int max = 256; int curr = 0; while (count < spaces && curr < max) { c = (byte) pin.read(); curr++; if (c == ' ') { count++; String currHeader = new String(buff.array(), 0, buff.position(), Constants.ENC_UTF8); buff.clear(); switch (count) { case 1: timestamp = currHeader; break; case 2: host = currHeader; break; case 3: app = currHeader; break; case 4: proc = currHeader; break; case 5: mid = currHeader; break; } } else { buff.put(c); } } if (timestamp == null) { throw new SyslogException("no timestamp defined"); } c = (byte) pin.read(); List<StructuredElement> els = new ArrayList<StructuredElement>(); if (c == '-') { c = (byte) pin.read(); if (c != ' ') { throw new SyslogException("not a space"); } } else if (c == '[') { pin.unread(c); els = StructuredElement.parse(pin); } else { throw new SyslogException("Illegal Structured data"); } LogMessage logMessage = getLogMessage(mid); String encoding = readBom(pin, logMessage.getExpectedEncoding()); logMessage.read(pin, encoding); facility = priority / 8; severity = priority % 8; ProtocolMessage sm = new ProtocolMessage(facility, severity, timestamp, host, logMessage, app, mid, proc); for (StructuredElement el : els) { sm.addStructuredElement(el); } return sm; } catch (IOException e) { e.printStackTrace(); throw new SyslogException(e); } }
From source file:com.github.lucapino.sheetmaker.renderer.GmTemplateRenderer.java
private InputStream checkForUtf8BOMAndDiscardIfAny(InputStream inputStream) throws IOException { PushbackInputStream pushbackInputStream = new PushbackInputStream(new BufferedInputStream(inputStream), 3); byte[] bom = new byte[3]; if (pushbackInputStream.read(bom) != -1) { if (!(bom[0] == (byte) 0xEF && bom[1] == (byte) 0xBB && bom[2] == (byte) 0xBF)) { pushbackInputStream.unread(bom); }/*from w w w . ja va2s . c om*/ } return pushbackInputStream; }
From source file:net.stuxcrystal.simpledev.configuration.parser.generators.xml.XMLParser.java
/** * Parse the XML-File./*from ww w. ja v a 2 s. com*/ * @param stream The stream to use. * @return The Node-Tree. * @throws IOException if an I/O-Operation fails. */ public static Node<?> parse(InputStream stream) throws IOException { // Make sure empty files are supported... stream = new PushbackInputStream(stream, 1); if (XMLParser.isEmpty((PushbackInputStream) stream)) { // The node has no content. return new MapNode(new Node[0]); } SAXParser parser; try { parser = getParser(); } catch (ParserConfigurationException | SAXException e) { throw new IOException(e.getLocalizedMessage(), e); } XMLParser raw_parser = new XMLParser(); try { parser.parse(toSource(stream), raw_parser); } catch (SAXException e) { throw new IOException(e.getLocalizedMessage(), e); } return raw_parser.base; }
From source file:UnicodeInputStream.java
/** * Creates a new UnicodeInputStream object. * //from w w w .jav a2 s . c o m * @param inputStream * The input stream to use for reading. * @param skipBOM * If this is set to true, a BOM read from the stream is discarded. * This parameter should normally be true. */ public UnicodeInputStream(final InputStream inputStream, boolean skipBOM) throws IllegalStateException, IOException { super(); this.skipBOM = skipBOM; this.inputStream = new PushbackInputStream(inputStream, MAX_BOM_SIZE); try { this.encoding = readEncoding(); } catch (IOException ioe) { IllegalStateException ex = new IllegalStateException("Could not read BOM from Stream"); // ExceptionUtils.setCause(ex, ioe); throw ex; } }
From source file:org.talend.dataprep.schema.xls.XlsSchemaParser.java
/** * Parse all xls sheets.// www .j a va 2 s . co m * * @param request the schema parser request. * @return the list of parsed xls sheet. * @throws IOException if an error occurs. */ protected List<Schema.SheetContent> parseAllSheets(Request request) throws IOException { InputStream inputStream = request.getContent(); if (!inputStream.markSupported()) { inputStream = new PushbackInputStream(inputStream, 8); } boolean newExcelFormat = XlsUtils.isNewExcelFormat(inputStream); // parse the xls input stream using the correct format if (newExcelFormat) { return parseAllSheetsStream(new Request(inputStream, request.getMetadata())); } else { return parseAllSheetsOldFormat(new Request(inputStream, request.getMetadata())); } }
From source file:us.levk.math.linear.HugeRealMatrix.java
/** * Parse a matrix from a stream//from w w w . ja va2s .com * * @param stream * @param columnDelimiters * @param rowDelimiters * @param parser * @throws IOException * @throws ParseException */ public HugeRealMatrix(InputStream stream, char[] columnDelimiters, char[] rowDelimiters, NumberFormat parser) throws IOException, ParseException { StringBuilder word = new StringBuilder(); Set<Integer> columnDelims = new HashSet<>(); Set<Integer> rowDelims = new HashSet<>(); for (char b : columnDelimiters) columnDelims.add((int) b); for (char b : rowDelimiters) rowDelims.add((int) b); String name = randomFileName(); try (RandomAccessFile file = new RandomAccessFile(name, "rw")) { int columns = 0; int rows = 0; int prevColumns = -1; PushbackInputStream in = new PushbackInputStream(stream, 1024); startMatrixParse(in, columnDelims, rowDelims); boolean newRow = true; for (int c;;) { if (newRow) { startRowParse(in, rows, columnDelims, parser); newRow = false; } c = in.read(); if (columnDelims.contains(c) || rowDelims.contains(c) || c < 0) { try { double value = parser.parse(word.toString().trim()).doubleValue(); file.writeDouble(value); } catch (ParseException e) { if (columns == 0) break; else throw e; } columns++; word = new StringBuilder(); if (rowDelims.contains(c) || c < 0) { rows++; if (columns != prevColumns && prevColumns >= 0) throw new IOException("Jagged row detected, previous row " + prevColumns + " columns, current row " + columns + " columns"); prevColumns = columns; columns = 0; if (c < 0) break; else newRow = true; } } else word.append((char) c); } endMatrixParse(in, prevColumns, rows); this.name = name; this.file = file; this.columnDimension = prevColumns; this.rowDimension = rows; long size = 8L * rowDimension * columnDimension; for (long offset = 0; offset < size; offset += MAPPING_SIZE) mappings.add(file.getChannel().map(READ_WRITE, offset, min(size - offset, MAPPING_SIZE))); } catch (IOException | ParseException | RuntimeException | Error e) { new File(name).delete(); throw e; } }
From source file:org.mcxiaoke.commons.http.impl.DeflateDecompressingEntity.java
/** * Returns the non-null InputStream that should be returned to by all * requests to {@link #getContent()}./* w ww . ja v a 2 s. c o m*/ * * @return a non-null InputStream * @throws IOException * if there was a problem */ @Override InputStream getDecompressingInputStream(final InputStream wrapped) throws IOException { /* * A zlib stream will have a header. * * CMF | FLG [| DICTID ] | ...compressed data | ADLER32 | * * * CMF is one byte. * * * FLG is one byte. * * * DICTID is four bytes, and only present if FLG.FDICT is set. * * Sniff the content. Does it look like a zlib stream, with a CMF, etc? * c.f. RFC1950, section 2.2. http://tools.ietf.org/html/rfc1950#page-4 * * We need to see if it looks like a proper zlib stream, or whether it * is just a deflate stream. RFC2616 calls zlib streams deflate. * Confusing, isn't it? That's why some servers implement deflate * Content-Encoding using deflate streams, rather than zlib streams. * * We could start looking at the bytes, but to be honest, someone else * has already read the RFCs and implemented that for us. So we'll just * use the JDK libraries and exception handling to do this. If that * proves slow, then we could potentially change this to check the first * byte - does it look like a CMF? What about the second byte - does it * look like a FLG, etc. */ /* We read a small buffer to sniff the content. */ byte[] peeked = new byte[6]; PushbackInputStream pushback = new PushbackInputStream(wrapped, peeked.length); int headerLength = pushback.read(peeked); if (headerLength == -1) { throw new IOException("Unable to read the response"); } /* We try to read the first uncompressed byte. */ byte[] dummy = new byte[1]; Inflater inf = new Inflater(); try { int n; while ((n = inf.inflate(dummy)) == 0) { if (inf.finished()) { /* Not expecting this, so fail loudly. */ throw new IOException("Unable to read the response"); } if (inf.needsDictionary()) { /* * Need dictionary - then it must be zlib stream with DICTID * part? */ break; } if (inf.needsInput()) { inf.setInput(peeked); } } if (n == -1) { throw new IOException("Unable to read the response"); } /* * We read something without a problem, so it's a valid zlib stream. * Just need to reset and return an unused InputStream now. */ pushback.unread(peeked, 0, headerLength); return new InflaterInputStream(pushback); } catch (DataFormatException e) { /* * Presume that it's an RFC1951 deflate stream rather than RFC1950 * zlib stream and try again. */ pushback.unread(peeked, 0, headerLength); return new InflaterInputStream(pushback, new Inflater(true)); } }
From source file:com.fanfou.app.opensource.http.support.DeflateDecompressingEntity.java
/** * Returns the non-null InputStream that should be returned to by all * requests to {@link #getContent()}./*from w w w .ja va 2 s .c o m*/ * * @return a non-null InputStream * @throws IOException * if there was a problem */ @Override InputStream getDecompressingInputStream(final InputStream wrapped) throws IOException { /* * A zlib stream will have a header. * * CMF | FLG [| DICTID ] | ...compressed data | ADLER32 | * * * CMF is one byte. * * * FLG is one byte. * * * DICTID is four bytes, and only present if FLG.FDICT is set. * * Sniff the content. Does it look like a zlib stream, with a CMF, etc? * c.f. RFC1950, section 2.2. http://tools.ietf.org/html/rfc1950#page-4 * * We need to see if it looks like a proper zlib stream, or whether it * is just a deflate stream. RFC2616 calls zlib streams deflate. * Confusing, isn't it? That's why some servers implement deflate * Content-Encoding using deflate streams, rather than zlib streams. * * We could start looking at the bytes, but to be honest, someone else * has already read the RFCs and implemented that for us. So we'll just * use the JDK libraries and exception handling to do this. If that * proves slow, then we could potentially change this to check the first * byte - does it look like a CMF? What about the second byte - does it * look like a FLG, etc. */ /* We read a small buffer to sniff the content. */ final byte[] peeked = new byte[6]; final PushbackInputStream pushback = new PushbackInputStream(wrapped, peeked.length); final int headerLength = pushback.read(peeked); if (headerLength == -1) { throw new IOException("Unable to read the response"); } /* We try to read the first uncompressed byte. */ final byte[] dummy = new byte[1]; final Inflater inf = new Inflater(); try { int n; while ((n = inf.inflate(dummy)) == 0) { if (inf.finished()) { /* Not expecting this, so fail loudly. */ throw new IOException("Unable to read the response"); } if (inf.needsDictionary()) { /* * Need dictionary - then it must be zlib stream with DICTID * part? */ break; } if (inf.needsInput()) { inf.setInput(peeked); } } if (n == -1) { throw new IOException("Unable to read the response"); } /* * We read something without a problem, so it's a valid zlib stream. * Just need to reset and return an unused InputStream now. */ pushback.unread(peeked, 0, headerLength); return new InflaterInputStream(pushback); } catch (final DataFormatException e) { /* * Presume that it's an RFC1951 deflate stream rather than RFC1950 * zlib stream and try again. */ pushback.unread(peeked, 0, headerLength); return new InflaterInputStream(pushback, new Inflater(true)); } }