List of usage examples for org.apache.http.client.methods CloseableHttpResponse setHeader
void setHeader(String str, String str2);
From source file:org.esigate.cache.CacheAdapter.java
public ClientExecChain wrapBackendHttpClient(final ClientExecChain wrapped) { return new ClientExecChain() { private boolean isCacheableStatus(int statusCode) { return (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY || statusCode == HttpStatus.SC_NOT_FOUND || statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR || statusCode == HttpStatus.SC_SERVICE_UNAVAILABLE || statusCode == HttpStatus.SC_NOT_MODIFIED || statusCode == HttpStatus.SC_GATEWAY_TIMEOUT); }// w w w .j a v a 2s .c om /** * Fire pre-fetch and post-fetch events Enables cache for all GET requests if cache ttl was forced to a * certain duration in the configuration. This is done even for non 200 return codes! This is a very * aggressive but efficient caching policy. Adds "stale-while-revalidate" and "stale-if-error" cache-control * directives depending on the configuration. * * @throws HttpException * @throws IOException */ @Override public CloseableHttpResponse execute(HttpRoute route, HttpRequestWrapper request, HttpClientContext httpClientContext, HttpExecutionAware execAware) throws IOException, HttpException { OutgoingRequestContext context = OutgoingRequestContext.adapt(httpClientContext); CloseableHttpResponse response = wrapped.execute(route, request, context, execAware); String method = request.getRequestLine().getMethod(); int statusCode = response.getStatusLine().getStatusCode(); // If ttl is set, force caching even for error pages if (ttl > 0 && method.equalsIgnoreCase("GET") && isCacheableStatus(statusCode)) { response.removeHeaders("Date"); response.removeHeaders("Cache-control"); response.removeHeaders("Expires"); response.setHeader("Date", DateUtils.formatDate(new Date(System.currentTimeMillis()))); response.setHeader("Cache-control", "public, max-age=" + ttl); response.setHeader("Expires", DateUtils.formatDate(new Date(System.currentTimeMillis() + ((long) ttl) * 1000))); } if (request.getRequestLine().getMethod().equalsIgnoreCase("GET")) { String cacheControlHeader = ""; if (staleWhileRevalidate > 0) { cacheControlHeader += "stale-while-revalidate=" + staleWhileRevalidate; } if (staleIfError > 0) { if (cacheControlHeader.length() > 0) { cacheControlHeader += ","; } cacheControlHeader += "stale-if-error=" + staleIfError; } if (cacheControlHeader.length() > 0) { response.addHeader("Cache-control", cacheControlHeader); } } return response; } }; }