GatheringByteArrayInputStream extends InputStream { @Override public synchronized int read(byte[] buffer) { return read(buffer, 0, buffer.length); } GatheringByteArrayInputStream(List<byte[]> buffers, long totalBytes); @Override synchronized int read(byte[] buffer); @Override synchronized int read(); @Override synchronized long skip(long n); @Override synchronized int read(byte[] buffer, int offset, int length); @Override void close();  }
@Test public void testNormal() { byte[] lastStringArray = "client".getBytes(UTF_8); byte[] lastArray = Arrays.copyOf(lastStringArray, lastStringArray.length + 32); arraycopy(lastStringArray, 0, lastArray, 0, lastStringArray.length); List<byte[]> buffers = ImmutableList.of( "hello ".getBytes(UTF_8), "this ".getBytes(UTF_8), "is ".getBytes(UTF_8), "http ".getBytes(UTF_8), lastArray); byte[] expectedAll = "hello this is http client".getBytes(); byte[] expectedPartial = "hello this".getBytes(); try (GatheringByteArrayInputStream in = new GatheringByteArrayInputStream(buffers, expectedAll.length)) { byte[] buffer = new byte[expectedAll.length + 32]; assertEquals(in.read(buffer, 0, expectedPartial.length), expectedPartial.length); assertByteArrayEquals(buffer, 0, expectedPartial, 0, expectedPartial.length); assertEquals(in.read(buffer, expectedPartial.length, buffer.length - expectedPartial.length), expectedAll.length - expectedPartial.length); assertByteArrayEquals(buffer, 0, expectedAll, 0, expectedAll.length); assertEquals(-1, in.read(buffer, 0, expectedAll.length)); } }
@Test public void testSingleByteRead() { byte[] expected = "This is a test for single byte read".getBytes(UTF_8); List<byte[]> buffers = ImmutableList.of( "This ".getBytes(UTF_8), "is ".getBytes(UTF_8), "a test ".getBytes(UTF_8), "for".getBytes(UTF_8), " single byte read".getBytes(UTF_8)); byte[] resultBuffer = new byte[expected.length]; try (GatheringByteArrayInputStream in = new GatheringByteArrayInputStream(buffers, expected.length)) { for (int i = 0; i < expected.length; i++) { resultBuffer[i] = (byte) in.read(); } assertByteArrayEquals(resultBuffer, 0, expected, 0, expected.length); assertEquals(in.read(), -1); } }
@Test public void testNegativeSingleByteRead() { byte[] expected = new byte[1]; expected[0] = -100; try (GatheringByteArrayInputStream in = new GatheringByteArrayInputStream(ImmutableList.of(expected), expected.length)) { assertEquals(in.read(), expected[0] & 0x000000ff); assertEquals(in.read(), -1); } }