ByteAccumulator { public void copyChunk(byte[] buf, int offset, int length) { if (this.length + length > maxSize) { String err = String.format("Resulting message size [%,d] is too large for configured max of [%,d]", this.length + length, maxSize); throw new MessageTooLargeException(err); } byte[] copy = new byte[length - offset]; System.arraycopy(buf, offset, copy, 0, length); chunks.add(copy); this.length += length; } ByteAccumulator(int maxOverallBufferSize); void copyChunk(byte[] buf, int offset, int length); int getLength(); void transferTo(ByteBuffer buffer);  }
@Test public void testCopyChunkNotEnoughSpace() { byte[] hello = "Hello".getBytes(UTF_8); byte[] space = " ".getBytes(UTF_8); byte[] world = "World".getBytes(UTF_8); int length = hello.length + space.length + world.length; ByteAccumulator accumulator = new ByteAccumulator(length - 2); accumulator.copyChunk(hello, 0, hello.length); accumulator.copyChunk(space, 0, space.length); MessageTooLargeException e = assertThrows(MessageTooLargeException.class, () -> accumulator.copyChunk(world, 0, world.length)); System.out.println(e.getMessage()); assertTrue(e.getMessage().contains("too large for configured max")); }