CacheControl so umgebaut, dass es sich über Annotationen einbinden lässt
[percentcodec] / cachecontrol / src / main / java / de / halbekunst / juplo / cachecontrol / CacheControl.java
diff --git a/cachecontrol/src/main/java/de/halbekunst/juplo/cachecontrol/CacheControl.java b/cachecontrol/src/main/java/de/halbekunst/juplo/cachecontrol/CacheControl.java
new file mode 100644 (file)
index 0000000..07f4c58
--- /dev/null
@@ -0,0 +1,481 @@
+package de.halbekunst.juplo.cachecontrol;
+
+import de.halbekunst.juplo.cachecontrol.annotations.CacheSeconds;
+import de.halbekunst.juplo.cachecontrol.annotations.Accepts;
+import de.halbekunst.juplo.cachecontrol.annotations.LastModified;
+import de.halbekunst.juplo.cachecontrol.annotations.ETag;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.Date;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.TreeMap;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ *
+ * @author kai
+ */
+public class CacheControl {
+  private final static Logger log = LoggerFactory.getLogger(CacheControl.class);
+
+  public static final String HEADER_DATE = "Date";
+  public static final String HEADER_CACHE_CONTROL = "Cache-Control";
+  public static final String HEADER_LAST_MODIFIED = "Last-Modified";
+  public static final String HEADER_ETAG = "ETag";
+  public static final String HEADER_EXPIRES = "Expires";
+  public static final String HEADER_PRAGMA = "Pragma";
+  public static final String HEADER_IF_MODIFIED_SINCE = "If-Modified-Since";
+  public static final String HEADER_IF_NONE_MATCH = "If-None-Match";
+
+  private static final ThreadLocal<CacheMethodHandle> tl = new ThreadLocal<CacheMethodHandle>();
+
+  private Integer defaultCacheSeconds;
+  private Long defaultLastModified;
+
+
+  public void init(Object handler) throws Exception {
+    if (CacheControl.tl.get() == null)
+      CacheControl.tl.set(new ReflectionCacheMethodHandle(handler));
+  }
+
+  public boolean decorate(
+      HttpServletRequest request,
+      HttpServletResponse response,
+      Object handler
+      ) throws Exception
+  {
+    try {
+    CacheMethodHandle controller = CacheControl.tl.get();
+
+    /** Doppelte Ausführung verhindern... */
+    if (controller == null) {
+      /** Dekoration wurde bereits durchgeführt! */
+      return true;
+    }
+
+    /**
+     * Alle Antworten (insbesondere auch 304) sollen nach dem {@plainlink
+     * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.18 RFC 2616,
+     * Abschnitt 14.18} einen Date-Header enthalten
+     */
+    response.setDateHeader(HEADER_DATE, controller.getTimestamp());
+
+    /** Besondere Maßnahmen für besondere HTTP-Status-Codes ?!? */
+    int status = controller.accepts(request);
+    switch (status) {
+      case HttpServletResponse.SC_OK: // 200
+      case HttpServletResponse.SC_NO_CONTENT: // 204
+      case HttpServletResponse.SC_PARTIAL_CONTENT: // 206
+        /** Normale Antwort! Antwort dekorieren... */
+        break;
+      case HttpServletResponse.SC_BAD_REQUEST: // 400
+      case HttpServletResponse.SC_UNAUTHORIZED: // 401
+      case HttpServletResponse.SC_PAYMENT_REQUIRED: // 402
+      case HttpServletResponse.SC_FORBIDDEN: // 403
+      case HttpServletResponse.SC_NOT_FOUND: // 404
+      case HttpServletResponse.SC_METHOD_NOT_ALLOWED: // 405
+      case HttpServletResponse.SC_NOT_ACCEPTABLE: // 406
+      case HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED: // 407
+      case HttpServletResponse.SC_REQUEST_TIMEOUT: // 408
+      case HttpServletResponse.SC_CONFLICT: // 409
+      case HttpServletResponse.SC_GONE: // 410
+      case HttpServletResponse.SC_LENGTH_REQUIRED: // 411
+      case HttpServletResponse.SC_PRECONDITION_FAILED: // 412
+      case HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE: // 413
+      case HttpServletResponse.SC_REQUEST_URI_TOO_LONG: // 414
+      case HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE: // 415
+      case HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE: // 416
+      case HttpServletResponse.SC_INTERNAL_SERVER_ERROR: // 500
+      case HttpServletResponse.SC_NOT_IMPLEMENTED: // 501
+      case HttpServletResponse.SC_SERVICE_UNAVAILABLE: // 503
+      case HttpServletResponse.SC_HTTP_VERSION_NOT_SUPPORTED: // 505
+        /**
+         * Ein Fehlercode kann stellvertretend für den Handler gesendet werden,
+         * da im Fehlerfall eh keine weiteren Daten ausgegeben werden!
+         */
+        response.sendError(status);
+        return true;
+      default:
+        /**
+         * Es ist nicht klar, was der Handler noch machen wird/muss:
+         * Antwort nicht dekorieren und Kontroller an den Handler übergeben...
+         */
+        return false;
+    }
+
+    String url = null;
+    if (log.isDebugEnabled()) {
+      if (request.getQueryString() == null) {
+        url = request.getRequestURI();
+      }
+      else {
+        StringBuilder builder = new StringBuilder();
+        builder.append(request.getRequestURI());
+        builder.append('?');
+        builder.append(request.getQueryString());
+        url = builder.toString();
+      }
+    }
+
+    int cacheSeconds = controller.getCacheSeconds(request);
+    if (cacheSeconds < 1) {
+      log.debug("{}: caching disabled!", url);
+      response.setDateHeader(HEADER_DATE, controller.getTimestamp());
+      response.setDateHeader(HEADER_EXPIRES, 0);
+      response.addHeader(HEADER_PRAGMA, "no-cache");
+      response.addHeader(HEADER_CACHE_CONTROL, "private");
+      response.addHeader(HEADER_CACHE_CONTROL, "no-cache");
+      response.addHeader(HEADER_CACHE_CONTROL, "no-store");
+      response.addHeader(HEADER_CACHE_CONTROL, "max-age=0");
+      response.addHeader(HEADER_CACHE_CONTROL, "s-max-age=0");
+      return true;
+    }
+
+    long ifModifiedSince = -1;
+    try {
+      ifModifiedSince = request.getDateHeader(HEADER_IF_MODIFIED_SINCE);
+    }
+    catch (Exception e) {
+      log.error("Exception while fetching If-Modified-Since: {}", e);
+    }
+
+    long lastModified = controller.getLastModified(request);
+
+    /**
+     * Sicherstellen, dass der Wert keine Millisekunden enthält, da die
+     * Zeitangabe aus dem Modified-Since-Header keine Millisekunden enthalten
+     * kann und der Test unten dann stets fehlschlagen würde!
+     */
+    lastModified = lastModified - (lastModified % 1000);
+
+    String ifNoneMatch = request.getHeader(HEADER_IF_NONE_MATCH);
+    String eTag = controller.getETag(request);
+
+    /**
+     * 304-Antworten sollen nach dem {@plainlink
+     * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5 RFC
+     * 2616, Abschnitt 10.3.5} einen ETag-Header enthalten, wenn auch die
+     * 200-Antwort einen enthalten hätte.
+     */
+    if (eTag != null)
+      response.setHeader(HEADER_ETAG, eTag);
+
+
+    if (ifModifiedSince >= lastModified && lastModified > 0) {
+      /**
+       * request.getDateHeader liefert die Zeit als long, oder -1, wenn der
+       * Header nicht existiert. D.h., wenn "If-Modified-Since" nicht gesetzt
+       * ist, wird die komplette Seite ausgeliefert.
+       * Der zusätzliche Test, ob lastModified größer 0 ist, ist nötig, um
+       * Fehler auszuschließen, wenn die Implementierung von Cachable
+       * negative Werte für Last-Modified zurückliefert.
+       */
+      if (log.isDebugEnabled())
+        log.debug("{}: Not modified since {}", url, new Date(ifModifiedSince));
+
+      if (ifNoneMatch == null) {
+        /** Neue Anfrage oder HTTP/1.0 Client! */
+        log.debug("{}: ETag nicht gesetzt -> 304", url);
+        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
+        return false;
+      }
+    }
+
+    if (ifNoneMatch != null && ifNoneMatch.equals(eTag)) {
+      log.debug("{}: ETag {} not changed -> 304 ", url, ifNoneMatch);
+      response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
+      return false;
+    }
+
+
+    log.debug("{}: first up!", url);
+
+    /** HTTP/1.1-Caching-Header richtig setzen!! */
+    response.setDateHeader(HEADER_LAST_MODIFIED, lastModified);
+
+    /** Cache-Control für HTTP/1.1-Clients generieren */
+    Map<String, String> cacheControl = new TreeMap<String, String>();
+
+    /**
+     * Wenn eins JSESSIONID in der URL enthalten ist, darf die Anfrage nur vom
+     * Browser gecached werden!
+     */
+    if (request.isRequestedSessionIdFromURL()) {
+      cacheControl.put("private", null);
+    }
+    else {
+      /**
+       * Hier muss nicht geprüft werden, ob cacheSeconds > 0 gilt, da in diesem
+       * Fall oben bereits No-Cache-Header generiert und <code>false</code>
+       * zurückgeliefert werden!
+       *
+       * Den Wert als <code>max-age</code> zu den Schlüssel-Wert-Paaren für den
+       * <code>Cache-Control</code>-Header hinzufügen und einen entsprechenden
+       * <code>Expires</code>-Header für HTTP/1.0-Clients setzen.
+       */
+      cacheControl.put("max-age", Integer.toString(cacheSeconds));
+      response.setDateHeader(HEADER_EXPIRES, (controller.getTimestamp() + (long) cacheSeconds * 1000));
+    }
+
+    /** Dem Handler die Gelegenheit geben, den Cache-Controll-Header anzupassen */
+    controller.cacheControl(request, cacheControl);
+
+
+    if (cacheControl.containsKey("private")) {
+      /**
+       * HTTP/1.0 Caches davon abhalten, die Ressource zu cachen (vgl.: RFC
+       * 2616, {@plainlink
+       * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.3
+       * Abschnitt 14.9.3} und {@plainlink
+       * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.32
+       * Abschnitt 14.32})
+       */
+      response.setDateHeader(HEADER_EXPIRES, 0l);
+      response.addHeader(HEADER_PRAGMA, "no-cache");
+    }
+
+    StringBuilder builder = new StringBuilder();
+    for (Entry<String, String> entry : cacheControl.entrySet()) {
+      builder.setLength(0);
+      builder.append(entry.getKey());
+      if (entry.getValue() != null) {
+        builder.append('=');
+        builder.append(entry.getValue());
+      }
+      response.addHeader(HEADER_CACHE_CONTROL, builder.toString());
+    }
+
+    return true;
+    }
+    finally {
+      /**
+       * Thread-Locale-Variable zurücksetzen, damit
+       * 1.) ein doppelter Aufruf dieser Methode pro Request erkannt werden kann
+       * 2.) der nächste Request nicht mit dem selben Handle weiterarbeitet
+       */
+      CacheControl.tl.set(null);
+    }
+  }
+
+  public void release() {
+    CacheControl.tl.set(null);
+  }
+
+
+  interface CacheMethodHandle {
+    long getTimestamp();
+    int accepts(HttpServletRequest request) throws Exception;
+    int getCacheSeconds(HttpServletRequest request) throws Exception;
+    long getLastModified(HttpServletRequest request) throws Exception;
+    String getETag(HttpServletRequest request) throws Exception;
+    void cacheControl(HttpServletRequest request, Map<String, String> cacheControlMap) throws Exception;
+  }
+
+  class DefaultCacheMethodHandle implements CacheMethodHandle {
+
+    long now = System.currentTimeMillis();
+    Integer cacheSeconds;
+    Long lastModified;
+    String eTag;
+
+
+    DefaultCacheMethodHandle() {
+      this.cacheSeconds = CacheControl.this.defaultCacheSeconds;
+      this.lastModified = CacheControl.this.defaultLastModified;
+      this.eTag = null;
+    }
+
+
+    @Override
+    public long getTimestamp() {
+      return now;
+    }
+
+    @Override
+    public int accepts(HttpServletRequest request) {
+      return HttpServletResponse.SC_OK;
+    }
+
+    @Override
+    public int getCacheSeconds(HttpServletRequest request) {
+      return cacheSeconds;
+    }
+
+    @Override
+    public long getLastModified(HttpServletRequest request) {
+      return lastModified;
+    }
+
+    @Override
+    public String getETag(HttpServletRequest request) {
+      return eTag;
+    }
+
+    @Override
+    public void cacheControl(HttpServletRequest request, Map<String, String> cacheControlMap) {
+    }
+  }
+
+  class ReflectionCacheMethodHandle implements CacheMethodHandle {
+
+    private Object handler;
+    private DefaultCacheMethodHandle defaults = new DefaultCacheMethodHandle();
+    private Method accepts, cacheSeconds, lastModified, eTag, cacheControl;
+    private boolean isAcceptsDefined, isCacheSecondsDefined, isLastModifiedDefined, isETagDefined, isCacheControlDefined;
+
+
+    ReflectionCacheMethodHandle(Object handler) throws NoSuchMethodException {
+      this.handler = handler;
+      /** Class-Level-Annotations auslesen */
+      for (Annotation annotation : handler.getClass().getAnnotations()) {
+        if (annotation.annotationType().equals(CacheSeconds.class)) {
+          defaults.cacheSeconds = ((CacheSeconds)annotation).value();
+          isCacheSecondsDefined = true;
+          continue;
+        }
+        if (annotation.annotationType().equals(LastModified.class)) {
+          defaults.lastModified = ((LastModified)annotation).value();
+          if (defaults.lastModified < 1) {
+            /**
+             * Ein Last-Modified-Header wurde angefordert, aber es wurde kein
+             * statischer Wert spezifiziert:
+             * globalen statischen Default-Wert benutzen!
+             */
+            defaults.lastModified = defaultLastModified;
+          }
+          isLastModifiedDefined = true;
+          continue;
+        }
+        if (annotation.annotationType().equals(ETag.class)) {
+          defaults.eTag = ((ETag)annotation).value();
+          isETagDefined = true;
+          continue;
+        }
+      }
+
+      /** Method-Level-Annotations auslesen */
+      for (Method method : handler.getClass().getMethods()) {
+        for (Annotation annotation : method.getAnnotations()) {
+          if (annotation.annotationType().equals(Accepts.class)) {
+            if (isAcceptsDefined)
+              throw new IllegalArgumentException("Die Annotation @Accept wurde in der Klasse " + handler.getClass().getSimpleName() + " mehrfach verwendet!");
+            accepts = method;
+            isAcceptsDefined = true;
+            continue;
+          }
+          if (annotation.annotationType().equals(CacheSeconds.class)) {
+            if (isCacheSecondsDefined)
+              throw new IllegalArgumentException("Die Annotation @CacheSeconds wurde in der Klasse " + handler.getClass().getSimpleName() + " mehrfach verwendet!");
+            cacheSeconds = method;
+            isCacheSecondsDefined = true;
+            continue;
+          }
+          if (annotation.annotationType().equals(LastModified.class)) {
+            if (isLastModifiedDefined)
+              throw new IllegalArgumentException("Die Annotation @LastModified wurde in der Klasse " + handler.getClass().getSimpleName() + " mehrfach verwendet!");
+            lastModified = method;
+            isLastModifiedDefined = true;
+            continue;
+          }
+          if (annotation.annotationType().equals(ETag.class)) {
+            if (isETagDefined)
+              throw new IllegalArgumentException("Die Annotation @ETag wurde in der Klasse " + handler.getClass().getSimpleName() + " mehrfach verwendet!");
+            eTag = method;
+            isETagDefined = true;
+            continue;
+          }
+          if (annotation.annotationType().equals(de.halbekunst.juplo.cachecontrol.annotations.CacheControl.class)) {
+            if (isCacheControlDefined)
+              throw new IllegalArgumentException("Die Annotation @CacheControl wurde in der Klasse " + handler.getClass().getSimpleName() + " mehrfach verwendet!");
+            cacheControl = method;
+            isCacheControlDefined = true;
+            continue;
+          }
+        }
+      }
+    }
+
+
+    @Override
+    public long getTimestamp() {
+      return defaults.now;
+    }
+
+    @Override
+    public int accepts(HttpServletRequest request)
+        throws IllegalAccessException,
+               IllegalArgumentException,
+               InvocationTargetException
+    {
+      if (accepts == null)
+        return defaults.accepts(request);
+      else
+        return (Integer)accepts.invoke(handler, request);
+    }
+
+    @Override
+    public int getCacheSeconds(HttpServletRequest request)
+        throws IllegalAccessException,
+               IllegalArgumentException,
+               InvocationTargetException
+    {
+      if (cacheSeconds == null)
+        return defaults.getCacheSeconds(request);
+      else
+        return (Integer)cacheSeconds.invoke(handler, request);
+    }
+
+    @Override
+    public long getLastModified(HttpServletRequest request)
+        throws IllegalAccessException,
+               IllegalArgumentException,
+               InvocationTargetException
+    {
+      if (lastModified == null)
+        return defaults.getLastModified(request);
+      else
+        return (Long)lastModified.invoke(handler, request);
+    }
+
+    @Override
+    public String getETag(HttpServletRequest request)
+        throws IllegalAccessException,
+               IllegalArgumentException,
+               InvocationTargetException
+    {
+      if (eTag == null)
+        return defaults.getETag(request);
+      else
+        return (String)eTag.invoke(handler, request);
+    }
+
+    @Override
+    public void cacheControl(
+        HttpServletRequest request,
+        Map<String, String> cacheControlMap
+        )
+        throws IllegalAccessException,
+               IllegalArgumentException,
+               InvocationTargetException
+    {
+      if (cacheControl == null)
+        defaults.cacheControl(request, cacheControlMap);
+      else
+        cacheControl.invoke(handler, request, cacheControlMap);
+    }
+  }
+
+
+  public void setDefaultCacheSeconds(Integer defaultCacheSeconds) {
+    this.defaultCacheSeconds = defaultCacheSeconds;
+  }
+
+  public void setDefaultLastModified(Long defaultLastModified) {
+    this.defaultLastModified = defaultLastModified;
+  }
+}