private Map<String, ByteArrayOutputStream> temp = new HashMap<>();
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
ContentResponse cachedResponse = cache.get(request.getRequestURI());
if (cachedResponse != null)
{
response.setStatus(cachedResponse.getStatus());
// Should copy headers too, but keep it simple
response.addHeader(cacheHeader, "true");
response.getOutputStream().write(cachedResponse.getContent());
}
else
{
super.service(request, response);
}
}
@Override
protected void onResponseContent(HttpServletRequest request, HttpServletResponse response, Response proxyResponse, byte[] buffer, int offset, int length, Callback callback)
{
// Accumulate the response content
ByteArrayOutputStream baos = temp.get(request.getRequestURI());
if (baos == null)
{
baos = new ByteArrayOutputStream();
temp.put(request.getRequestURI(), baos);
}
baos.write(buffer, offset, length);
super.onResponseContent(request, response, proxyResponse, buffer, offset, length, callback);
}
@Override
protected void onResponseSuccess(HttpServletRequest request, HttpServletResponse response, Response proxyResponse)
{
byte[] content = temp.remove(request.getRequestURI()).toByteArray();
ContentResponse cached = new HttpContentResponse(proxyResponse, content, null, null);
cache.put(request.getRequestURI(), cached);
super.onResponseSuccess(request, response, proxyResponse);
}
};
prepareProxy();
// First request
ContentResponse response = client.newRequest("localhost", serverConnector.getLocalPort())
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(200, response.getStatus());
Assert.assertTrue(response.getHeaders().containsKey(PROXIED_HEADER));
Assert.assertArrayEquals(content, response.getContent());
// Second request should be cached
response = client.newRequest("localhost", serverConnector.getLocalPort())
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(200, response.getStatus());
Assert.assertTrue(response.getHeaders().containsKey(cacheHeader));
Assert.assertArrayEquals(content, response.getContent());
}