MemoryLimitsAwareOutputStream extends ByteArrayOutputStream { @Override public synchronized void write(byte[] b, int off, int len) { if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) - b.length > 0)) { throw new IndexOutOfBoundsException(); } int minCapacity = count + len; if (minCapacity < 0) { throw new MemoryLimitsAwareException(PdfException.DuringDecompressionSingleStreamOccupiedMoreThanMaxIntegerValue); } if (minCapacity > maxStreamSize) { throw new MemoryLimitsAwareException(PdfException.DuringDecompressionSingleStreamOccupiedMoreMemoryThanAllowed); } int oldCapacity = buf.length; int newCapacity = oldCapacity << 1; if (newCapacity < 0 || newCapacity - minCapacity < 0) { newCapacity = minCapacity; } if (newCapacity - maxStreamSize > 0) { newCapacity = maxStreamSize; buf = Arrays.copyOf(buf, newCapacity); } super.write(b, off, len); } MemoryLimitsAwareOutputStream();  MemoryLimitsAwareOutputStream(int size); long getMaxStreamSize(); MemoryLimitsAwareOutputStream setMaxStreamSize(int maxStreamSize); @Override synchronized void write(byte[] b, int off, int len);  }
@Test public void testIncorrectLength() { junitExpectedException.expect(IndexOutOfBoundsException.class); MemoryLimitsAwareOutputStream stream = new MemoryLimitsAwareOutputStream(); stream.write(new byte[1],0, -1); }