1 package de.halbekunst.juplo.cachecontrol;
3 import de.halbekunst.juplo.cachecontrol.annotations.CacheSeconds;
4 import de.halbekunst.juplo.cachecontrol.annotations.Accepts;
5 import de.halbekunst.juplo.cachecontrol.annotations.LastModified;
6 import de.halbekunst.juplo.cachecontrol.annotations.ETag;
7 import java.lang.annotation.Annotation;
8 import java.lang.reflect.InvocationTargetException;
9 import java.lang.reflect.Method;
10 import java.util.Date;
12 import java.util.Map.Entry;
13 import java.util.TreeMap;
14 import javax.servlet.http.HttpServletRequest;
15 import javax.servlet.http.HttpServletResponse;
16 import org.slf4j.Logger;
17 import org.slf4j.LoggerFactory;
23 public class CacheControl {
24 private final static Logger log = LoggerFactory.getLogger(CacheControl.class);
26 public static final String HEADER_DATE = "Date";
27 public static final String HEADER_CACHE_CONTROL = "Cache-Control";
28 public static final String HEADER_LAST_MODIFIED = "Last-Modified";
29 public static final String HEADER_ETAG = "ETag";
30 public static final String HEADER_EXPIRES = "Expires";
31 public static final String HEADER_PRAGMA = "Pragma";
32 public static final String HEADER_IF_MODIFIED_SINCE = "If-Modified-Since";
33 public static final String HEADER_IF_NONE_MATCH = "If-None-Match";
34 public static final String HEADER_RANGE = "Range";
36 private static final ThreadLocal<CacheMethodHandle> tl = new ThreadLocal<CacheMethodHandle>();
38 private Integer defaultCacheSeconds;
39 private Long defaultLastModified;
42 public void init(Object handler) throws Exception {
43 if (CacheControl.tl.get() == null)
44 CacheControl.tl.set(new ReflectionCacheMethodHandle(handler));
47 public boolean decorate(
48 HttpServletRequest request,
49 HttpServletResponse response,
54 CacheMethodHandle controller = CacheControl.tl.get();
56 /** Doppelte Ausführung verhindern... */
57 if (controller == null) {
58 /** Dekoration wurde bereits durchgeführt! */
63 * Alle Antworten (insbesondere auch 304) sollen nach dem {@plainlink
64 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.18 RFC 2616,
65 * Abschnitt 14.18} einen Date-Header enthalten
67 response.setDateHeader(HEADER_DATE, controller.getTimestamp());
69 /** Besondere Maßnahmen für besondere HTTP-Status-Codes ?!? */
70 int status = controller.accepts(request);
72 case HttpServletResponse.SC_OK: // 200
73 case HttpServletResponse.SC_NO_CONTENT: // 204
74 case HttpServletResponse.SC_PARTIAL_CONTENT: // 206
75 /** Normale Antwort! Antwort dekorieren... */
77 case HttpServletResponse.SC_BAD_REQUEST: // 400
78 case HttpServletResponse.SC_UNAUTHORIZED: // 401
79 case HttpServletResponse.SC_PAYMENT_REQUIRED: // 402
80 case HttpServletResponse.SC_FORBIDDEN: // 403
81 case HttpServletResponse.SC_NOT_FOUND: // 404
82 case HttpServletResponse.SC_METHOD_NOT_ALLOWED: // 405
83 case HttpServletResponse.SC_NOT_ACCEPTABLE: // 406
84 case HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED: // 407
85 case HttpServletResponse.SC_REQUEST_TIMEOUT: // 408
86 case HttpServletResponse.SC_CONFLICT: // 409
87 case HttpServletResponse.SC_GONE: // 410
88 case HttpServletResponse.SC_LENGTH_REQUIRED: // 411
89 case HttpServletResponse.SC_PRECONDITION_FAILED: // 412
90 case HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE: // 413
91 case HttpServletResponse.SC_REQUEST_URI_TOO_LONG: // 414
92 case HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE: // 415
93 case HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE: // 416
94 case HttpServletResponse.SC_INTERNAL_SERVER_ERROR: // 500
95 case HttpServletResponse.SC_NOT_IMPLEMENTED: // 501
96 case HttpServletResponse.SC_SERVICE_UNAVAILABLE: // 503
97 case HttpServletResponse.SC_HTTP_VERSION_NOT_SUPPORTED: // 505
99 * Ein Fehlercode kann stellvertretend für den Handler gesendet werden,
100 * da im Fehlerfall eh keine weiteren Daten ausgegeben werden!
102 response.sendError(status);
106 * Es ist nicht klar, was der Handler noch machen wird/muss:
107 * Antwort nicht dekorieren und Kontroller an den Handler übergeben...
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 = controller.getCacheSeconds(request);
127 if (cacheSeconds < 1) {
128 log.debug("{}: caching disabled!", url);
129 response.setDateHeader(HEADER_DATE, controller.getTimestamp());
130 response.setDateHeader(HEADER_EXPIRES, 0);
131 response.addHeader(HEADER_PRAGMA, "no-cache");
132 response.addHeader(HEADER_CACHE_CONTROL, "private");
133 response.addHeader(HEADER_CACHE_CONTROL, "no-cache");
134 response.addHeader(HEADER_CACHE_CONTROL, "no-store");
135 response.addHeader(HEADER_CACHE_CONTROL, "max-age=0");
136 response.addHeader(HEADER_CACHE_CONTROL, "s-max-age=0");
140 long ifModifiedSince = -1;
142 ifModifiedSince = request.getDateHeader(HEADER_IF_MODIFIED_SINCE);
144 catch (Exception e) {
145 log.error("Exception while fetching If-Modified-Since: {}", e);
148 long lastModified = controller.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(HEADER_IF_NONE_MATCH);
158 String eTag = controller.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 (controller.isETagWeak())
169 builder.append("W/");
171 builder.append(eTag);
173 response.setHeader(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(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) && (controller.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(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(HEADER_EXPIRES, (controller.getTimestamp() + (long) cacheSeconds * 1000));
254 /** Dem Handler die Gelegenheit geben, den Cache-Controll-Header anzupassen */
255 controller.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(HEADER_EXPIRES, 0l);
268 response.addHeader(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(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 interface CacheMethodHandle {
301 int accepts(HttpServletRequest request) throws Exception;
302 int getCacheSeconds(HttpServletRequest request) throws Exception;
303 long getLastModified(HttpServletRequest request) throws Exception;
304 String getETag(HttpServletRequest request) throws Exception;
305 boolean isETagWeak();
306 void cacheControl(HttpServletRequest request, Map<String, String> cacheControlMap) throws Exception;
310 class ReflectionCacheMethodHandle implements CacheMethodHandle {
312 private Object handler;
313 private long now = System.currentTimeMillis();
314 private Integer cacheSeconds;
315 private Long lastModified;
317 private Method acceptsMethod;
318 private Method cacheSecondsMethod;
319 private Method lastModifiedMethod;
320 private Method eTagMethod;
321 private Method cacheControlMethod;
322 private boolean isAcceptsMethodDefined;
323 private boolean isCacheSecondsMethodDefined;
324 private boolean isLastModifiedMethodDefined;
325 private boolean isETagMethodDefined;
326 private boolean isCacheControlMethodDefined;
327 private boolean weak;
330 ReflectionCacheMethodHandle(Object handler) throws NoSuchMethodException {
332 this.handler = handler;
334 cacheSeconds = CacheControl.this.defaultCacheSeconds;
335 lastModified = CacheControl.this.defaultLastModified;
338 /** Class-Level-Annotations auslesen */
339 for (Annotation annotation : handler.getClass().getAnnotations()) {
340 if (annotation.annotationType().equals(CacheSeconds.class)) {
341 cacheSeconds = ((CacheSeconds)annotation).value();
342 isCacheSecondsMethodDefined = true;
345 if (annotation.annotationType().equals(LastModified.class)) {
346 lastModified = ((LastModified)annotation).value();
347 if (lastModified < 1) {
349 * Ein Last-Modified-Header wurde angefordert, aber es wurde kein
350 * statischer Wert spezifiziert:
351 * globalen statischen Default-Wert benutzen!
353 lastModified = defaultLastModified;
355 isLastModifiedMethodDefined = true;
358 if (annotation.annotationType().equals(ETag.class)) {
359 ETag eTagAnnotation = (ETag)annotation;
360 eTag = eTagAnnotation.value();
361 weak = eTagAnnotation.weak();
362 isETagMethodDefined = true;
367 /** Method-Level-Annotations auslesen */
368 for (Method method : handler.getClass().getMethods()) {
369 for (Annotation annotation : method.getAnnotations()) {
370 if (annotation.annotationType().equals(Accepts.class)) {
371 if (isAcceptsMethodDefined)
372 throw new IllegalArgumentException("Die Annotation @Accept wurde in der Klasse " + handler.getClass().getSimpleName() + " mehrfach verwendet!");
373 acceptsMethod = method;
374 isAcceptsMethodDefined = true;
377 if (annotation.annotationType().equals(CacheSeconds.class)) {
378 if (isCacheSecondsMethodDefined)
379 throw new IllegalArgumentException("Die Annotation @CacheSeconds wurde in der Klasse " + handler.getClass().getSimpleName() + " mehrfach verwendet!");
380 cacheSecondsMethod = method;
381 isCacheSecondsMethodDefined = true;
384 if (annotation.annotationType().equals(LastModified.class)) {
385 if (isLastModifiedMethodDefined)
386 throw new IllegalArgumentException("Die Annotation @LastModified wurde in der Klasse " + handler.getClass().getSimpleName() + " mehrfach verwendet!");
387 lastModifiedMethod = method;
388 isLastModifiedMethodDefined = true;
391 if (annotation.annotationType().equals(ETag.class)) {
392 if (isETagMethodDefined)
393 throw new IllegalArgumentException("Die Annotation @ETag wurde in der Klasse " + handler.getClass().getSimpleName() + " mehrfach verwendet!");
395 weak = ((ETag)annotation).weak();
396 isETagMethodDefined = true;
399 if (annotation.annotationType().equals(de.halbekunst.juplo.cachecontrol.annotations.CacheControl.class)) {
400 if (isCacheControlMethodDefined)
401 throw new IllegalArgumentException("Die Annotation @CacheControl wurde in der Klasse " + handler.getClass().getSimpleName() + " mehrfach verwendet!");
402 cacheControlMethod = method;
403 isCacheControlMethodDefined = true;
412 public long getTimestamp() {
417 public int accepts(HttpServletRequest request)
418 throws IllegalAccessException,
419 IllegalArgumentException,
420 InvocationTargetException
422 if (acceptsMethod == null)
423 return HttpServletResponse.SC_OK;
425 return (Integer)acceptsMethod.invoke(handler, request);
429 public int getCacheSeconds(HttpServletRequest request)
430 throws IllegalAccessException,
431 IllegalArgumentException,
432 InvocationTargetException
434 if (cacheSecondsMethod == null)
437 return (Integer)cacheSecondsMethod.invoke(handler, request);
441 public long getLastModified(HttpServletRequest request)
442 throws IllegalAccessException,
443 IllegalArgumentException,
444 InvocationTargetException
446 if (lastModifiedMethod == null)
449 return (Long)lastModifiedMethod.invoke(handler, request);
453 public String getETag(HttpServletRequest request)
454 throws IllegalAccessException,
455 IllegalArgumentException,
456 InvocationTargetException
458 if (eTagMethod == null)
461 return (String)eTagMethod.invoke(handler, request);
465 public boolean isETagWeak() {
470 public void cacheControl(
471 HttpServletRequest request,
472 Map<String, String> cacheControlMap
474 throws IllegalAccessException,
475 IllegalArgumentException,
476 InvocationTargetException
478 if (cacheControlMethod != null)
479 cacheControlMethod.invoke(handler, request, cacheControlMap);
484 public void setDefaultCacheSeconds(Integer defaultCacheSeconds) {
485 this.defaultCacheSeconds = defaultCacheSeconds;
488 public void setDefaultLastModified(Long defaultLastModified) {
489 this.defaultLastModified = defaultLastModified;