@URLPattern("**")
@Priority(CACHE_PRIORITY)
public Object cache() {
try {
ThreadContext.getDependencyMap().beginTransaction(true);
ThreadContext c = ThreadContext.get();
HttpServletRequest request = c.getServletRequest();
HttpServletResponse response = c.getServletResponse();
Cache cache = ThreadContext.getCache();
String cacheURL = c.getRequestURL();
Response cachedResponse = cache.get(cacheURL);
if (cachedResponse == null) {
String augmentationString = "<|>"
+ WebApp.get().getWebSite()
.getCacheAugmentationString();
cacheURL = c.getRequestURL() + augmentationString;
cachedResponse = cache.get(cacheURL);
}
if (cachedResponse != null) {
String cacheControl = request.getHeader("cache-control");
long if_modified_since = -1;
try {
if_modified_since = request
.getDateHeader("If-Modified-Since");
} catch (IllegalArgumentException e) {
log.info("Client sent invalid If-Modified-Since");
}
try {
String if_none_match = request.getHeader("If-None-Match");
long lastModified = (cachedResponse.getLastModified() / 1000) * 1000;
long ifModifiedSince = (if_modified_since / 1000) * 1000;
if (if_none_match == null && if_modified_since == -1
&& cacheControl != null
&& cacheControl.equals("max-age=0")) {
log.info("Client refreshed the page. Removing the old one from the cache");
cache.remove(cacheURL);
} else {
if ((if_none_match != null && if_none_match.equals("\""
+ cachedResponse.getETag() + "\""))
|| (if_none_match == null
&& if_modified_since != -1 && lastModified <= ifModifiedSince)) {
response.setStatus(304);
response.flushBuffer();
log.info("Client cache valid");
return null;
}
log.info("Response in server cache");
ThreadContext.get().setResponse(cachedResponse);
return cachedResponse.getObject();
}
} catch (IOException e) {
log.info("IOException in serverCache", e);
if (response.isCommitted()) {
return null;
}
}
}
Object result = next();
if (result instanceof XML || result instanceof String) {
Response currentResponse = ThreadContext.get().getResponse();
currentResponse.setResult(result);
// This may also remove pages from the cache
boolean shouldCache = ThreadContext.getDependencyMap().mergeTransaction();
if (shouldCache && currentResponse.getStatus() == HttpServletResponse.SC_OK) {
String url = c.getRequestURL();
url = getCacheAugmentedString(url);
Response newResponseForCache = new Response(currentResponse);
newResponseForCache.setResult(currentResponse.getResult());
ThreadContext.getCache().put(url, newResponseForCache);
}