CacheControl berücksichtigt die Regeln bzgl. starken vs. schwachen ETag's
[percentcodec] / cachecontrol / src / main / java / de / halbekunst / juplo / cachecontrol / CacheControl.java
1 package de.halbekunst.juplo.cachecontrol;
2
3 import de.halbekunst.juplo.cachecontrol.annotations.CacheSeconds;
4 import de.halbekunst.juplo.cachecontrol.annotations.Accepts;
5 import de.halbekunst.juplo.cachecontrol.annotations.LastModified;
6 import de.halbekunst.juplo.cachecontrol.annotations.ETag;
7 import java.lang.annotation.Annotation;
8 import java.lang.reflect.InvocationTargetException;
9 import java.lang.reflect.Method;
10 import java.util.Date;
11 import java.util.Map;
12 import java.util.Map.Entry;
13 import java.util.TreeMap;
14 import javax.servlet.http.HttpServletRequest;
15 import javax.servlet.http.HttpServletResponse;
16 import org.slf4j.Logger;
17 import org.slf4j.LoggerFactory;
18
19 /**
20  *
21  * @author kai
22  */
23 public class CacheControl {
24   private final static Logger log = LoggerFactory.getLogger(CacheControl.class);
25
26   public static final String HEADER_DATE = "Date";
27   public static final String HEADER_CACHE_CONTROL = "Cache-Control";
28   public static final String HEADER_LAST_MODIFIED = "Last-Modified";
29   public static final String HEADER_ETAG = "ETag";
30   public static final String HEADER_EXPIRES = "Expires";
31   public static final String HEADER_PRAGMA = "Pragma";
32   public static final String HEADER_IF_MODIFIED_SINCE = "If-Modified-Since";
33   public static final String HEADER_IF_NONE_MATCH = "If-None-Match";
34   public static final String HEADER_RANGE = "Range";
35
36   private static final ThreadLocal<CacheMethodHandle> tl = new ThreadLocal<CacheMethodHandle>();
37
38   private Integer defaultCacheSeconds;
39   private Long defaultLastModified;
40
41
42   public void init(Object handler) throws Exception {
43     if (CacheControl.tl.get() == null)
44       CacheControl.tl.set(new ReflectionCacheMethodHandle(handler));
45   }
46
47   public boolean decorate(
48       HttpServletRequest request,
49       HttpServletResponse response,
50       Object handler
51       ) throws Exception
52   {
53     try {
54     CacheMethodHandle controller = CacheControl.tl.get();
55
56     /** Doppelte Ausführung verhindern... */
57     if (controller == null) {
58       /** Dekoration wurde bereits durchgeführt! */
59       return true;
60     }
61
62     /**
63      * Alle Antworten (insbesondere auch 304) sollen nach dem {@plainlink
64      * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.18 RFC 2616,
65      * Abschnitt 14.18} einen Date-Header enthalten
66      */
67     response.setDateHeader(HEADER_DATE, controller.getTimestamp());
68
69     /** Besondere Maßnahmen für besondere HTTP-Status-Codes ?!? */
70     int status = controller.accepts(request);
71     switch (status) {
72       case HttpServletResponse.SC_OK: // 200
73       case HttpServletResponse.SC_NO_CONTENT: // 204
74       case HttpServletResponse.SC_PARTIAL_CONTENT: // 206
75         /** Normale Antwort! Antwort dekorieren... */
76         break;
77       case HttpServletResponse.SC_BAD_REQUEST: // 400
78       case HttpServletResponse.SC_UNAUTHORIZED: // 401
79       case HttpServletResponse.SC_PAYMENT_REQUIRED: // 402
80       case HttpServletResponse.SC_FORBIDDEN: // 403
81       case HttpServletResponse.SC_NOT_FOUND: // 404
82       case HttpServletResponse.SC_METHOD_NOT_ALLOWED: // 405
83       case HttpServletResponse.SC_NOT_ACCEPTABLE: // 406
84       case HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED: // 407
85       case HttpServletResponse.SC_REQUEST_TIMEOUT: // 408
86       case HttpServletResponse.SC_CONFLICT: // 409
87       case HttpServletResponse.SC_GONE: // 410
88       case HttpServletResponse.SC_LENGTH_REQUIRED: // 411
89       case HttpServletResponse.SC_PRECONDITION_FAILED: // 412
90       case HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE: // 413
91       case HttpServletResponse.SC_REQUEST_URI_TOO_LONG: // 414
92       case HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE: // 415
93       case HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE: // 416
94       case HttpServletResponse.SC_INTERNAL_SERVER_ERROR: // 500
95       case HttpServletResponse.SC_NOT_IMPLEMENTED: // 501
96       case HttpServletResponse.SC_SERVICE_UNAVAILABLE: // 503
97       case HttpServletResponse.SC_HTTP_VERSION_NOT_SUPPORTED: // 505
98         /**
99          * Ein Fehlercode kann stellvertretend für den Handler gesendet werden,
100          * da im Fehlerfall eh keine weiteren Daten ausgegeben werden!
101          */
102         response.sendError(status);
103         return true;
104       default:
105         /**
106          * Es ist nicht klar, was der Handler noch machen wird/muss:
107          * Antwort nicht dekorieren und Kontroller an den Handler übergeben...
108          */
109         return false;
110     }
111
112     String url = null;
113     if (log.isDebugEnabled()) {
114       if (request.getQueryString() == null) {
115         url = request.getRequestURI();
116       }
117       else {
118         StringBuilder builder = new StringBuilder();
119         builder.append(request.getRequestURI());
120         builder.append('?');
121         builder.append(request.getQueryString());
122         url = builder.toString();
123       }
124     }
125
126     int cacheSeconds = controller.getCacheSeconds(request);
127     if (cacheSeconds < 1) {
128       log.debug("{}: caching disabled!", url);
129       response.setDateHeader(HEADER_DATE, controller.getTimestamp());
130       response.setDateHeader(HEADER_EXPIRES, 0);
131       response.addHeader(HEADER_PRAGMA, "no-cache");
132       response.addHeader(HEADER_CACHE_CONTROL, "private");
133       response.addHeader(HEADER_CACHE_CONTROL, "no-cache");
134       response.addHeader(HEADER_CACHE_CONTROL, "no-store");
135       response.addHeader(HEADER_CACHE_CONTROL, "max-age=0");
136       response.addHeader(HEADER_CACHE_CONTROL, "s-max-age=0");
137       return true;
138     }
139
140     long ifModifiedSince = -1;
141     try {
142       ifModifiedSince = request.getDateHeader(HEADER_IF_MODIFIED_SINCE);
143     }
144     catch (Exception e) {
145       log.error("Exception while fetching If-Modified-Since: {}", e);
146     }
147
148     long lastModified = controller.getLastModified(request);
149
150     /**
151      * Sicherstellen, dass der Wert keine Millisekunden enthält, da die
152      * Zeitangabe aus dem Modified-Since-Header keine Millisekunden enthalten
153      * kann und der Test unten dann stets fehlschlagen würde!
154      */
155     lastModified = lastModified - (lastModified % 1000);
156
157     String ifNoneMatch = request.getHeader(HEADER_IF_NONE_MATCH);
158     String eTag = controller.getETag(request);
159
160     /**
161      * 304-Antworten sollen nach dem {@plainlink
162      * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5 RFC
163      * 2616, Abschnitt 10.3.5} einen ETag-Header enthalten, wenn auch die
164      * 200-Antwort einen enthalten hätte.
165      */
166     if (eTag != null) {
167       StringBuilder builder = new StringBuilder();
168       if (controller.isETagWeak())
169         builder.append("W/");
170       builder.append('"');
171       builder.append(eTag);
172       builder.append('"');
173       response.setHeader(HEADER_ETAG, builder.toString());
174     }
175
176
177     if (ifModifiedSince >= lastModified && lastModified > 0) {
178       /**
179        * request.getDateHeader liefert die Zeit als long, oder -1, wenn der
180        * Header nicht existiert. D.h., wenn "If-Modified-Since" nicht gesetzt
181        * ist, wird die komplette Seite ausgeliefert.
182        * Der zusätzliche Test, ob lastModified größer 0 ist, ist nötig, um
183        * Fehler auszuschließen, wenn die Implementierung von Cachable
184        * negative Werte für Last-Modified zurückliefert.
185        */
186       if (log.isDebugEnabled())
187         log.debug("{}: Not modified since {}", url, new Date(ifModifiedSince));
188
189       if (ifNoneMatch == null) {
190         /** Neue Anfrage oder HTTP/1.0 Client! */
191         log.debug("{}: ETag nicht gesetzt -> 304", url);
192         response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
193         return false;
194       }
195     }
196
197     if (ifNoneMatch != null) {
198       boolean weak = false;
199       if (ifNoneMatch.startsWith("W/")) {
200         weak = true;
201         ifNoneMatch = ifNoneMatch.substring(3, ifNoneMatch.length() - 1);
202       }
203       else {
204         ifNoneMatch = ifNoneMatch.substring(1, ifNoneMatch.length() - 1);
205       }
206
207       if (!weak || (request.getMethod().equals("GET") && request.getHeader(HEADER_RANGE) == null)) {
208         /**
209          * Die Gleichheit gilt nur, wenn die ETag's der Anfrage _und_ der
210          * Antwort stark sind (starke Gleichheit!), oder wenn die Antwort nur
211          * schwache Gleichheit fordert...
212          */
213         if (ifNoneMatch.equals(eTag) && (controller.isETagWeak() || !weak)) {
214           log.debug("{}: ETag {} not changed -> 304 ", url, ifNoneMatch);
215           response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
216           return false;
217         }
218       }
219       else {
220         log.warn("{}: ignoring weak ETag W/\"{}\", because the request was no GET-request or the Range-Header was present!", url, ifNoneMatch);
221       }
222     }
223
224
225     log.debug("{}: first up!", url);
226
227     /** HTTP/1.1-Caching-Header richtig setzen!! */
228     response.setDateHeader(HEADER_LAST_MODIFIED, lastModified);
229
230     /** Cache-Control für HTTP/1.1-Clients generieren */
231     Map<String, String> cacheControl = new TreeMap<String, String>();
232
233     /**
234      * Wenn eins JSESSIONID in der URL enthalten ist, darf die Anfrage nur vom
235      * Browser gecached werden!
236      */
237     if (request.isRequestedSessionIdFromURL()) {
238       cacheControl.put("private", null);
239     }
240     else {
241       /**
242        * Hier muss nicht geprüft werden, ob cacheSeconds > 0 gilt, da in diesem
243        * Fall oben bereits No-Cache-Header generiert und <code>false</code>
244        * zurückgeliefert werden!
245        *
246        * Den Wert als <code>max-age</code> zu den Schlüssel-Wert-Paaren für den
247        * <code>Cache-Control</code>-Header hinzufügen und einen entsprechenden
248        * <code>Expires</code>-Header für HTTP/1.0-Clients setzen.
249        */
250       cacheControl.put("max-age", Integer.toString(cacheSeconds));
251       response.setDateHeader(HEADER_EXPIRES, (controller.getTimestamp() + (long) cacheSeconds * 1000));
252     }
253
254     /** Dem Handler die Gelegenheit geben, den Cache-Controll-Header anzupassen */
255     controller.cacheControl(request, cacheControl);
256
257
258     if (cacheControl.containsKey("private")) {
259       /**
260        * HTTP/1.0 Caches davon abhalten, die Ressource zu cachen (vgl.: RFC
261        * 2616, {@plainlink
262        * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.3
263        * Abschnitt 14.9.3} und {@plainlink
264        * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.32
265        * Abschnitt 14.32})
266        */
267       response.setDateHeader(HEADER_EXPIRES, 0l);
268       response.addHeader(HEADER_PRAGMA, "no-cache");
269     }
270
271     StringBuilder builder = new StringBuilder();
272     for (Entry<String, String> entry : cacheControl.entrySet()) {
273       builder.setLength(0);
274       builder.append(entry.getKey());
275       if (entry.getValue() != null) {
276         builder.append('=');
277         builder.append(entry.getValue());
278       }
279       response.addHeader(HEADER_CACHE_CONTROL, builder.toString());
280     }
281
282     return true;
283     }
284     finally {
285       /**
286        * Thread-Locale-Variable zurücksetzen, damit
287        * 1.) ein doppelter Aufruf dieser Methode pro Request erkannt werden kann
288        * 2.) der nächste Request nicht mit dem selben Handle weiterarbeitet
289        */
290       CacheControl.tl.set(null);
291     }
292   }
293
294   public void release() {
295     CacheControl.tl.set(null);
296   }
297
298
299   interface CacheMethodHandle {
300     long getTimestamp();
301     int accepts(HttpServletRequest request) throws Exception;
302     int getCacheSeconds(HttpServletRequest request) throws Exception;
303     long getLastModified(HttpServletRequest request) throws Exception;
304     String getETag(HttpServletRequest request) throws Exception;
305     boolean isETagWeak();
306     void cacheControl(HttpServletRequest request, Map<String, String> cacheControlMap) throws Exception;
307   }
308
309
310   class ReflectionCacheMethodHandle implements CacheMethodHandle {
311
312     private Object handler;
313     private long now = System.currentTimeMillis();
314     private Integer cacheSeconds;
315     private Long lastModified;
316     private String eTag;
317     private Method acceptsMethod;
318     private Method cacheSecondsMethod;
319     private Method lastModifiedMethod;
320     private Method eTagMethod;
321     private Method cacheControlMethod;
322     private boolean isAcceptsMethodDefined;
323     private boolean isCacheSecondsMethodDefined;
324     private boolean isLastModifiedMethodDefined;
325     private boolean isETagMethodDefined;
326     private boolean isCacheControlMethodDefined;
327     private boolean weak;
328
329
330     ReflectionCacheMethodHandle(Object handler) throws NoSuchMethodException {
331
332       this.handler = handler;
333
334       cacheSeconds = CacheControl.this.defaultCacheSeconds;
335       lastModified = CacheControl.this.defaultLastModified;
336       eTag = "";
337
338       /** Class-Level-Annotations auslesen */
339       for (Annotation annotation : handler.getClass().getAnnotations()) {
340         if (annotation.annotationType().equals(CacheSeconds.class)) {
341           cacheSeconds = ((CacheSeconds)annotation).value();
342           isCacheSecondsMethodDefined = true;
343           continue;
344         }
345         if (annotation.annotationType().equals(LastModified.class)) {
346           lastModified = ((LastModified)annotation).value();
347           if (lastModified < 1) {
348             /**
349              * Ein Last-Modified-Header wurde angefordert, aber es wurde kein
350              * statischer Wert spezifiziert:
351              * globalen statischen Default-Wert benutzen!
352              */
353             lastModified = defaultLastModified;
354           }
355           isLastModifiedMethodDefined = true;
356           continue;
357         }
358         if (annotation.annotationType().equals(ETag.class)) {
359           ETag eTagAnnotation = (ETag)annotation;
360           eTag = eTagAnnotation.value();
361           weak = eTagAnnotation.weak();
362           isETagMethodDefined = true;
363           continue;
364         }
365       }
366
367       /** Method-Level-Annotations auslesen */
368       for (Method method : handler.getClass().getMethods()) {
369         for (Annotation annotation : method.getAnnotations()) {
370           if (annotation.annotationType().equals(Accepts.class)) {
371             if (isAcceptsMethodDefined)
372               throw new IllegalArgumentException("Die Annotation @Accept wurde in der Klasse " + handler.getClass().getSimpleName() + " mehrfach verwendet!");
373             acceptsMethod = method;
374             isAcceptsMethodDefined = true;
375             continue;
376           }
377           if (annotation.annotationType().equals(CacheSeconds.class)) {
378             if (isCacheSecondsMethodDefined)
379               throw new IllegalArgumentException("Die Annotation @CacheSeconds wurde in der Klasse " + handler.getClass().getSimpleName() + " mehrfach verwendet!");
380             cacheSecondsMethod = method;
381             isCacheSecondsMethodDefined = true;
382             continue;
383           }
384           if (annotation.annotationType().equals(LastModified.class)) {
385             if (isLastModifiedMethodDefined)
386               throw new IllegalArgumentException("Die Annotation @LastModified wurde in der Klasse " + handler.getClass().getSimpleName() + " mehrfach verwendet!");
387             lastModifiedMethod = method;
388             isLastModifiedMethodDefined = true;
389             continue;
390           }
391           if (annotation.annotationType().equals(ETag.class)) {
392             if (isETagMethodDefined)
393               throw new IllegalArgumentException("Die Annotation @ETag wurde in der Klasse " + handler.getClass().getSimpleName() + " mehrfach verwendet!");
394             eTagMethod = method;
395             weak = ((ETag)annotation).weak();
396             isETagMethodDefined = true;
397             continue;
398           }
399           if (annotation.annotationType().equals(de.halbekunst.juplo.cachecontrol.annotations.CacheControl.class)) {
400             if (isCacheControlMethodDefined)
401               throw new IllegalArgumentException("Die Annotation @CacheControl wurde in der Klasse " + handler.getClass().getSimpleName() + " mehrfach verwendet!");
402             cacheControlMethod = method;
403             isCacheControlMethodDefined = true;
404             continue;
405           }
406         }
407       }
408     }
409
410
411     @Override
412     public long getTimestamp() {
413       return now;
414     }
415
416     @Override
417     public int accepts(HttpServletRequest request)
418         throws IllegalAccessException,
419                IllegalArgumentException,
420                InvocationTargetException
421     {
422       if (acceptsMethod == null)
423         return HttpServletResponse.SC_OK;
424       else
425         return (Integer)acceptsMethod.invoke(handler, request);
426     }
427
428     @Override
429     public int getCacheSeconds(HttpServletRequest request)
430         throws IllegalAccessException,
431                IllegalArgumentException,
432                InvocationTargetException
433     {
434       if (cacheSecondsMethod == null)
435         return cacheSeconds;
436       else
437         return (Integer)cacheSecondsMethod.invoke(handler, request);
438     }
439
440     @Override
441     public long getLastModified(HttpServletRequest request)
442         throws IllegalAccessException,
443                IllegalArgumentException,
444                InvocationTargetException
445     {
446       if (lastModifiedMethod == null)
447         return lastModified;
448       else
449         return (Long)lastModifiedMethod.invoke(handler, request);
450     }
451
452     @Override
453     public String getETag(HttpServletRequest request)
454         throws IllegalAccessException,
455                IllegalArgumentException,
456                InvocationTargetException
457     {
458       if (eTagMethod == null)
459         return eTag;
460       else
461         return (String)eTagMethod.invoke(handler, request);
462     }
463
464     @Override
465     public boolean isETagWeak() {
466       return weak;
467     }
468
469     @Override
470     public void cacheControl(
471         HttpServletRequest request,
472         Map<String, String> cacheControlMap
473         )
474         throws IllegalAccessException,
475                IllegalArgumentException,
476                InvocationTargetException
477     {
478       if (cacheControlMethod != null)
479         cacheControlMethod.invoke(handler, request, cacheControlMap);
480     }
481   }
482
483
484   public void setDefaultCacheSeconds(Integer defaultCacheSeconds) {
485     this.defaultCacheSeconds = defaultCacheSeconds;
486   }
487
488   public void setDefaultLastModified(Long defaultLastModified) {
489     this.defaultLastModified = defaultLastModified;
490   }
491 }