1 package de.halbekunst.juplo.cachecontrol;
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;
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;
29 public class CacheControl {
30 private final static Logger log = LoggerFactory.getLogger(CacheControl.class);
32 private static final ThreadLocal<CacheMethodHandle> tl = new ThreadLocal<CacheMethodHandle>();
34 @Autowired @Qualifier("cacheSeconds") private Integer defaultCacheSeconds;
35 @Autowired @Qualifier("lastModified") private Long defaultLastModified;
38 public void init(CacheMethodHandle handle) {
39 CacheControl.tl.set(handle);
42 void init(Object handler, AccelerationWrapper wrapper) throws NoSuchMethodException {
43 CacheControl.tl.set(new ReflectionCacheMethodHandle(handler, wrapper == null ? false : wrapper.zipped));
46 public boolean decorate(
47 HttpServletRequest request,
48 HttpServletResponse response
52 CacheMethodHandle handle = CacheControl.tl.get();
54 /** Doppelte Ausführung verhindern... */
56 /** Dekoration wurde bereits durchgeführt! */
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
65 response.setDateHeader(Headers.HEADER_DATE, handle.getTimestamp());
67 /** Besondere Maßnahmen für besondere HTTP-Status-Codes ?!? */
68 int status = handle.accepts(request);
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... */
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
99 * Es ist nicht klar, was der Handler noch machen wird/muss:
100 * Antwort nicht dekorieren und Kontroller an den Handler übergeben...
105 if (handle.isZipped())
106 response.addHeader(Headers.HEADER_CONTENT_ENCODING, "gzip");
108 Map<String,String> headers = handle.getAdditionalHeaders(request);
109 for (String name : headers.keySet())
110 response.addHeader(name, headers.get(name));
113 if (log.isDebugEnabled()) {
114 if (request.getQueryString() == null) {
115 url = request.getRequestURI();
118 StringBuilder builder = new StringBuilder();
119 builder.append(request.getRequestURI());
121 builder.append(request.getQueryString());
122 url = builder.toString();
126 int cacheSeconds = handle.getCacheSeconds(request);
127 if (cacheSeconds < 1) {
128 log.debug("{}: caching disabled!", url);
129 response.setDateHeader(Headers.HEADER_DATE, handle.getTimestamp());
130 response.setDateHeader(Headers.HEADER_EXPIRES, 0);
131 response.addHeader(Headers.HEADER_PRAGMA, "no-cache");
132 response.addHeader(Headers.HEADER_CACHE_CONTROL, "private");
133 response.addHeader(Headers.HEADER_CACHE_CONTROL, "no-cache");
134 response.addHeader(Headers.HEADER_CACHE_CONTROL, "no-store");
135 response.addHeader(Headers.HEADER_CACHE_CONTROL, "max-age=0");
136 response.addHeader(Headers.HEADER_CACHE_CONTROL, "s-max-age=0");
140 long ifModifiedSince = -1;
142 ifModifiedSince = request.getDateHeader(Headers.HEADER_IF_MODIFIED_SINCE);
144 catch (Exception e) {
145 log.error("Exception while fetching If-Modified-Since: {}", e);
148 long lastModified = handle.getLastModified(request);
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!
155 lastModified = lastModified - (lastModified % 1000);
157 String ifNoneMatch = request.getHeader(Headers.HEADER_IF_NONE_MATCH);
158 String eTag = handle.getETag(request);
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.
167 StringBuilder builder = new StringBuilder();
168 if (handle.isETagWeak())
169 builder.append("W/");
171 builder.append(eTag);
173 response.setHeader(Headers.HEADER_ETAG, builder.toString());
177 if (ifModifiedSince >= lastModified && lastModified > 0) {
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.
186 if (log.isDebugEnabled())
187 log.debug("{}: Not modified since {}", url, new Date(ifModifiedSince));
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);
197 if (ifNoneMatch != null) {
198 boolean weak = false;
199 if (ifNoneMatch.startsWith("W/")) {
201 ifNoneMatch = ifNoneMatch.substring(3, ifNoneMatch.length() - 1);
204 ifNoneMatch = ifNoneMatch.substring(1, ifNoneMatch.length() - 1);
207 if (!weak || (request.getMethod().equals("GET") && request.getHeader(Headers.HEADER_RANGE) == null)) {
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...
213 if (ifNoneMatch.equals(eTag) && (handle.isETagWeak() || !weak)) {
214 log.debug("{}: ETag {} not changed -> 304 ", url, ifNoneMatch);
215 response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
220 log.warn("{}: ignoring weak ETag W/\"{}\", because the request was no GET-request or the Range-Header was present!", url, ifNoneMatch);
225 log.debug("{}: first up!", url);
227 /** HTTP/1.1-Caching-Header richtig setzen!! */
228 response.setDateHeader(Headers.HEADER_LAST_MODIFIED, lastModified);
230 /** Cache-Control für HTTP/1.1-Clients generieren */
231 Map<String, String> cacheControl = new TreeMap<String, String>();
234 * Wenn eins JSESSIONID in der URL enthalten ist, darf die Anfrage nur vom
235 * Browser gecached werden!
237 if (request.isRequestedSessionIdFromURL()) {
238 cacheControl.put("private", null);
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!
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.
250 cacheControl.put("max-age", Integer.toString(cacheSeconds));
251 response.setDateHeader(Headers.HEADER_EXPIRES, (handle.getTimestamp() + (long) cacheSeconds * 1000));
254 /** Dem Handler die Gelegenheit geben, den Cache-Controll-Header anzupassen */
255 handle.cacheControl(request, cacheControl);
258 if (cacheControl.containsKey("private")) {
260 * HTTP/1.0 Caches davon abhalten, die Ressource zu cachen (vgl.: RFC
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
267 response.setDateHeader(Headers.HEADER_EXPIRES, 0l);
268 response.addHeader(Headers.HEADER_PRAGMA, "no-cache");
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) {
277 builder.append(entry.getValue());
279 response.addHeader(Headers.HEADER_CACHE_CONTROL, builder.toString());
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
290 CacheControl.tl.set(null);
294 public void release() {
295 CacheControl.tl.set(null);
299 class ReflectionCacheMethodHandle implements CacheMethodHandle {
301 private Object handler;
302 private long now = System.currentTimeMillis();
303 private Integer cacheSeconds;
304 private Long lastModified;
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;
323 ReflectionCacheMethodHandle(Object handler, boolean zipped) throws NoSuchMethodException {
325 this.handler = handler;
326 this.zipped = zipped;
328 cacheSeconds = CacheControl.this.defaultCacheSeconds;
329 lastModified = CacheControl.this.defaultLastModified;
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;
339 if (annotation.annotationType().equals(LastModified.class)) {
340 lastModified = ((LastModified)annotation).value();
341 if (lastModified < 1) {
343 * Ein Last-Modified-Header wurde angefordert, aber es wurde kein
344 * statischer Wert spezifiziert:
345 * globalen statischen Default-Wert benutzen!
347 lastModified = defaultLastModified;
349 isLastModifiedMethodDefined = true;
352 if (annotation.annotationType().equals(ETag.class)) {
353 ETag eTagAnnotation = (ETag)annotation;
354 eTag = eTagAnnotation.value();
355 weak = eTagAnnotation.weak();
356 isETagMethodDefined = true;
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(':');
365 log.error("invalid header: [{}]", header);
368 String name = header.substring(0,i).trim();
369 String value = header.substring(i+1,header.length()).trim();
370 additionalHeaders.put(name, value);
373 isAdditionalHeadersMethodDefined = true;
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;
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;
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;
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!");
406 weak = ((ETag)annotation).weak();
407 isETagMethodDefined = true;
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;
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;
427 if (!isAdditionalHeadersMethodDefined)
428 additionalHeaders = new HashMap<String,String>();
433 public boolean isZipped() {
438 public long getTimestamp() {
443 public int accepts(HttpServletRequest request) throws IllegalArgumentException {
444 if (acceptsMethod == null) {
445 return HttpServletResponse.SC_OK;
449 return (Integer)acceptsMethod.invoke(handler, request);
451 catch (Exception e) {
452 throw new IllegalArgumentException(e);
458 public int getCacheSeconds(HttpServletRequest request) throws IllegalArgumentException {
459 if (cacheSecondsMethod == null) {
464 return (Integer)cacheSecondsMethod.invoke(handler, request);
466 catch (Exception e) {
467 throw new IllegalArgumentException(e);
473 public long getLastModified(HttpServletRequest request) throws IllegalArgumentException {
474 if (lastModifiedMethod == null) {
479 return (Long)lastModifiedMethod.invoke(handler, request);
481 catch (Exception e) {
482 throw new IllegalArgumentException(e);
488 public String getETag(HttpServletRequest request) throws IllegalArgumentException {
489 if (eTagMethod == null) {
494 return (String)eTagMethod.invoke(handler, request);
496 catch (Exception e) {
497 throw new IllegalArgumentException(e);
503 public boolean isETagWeak() {
508 public void cacheControl(
509 HttpServletRequest request,
510 Map<String, String> cacheControlMap
512 throws IllegalArgumentException
514 if (cacheControlMethod != null) {
516 cacheControlMethod.invoke(handler, request, cacheControlMap);
518 catch (Exception e) {
519 throw new IllegalArgumentException(e);
525 public Map<String,String> getAdditionalHeaders(HttpServletRequest request) throws IllegalArgumentException {
526 if (additionalHeadersMethod == null) {
527 return additionalHeaders;
531 return (Map<String,String>)additionalHeadersMethod.invoke(handler, request);
533 catch (Exception e) {
534 throw new IllegalArgumentException(e);