01: package com.icesoft.faces.webapp.http.common.standard;
02:
03: import com.icesoft.faces.webapp.http.common.Request;
04: import com.icesoft.faces.webapp.http.common.RequestProxy;
05: import com.icesoft.faces.webapp.http.common.Response;
06: import com.icesoft.faces.webapp.http.common.ResponseHandler;
07: import com.icesoft.faces.webapp.http.common.Server;
08:
09: import java.util.Collection;
10: import java.util.Date;
11: import java.util.HashSet;
12:
13: public class CacheControlledServer implements Server {
14: private static final Date ExpirationDate = new Date(System
15: .currentTimeMillis() + 2629743830l);
16: private static final Collection cache = new HashSet();
17: private static final Date StartupTime = new Date();
18: private Server server;
19: private boolean served;
20:
21: public CacheControlledServer(Server server) {
22: this .server = server;
23: //todo: run a thread to clean up the cache.
24: }
25:
26: public void service(Request request) throws Exception {
27: if (served) {
28: //tell to IE to cache these resources
29: //see: http://mir.aculo.us/articles/2005/08/28/internet-explorer-and-ajax-image-caching-woes
30: //see: http://www.bazon.net/mishoo/articles.epl?art_id=958
31: //see: http://support.microsoft.com/default.aspx?scid=kb;en-us;319546
32: if (cache.contains(request.getHeader("If-None-Match"))) {
33: request.respondWith(new NotModifiedHandler(
34: ExpirationDate));
35: } else {
36: try {
37: Date modifiedSince = request
38: .getHeaderAsDate("If-Modified-Since");
39: if (StartupTime.getTime() - modifiedSince.getTime() > 1000) {
40: server.service(new EnhancedRequest(request));
41: } else {
42: request.respondWith(new NotModifiedHandler(
43: ExpirationDate));
44: }
45: } catch (Exception e) {
46: server.service(new EnhancedRequest(request));
47: }
48: }
49: } else {
50: server.service(new EnhancedRequest(request));
51: served = true;
52: }
53: }
54:
55: public void shutdown() {
56: cache.clear();
57: served = false;
58: }
59:
60: private class EnhancedRequest extends RequestProxy {
61:
62: public EnhancedRequest(Request request) {
63: super (request);
64: }
65:
66: public void respondWith(final ResponseHandler handler)
67: throws Exception {
68: request.respondWith(new ResponseHandler() {
69: public void respond(Response response) throws Exception {
70: String eTag = String.valueOf(Math.abs(request
71: .getURI().hashCode()));
72: cache.add(eTag);
73: response.setHeader("ETag", eTag);
74: response.setHeader("Cache-Control", new String[] {
75: "private", "max-age=86400" });
76: response.setHeader("Last-Modified", StartupTime);
77: handler.respond(response);
78: }
79: });
80: }
81: }
82: }
|