486cb33f4de1d577ccb73e85e08e67450014473c
[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         return true;
97       default:
98         /**
99          * Es ist nicht klar, was der Handler noch machen wird/muss:
100          * Antwort nicht dekorieren und Kontroller an den Handler übergeben...
101          */
102         return false;
103     }
104
105     Map<String,String> headers = handle.getAdditionalHeaders(request);
106     for (String name : headers.keySet())
107       response.addHeader(name, headers.get(name));
108
109     String url = null;
110     if (log.isDebugEnabled()) {
111       if (request.getQueryString() == null) {
112         url = request.getRequestURI();
113       }
114       else {
115         StringBuilder builder = new StringBuilder();
116         builder.append(request.getRequestURI());
117         builder.append('?');
118         builder.append(request.getQueryString());
119         url = builder.toString();
120       }
121     }
122
123     int cacheSeconds = handle.getCacheSeconds(request);
124     if (cacheSeconds < 1) {
125       log.debug("{}: caching disabled!", url);
126       response.setDateHeader(Headers.HEADER_DATE, handle.getTimestamp());
127       response.setDateHeader(Headers.HEADER_EXPIRES, 0);
128       response.addHeader(Headers.HEADER_PRAGMA, "no-cache");
129       response.addHeader(Headers.HEADER_CACHE_CONTROL, "private");
130       response.addHeader(Headers.HEADER_CACHE_CONTROL, "no-cache");
131       response.addHeader(Headers.HEADER_CACHE_CONTROL, "no-store");
132       response.addHeader(Headers.HEADER_CACHE_CONTROL, "max-age=0");
133       response.addHeader(Headers.HEADER_CACHE_CONTROL, "s-max-age=0");
134       return true;
135     }
136
137     long ifModifiedSince = -1;
138     try {
139       ifModifiedSince = request.getDateHeader(Headers.HEADER_IF_MODIFIED_SINCE);
140     }
141     catch (Exception e) {
142       log.error("Exception while fetching If-Modified-Since: {}", e);
143     }
144
145     long lastModified = handle.getLastModified(request);
146
147     /**
148      * Sicherstellen, dass der Wert keine Millisekunden enthält, da die
149      * Zeitangabe aus dem Modified-Since-Header keine Millisekunden enthalten
150      * kann und der Test unten dann stets fehlschlagen würde!
151      */
152     lastModified = lastModified - (lastModified % 1000);
153
154     String ifNoneMatch = request.getHeader(Headers.HEADER_IF_NONE_MATCH);
155     String eTag = handle.getETag(request);
156
157     /**
158      * 304-Antworten sollen nach dem {@plainlink
159      * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5 RFC
160      * 2616, Abschnitt 10.3.5} einen ETag-Header enthalten, wenn auch die
161      * 200-Antwort einen enthalten hätte.
162      */
163     if (eTag != null) {
164       StringBuilder builder = new StringBuilder();
165       if (handle.isETagWeak())
166         builder.append("W/");
167       builder.append('"');
168       builder.append(eTag);
169       builder.append('"');
170       response.setHeader(Headers.HEADER_ETAG, builder.toString());
171     }
172
173
174     if (ifModifiedSince >= lastModified && lastModified > 0) {
175       /**
176        * request.getDateHeader liefert die Zeit als long, oder -1, wenn der
177        * Header nicht existiert. D.h., wenn "If-Modified-Since" nicht gesetzt
178        * ist, wird die komplette Seite ausgeliefert.
179        * Der zusätzliche Test, ob lastModified größer 0 ist, ist nötig, um
180        * Fehler auszuschließen, wenn die Implementierung von Cachable
181        * negative Werte für Last-Modified zurückliefert.
182        */
183       if (log.isDebugEnabled())
184         log.debug("{}: Not modified since {}", url, new Date(ifModifiedSince));
185
186       if (ifNoneMatch == null) {
187         /** Neue Anfrage oder HTTP/1.0 Client! */
188         log.debug("{}: ETag nicht gesetzt -> 304", url);
189         response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
190         return false;
191       }
192     }
193
194     if (ifNoneMatch != null) {
195       boolean weak = false;
196       if (ifNoneMatch.startsWith("W/")) {
197         weak = true;
198         ifNoneMatch = ifNoneMatch.substring(3, ifNoneMatch.length() - 1);
199       }
200       else {
201         ifNoneMatch = ifNoneMatch.substring(1, ifNoneMatch.length() - 1);
202       }
203
204       if (!weak || (request.getMethod().equals("GET") && request.getHeader(Headers.HEADER_RANGE) == null)) {
205         /**
206          * Die Gleichheit gilt nur, wenn die ETag's der Anfrage _und_ der
207          * Antwort stark sind (starke Gleichheit!), oder wenn die Antwort nur
208          * schwache Gleichheit fordert...
209          */
210         if (ifNoneMatch.equals(eTag) && (handle.isETagWeak() || !weak)) {
211           log.debug("{}: ETag {} not changed -> 304 ", url, ifNoneMatch);
212           response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
213           return false;
214         }
215       }
216       else {
217         log.warn("{}: ignoring weak ETag W/\"{}\", because the request was no GET-request or the Range-Header was present!", url, ifNoneMatch);
218       }
219     }
220
221
222     log.debug("{}: first up!", url);
223
224     if (handle.isZipped())
225       response.addHeader(Headers.HEADER_CONTENT_ENCODING, "gzip");
226
227     /** HTTP/1.1-Caching-Header richtig setzen!! */
228     response.setDateHeader(Headers.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(Headers.HEADER_EXPIRES, (handle.getTimestamp() + (long) cacheSeconds * 1000));
252     }
253
254     /** Dem Handler die Gelegenheit geben, den Cache-Controll-Header anzupassen */
255     handle.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(Headers.HEADER_EXPIRES, 0l);
268       response.addHeader(Headers.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(Headers.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   class ReflectionCacheMethodHandle implements CacheMethodHandle {
300
301     private Object handler;
302     private long now = System.currentTimeMillis();
303     private Integer cacheSeconds;
304     private Long lastModified;
305     private String eTag;
306     private Map<String,String> additionalHeaders;
307     private Method acceptsMethod;
308     private Method cacheSecondsMethod;
309     private Method lastModifiedMethod;
310     private Method eTagMethod;
311     private Method cacheControlMethod;
312     private Method additionalHeadersMethod;
313     private boolean isAcceptsMethodDefined;
314     private boolean isCacheSecondsMethodDefined;
315     private boolean isLastModifiedMethodDefined;
316     private boolean isETagMethodDefined;
317     private boolean isCacheControlMethodDefined;
318     private boolean isAdditionalHeadersMethodDefined;
319     private boolean weak;
320     private boolean zipped;
321
322
323     ReflectionCacheMethodHandle(Object handler, boolean zipped) throws NoSuchMethodException {
324
325       this.handler = handler;
326       this.zipped = zipped;
327
328       cacheSeconds = CacheControl.this.defaultCacheSeconds;
329       lastModified = CacheControl.this.defaultLastModified;
330       eTag = "";
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 }