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
98 * Es ist nicht klar, was der Handler noch machen wird/muss:
99 * Antwort nicht dekorieren und Kontroller an den Handler übergeben...
104 Map<String,String> headers = handle.getAdditionalHeaders(request);
105 for (String name : headers.keySet())
106 response.addHeader(name, headers.get(name));
109 if (log.isDebugEnabled()) {
110 if (request.getQueryString() == null) {
111 url = request.getRequestURI();
114 StringBuilder builder = new StringBuilder();
115 builder.append(request.getRequestURI());
117 builder.append(request.getQueryString());
118 url = builder.toString();
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");
136 long ifModifiedSince = -1;
138 ifModifiedSince = request.getDateHeader(Headers.HEADER_IF_MODIFIED_SINCE);
140 catch (Exception e) {
141 log.error("Exception while fetching If-Modified-Since: {}", e);
144 long lastModified = handle.getLastModified(request);
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!
151 lastModified = lastModified - (lastModified % 1000);
153 String ifNoneMatch = request.getHeader(Headers.HEADER_IF_NONE_MATCH);
154 String eTag = handle.getETag(request);
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.
163 StringBuilder builder = new StringBuilder();
164 if (handle.isETagWeak())
165 builder.append("W/");
167 builder.append(eTag);
169 response.setHeader(Headers.HEADER_ETAG, builder.toString());
173 if (ifModifiedSince >= lastModified && lastModified > 0) {
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.
182 if (log.isDebugEnabled())
183 log.debug("{}: Not modified since {}", url, new Date(ifModifiedSince));
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);
193 if (ifNoneMatch != null) {
194 boolean weak = false;
195 if (ifNoneMatch.startsWith("W/")) {
197 ifNoneMatch = ifNoneMatch.substring(3, ifNoneMatch.length() - 1);
200 ifNoneMatch = ifNoneMatch.substring(1, ifNoneMatch.length() - 1);
203 if (!weak || (request.getMethod().equals("GET") && request.getHeader(Headers.HEADER_RANGE) == null)) {
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...
209 if (ifNoneMatch.equals(eTag) && (handle.isETagWeak() || !weak)) {
210 log.debug("{}: ETag {} not changed -> 304 ", url, ifNoneMatch);
211 response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
216 log.warn("{}: ignoring weak ETag W/\"{}\", because the request was no GET-request or the Range-Header was present!", url, ifNoneMatch);
221 log.debug("{}: first up!", url);
223 if (handle.isZipped())
224 response.addHeader(Headers.HEADER_CONTENT_ENCODING, "gzip");
226 /** HTTP/1.1-Caching-Header richtig setzen!! */
227 response.setDateHeader(Headers.HEADER_LAST_MODIFIED, lastModified);
229 /** Cache-Control für HTTP/1.1-Clients generieren */
230 Map<String, String> cacheControl = new TreeMap<String, String>();
233 * Wenn eins JSESSIONID in der URL enthalten ist, darf die Anfrage nur vom
234 * Browser gecached werden!
236 if (request.isRequestedSessionIdFromURL()) {
237 cacheControl.put("private", null);
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!
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.
249 cacheControl.put("max-age", Integer.toString(cacheSeconds));
250 response.setDateHeader(Headers.HEADER_EXPIRES, (handle.getTimestamp() + (long) cacheSeconds * 1000));
253 /** Dem Handler die Gelegenheit geben, den Cache-Controll-Header anzupassen */
254 handle.cacheControl(request, cacheControl);
257 if (cacheControl.containsKey("private")) {
259 * HTTP/1.0 Caches davon abhalten, die Ressource zu cachen (vgl.: RFC
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
266 response.setDateHeader(Headers.HEADER_EXPIRES, 0l);
267 response.addHeader(Headers.HEADER_PRAGMA, "no-cache");
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) {
276 builder.append(entry.getValue());
278 response.addHeader(Headers.HEADER_CACHE_CONTROL, builder.toString());
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
289 CacheControl.tl.set(null);
293 public void release() {
294 CacheControl.tl.set(null);
298 class ReflectionCacheMethodHandle implements CacheMethodHandle {
300 private Object handler;
301 private long now = System.currentTimeMillis();
302 private Integer cacheSeconds;
303 private Long lastModified;
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;
322 ReflectionCacheMethodHandle(Object handler, boolean zipped) throws NoSuchMethodException {
324 this.handler = handler;
325 this.zipped = zipped;
327 cacheSeconds = CacheControl.this.defaultCacheSeconds;
328 lastModified = CacheControl.this.defaultLastModified;
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;
338 if (annotation.annotationType().equals(LastModified.class)) {
339 lastModified = ((LastModified)annotation).value();
340 if (lastModified < 1) {
342 * Ein Last-Modified-Header wurde angefordert, aber es wurde kein
343 * statischer Wert spezifiziert:
344 * globalen statischen Default-Wert benutzen!
346 lastModified = defaultLastModified;
348 isLastModifiedMethodDefined = true;
351 if (annotation.annotationType().equals(ETag.class)) {
352 ETag eTagAnnotation = (ETag)annotation;
353 eTag = eTagAnnotation.value();
354 weak = eTagAnnotation.weak();
355 isETagMethodDefined = true;
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(':');
364 log.error("invalid header: [{}]", header);
367 String name = header.substring(0,i).trim();
368 String value = header.substring(i+1,header.length()).trim();
369 additionalHeaders.put(name, value);
372 isAdditionalHeadersMethodDefined = true;
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;
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;
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;
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!");
405 weak = ((ETag)annotation).weak();
406 isETagMethodDefined = true;
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;
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;
426 if (!isAdditionalHeadersMethodDefined)
427 additionalHeaders = new HashMap<String,String>();
432 public boolean isZipped() {
437 public long getTimestamp() {
442 public int accepts(HttpServletRequest request) throws IllegalArgumentException {
443 if (acceptsMethod == null) {
444 return HttpServletResponse.SC_OK;
448 return (Integer)acceptsMethod.invoke(handler, request);
450 catch (Exception e) {
451 throw new IllegalArgumentException(e);
457 public int getCacheSeconds(HttpServletRequest request) throws IllegalArgumentException {
458 if (cacheSecondsMethod == null) {
463 return (Integer)cacheSecondsMethod.invoke(handler, request);
465 catch (Exception e) {
466 throw new IllegalArgumentException(e);
472 public long getLastModified(HttpServletRequest request) throws IllegalArgumentException {
473 if (lastModifiedMethod == null) {
478 return (Long)lastModifiedMethod.invoke(handler, request);
480 catch (Exception e) {
481 throw new IllegalArgumentException(e);
487 public String getETag(HttpServletRequest request) throws IllegalArgumentException {
488 if (eTagMethod == null) {
493 return (String)eTagMethod.invoke(handler, request);
495 catch (Exception e) {
496 throw new IllegalArgumentException(e);
502 public boolean isETagWeak() {
507 public void cacheControl(
508 HttpServletRequest request,
509 Map<String, String> cacheControlMap
511 throws IllegalArgumentException
513 if (cacheControlMethod != null) {
515 cacheControlMethod.invoke(handler, request, cacheControlMap);
517 catch (Exception e) {
518 throw new IllegalArgumentException(e);
524 public Map<String,String> getAdditionalHeaders(HttpServletRequest request) throws IllegalArgumentException {
525 if (additionalHeadersMethod == null) {
526 return additionalHeaders;
530 return (Map<String,String>)additionalHeadersMethod.invoke(handler, request);
532 catch (Exception e) {
533 throw new IllegalArgumentException(e);