private void copy(final ByteArrayOutputStream baos, final InputStream is) throws IOException { final NullOutputStream looseIt = new NullOutputStream(); long byteSize = 0; final byte[] buffer = new byte[2048]; int length; while ((length = is.read(buffer)) != -1) { byteSize += length; if (isTooLarge(byteSize)) { baos.close(); // we need to consume the rest of the payload in order to reply. looseIt.write(buffer, 0, length); } else { baos.write(buffer, 0, length); } } if (isTooLarge(byteSize)) { LOGGER.info(ProxyCodes.PAYLOAD_TOO_LARGE, "Aborting payload read: {0} - Cached request cannot exceed: {1}MB - Was: {2}MB", getIn().getRequestUri(), SizeUnit.BYTES.toMegabytes(MAX_FILE_UPLOAD_SIZE), SizeUnit.BYTES.toMegabytes(byteSize)); throw new PayloadTooLargeException("Aborting payload read. Cached request cannot exceed: " + SizeUnit.BYTES.toMegabytes(MAX_FILE_UPLOAD_SIZE) + "MB"); } }