Fehler im Zusammenhang mit dem Komprimieren gepufferter Antworten korrigiert
[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       Object handler
50       )
51   {
52     try {
53     CacheMethodHandle handle = CacheControl.tl.get();
54
55     /** Doppelte Ausführung verhindern... */
56     if (handle == null) {
57       /** Dekoration wurde bereits durchgeführt! */
58       return true;
59     }
60
61     /**
62      * Alle Antworten (insbesondere auch 304) sollen nach dem {@plainlink
63      * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.18 RFC 2616,
64      * Abschnitt 14.18} einen Date-Header enthalten
65      */
66     response.setDateHeader(Headers.HEADER_DATE, handle.getTimestamp());
67
68     /** Besondere Maßnahmen für besondere HTTP-Status-Codes ?!? */
69     int status = handle.accepts(request);
70     switch (status) {
71       case HttpServletResponse.SC_OK: // 200
72       case HttpServletResponse.SC_NO_CONTENT: // 204
73       case HttpServletResponse.SC_PARTIAL_CONTENT: // 206
74         /** Normale Antwort! Antwort dekorieren... */
75         break;
76       case HttpServletResponse.SC_BAD_REQUEST: // 400
77       case HttpServletResponse.SC_UNAUTHORIZED: // 401
78       case HttpServletResponse.SC_PAYMENT_REQUIRED: // 402
79       case HttpServletResponse.SC_FORBIDDEN: // 403
80       case HttpServletResponse.SC_NOT_FOUND: // 404
81       case HttpServletResponse.SC_METHOD_NOT_ALLOWED: // 405
82       case HttpServletResponse.SC_NOT_ACCEPTABLE: // 406
83       case HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED: // 407
84       case HttpServletResponse.SC_REQUEST_TIMEOUT: // 408
85       case HttpServletResponse.SC_CONFLICT: // 409
86       case HttpServletResponse.SC_GONE: // 410
87       case HttpServletResponse.SC_LENGTH_REQUIRED: // 411
88       case HttpServletResponse.SC_PRECONDITION_FAILED: // 412
89       case HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE: // 413
90       case HttpServletResponse.SC_REQUEST_URI_TOO_LONG: // 414
91       case HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE: // 415
92       case HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE: // 416
93       case HttpServletResponse.SC_INTERNAL_SERVER_ERROR: // 500
94       case HttpServletResponse.SC_NOT_IMPLEMENTED: // 501
95       case HttpServletResponse.SC_SERVICE_UNAVAILABLE: // 503
96       case HttpServletResponse.SC_HTTP_VERSION_NOT_SUPPORTED: // 505
97         return true;
98       default:
99         /**
100          * Es ist nicht klar, was der Handler noch machen wird/muss:
101          * Antwort nicht dekorieren und Kontroller an den Handler übergeben...
102          */
103         return false;
104     }
105
106     if (handle.isZipped())
107       response.addHeader(Headers.HEADER_CONTENT_ENCODING, "gzip");
108
109     Map<String,String> headers = handle.getAdditionalHeaders(request);
110     for (String name : headers.keySet())
111       response.addHeader(name, headers.get(name));
112
113     String url = null;
114     if (log.isDebugEnabled()) {
115       if (request.getQueryString() == null) {
116         url = request.getRequestURI();
117       }
118       else {
119         StringBuilder builder = new StringBuilder();
120         builder.append(request.getRequestURI());
121         builder.append('?');
122         builder.append(request.getQueryString());
123         url = builder.toString();
124       }
125     }
126
127     int cacheSeconds = handle.getCacheSeconds(request);
128     if (cacheSeconds < 1) {
129       log.debug("{}: caching disabled!", url);
130       response.setDateHeader(Headers.HEADER_DATE, handle.getTimestamp());
131       response.setDateHeader(Headers.HEADER_EXPIRES, 0);
132       response.addHeader(Headers.HEADER_PRAGMA, "no-cache");
133       response.addHeader(Headers.HEADER_CACHE_CONTROL, "private");
134       response.addHeader(Headers.HEADER_CACHE_CONTROL, "no-cache");
135       response.addHeader(Headers.HEADER_CACHE_CONTROL, "no-store");
136       response.addHeader(Headers.HEADER_CACHE_CONTROL, "max-age=0");
137       response.addHeader(Headers.HEADER_CACHE_CONTROL, "s-max-age=0");
138       return true;
139     }
140
141     long ifModifiedSince = -1;
142     try {
143       ifModifiedSince = request.getDateHeader(Headers.HEADER_IF_MODIFIED_SINCE);
144     }
145     catch (Exception e) {
146       log.error("Exception while fetching If-Modified-Since: {}", e);
147     }
148
149     long lastModified = handle.getLastModified(request);
150
151     /**
152      * Sicherstellen, dass der Wert keine Millisekunden enthält, da die
153      * Zeitangabe aus dem Modified-Since-Header keine Millisekunden enthalten
154      * kann und der Test unten dann stets fehlschlagen würde!
155      */
156     lastModified = lastModified - (lastModified % 1000);
157
158     String ifNoneMatch = request.getHeader(Headers.HEADER_IF_NONE_MATCH);
159     String eTag = handle.getETag(request);
160
161     /**
162      * 304-Antworten sollen nach dem {@plainlink
163      * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5 RFC
164      * 2616, Abschnitt 10.3.5} einen ETag-Header enthalten, wenn auch die
165      * 200-Antwort einen enthalten hätte.
166      */
167     if (eTag != null) {
168       StringBuilder builder = new StringBuilder();
169       if (handle.isETagWeak())
170         builder.append("W/");
171       builder.append('"');
172       builder.append(eTag);
173       builder.append('"');
174       response.setHeader(Headers.HEADER_ETAG, builder.toString());
175     }
176
177
178     if (ifModifiedSince >= lastModified && lastModified > 0) {
179       /**
180        * request.getDateHeader liefert die Zeit als long, oder -1, wenn der
181        * Header nicht existiert. D.h., wenn "If-Modified-Since" nicht gesetzt
182        * ist, wird die komplette Seite ausgeliefert.
183        * Der zusätzliche Test, ob lastModified größer 0 ist, ist nötig, um
184        * Fehler auszuschließen, wenn die Implementierung von Cachable
185        * negative Werte für Last-Modified zurückliefert.
186        */
187       if (log.isDebugEnabled())
188         log.debug("{}: Not modified since {}", url, new Date(ifModifiedSince));
189
190       if (ifNoneMatch == null) {
191         /** Neue Anfrage oder HTTP/1.0 Client! */
192         log.debug("{}: ETag nicht gesetzt -> 304", url);
193         response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
194         return false;
195       }
196     }
197
198     if (ifNoneMatch != null) {
199       boolean weak = false;
200       if (ifNoneMatch.startsWith("W/")) {
201         weak = true;
202         ifNoneMatch = ifNoneMatch.substring(3, ifNoneMatch.length() - 1);
203       }
204       else {
205         ifNoneMatch = ifNoneMatch.substring(1, ifNoneMatch.length() - 1);
206       }
207
208       if (!weak || (request.getMethod().equals("GET") && request.getHeader(Headers.HEADER_RANGE) == null)) {
209         /**
210          * Die Gleichheit gilt nur, wenn die ETag's der Anfrage _und_ der
211          * Antwort stark sind (starke Gleichheit!), oder wenn die Antwort nur
212          * schwache Gleichheit fordert...
213          */
214         if (ifNoneMatch.equals(eTag) && (handle.isETagWeak() || !weak)) {
215           log.debug("{}: ETag {} not changed -> 304 ", url, ifNoneMatch);
216           response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
217           return false;
218         }
219       }
220       else {
221         log.warn("{}: ignoring weak ETag W/\"{}\", because the request was no GET-request or the Range-Header was present!", url, ifNoneMatch);
222       }
223     }
224
225
226     log.debug("{}: first up!", url);
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       eTag = "";
332
333       /** Class-Level-Annotations auslesen */
334       for (Annotation annotation : handler.getClass().getAnnotations()) {
335         if (annotation.annotationType().equals(CacheSeconds.class)) {
336           cacheSeconds = ((CacheSeconds)annotation).value();
337           isCacheSecondsMethodDefined = true;
338           continue;
339         }
340         if (annotation.annotationType().equals(LastModified.class)) {
341           lastModified = ((LastModified)annotation).value();
342           if (lastModified < 1) {
343             /**
344              * Ein Last-Modified-Header wurde angefordert, aber es wurde kein
345              * statischer Wert spezifiziert:
346              * globalen statischen Default-Wert benutzen!
347              */
348             lastModified = defaultLastModified;
349           }
350           isLastModifiedMethodDefined = true;
351           continue;
352         }
353         if (annotation.annotationType().equals(ETag.class)) {
354           ETag eTagAnnotation = (ETag)annotation;
355           eTag = eTagAnnotation.value();
356           weak = eTagAnnotation.weak();
357           isETagMethodDefined = true;
358           continue;
359         }
360         if (annotation.annotationType().equals(AdditionalHeaders.class)) {
361           AdditionalHeaders additionalHeadersAnnotation = (AdditionalHeaders)annotation;
362           additionalHeaders = new HashMap<String,String>();
363           for (String header : additionalHeadersAnnotation.value()) {
364             int i = header.indexOf(':');
365             if (i < 0) {
366               log.error("invalid header: [{}]", header);
367             }
368             else {
369               String name = header.substring(0,i).trim();
370               String value = header.substring(i+1,header.length()).trim();
371               additionalHeaders.put(name, value);
372             }
373           }
374           isAdditionalHeadersMethodDefined = true;
375           continue;
376         }
377       }
378
379       /** Method-Level-Annotations auslesen */
380       for (Method method : handler.getClass().getMethods()) {
381         for (Annotation annotation : method.getAnnotations()) {
382           if (annotation.annotationType().equals(Accepts.class)) {
383             if (isAcceptsMethodDefined)
384               throw new IllegalArgumentException("Die Annotation @Accept wurde in der Klasse " + handler.getClass().getSimpleName() + " mehrfach verwendet!");
385             acceptsMethod = method;
386             isAcceptsMethodDefined = true;
387             continue;
388           }
389           if (annotation.annotationType().equals(CacheSeconds.class)) {
390             if (isCacheSecondsMethodDefined)
391               throw new IllegalArgumentException("Die Annotation @CacheSeconds wurde in der Klasse " + handler.getClass().getSimpleName() + " mehrfach verwendet!");
392             cacheSecondsMethod = method;
393             isCacheSecondsMethodDefined = true;
394             continue;
395           }
396           if (annotation.annotationType().equals(LastModified.class)) {
397             if (isLastModifiedMethodDefined)
398               throw new IllegalArgumentException("Die Annotation @LastModified wurde in der Klasse " + handler.getClass().getSimpleName() + " mehrfach verwendet!");
399             lastModifiedMethod = method;
400             isLastModifiedMethodDefined = true;
401             continue;
402           }
403           if (annotation.annotationType().equals(ETag.class)) {
404             if (isETagMethodDefined)
405               throw new IllegalArgumentException("Die Annotation @ETag wurde in der Klasse " + handler.getClass().getSimpleName() + " mehrfach verwendet!");
406             eTagMethod = method;
407             weak = ((ETag)annotation).weak();
408             isETagMethodDefined = true;
409             continue;
410           }
411           if (annotation.annotationType().equals(de.halbekunst.juplo.cachecontrol.annotations.CacheControl.class)) {
412             if (isCacheControlMethodDefined)
413               throw new IllegalArgumentException("Die Annotation @CacheControl wurde in der Klasse " + handler.getClass().getSimpleName() + " mehrfach verwendet!");
414             cacheControlMethod = method;
415             isCacheControlMethodDefined = true;
416             continue;
417           }
418           if (annotation.annotationType().equals(AdditionalHeaders.class)) {
419             if (isAdditionalHeadersMethodDefined)
420               throw new IllegalArgumentException("Die Annotation @AdditionalHeaders wurde in der Klasse " + handler.getClass().getSimpleName() + " mehrfach verwendet!");
421             additionalHeadersMethod = method;
422             isAdditionalHeadersMethodDefined = true;
423             continue;
424           }
425         }
426       }
427
428       if (!isAdditionalHeadersMethodDefined)
429         additionalHeaders = new HashMap<String,String>();
430     }
431
432
433     @Override
434     public boolean isZipped() {
435       return zipped;
436     }
437
438     @Override
439     public long getTimestamp() {
440       return now;
441     }
442
443     @Override
444     public int accepts(HttpServletRequest request) throws IllegalArgumentException {
445       if (acceptsMethod == null) {
446         return HttpServletResponse.SC_OK;
447       }
448       else {
449         try {
450           return (Integer)acceptsMethod.invoke(handler, request);
451         }
452         catch (Exception e) {
453           throw new IllegalArgumentException(e);
454         }
455       }
456     }
457
458     @Override
459     public int getCacheSeconds(HttpServletRequest request) throws IllegalArgumentException {
460       if (cacheSecondsMethod == null) {
461         return cacheSeconds;
462       }
463       else {
464         try {
465           return (Integer)cacheSecondsMethod.invoke(handler, request);
466         }
467         catch (Exception e) {
468           throw new IllegalArgumentException(e);
469         }
470       }
471     }
472
473     @Override
474     public long getLastModified(HttpServletRequest request) throws IllegalArgumentException {
475       if (lastModifiedMethod == null) {
476         return lastModified;
477       }
478       else {
479         try {
480           return (Long)lastModifiedMethod.invoke(handler, request);
481         }
482         catch (Exception e) {
483           throw new IllegalArgumentException(e);
484         }
485       }
486     }
487
488     @Override
489     public String getETag(HttpServletRequest request) throws IllegalArgumentException {
490       if (eTagMethod == null) {
491         return eTag;
492       }
493       else {
494         try {
495           return (String)eTagMethod.invoke(handler, request);
496         }
497         catch (Exception e) {
498           throw new IllegalArgumentException(e);
499         }
500       }
501     }
502
503     @Override
504     public boolean isETagWeak() {
505       return weak;
506     }
507
508     @Override
509     public void cacheControl(
510         HttpServletRequest request,
511         Map<String, String> cacheControlMap
512         )
513         throws IllegalArgumentException
514     {
515       if (cacheControlMethod != null) {
516         try {
517           cacheControlMethod.invoke(handler, request, cacheControlMap);
518         }
519         catch (Exception e) {
520           throw new IllegalArgumentException(e);
521         }
522       }
523     }
524
525     @Override
526     public Map<String,String> getAdditionalHeaders(HttpServletRequest request) throws IllegalArgumentException {
527       if (additionalHeadersMethod == null) {
528         return additionalHeaders;
529       }
530       else {
531         try {
532           return (Map<String,String>)additionalHeadersMethod.invoke(handler, request);
533         }
534         catch (Exception e) {
535           throw new IllegalArgumentException(e);
536         }
537       }
538     }
539   }
540 }