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