List of usage examples for java.io ByteArrayInputStream mark
int mark
To view the source code for java.io ByteArrayInputStream mark.
Click Source Link
From source file:Main.java
public static void main(String[] args) throws IOException { byte[] buf = { 65, 66, 67, 68, 69 }; // create new byte array input stream ByteArrayInputStream bais = new ByteArrayInputStream(buf); // print bytes System.out.println(bais.read()); System.out.println(bais.read()); System.out.println(bais.read()); System.out.println("Mark() invocation"); // mark() invocation; bais.mark(0); System.out.println(bais.read()); System.out.println(bais.read()); System.out.println("Reset() invocation"); // reset() invocation bais.reset();/* ww w .j ava2s . co m*/ System.out.println(bais.read()); System.out.println(bais.read()); }
From source file:Main.java
public static void main(String[] args) throws IOException { byte[] buf = { 65, 66, 67, 68, 69 }; // create new byte array input stream ByteArrayInputStream bais = new ByteArrayInputStream(buf); // test support for mark() and reset() methods invocation boolean isMarkSupported = bais.markSupported(); System.out.println("Is mark supported : " + isMarkSupported); System.out.println("Following is the proof:"); // print bytes System.out.println(bais.read()); System.out.println(bais.read()); System.out.println(bais.read()); System.out.println("Mark() invocation"); // mark() invocation; bais.mark(0); System.out.println(bais.read()); System.out.println(bais.read()); System.out.println("Reset() invocation"); // reset() invocation bais.reset();//from w ww . j a v a 2 s .co m System.out.println(bais.read()); System.out.println(bais.read()); }
From source file:Main.java
protected static byte[] parseWapTextString(ByteArrayInputStream bais) { assert (null != bais); bais.mark(1); int temp = bais.read(); assert (-1 != temp); if (temp == QUOTE) { bais.mark(1);/*from w ww .ja va 2 s. co m*/ } return getWapTextString(bais); }
From source file:at.jku.rdfstats.hist.builder.HistogramCodec.java
public static String readString(ByteArrayInputStream stream) { try {//from ww w . ja v a 2s . co m int next; String s; StringBuilder sb = new StringBuilder(); stream.mark(0); InputStreamReader in = new InputStreamReader(stream); while (true) { next = in.read(); if (next < 0 || (char) next == END_OF_STRING) { s = sb.toString(); break; } else if ((char) next == EMPTY_STRING) { s = ""; break; } else sb.append((char) next); } stream.reset(); stream.skip(s.length() + 1); return s; } catch (IOException e) { throw new RuntimeException("Unexpected error: cannot read String from ByteArrayOutputStream.", e); } }
From source file:com.github.devnied.emvnfccard.utils.TlvUtil.java
public static String prettyPrintAPDUResponse(final byte[] data, final int indentLength) { StringBuilder buf = new StringBuilder(); ByteArrayInputStream stream = new ByteArrayInputStream(data); while (stream.available() > 0) { buf.append("\n"); if (stream.available() == 2) { stream.mark(0); byte[] value = new byte[2]; try { stream.read(value);//from w ww.j a va 2 s . c o m } catch (IOException e) { } SwEnum sw = SwEnum.getSW(value); if (sw != null) { buf.append(getSpaces(0)); buf.append(BytesUtils.bytesToString(value)).append(" -- "); buf.append(sw.getDetail()); continue; } stream.reset(); } buf.append(getSpaces(indentLength)); TLV tlv = TlvUtil.getNextTLV(stream); byte[] tagBytes = tlv.getTagBytes(); byte[] lengthBytes = tlv.getRawEncodedLengthBytes(); byte[] valueBytes = tlv.getValueBytes(); ITag tag = tlv.getTag(); buf.append(prettyPrintHex(tagBytes)); buf.append(" "); buf.append(prettyPrintHex(lengthBytes)); buf.append(" -- "); buf.append(tag.getName()); int extraIndent = (lengthBytes.length + tagBytes.length) * 3; if (tag.isConstructed()) { // indentLength += extraIndent; //TODO check this // Recursion buf.append(prettyPrintAPDUResponse(valueBytes, indentLength + extraIndent)); } else { buf.append("\n"); if (tag.getTagValueType() == TagValueTypeEnum.DOL) { buf.append(TlvUtil.getFormattedTagAndLength(valueBytes, indentLength + extraIndent)); } else { buf.append(getSpaces(indentLength + extraIndent)); buf.append(prettyPrintHex(BytesUtils.bytesToStringNoSpace(valueBytes), indentLength + extraIndent)); buf.append(" ("); buf.append(TlvUtil.getTagValueAsString(tag, valueBytes)); buf.append(")"); } } } return buf.toString(); }
From source file:com.github.devnied.emvnfccard.utils.TlvUtil.java
public static TLV getNextTLV(final ByteArrayInputStream stream) { if (stream.available() < 2) { throw new TlvException("Error parsing data. Available bytes < 2 . Length=" + stream.available()); }//w w w .jav a 2s . c om // ISO/IEC 7816 uses neither '00' nor 'FF' as tag value. // Before, between, or after TLV-coded data objects, // '00' or 'FF' bytes without any meaning may occur // (for example, due to erased or modified TLV-coded data objects). stream.mark(0); int peekInt = stream.read(); byte peekByte = (byte) peekInt; // peekInt == 0xffffffff indicates EOS while (peekInt != -1 && (peekByte == (byte) 0xFF || peekByte == (byte) 0x00)) { stream.mark(0); // Current position peekInt = stream.read(); peekByte = (byte) peekInt; } stream.reset(); // Reset back to the last known position without 0x00 or 0xFF if (stream.available() < 2) { throw new TlvException("Error parsing data. Available bytes < 2 . Length=" + stream.available()); } byte[] tagIdBytes = TlvUtil.readTagIdBytes(stream); // We need to get the raw length bytes. // Use quick and dirty workaround stream.mark(0); int posBefore = stream.available(); // Now parse the lengthbyte(s) // This method will read all length bytes. We can then find out how many bytes was read. int length = TlvUtil.readTagLength(stream); // Decoded // Now find the raw (encoded) length bytes int posAfter = stream.available(); stream.reset(); byte[] lengthBytes = new byte[posBefore - posAfter]; if (lengthBytes.length < 1 || lengthBytes.length > 4) { throw new TlvException("Number of length bytes must be from 1 to 4. Found " + lengthBytes.length); } stream.read(lengthBytes, 0, lengthBytes.length); int rawLength = BytesUtils.byteArrayToInt(lengthBytes); byte[] valueBytes; ITag tag = searchTagById(tagIdBytes); // Find VALUE bytes if (rawLength == 128) { // 1000 0000 // indefinite form stream.mark(0); int prevOctet = 1; int curOctet; int len = 0; while (true) { len++; curOctet = stream.read(); if (curOctet < 0) { throw new TlvException( "Error parsing data. TLV " + "length byte indicated indefinite length, but EOS " + "was reached before 0x0000 was found" + stream.available()); } if (prevOctet == 0 && curOctet == 0) { break; } prevOctet = curOctet; } len -= 2; valueBytes = new byte[len]; stream.reset(); stream.read(valueBytes, 0, len); length = len; } else { if (stream.available() < length) { throw new TlvException("Length byte(s) indicated " + length + " value bytes, but only " + stream.available() + " " + (stream.available() > 1 ? "are" : "is") + " available"); } // definite form valueBytes = new byte[length]; stream.read(valueBytes, 0, length); } // Remove any trailing 0x00 and 0xFF stream.mark(0); peekInt = stream.read(); peekByte = (byte) peekInt; while (peekInt != -1 && (peekByte == (byte) 0xFF || peekByte == (byte) 0x00)) { stream.mark(0); peekInt = stream.read(); peekByte = (byte) peekInt; } stream.reset(); // Reset back to the last known position without 0x00 or 0xFF return new TLV(tag, length, lengthBytes, valueBytes); }
From source file:com.cyberway.issue.io.arc.ARCRecord.java
/** * Read http header if present. Technique borrowed from HttpClient HttpParse * class.//from w w w . ja v a2s .co m * * @return ByteArrayInputStream with the http header in it or null if no * http header. * @throws IOException */ private InputStream readHttpHeader() throws IOException { // If judged a record that doesn't have an http header, return // immediately. if (!getHeader().getUrl().startsWith("http") || getHeader().getLength() <= MIN_HTTP_HEADER_LENGTH) { return null; } byte[] statusBytes = HttpParser.readRawLine(getIn()); int eolCharCount = getEolCharsCount(statusBytes); if (eolCharCount <= 0) { throw new IOException("Failed to read http status where one was expected: " + ((statusBytes == null) ? "" : new String(statusBytes))); } String statusLine = EncodingUtil.getString(statusBytes, 0, statusBytes.length - eolCharCount, ARCConstants.DEFAULT_ENCODING); if ((statusLine == null) || !StatusLine.startsWithHTTP(statusLine)) { if (statusLine.startsWith("DELETED")) { // Some old ARCs have deleted records like following: // http://vireo.gatech.edu:80/ebt-bin/nph-dweb/dynaweb/SGI_Developer/SGITCL_PG/@Generic__BookTocView/11108%3Btd%3D2 130.207.168.42 19991010131803 text/html 29202 // DELETED_TIME=20000425001133_DELETER=Kurt_REASON=alexalist // (follows ~29K spaces) // For now, throw a RecoverableIOException so if iterating over // records, we keep going. TODO: Later make a legitimate // ARCRecord from the deleted record rather than throw // exception. throw new DeletedARCRecordIOException(statusLine); } else { throw new IOException("Failed parse of http status line."); } } this.httpStatus = new StatusLine(statusLine); // Save off all bytes read. Keep them as bytes rather than // convert to strings so we don't have to worry about encodings // though this should never be a problem doing http headers since // its all supposed to be ascii. ByteArrayOutputStream baos = new ByteArrayOutputStream(statusBytes.length + 4 * 1024); baos.write(statusBytes); // Now read rest of the header lines looking for the separation // between header and body. for (byte[] lineBytes = null; true;) { lineBytes = HttpParser.readRawLine(getIn()); eolCharCount = getEolCharsCount(lineBytes); if (eolCharCount <= 0) { throw new IOException( "Failed reading http headers: " + ((lineBytes != null) ? new String(lineBytes) : null)); } // Save the bytes read. baos.write(lineBytes); if ((lineBytes.length - eolCharCount) <= 0) { // We've finished reading the http header. break; } } byte[] headerBytes = baos.toByteArray(); // Save off where body starts. this.getMetaData().setContentBegin(headerBytes.length); ByteArrayInputStream bais = new ByteArrayInputStream(headerBytes); if (!bais.markSupported()) { throw new IOException("ByteArrayInputStream does not support mark"); } bais.mark(headerBytes.length); // Read the status line. Don't let it into the parseHeaders function. // It doesn't know what to do with it. bais.read(statusBytes, 0, statusBytes.length); this.httpHeaders = HttpParser.parseHeaders(bais, ARCConstants.DEFAULT_ENCODING); this.getMetaData().setStatusCode(Integer.toString(getStatusCode())); bais.reset(); return bais; }
From source file:org.alfresco.encoding.BomCharactersetFinder.java
/** * Just searches the Byte Order Marker, i.e. the first three characters for a sign of * the encoding./*w w w.ja v a2s .c o m*/ */ protected Charset detectCharsetImpl(byte[] buffer) throws Exception { Charset charset = null; ByteArrayInputStream bis = null; try { bis = new ByteArrayInputStream(buffer); bis.mark(3); char[] byteHeader = new char[3]; InputStreamReader in = new InputStreamReader(bis); int bytesRead = in.read(byteHeader); bis.reset(); if (bytesRead < 2) { // ASCII charset = Charset.forName("Cp1252"); } else if (byteHeader[0] == 0xFE && byteHeader[1] == 0xFF) { // UCS-2 Big Endian charset = Charset.forName("UTF-16BE"); } else if (byteHeader[0] == 0xFF && byteHeader[1] == 0xFE) { // UCS-2 Little Endian charset = Charset.forName("UTF-16LE"); } else if (bytesRead >= 3 && byteHeader[0] == 0xEF && byteHeader[1] == 0xBB && byteHeader[2] == 0xBF) { // UTF-8 charset = Charset.forName("UTF-8"); } else { // No idea charset = null; } // Done return charset; } finally { if (bis != null) { try { bis.close(); } catch (Throwable e) { } } } }
From source file:org.apache.hadoop.io.TestIOUtils.java
@Test public void testSkipFully() throws IOException { byte inArray[] = new byte[] { 0, 1, 2, 3, 4 }; ByteArrayInputStream in = new ByteArrayInputStream(inArray); try {//from w ww . java2 s. c o m in.mark(inArray.length); IOUtils.skipFully(in, 2); IOUtils.skipFully(in, 2); try { IOUtils.skipFully(in, 2); fail("expected to get a PrematureEOFException"); } catch (EOFException e) { assertEquals("Premature EOF from inputStream " + "after skipping 1 byte(s).", e.getMessage()); } in.reset(); try { IOUtils.skipFully(in, 20); fail("expected to get a PrematureEOFException"); } catch (EOFException e) { assertEquals("Premature EOF from inputStream " + "after skipping 5 byte(s).", e.getMessage()); } in.reset(); IOUtils.skipFully(in, 5); try { IOUtils.skipFully(in, 10); fail("expected to get a PrematureEOFException"); } catch (EOFException e) { assertEquals("Premature EOF from inputStream " + "after skipping 0 byte(s).", e.getMessage()); } } finally { in.close(); } }
From source file:org.archive.io.arc.ARCRecord.java
/** * Read http header if present. Technique borrowed from HttpClient HttpParse * class. set errors when found./*from w ww.ja v a2 s.co m*/ * * @return ByteArrayInputStream with the http header in it or null if no * http header. * @throws IOException */ private InputStream readHttpHeader() throws IOException { // this can be helpful when simply iterating over records, // looking for problems. Logger logger = Logger.getLogger(this.getClass().getName()); ArchiveRecordHeader h = this.getHeader(); // If judged a record that doesn't have an http header, return // immediately. String url = getHeader().getUrl(); if (!url.startsWith("http") || getHeader().getLength() <= MIN_HTTP_HEADER_LENGTH) { return null; } String statusLine; byte[] statusBytes; int eolCharCount = 0; int errOffset = 0; // Read status line, skipping any errant http headers found before it // This allows a larger number of 'corrupt' arcs -- where headers were accidentally // inserted before the status line to be readable while (true) { statusBytes = LaxHttpParser.readRawLine(getIn()); eolCharCount = getEolCharsCount(statusBytes); if (eolCharCount <= 0) { throw new RecoverableIOException("Failed to read http status where one was expected: " + ((statusBytes == null) ? "" : new String(statusBytes))); } statusLine = EncodingUtil.getString(statusBytes, 0, statusBytes.length - eolCharCount, ARCConstants.DEFAULT_ENCODING); // If a null or DELETED break immediately if ((statusLine == null) || statusLine.startsWith("DELETED")) { break; } // If it's actually the status line, break, otherwise continue skipping any // previous header values if (!statusLine.contains(":") && StatusLine.startsWithHTTP(statusLine)) { break; } // Add bytes read to error "offset" to add to position errOffset += statusBytes.length; } if (errOffset > 0) { this.incrementPosition(errOffset); } if ((statusLine == null) || !StatusLine.startsWithHTTP(statusLine)) { if (statusLine.startsWith("DELETED")) { // Some old ARCs have deleted records like following: // http://vireo.gatech.edu:80/ebt-bin/nph-dweb/dynaweb/SGI_Developer/SGITCL_PG/@Generic__BookTocView/11108%3Btd%3D2 130.207.168.42 19991010131803 text/html 29202 // DELETED_TIME=20000425001133_DELETER=Kurt_REASON=alexalist // (follows ~29K spaces) // For now, throw a RecoverableIOException so if iterating over // records, we keep going. TODO: Later make a legitimate // ARCRecord from the deleted record rather than throw // exception. throw new DeletedARCRecordIOException(statusLine); } else { this.errors.add(ArcRecordErrors.HTTP_STATUS_LINE_INVALID); } } try { this.httpStatus = new StatusLine(statusLine); } catch (IOException e) { logger.warning(e.getMessage() + " at offset: " + h.getOffset()); this.errors.add(ArcRecordErrors.HTTP_STATUS_LINE_EXCEPTION); } // Save off all bytes read. Keep them as bytes rather than // convert to strings so we don't have to worry about encodings // though this should never be a problem doing http headers since // its all supposed to be ascii. ByteArrayOutputStream baos = new ByteArrayOutputStream(statusBytes.length + 4 * 1024); baos.write(statusBytes); // Now read rest of the header lines looking for the separation // between header and body. for (byte[] lineBytes = null; true;) { lineBytes = LaxHttpParser.readRawLine(getIn()); eolCharCount = getEolCharsCount(lineBytes); if (eolCharCount <= 0) { if (getIn().available() == 0) { httpHeaderBytesRead += statusBytes.length; logger.warning("HTTP header truncated at offset: " + h.getOffset()); this.errors.add(ArcRecordErrors.HTTP_HEADER_TRUNCATED); this.setEor(true); break; } else { throw new IOException( "Failed reading http headers: " + ((lineBytes != null) ? new String(lineBytes) : null)); } } else { httpHeaderBytesRead += lineBytes.length; } // Save the bytes read. baos.write(lineBytes); if ((lineBytes.length - eolCharCount) <= 0) { // We've finished reading the http header. break; } } byte[] headerBytes = baos.toByteArray(); // Save off where body starts. this.getMetaData().setContentBegin(headerBytes.length); ByteArrayInputStream bais = new ByteArrayInputStream(headerBytes); if (!bais.markSupported()) { throw new IOException("ByteArrayInputStream does not support mark"); } bais.mark(headerBytes.length); // Read the status line. Don't let it into the parseHeaders function. // It doesn't know what to do with it. bais.read(statusBytes, 0, statusBytes.length); this.httpHeaders = LaxHttpParser.parseHeaders(bais, ARCConstants.DEFAULT_ENCODING); this.getMetaData().setStatusCode(Integer.toString(getStatusCode())); bais.reset(); return bais; }