X-Git-Url: https://juplo.de/gitweb/?p=percentcodec;a=blobdiff_plain;f=cachecontrol%2Fsrc%2Fmain%2Fjava%2Fde%2Fhalbekunst%2Fjuplo%2Fcachecontrol%2FCacheControl.java;h=0512de4a0a84cd7301e78c2c015dc6ab21e7580b;hp=07f4c58e13875f745f3380adf7a51610fdcc70dc;hb=2ae9a9d1011d3cb6cb0a172b629cb390c4fdf0ea;hpb=75b55d74f57705c6c5ebee2bcd66c87f3f09089d diff --git a/cachecontrol/src/main/java/de/halbekunst/juplo/cachecontrol/CacheControl.java b/cachecontrol/src/main/java/de/halbekunst/juplo/cachecontrol/CacheControl.java index 07f4c58e..0512de4a 100644 --- a/cachecontrol/src/main/java/de/halbekunst/juplo/cachecontrol/CacheControl.java +++ b/cachecontrol/src/main/java/de/halbekunst/juplo/cachecontrol/CacheControl.java @@ -1,13 +1,15 @@ package de.halbekunst.juplo.cachecontrol; +import de.halbekunst.juplo.cachecontrol.AcceleratorFilter.AccelerationWrapper; import de.halbekunst.juplo.cachecontrol.annotations.CacheSeconds; import de.halbekunst.juplo.cachecontrol.annotations.Accepts; +import de.halbekunst.juplo.cachecontrol.annotations.AdditionalHeaders; 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.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; @@ -15,45 +17,43 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Component; /** * * @author kai */ +@Component 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 tl = new ThreadLocal(); - private Integer defaultCacheSeconds; - private Long defaultLastModified; + @Autowired @Qualifier("cacheSeconds") private Integer defaultCacheSeconds; + @Autowired @Qualifier("lastModified") private Long defaultLastModified; + + public void init(CacheMethodHandle handle) { + CacheControl.tl.set(handle); + } - public void init(Object handler) throws Exception { - if (CacheControl.tl.get() == null) - CacheControl.tl.set(new ReflectionCacheMethodHandle(handler)); + void init(Object handler, AccelerationWrapper wrapper) throws NoSuchMethodException { + CacheControl.tl.set(new ReflectionCacheMethodHandle(handler, wrapper == null ? false : wrapper.zipped)); } public boolean decorate( HttpServletRequest request, HttpServletResponse response, Object handler - ) throws Exception + ) { try { - CacheMethodHandle controller = CacheControl.tl.get(); + CacheMethodHandle handle = CacheControl.tl.get(); /** Doppelte Ausführung verhindern... */ - if (controller == null) { + if (handle == null) { /** Dekoration wurde bereits durchgeführt! */ return true; } @@ -63,10 +63,10 @@ public class CacheControl { * 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()); + response.setDateHeader(Headers.HEADER_DATE, handle.getTimestamp()); /** Besondere Maßnahmen für besondere HTTP-Status-Codes ?!? */ - int status = controller.accepts(request); + int status = handle.accepts(request); switch (status) { case HttpServletResponse.SC_OK: // 200 case HttpServletResponse.SC_NO_CONTENT: // 204 @@ -94,11 +94,6 @@ public class CacheControl { 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: /** @@ -108,6 +103,13 @@ public class CacheControl { return false; } + if (handle.isZipped()) + response.addHeader(Headers.HEADER_CONTENT_ENCODING, "gzip"); + + Map headers = handle.getAdditionalHeaders(request); + for (String name : headers.keySet()) + response.addHeader(name, headers.get(name)); + String url = null; if (log.isDebugEnabled()) { if (request.getQueryString() == null) { @@ -122,29 +124,29 @@ public class CacheControl { } } - int cacheSeconds = controller.getCacheSeconds(request); + int cacheSeconds = handle.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"); + response.setDateHeader(Headers.HEADER_DATE, handle.getTimestamp()); + response.setDateHeader(Headers.HEADER_EXPIRES, 0); + response.addHeader(Headers.HEADER_PRAGMA, "no-cache"); + response.addHeader(Headers.HEADER_CACHE_CONTROL, "private"); + response.addHeader(Headers.HEADER_CACHE_CONTROL, "no-cache"); + response.addHeader(Headers.HEADER_CACHE_CONTROL, "no-store"); + response.addHeader(Headers.HEADER_CACHE_CONTROL, "max-age=0"); + response.addHeader(Headers.HEADER_CACHE_CONTROL, "s-max-age=0"); return true; } long ifModifiedSince = -1; try { - ifModifiedSince = request.getDateHeader(HEADER_IF_MODIFIED_SINCE); + ifModifiedSince = request.getDateHeader(Headers.HEADER_IF_MODIFIED_SINCE); } catch (Exception e) { log.error("Exception while fetching If-Modified-Since: {}", e); } - long lastModified = controller.getLastModified(request); + long lastModified = handle.getLastModified(request); /** * Sicherstellen, dass der Wert keine Millisekunden enthält, da die @@ -153,8 +155,8 @@ public class CacheControl { */ lastModified = lastModified - (lastModified % 1000); - String ifNoneMatch = request.getHeader(HEADER_IF_NONE_MATCH); - String eTag = controller.getETag(request); + String ifNoneMatch = request.getHeader(Headers.HEADER_IF_NONE_MATCH); + String eTag = handle.getETag(request); /** * 304-Antworten sollen nach dem {@plainlink @@ -162,8 +164,15 @@ public class CacheControl { * 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 (eTag != null) { + StringBuilder builder = new StringBuilder(); + if (handle.isETagWeak()) + builder.append("W/"); + builder.append('"'); + builder.append(eTag); + builder.append('"'); + response.setHeader(Headers.HEADER_ETAG, builder.toString()); + } if (ifModifiedSince >= lastModified && lastModified > 0) { @@ -186,17 +195,38 @@ public class CacheControl { } } - if (ifNoneMatch != null && ifNoneMatch.equals(eTag)) { - log.debug("{}: ETag {} not changed -> 304 ", url, ifNoneMatch); - response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); - return false; + if (ifNoneMatch != null) { + boolean weak = false; + if (ifNoneMatch.startsWith("W/")) { + weak = true; + ifNoneMatch = ifNoneMatch.substring(3, ifNoneMatch.length() - 1); + } + else { + ifNoneMatch = ifNoneMatch.substring(1, ifNoneMatch.length() - 1); + } + + if (!weak || (request.getMethod().equals("GET") && request.getHeader(Headers.HEADER_RANGE) == null)) { + /** + * Die Gleichheit gilt nur, wenn die ETag's der Anfrage _und_ der + * Antwort stark sind (starke Gleichheit!), oder wenn die Antwort nur + * schwache Gleichheit fordert... + */ + if (ifNoneMatch.equals(eTag) && (handle.isETagWeak() || !weak)) { + log.debug("{}: ETag {} not changed -> 304 ", url, ifNoneMatch); + response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); + return false; + } + } + else { + log.warn("{}: ignoring weak ETag W/\"{}\", because the request was no GET-request or the Range-Header was present!", url, ifNoneMatch); + } } log.debug("{}: first up!", url); /** HTTP/1.1-Caching-Header richtig setzen!! */ - response.setDateHeader(HEADER_LAST_MODIFIED, lastModified); + response.setDateHeader(Headers.HEADER_LAST_MODIFIED, lastModified); /** Cache-Control für HTTP/1.1-Clients generieren */ Map cacheControl = new TreeMap(); @@ -219,11 +249,11 @@ public class CacheControl { * Expires-Header für HTTP/1.0-Clients setzen. */ cacheControl.put("max-age", Integer.toString(cacheSeconds)); - response.setDateHeader(HEADER_EXPIRES, (controller.getTimestamp() + (long) cacheSeconds * 1000)); + response.setDateHeader(Headers.HEADER_EXPIRES, (handle.getTimestamp() + (long) cacheSeconds * 1000)); } /** Dem Handler die Gelegenheit geben, den Cache-Controll-Header anzupassen */ - controller.cacheControl(request, cacheControl); + handle.cacheControl(request, cacheControl); if (cacheControl.containsKey("private")) { @@ -235,8 +265,8 @@ public class CacheControl { * 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"); + response.setDateHeader(Headers.HEADER_EXPIRES, 0l); + response.addHeader(Headers.HEADER_PRAGMA, "no-cache"); } StringBuilder builder = new StringBuilder(); @@ -247,7 +277,7 @@ public class CacheControl { builder.append('='); builder.append(entry.getValue()); } - response.addHeader(HEADER_CACHE_CONTROL, builder.toString()); + response.addHeader(Headers.HEADER_CACHE_CONTROL, builder.toString()); } return true; @@ -267,93 +297,81 @@ public class CacheControl { } - 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 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 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; - + private long now = System.currentTimeMillis(); + private Integer cacheSeconds; + private Long lastModified; + private String eTag; + private Map additionalHeaders; + private Method acceptsMethod; + private Method cacheSecondsMethod; + private Method lastModifiedMethod; + private Method eTagMethod; + private Method cacheControlMethod; + private Method additionalHeadersMethod; + private boolean isAcceptsMethodDefined; + private boolean isCacheSecondsMethodDefined; + private boolean isLastModifiedMethodDefined; + private boolean isETagMethodDefined; + private boolean isCacheControlMethodDefined; + private boolean isAdditionalHeadersMethodDefined; + private boolean weak; + private boolean zipped; + + + ReflectionCacheMethodHandle(Object handler, boolean zipped) throws NoSuchMethodException { - ReflectionCacheMethodHandle(Object handler) throws NoSuchMethodException { this.handler = handler; + this.zipped = zipped; + + cacheSeconds = CacheControl.this.defaultCacheSeconds; + lastModified = CacheControl.this.defaultLastModified; + eTag = ""; + /** Class-Level-Annotations auslesen */ for (Annotation annotation : handler.getClass().getAnnotations()) { if (annotation.annotationType().equals(CacheSeconds.class)) { - defaults.cacheSeconds = ((CacheSeconds)annotation).value(); - isCacheSecondsDefined = true; + cacheSeconds = ((CacheSeconds)annotation).value(); + isCacheSecondsMethodDefined = true; continue; } if (annotation.annotationType().equals(LastModified.class)) { - defaults.lastModified = ((LastModified)annotation).value(); - if (defaults.lastModified < 1) { + lastModified = ((LastModified)annotation).value(); + if (lastModified < 1) { /** * Ein Last-Modified-Header wurde angefordert, aber es wurde kein * statischer Wert spezifiziert: * globalen statischen Default-Wert benutzen! */ - defaults.lastModified = defaultLastModified; + lastModified = defaultLastModified; } - isLastModifiedDefined = true; + isLastModifiedMethodDefined = true; continue; } if (annotation.annotationType().equals(ETag.class)) { - defaults.eTag = ((ETag)annotation).value(); - isETagDefined = true; + ETag eTagAnnotation = (ETag)annotation; + eTag = eTagAnnotation.value(); + weak = eTagAnnotation.weak(); + isETagMethodDefined = true; + continue; + } + if (annotation.annotationType().equals(AdditionalHeaders.class)) { + AdditionalHeaders additionalHeadersAnnotation = (AdditionalHeaders)annotation; + additionalHeaders = new HashMap(); + for (String header : additionalHeadersAnnotation.value()) { + int i = header.indexOf(':'); + if (i < 0) { + log.error("invalid header: [{}]", header); + } + else { + String name = header.substring(0,i).trim(); + String value = header.substring(i+1,header.length()).trim(); + additionalHeaders.put(name, value); + } + } + isAdditionalHeadersMethodDefined = true; continue; } } @@ -362,96 +380,129 @@ public class CacheControl { for (Method method : handler.getClass().getMethods()) { for (Annotation annotation : method.getAnnotations()) { if (annotation.annotationType().equals(Accepts.class)) { - if (isAcceptsDefined) + if (isAcceptsMethodDefined) throw new IllegalArgumentException("Die Annotation @Accept wurde in der Klasse " + handler.getClass().getSimpleName() + " mehrfach verwendet!"); - accepts = method; - isAcceptsDefined = true; + acceptsMethod = method; + isAcceptsMethodDefined = true; continue; } if (annotation.annotationType().equals(CacheSeconds.class)) { - if (isCacheSecondsDefined) + if (isCacheSecondsMethodDefined) throw new IllegalArgumentException("Die Annotation @CacheSeconds wurde in der Klasse " + handler.getClass().getSimpleName() + " mehrfach verwendet!"); - cacheSeconds = method; - isCacheSecondsDefined = true; + cacheSecondsMethod = method; + isCacheSecondsMethodDefined = true; continue; } if (annotation.annotationType().equals(LastModified.class)) { - if (isLastModifiedDefined) + if (isLastModifiedMethodDefined) throw new IllegalArgumentException("Die Annotation @LastModified wurde in der Klasse " + handler.getClass().getSimpleName() + " mehrfach verwendet!"); - lastModified = method; - isLastModifiedDefined = true; + lastModifiedMethod = method; + isLastModifiedMethodDefined = true; continue; } if (annotation.annotationType().equals(ETag.class)) { - if (isETagDefined) + if (isETagMethodDefined) throw new IllegalArgumentException("Die Annotation @ETag wurde in der Klasse " + handler.getClass().getSimpleName() + " mehrfach verwendet!"); - eTag = method; - isETagDefined = true; + eTagMethod = method; + weak = ((ETag)annotation).weak(); + isETagMethodDefined = true; continue; } if (annotation.annotationType().equals(de.halbekunst.juplo.cachecontrol.annotations.CacheControl.class)) { - if (isCacheControlDefined) + if (isCacheControlMethodDefined) throw new IllegalArgumentException("Die Annotation @CacheControl wurde in der Klasse " + handler.getClass().getSimpleName() + " mehrfach verwendet!"); - cacheControl = method; - isCacheControlDefined = true; + cacheControlMethod = method; + isCacheControlMethodDefined = true; + continue; + } + if (annotation.annotationType().equals(AdditionalHeaders.class)) { + if (isAdditionalHeadersMethodDefined) + throw new IllegalArgumentException("Die Annotation @AdditionalHeaders wurde in der Klasse " + handler.getClass().getSimpleName() + " mehrfach verwendet!"); + additionalHeadersMethod = method; + isAdditionalHeadersMethodDefined = true; continue; } } } + + if (!isAdditionalHeadersMethodDefined) + additionalHeaders = new HashMap(); } + @Override + public boolean isZipped() { + return zipped; + } + @Override public long getTimestamp() { - return defaults.now; + return 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); + public int accepts(HttpServletRequest request) throws IllegalArgumentException { + if (acceptsMethod == null) { + return HttpServletResponse.SC_OK; + } + else { + try { + return (Integer)acceptsMethod.invoke(handler, request); + } + catch (Exception e) { + throw new IllegalArgumentException(e); + } + } } @Override - public int getCacheSeconds(HttpServletRequest request) - throws IllegalAccessException, - IllegalArgumentException, - InvocationTargetException - { - if (cacheSeconds == null) - return defaults.getCacheSeconds(request); - else - return (Integer)cacheSeconds.invoke(handler, request); + public int getCacheSeconds(HttpServletRequest request) throws IllegalArgumentException { + if (cacheSecondsMethod == null) { + return cacheSeconds; + } + else { + try { + return (Integer)cacheSecondsMethod.invoke(handler, request); + } + catch (Exception e) { + throw new IllegalArgumentException(e); + } + } } @Override - public long getLastModified(HttpServletRequest request) - throws IllegalAccessException, - IllegalArgumentException, - InvocationTargetException - { - if (lastModified == null) - return defaults.getLastModified(request); - else - return (Long)lastModified.invoke(handler, request); + public long getLastModified(HttpServletRequest request) throws IllegalArgumentException { + if (lastModifiedMethod == null) { + return lastModified; + } + else { + try { + return (Long)lastModifiedMethod.invoke(handler, request); + } + catch (Exception e) { + throw new IllegalArgumentException(e); + } + } } @Override - public String getETag(HttpServletRequest request) - throws IllegalAccessException, - IllegalArgumentException, - InvocationTargetException - { - if (eTag == null) - return defaults.getETag(request); - else - return (String)eTag.invoke(handler, request); + public String getETag(HttpServletRequest request) throws IllegalArgumentException { + if (eTagMethod == null) { + return eTag; + } + else { + try { + return (String)eTagMethod.invoke(handler, request); + } + catch (Exception e) { + throw new IllegalArgumentException(e); + } + } + } + + @Override + public boolean isETagWeak() { + return weak; } @Override @@ -459,23 +510,31 @@ public class CacheControl { HttpServletRequest request, Map cacheControlMap ) - throws IllegalAccessException, - IllegalArgumentException, - InvocationTargetException + throws IllegalArgumentException { - if (cacheControl == null) - defaults.cacheControl(request, cacheControlMap); - else - cacheControl.invoke(handler, request, cacheControlMap); + if (cacheControlMethod != null) { + try { + cacheControlMethod.invoke(handler, request, cacheControlMap); + } + catch (Exception e) { + throw new IllegalArgumentException(e); + } + } } - } - - public void setDefaultCacheSeconds(Integer defaultCacheSeconds) { - this.defaultCacheSeconds = defaultCacheSeconds; - } - - public void setDefaultLastModified(Long defaultLastModified) { - this.defaultLastModified = defaultLastModified; + @Override + public Map getAdditionalHeaders(HttpServletRequest request) throws IllegalArgumentException { + if (additionalHeadersMethod == null) { + return additionalHeaders; + } + else { + try { + return (Map)additionalHeadersMethod.invoke(handler, request); + } + catch (Exception e) { + throw new IllegalArgumentException(e); + } + } + } } }