ZippedContentCache implements ContentCache { @Override @VolumeMetered public InputStream get(ContentCacheKey key) { return ofNullable(delegate.get(key)) .map(entry -> { try { return new GZIPInputStream(entry); } catch (ZipException e) { try { entry.close(); } catch (IOException closeException) { LOGGER.debug("Unable to close stream", e); } return delegate.get(key); } catch (IOException e) { throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e); } }) .orElse(null); } ZippedContentCache(ContentCache delegate); @Override @Timed boolean has(ContentCacheKey key); @Override @VolumeMetered InputStream get(ContentCacheKey key); @Override @VolumeMetered OutputStream put(ContentCacheKey key, TimeToLive timeToLive); @Override @Timed void evict(ContentCacheKey key); @Override @Timed void evictMatch(ContentCacheKey key); @Override @Timed void move(ContentCacheKey from, ContentCacheKey to, TimeToLive toTimeToLive); @Override @Timed void clear();  }
@Test public void shouldReadNonZippedInputStream() throws IOException { final String content = "non-zipped content"; when(delegate.get(any())) .then((Answer<InputStream>) invocation -> new ByteArrayInputStream(content.getBytes())); ContentCache contentCache = new ZippedContentCache(delegate); final InputStream stream = contentCache.get(() -> StringUtils.EMPTY); verify(delegate, times(2)).get(any()); assertEquals(ByteArrayInputStream.class, stream.getClass()); assertEquals(content, IOUtils.toString(stream, "UTF-8")); }
@Test public void shouldReturnZippedInputStream() throws IOException { final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try (GZIPOutputStream sampleContent = new GZIPOutputStream(outputStream)) { sampleContent.write('a'); } when(delegate.get(any())).thenReturn(new ByteArrayInputStream(outputStream.toByteArray())); ContentCache contentCache = new ZippedContentCache(delegate); final InputStream stream = contentCache.get(() -> StringUtils.EMPTY); verify(delegate, times(1)).get(any()); assertEquals(GZIPInputStream.class, stream.getClass()); }
@Test public void shouldReturnNullInputStream() { when(delegate.get(any())).thenReturn(null); ContentCache contentCache = new ZippedContentCache(delegate); final InputStream stream = contentCache.get(() -> StringUtils.EMPTY); verify(delegate, times(1)).get(any()); assertNull(stream); }