IOHelper { public static InputStream bufferStream(InputStream in, int maxMemSize) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buffer = new byte[8192]; int bytesNum; boolean overflow = false; while ((!overflow) && (bytesNum = in.read(buffer)) != -1) { bos.write(buffer, 0, bytesNum); overflow = bos.size() > maxMemSize; } if (overflow) { File file = FileCollector.getInstance().createFile(); try (FileOutputStream fos = new FileOutputStream(file)) { bos.writeTo(fos); while ((bytesNum = in.read(buffer)) != -1) { fos.write(buffer, 0, bytesNum); } } return new DeleteOnCloseFIS(file); } return new ByteArrayInputStream(bos.toByteArray()); } private  IOHelper(); @Deprecated // Guava used instead in everrest-core, in other modules will be replaced with Guava also static String readString(InputStream in, String cs); @Deprecated // Guava used instead in everrest-core, in other modules will be replaced with Guava also static void writeString(String s, OutputStream out, String cs); static InputStream bufferStream(InputStream in, int maxMemSize);  }
@Test public void buffersGivenInputStreamInMemoryWhenLengthDoesNotExceedThreshold() throws Exception { InputStream inputStream = new ByteArrayInputStream(testContent); InputStream bufferedStream = IOHelper.bufferStream(inputStream, testContent.length + 1); assertTrue(bufferedStream instanceof ByteArrayInputStream); assertArrayEquals(testContent, ByteStreams.toByteArray(bufferedStream)); }
@Test public void buffersGivenInputStreamInMemoryWhenLengthExceedsThreshold() throws Exception { InputStream inputStream = new ByteArrayInputStream(testContent); InputStream bufferedStream = IOHelper.bufferStream(inputStream, testContent.length - 1); assertTrue(bufferedStream instanceof FileInputStream); try { assertArrayEquals(testContent, ByteStreams.toByteArray(bufferedStream)); } finally { bufferedStream.close(); } }