@Test public void testSetByteCount() throws Exception { final AtomicBoolean reached = new AtomicBoolean(false); final ThresholdingOutputStream tos = new ThresholdingOutputStream(3) { { setByteCount(2); } @Override protected OutputStream getStream() throws IOException { return new ByteArrayOutputStream(4); } @Override protected void thresholdReached() throws IOException { reached.set( true); } }; tos.write(12); assertFalse( reached.get()); tos.write(12); assertTrue(reached.get()); tos.close(); } }
@Override public void write(byte[] b, int off, int len) throws IOException { int remaining = this.getThreshold() - (int)this.getByteCount(); if (!isThresholdExceeded() && len > remaining) { super.write(b, off, remaining); super.write(b, off + remaining, len - remaining); } else { super.write(b, off, len); } } }
@Test public void testTresholdCanBeSpecifiedForTimeConsumingResources() throws Exception { // GIVEN when(request.getAttribute(CacheResponseWrapper.ATTRIBUTE_IN_MEMORY_THRESHOLD)).thenReturn(20); CacheResponseWrapper responseWrapper = new CacheResponseWrapper(response, 10, false); ThresholdingOutputStream out = responseWrapper.getThresholdingOutputStream(); // WHEN out.write("1234567890".getBytes()); //10 bytes to the default threshold // THEN assertThat(out.isThresholdExceeded(), equalTo(false)); // WHEN out.write('c'); //one byte beyond the default threshold // THEN assertThat(out.isThresholdExceeded(), equalTo(false)); // WHEN out.write("123456789".getBytes()); //another 9 bytes to the threshold * 2 // THEN assertThat(out.isThresholdExceeded(), equalTo(false)); // WHEN out.write('c'); //one byte beyond the threshold * 2 // THEN assertThat(out.isThresholdExceeded(), equalTo(true)); }