6ded0112cbf22955a7a6092bab738e3c475a0f48
[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 < 1) {
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       return true;
134     }
135
136     long ifModifiedSince = -1;
137     try {
138       ifModifiedSince = request.getDateHeader(Headers.HEADER_IF_MODIFIED_SINCE);
139     }
140     catch (Exception e) {
141       log.error("Exception while fetching If-Modified-Since: {}", e);
142     }
143
144     long lastModified = handle.getLastModified(request);
145
146     /**
147      * Sicherstellen, dass der Wert keine Millisekunden enthält, da die
148      * Zeitangabe aus dem Modified-Since-Header keine Millisekunden enthalten
149      * kann und der Test unten dann stets fehlschlagen würde!
150      */
151     lastModified = lastModified - (lastModified % 1000);
152
153     String ifNoneMatch = request.getHeader(Headers.HEADER_IF_NONE_MATCH);
154     String eTag = handle.getETag(request);
155
156     /**
157      * 304-Antworten sollen nach dem {@plainlink
158      * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5 RFC
159      * 2616, Abschnitt 10.3.5} einen ETag-Header enthalten, wenn auch die
160      * 200-Antwort einen enthalten hätte.
161      */
162     if (eTag != null) {
163       StringBuilder builder = new StringBuilder();
164       if (handle.isETagWeak())
165         builder.append("W/");
166       builder.append('"');
167       builder.append(eTag);
168       builder.append('"');
169       response.setHeader(Headers.HEADER_ETAG, builder.toString());
170     }
171
172
173     if (ifModifiedSince >= lastModified && lastModified > 0) {
174       /**
175        * request.getDateHeader liefert die Zeit als long, oder -1, wenn der
176        * Header nicht existiert. D.h., wenn "If-Modified-Since" nicht gesetzt
177        * ist, wird die komplette Seite ausgeliefert.
178        * Der zusätzliche Test, ob lastModified größer 0 ist, ist nötig, um
179        * Fehler auszuschließen, wenn die Implementierung von Cachable
180        * negative Werte für Last-Modified zurückliefert.
181        */
182       if (log.isDebugEnabled())
183         log.debug("{}: Not modified since {}", url, new Date(ifModifiedSince));
184
185       if (ifNoneMatch == null) {
186         /** Neue Anfrage oder HTTP/1.0 Client! */
187         log.debug("{}: ETag nicht gesetzt -> 304", url);
188         response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
189         return false;
190       }
191     }
192
193     if (ifNoneMatch != null) {
194       boolean weak = false;
195       if (ifNoneMatch.startsWith("W/")) {
196         weak = true;
197         ifNoneMatch = ifNoneMatch.substring(3, ifNoneMatch.length() - 1);
198       }
199       else {
200         ifNoneMatch = ifNoneMatch.substring(1, ifNoneMatch.length() - 1);
201       }
202
203       if (!weak || (request.getMethod().equals("GET") && request.getHeader(Headers.HEADER_RANGE) == null)) {
204         /**
205          * Die Gleichheit gilt nur, wenn die ETag's der Anfrage _und_ der
206          * Antwort stark sind (starke Gleichheit!), oder wenn die Antwort nur
207          * schwache Gleichheit fordert...
208          */
209         if (ifNoneMatch.equals(eTag) && (handle.isETagWeak() || !weak)) {
210           log.debug("{}: ETag {} not changed -> 304 ", url, ifNoneMatch);
211           response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
212           return false;
213         }
214       }
215       else {
216         log.warn("{}: ignoring weak ETag W/\"{}\", because the request was no GET-request or the Range-Header was present!", url, ifNoneMatch);
217       }
218     }
219
220
221     log.debug("{}: first up!", url);
222
223     if (handle.isZipped())
224       response.addHeader(Headers.HEADER_CONTENT_ENCODING, "gzip");
225
226     /** HTTP/1.1-Caching-Header richtig setzen!! */
227     response.setDateHeader(Headers.HEADER_LAST_MODIFIED, lastModified);
228
229     /** Cache-Control für HTTP/1.1-Clients generieren */
230     Map<String, String> cacheControl = new TreeMap<String, String>();
231
232     /**
233      * Wenn eins JSESSIONID in der URL enthalten ist, darf die Anfrage nur vom
234      * Browser gecached werden!
235      */
236     if (request.isRequestedSessionIdFromURL()) {
237       cacheControl.put("private", null);
238     }
239     else {
240       /**
241        * Hier muss nicht geprüft werden, ob cacheSeconds > 0 gilt, da in diesem
242        * Fall oben bereits No-Cache-Header generiert und <code>false</code>
243        * zurückgeliefert werden!
244        *
245        * Den Wert als <code>max-age</code> zu den Schlüssel-Wert-Paaren für den
246        * <code>Cache-Control</code>-Header hinzufügen und einen entsprechenden
247        * <code>Expires</code>-Header für HTTP/1.0-Clients setzen.
248        */
249       cacheControl.put("max-age", Integer.toString(cacheSeconds));
250       response.setDateHeader(Headers.HEADER_EXPIRES, (handle.getTimestamp() + (long) cacheSeconds * 1000));
251     }
252
253     /** Dem Handler die Gelegenheit geben, den Cache-Controll-Header anzupassen */
254     handle.cacheControl(request, cacheControl);
255
256
257     if (cacheControl.containsKey("private")) {
258       /**
259        * HTTP/1.0 Caches davon abhalten, die Ressource zu cachen (vgl.: RFC
260        * 2616, {@plainlink
261        * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.3
262        * Abschnitt 14.9.3} und {@plainlink
263        * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.32
264        * Abschnitt 14.32})
265        */
266       response.setDateHeader(Headers.HEADER_EXPIRES, 0l);
267       response.addHeader(Headers.HEADER_PRAGMA, "no-cache");
268     }
269
270     StringBuilder builder = new StringBuilder();
271     for (Entry<String, String> entry : cacheControl.entrySet()) {
272       builder.setLength(0);
273       builder.append(entry.getKey());
274       if (entry.getValue() != null) {
275         builder.append('=');
276         builder.append(entry.getValue());
277       }
278       response.addHeader(Headers.HEADER_CACHE_CONTROL, builder.toString());
279     }
280
281     return true;
282     }
283     finally {
284       /**
285        * Thread-Locale-Variable zurücksetzen, damit
286        * 1.) ein doppelter Aufruf dieser Methode pro Request erkannt werden kann
287        * 2.) der nächste Request nicht mit dem selben Handle weiterarbeitet
288        */
289       CacheControl.tl.set(null);
290     }
291   }
292
293   public void release() {
294     CacheControl.tl.set(null);
295   }
296
297
298   class ReflectionCacheMethodHandle implements CacheMethodHandle {
299
300     private Object handler;
301     private long now = System.currentTimeMillis();
302     private Integer cacheSeconds;
303     private Long lastModified;
304     private String eTag;
305     private Map<String,String> additionalHeaders;
306     private Method acceptsMethod;
307     private Method cacheSecondsMethod;
308     private Method lastModifiedMethod;
309     private Method eTagMethod;
310     private Method cacheControlMethod;
311     private Method additionalHeadersMethod;
312     private boolean isAcceptsMethodDefined;
313     private boolean isCacheSecondsMethodDefined;
314     private boolean isLastModifiedMethodDefined;
315     private boolean isETagMethodDefined;
316     private boolean isCacheControlMethodDefined;
317     private boolean isAdditionalHeadersMethodDefined;
318     private boolean weak;
319     private boolean zipped;
320
321
322     ReflectionCacheMethodHandle(Object handler, boolean zipped) throws NoSuchMethodException {
323
324       this.handler = handler;
325       this.zipped = zipped;
326
327       cacheSeconds = CacheControl.this.defaultCacheSeconds;
328       lastModified = CacheControl.this.defaultLastModified;
329       eTag = "";
330
331       /** Class-Level-Annotations auslesen */
332       for (Annotation annotation : handler.getClass().getAnnotations()) {
333         if (annotation.annotationType().equals(CacheSeconds.class)) {
334           cacheSeconds = ((CacheSeconds)annotation).value();
335           isCacheSecondsMethodDefined = true;
336           continue;
337         }
338         if (annotation.annotationType().equals(LastModified.class)) {
339           lastModified = ((LastModified)annotation).value();
340           if (lastModified < 1) {
341             /**
342              * Ein Last-Modified-Header wurde angefordert, aber es wurde kein
343              * statischer Wert spezifiziert:
344              * globalen statischen Default-Wert benutzen!
345              */
346             lastModified = defaultLastModified;
347           }
348           isLastModifiedMethodDefined = true;
349           continue;
350         }
351         if (annotation.annotationType().equals(ETag.class)) {
352           ETag eTagAnnotation = (ETag)annotation;
353           eTag = eTagAnnotation.value();
354           weak = eTagAnnotation.weak();
355           isETagMethodDefined = true;
356           continue;
357         }
358         if (annotation.annotationType().equals(AdditionalHeaders.class)) {
359           AdditionalHeaders additionalHeadersAnnotation = (AdditionalHeaders)annotation;
360           additionalHeaders = new HashMap<String,String>();
361           for (String header : additionalHeadersAnnotation.value()) {
362             int i = header.indexOf(':');
363             if (i < 0) {
364               log.error("invalid header: [{}]", header);
365             }
366             else {
367               String name = header.substring(0,i).trim();
368               String value = header.substring(i+1,header.length()).trim();
369               additionalHeaders.put(name, value);
370             }
371           }
372           isAdditionalHeadersMethodDefined = true;
373           continue;
374         }
375       }
376
377       /** Method-Level-Annotations auslesen */
378       for (Method method : handler.getClass().getMethods()) {
379         for (Annotation annotation : method.getAnnotations()) {
380           if (annotation.annotationType().equals(Accepts.class)) {
381             if (isAcceptsMethodDefined)
382               throw new IllegalArgumentException("Die Annotation @Accept wurde in der Klasse " + handler.getClass().getSimpleName() + " mehrfach verwendet!");
383             acceptsMethod = method;
384             isAcceptsMethodDefined = true;
385             continue;
386           }
387           if (annotation.annotationType().equals(CacheSeconds.class)) {
388             if (isCacheSecondsMethodDefined)
389               throw new IllegalArgumentException("Die Annotation @CacheSeconds wurde in der Klasse " + handler.getClass().getSimpleName() + " mehrfach verwendet!");
390             cacheSecondsMethod = method;
391             isCacheSecondsMethodDefined = true;
392             continue;
393           }
394           if (annotation.annotationType().equals(LastModified.class)) {
395             if (isLastModifiedMethodDefined)
396               throw new IllegalArgumentException("Die Annotation @LastModified wurde in der Klasse " + handler.getClass().getSimpleName() + " mehrfach verwendet!");
397             lastModifiedMethod = method;
398             isLastModifiedMethodDefined = true;
399             continue;
400           }
401           if (annotation.annotationType().equals(ETag.class)) {
402             if (isETagMethodDefined)
403               throw new IllegalArgumentException("Die Annotation @ETag wurde in der Klasse " + handler.getClass().getSimpleName() + " mehrfach verwendet!");
404             eTagMethod = method;
405             weak = ((ETag)annotation).weak();
406             isETagMethodDefined = true;
407             continue;
408           }
409           if (annotation.annotationType().equals(de.halbekunst.juplo.cachecontrol.annotations.CacheControl.class)) {
410             if (isCacheControlMethodDefined)
411               throw new IllegalArgumentException("Die Annotation @CacheControl wurde in der Klasse " + handler.getClass().getSimpleName() + " mehrfach verwendet!");
412             cacheControlMethod = method;
413             isCacheControlMethodDefined = true;
414             continue;
415           }
416           if (annotation.annotationType().equals(AdditionalHeaders.class)) {
417             if (isAdditionalHeadersMethodDefined)
418               throw new IllegalArgumentException("Die Annotation @AdditionalHeaders wurde in der Klasse " + handler.getClass().getSimpleName() + " mehrfach verwendet!");
419             additionalHeadersMethod = method;
420             isAdditionalHeadersMethodDefined = true;
421             continue;
422           }
423         }
424       }
425
426       if (!isAdditionalHeadersMethodDefined)
427         additionalHeaders = new HashMap<String,String>();
428     }
429
430
431     @Override
432     public boolean isZipped() {
433       return zipped;
434     }
435
436     @Override
437     public long getTimestamp() {
438       return now;
439     }
440
441     @Override
442     public int accepts(HttpServletRequest request) throws IllegalArgumentException {
443       if (acceptsMethod == null) {
444         return HttpServletResponse.SC_OK;
445       }
446       else {
447         try {
448           return (Integer)acceptsMethod.invoke(handler, request);
449         }
450         catch (Exception e) {
451           throw new IllegalArgumentException(e);
452         }
453       }
454     }
455
456     @Override
457     public int getCacheSeconds(HttpServletRequest request) throws IllegalArgumentException {
458       if (cacheSecondsMethod == null) {
459         return cacheSeconds;
460       }
461       else {
462         try {
463           return (Integer)cacheSecondsMethod.invoke(handler, request);
464         }
465         catch (Exception e) {
466           throw new IllegalArgumentException(e);
467         }
468       }
469     }
470
471     @Override
472     public long getLastModified(HttpServletRequest request) throws IllegalArgumentException {
473       if (lastModifiedMethod == null) {
474         return lastModified;
475       }
476       else {
477         try {
478           return (Long)lastModifiedMethod.invoke(handler, request);
479         }
480         catch (Exception e) {
481           throw new IllegalArgumentException(e);
482         }
483       }
484     }
485
486     @Override
487     public String getETag(HttpServletRequest request) throws IllegalArgumentException {
488       if (eTagMethod == null) {
489         return eTag;
490       }
491       else {
492         try {
493           return (String)eTagMethod.invoke(handler, request);
494         }
495         catch (Exception e) {
496           throw new IllegalArgumentException(e);
497         }
498       }
499     }
500
501     @Override
502     public boolean isETagWeak() {
503       return weak;
504     }
505
506     @Override
507     public void cacheControl(
508         HttpServletRequest request,
509         Map<String, String> cacheControlMap
510         )
511         throws IllegalArgumentException
512     {
513       if (cacheControlMethod != null) {
514         try {
515           cacheControlMethod.invoke(handler, request, cacheControlMap);
516         }
517         catch (Exception e) {
518           throw new IllegalArgumentException(e);
519         }
520       }
521     }
522
523     @Override
524     public Map<String,String> getAdditionalHeaders(HttpServletRequest request) throws IllegalArgumentException {
525       if (additionalHeadersMethod == null) {
526         return additionalHeaders;
527       }
528       else {
529         try {
530           return (Map<String,String>)additionalHeadersMethod.invoke(handler, request);
531         }
532         catch (Exception e) {
533           throw new IllegalArgumentException(e);
534         }
535       }
536     }
537   }
538 }