HeaderChunk { void readHeader(InputStream is) throws IOException { int headerRead = 0; while (headerRead < HEADER_SIZE) { final int bytesRead = is.read(header, headerRead, HEADER_SIZE - headerRead); if (bytesRead < 0) { throw new EOFException("Failed to read header."); } headerRead += bytesRead; } LOGGER.trace("Header received {} size={}", toString(), getPacketSize()); if(header[0] != MAGIC_BYTE) { throw new IOException("Bad header. expected=80, received=" + header[0]); } if(hasFlags(FLAG_CIPHER | FLAG_YAML | FLAG_LZ4 | FLAG_LZO | FLAGS_NOHEADER)) { throw new IOException("unsupported flags detected"); } } HeaderChunk(); void writeHeader(OutputStream outputStream); void setFlags(int flags); void setPacketSize(int packetSize); @Override String toString(); static final int FLAG_ZLIB; static final int FLAG_RENCODE; static final int FLAG_CIPHER; static final int FLAG_YAML; static final int FLAG_LZ4; static final int FLAG_LZO; static final int FLAGS_NOHEADER; }
@Test public void testReadHeader() throws IOException { headerChunk.readHeader(new ByteArrayInputStream(HEADER)); assertEquals(FLAGS, headerChunk.getFlags()); assertEquals(COMPRESSION_LVL, headerChunk.getCompressionLevel()); assertEquals(PACKET_INDEX, headerChunk.getPacketIndex()); assertEquals(3, headerChunk.getPacketSize()); }
@Test public void testInvalidHeader_incomplete() { try { headerChunk.readHeader(new ByteArrayInputStream(new byte[1])); fail("Incomplete header"); } catch (IOException e) { } }
@Test public void testInvalidHeader_noMagicByte() { try { headerChunk.readHeader(new ByteArrayInputStream(new byte[8])); fail("Header should start with a magic byte"); } catch (IOException e) { } }