--- /dev/null
+package de.halbekunst.juplo.cachecontrol;
+
+import de.halbekunst.juplo.cachecontrol.CacheControl.CacheMethodHandle;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.PrintWriter;
+import java.util.Enumeration;
+import java.util.Map;
+import java.util.zip.GZIPOutputStream;
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletOutputStream;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpServletResponseWrapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Configurable;
+
+
+
+/**
+ *
+ * @author kai
+ */
+@Configurable
+public class AcceleratorFilter implements Filter {
+ private final static Logger log = LoggerFactory.getLogger(AcceleratorFilter.class);
+
+ public final static String REQUEST_URI_ATTRIBUTE = "javax.servlet.include.request_uri";
+
+
+ @Autowired CacheControl cacheControl;
+ @Autowired(required=true) Integer buffer;
+ @Autowired(required=true) String eTag;
+ @Autowired(required=true) Boolean weak;
+ @Autowired(required=true) Long lastModified;
+ @Autowired(required=true) Integer cacheSeconds;
+
+
+ @Override
+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
+ if (!(request instanceof HttpServletRequest)) {
+ log.error("AcceleratorFilter can only handle HTTP-requests");
+ chain.doFilter(request, response);
+ return;
+ }
+
+ /** Prüfen, ob es sich um eine Anfrage für einen JSP-Include handelt */
+ if (request.getAttribute(REQUEST_URI_ATTRIBUTE) != null) {
+ log.debug("Includes cannot be accelerated");
+ chain.doFilter(request, response);
+ return;
+ }
+
+ AccelerationWrapper wrapper = new AccelerationWrapper((HttpServletRequest)request, (HttpServletResponse)response);
+ cacheControl.init(wrapper);
+ chain.doFilter(request, wrapper);
+ wrapper.finish();
+ }
+
+ @Override
+ public void init(FilterConfig filterConfig) throws ServletException {
+ }
+
+ @Override
+ public void destroy() {
+ }
+
+
+ class AccelerationWrapper extends HttpServletResponseWrapper implements CacheMethodHandle {
+
+ private final HttpServletRequest request;
+ private final HttpServletResponse response;
+
+ private boolean zipped;
+ private GZIPServletOutputStream out;
+
+ private long now;
+ private int buffer;
+ private int status;
+ private String type;
+
+
+ AccelerationWrapper(HttpServletRequest request, HttpServletResponse response) throws IOException {
+ super(response);
+
+ this.request = request;
+ this.response = response;
+
+ now = System.currentTimeMillis();
+ buffer = AcceleratorFilter.this.buffer;
+ status = HttpServletResponse.SC_OK;
+
+ zipped = false;
+ Enumeration values = request.getHeaders(HeaderNames.HEADER_ACCEPT_ENCODING);
+ while (values.hasMoreElements()) {
+ String value = (String) values.nextElement();
+ if (value.indexOf("gzip") != -1) {
+ zipped = true;
+ response.addHeader(HeaderNames.HEADER_CONTENT_ENCODING, "gzip");
+ break;
+ }
+ }
+ }
+
+
+ public void finish() throws IOException {
+ if (zipped && out != null)
+ out.zout.finish();
+ }
+
+
+ @Override
+ public void setStatus(int sc) {
+ response.setStatus(sc);
+ status = sc;
+ try {
+ cacheControl.decorate(request, response, this);
+ }
+ catch (Exception e) {
+ log.error("Error while decorating response", e);
+ }
+ }
+
+ @Override
+ public void setStatus(int sc, String sm) {
+ response.setStatus(sc,sm);
+ status = sc;
+ try {
+ cacheControl.decorate(request, response, this);
+ }
+ catch (Exception e) {
+ log.error("Error while decorating response", e);
+ }
+ }
+
+ @Override
+ public ServletOutputStream getOutputStream() throws IOException {
+ if (out == null)
+ out = new GZIPServletOutputStream(response.getOutputStream(), zipped);
+ return out;
+ }
+
+ @Override
+ public PrintWriter getWriter() throws IOException {
+ return new PrintWriter(getOutputStream());
+ }
+
+ @Override
+ public void setContentType(String type) {
+ this.type = type;
+ response.setContentType(type);
+ }
+
+ @Override
+ public void setBufferSize(int size) {
+ this.buffer = size;
+ response.setBufferSize(size);
+ }
+
+ @Override
+ public int getBufferSize() {
+ return buffer;
+ }
+
+ @Override
+ public void flushBuffer() throws IOException {
+ cacheControl.decorate(request, response, this);
+ if (zipped && out != null) {
+ out.zout.finish();
+ }
+ response.flushBuffer();
+ }
+
+ @Override
+ public void resetBuffer() {
+ response.resetBuffer();
+ }
+
+ @Override
+ public boolean isCommitted() {
+ return response.isCommitted();
+ }
+
+ @Override
+ public void reset() {
+ response.reset();
+ }
+
+
+
+ @Override
+ public long getTimestamp() {
+ return now;
+ }
+
+ @Override
+ public int accepts(HttpServletRequest request) {
+ return status;
+ }
+
+ @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 boolean isETagWeak() {
+ return weak;
+ }
+
+ @Override
+ public void cacheControl(HttpServletRequest request, Map<String, String> cacheControlMap) {
+ }
+
+
+ class GZIPServletOutputStream extends ServletOutputStream {
+
+ private final OutputStream out;
+ private final GZIPOutputStream zout;
+ private boolean untouched = true;
+
+ public GZIPServletOutputStream(ServletOutputStream out, boolean zipped) throws IOException {
+ if (zipped) {
+ this.zout = new GZIPOutputStream(out, buffer);
+ this.out = this.zout;
+ }
+ else {
+ this.out = out;
+ this.zout = null;
+ }
+ }
+
+
+ @Override
+ public void write(int i) throws IOException {
+ if (untouched) {
+ untouched = false;
+ try {
+ AcceleratorFilter.this.cacheControl.decorate(AccelerationWrapper.this.request, response, buffer);
+ }
+ catch (Exception e) {
+ log.error("Error while guessing Cache-Header's", e);
+ response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ }
+ }
+ out.write(i);
+ }
+ }
+ }
+}
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;
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";
- public static final String HEADER_RANGE = "Range";
-
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 void init(CacheMethodHandle handle) {
+ CacheControl.tl.set(handle);
+ }
+
+ public void init(Object handler) throws NoSuchMethodException {
+ CacheControl.tl.set(new ReflectionCacheMethodHandle(handler));
}
public boolean decorate(
HttpServletRequest request,
HttpServletResponse response,
Object handler
- ) throws Exception
+ )
{
try {
CacheMethodHandle controller = CacheControl.tl.get();
* 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(HeaderNames.HEADER_DATE, controller.getTimestamp());
/** Besondere Maßnahmen für besondere HTTP-Status-Codes ?!? */
int status = controller.accepts(request);
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:
/**
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");
+ response.setDateHeader(HeaderNames.HEADER_DATE, controller.getTimestamp());
+ response.setDateHeader(HeaderNames.HEADER_EXPIRES, 0);
+ response.addHeader(HeaderNames.HEADER_PRAGMA, "no-cache");
+ response.addHeader(HeaderNames.HEADER_CACHE_CONTROL, "private");
+ response.addHeader(HeaderNames.HEADER_CACHE_CONTROL, "no-cache");
+ response.addHeader(HeaderNames.HEADER_CACHE_CONTROL, "no-store");
+ response.addHeader(HeaderNames.HEADER_CACHE_CONTROL, "max-age=0");
+ response.addHeader(HeaderNames.HEADER_CACHE_CONTROL, "s-max-age=0");
return true;
}
long ifModifiedSince = -1;
try {
- ifModifiedSince = request.getDateHeader(HEADER_IF_MODIFIED_SINCE);
+ ifModifiedSince = request.getDateHeader(HeaderNames.HEADER_IF_MODIFIED_SINCE);
}
catch (Exception e) {
log.error("Exception while fetching If-Modified-Since: {}", e);
*/
lastModified = lastModified - (lastModified % 1000);
- String ifNoneMatch = request.getHeader(HEADER_IF_NONE_MATCH);
+ String ifNoneMatch = request.getHeader(HeaderNames.HEADER_IF_NONE_MATCH);
String eTag = controller.getETag(request);
/**
builder.append('"');
builder.append(eTag);
builder.append('"');
- response.setHeader(HEADER_ETAG, builder.toString());
+ response.setHeader(HeaderNames.HEADER_ETAG, builder.toString());
}
ifNoneMatch = ifNoneMatch.substring(1, ifNoneMatch.length() - 1);
}
- if (!weak || (request.getMethod().equals("GET") && request.getHeader(HEADER_RANGE) == null)) {
+ if (!weak || (request.getMethod().equals("GET") && request.getHeader(HeaderNames.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
log.debug("{}: first up!", url);
/** HTTP/1.1-Caching-Header richtig setzen!! */
- response.setDateHeader(HEADER_LAST_MODIFIED, lastModified);
+ response.setDateHeader(HeaderNames.HEADER_LAST_MODIFIED, lastModified);
/** Cache-Control für HTTP/1.1-Clients generieren */
Map<String, String> cacheControl = new TreeMap<String, String>();
* <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));
+ response.setDateHeader(HeaderNames.HEADER_EXPIRES, (controller.getTimestamp() + (long) cacheSeconds * 1000));
}
/** Dem Handler die Gelegenheit geben, den Cache-Controll-Header anzupassen */
* 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(HeaderNames.HEADER_EXPIRES, 0l);
+ response.addHeader(HeaderNames.HEADER_PRAGMA, "no-cache");
}
StringBuilder builder = new StringBuilder();
builder.append('=');
builder.append(entry.getValue());
}
- response.addHeader(HEADER_CACHE_CONTROL, builder.toString());
+ response.addHeader(HeaderNames.HEADER_CACHE_CONTROL, builder.toString());
}
return true;
}
- interface CacheMethodHandle {
+ public 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;
+ int accepts(HttpServletRequest request);
+ int getCacheSeconds(HttpServletRequest request);
+ long getLastModified(HttpServletRequest request);
+ String getETag(HttpServletRequest request);
boolean isETagWeak();
- void cacheControl(HttpServletRequest request, Map<String, String> cacheControlMap) throws Exception;
+ void cacheControl(HttpServletRequest request, Map<String, String> cacheControlMap);
}
}
@Override
- public int accepts(HttpServletRequest request)
- throws IllegalAccessException,
- IllegalArgumentException,
- InvocationTargetException
- {
- if (acceptsMethod == null)
+ public int accepts(HttpServletRequest request) throws IllegalArgumentException {
+ if (acceptsMethod == null) {
return HttpServletResponse.SC_OK;
- else
- return (Integer)acceptsMethod.invoke(handler, request);
+ }
+ 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 (cacheSecondsMethod == null)
+ public int getCacheSeconds(HttpServletRequest request) throws IllegalArgumentException {
+ if (cacheSecondsMethod == null) {
return cacheSeconds;
- else
- return (Integer)cacheSecondsMethod.invoke(handler, request);
+ }
+ 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 (lastModifiedMethod == null)
+ public long getLastModified(HttpServletRequest request) throws IllegalArgumentException {
+ if (lastModifiedMethod == null) {
return lastModified;
- else
- return (Long)lastModifiedMethod.invoke(handler, request);
+ }
+ 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 (eTagMethod == null)
+ public String getETag(HttpServletRequest request) throws IllegalArgumentException {
+ if (eTagMethod == null) {
return eTag;
- else
- return (String)eTagMethod.invoke(handler, request);
+ }
+ else {
+ try {
+ return (String)eTagMethod.invoke(handler, request);
+ }
+ catch (Exception e) {
+ throw new IllegalArgumentException(e);
+ }
+ }
}
@Override
HttpServletRequest request,
Map<String, String> cacheControlMap
)
- throws IllegalAccessException,
- IllegalArgumentException,
- InvocationTargetException
+ throws IllegalArgumentException
{
- if (cacheControlMethod != null)
- cacheControlMethod.invoke(handler, request, cacheControlMap);
+ if (cacheControlMethod != null) {
+ try {
+ cacheControlMethod.invoke(handler, request, cacheControlMap);
+ }
+ catch (Exception e) {
+ throw new IllegalArgumentException(e);
+ }
+ }
}
}
+++ /dev/null
-package de.halbekunst.juplo.cachecontrol;
-
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.util.Locale;
-import javax.servlet.Filter;
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-import javax.servlet.ServletOutputStream;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.Cookie;
-import javax.servlet.http.HttpServletResponse;
-
-/**
- *
- * @author kai
- */
-public class CacheControlFilter implements Filter {
-
-
- @Override
- public void init(FilterConfig filterConfig) throws ServletException {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
- @Override
- public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
- @Override
- public void destroy() {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
-
- class HttpServletResponseWrapper implements HttpServletResponse {
-
- private final HttpServletResponse response;
-
-
- HttpServletResponseWrapper(HttpServletResponse response) {
- this.response = response;
- }
-
-
- @Override
- public void addCookie(Cookie cookie) {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
- @Override
- public boolean containsHeader(String name) {
- return response.containsHeader(name);
- }
-
- @Override
- public String encodeURL(String url) {
- return response.encodeURL(url);
- }
-
- @Override
- public String encodeRedirectURL(String url) {
- return response.encodeRedirectURL(url);
- }
-
- @Override
- public String encodeUrl(String url) {
- return response.encodeUrl(url);
- }
-
- @Override
- public String encodeRedirectUrl(String url) {
- return response.encodeRedirectUrl(url);
- }
-
- @Override
- public void sendError(int sc, String msg) throws IOException {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
- @Override
- public void sendError(int sc) throws IOException {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
- @Override
- public void sendRedirect(String location) throws IOException {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
- @Override
- public void setDateHeader(String name, long date) {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
- @Override
- public void addDateHeader(String name, long date) {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
- @Override
- public void setHeader(String name, String value) {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
- @Override
- public void addHeader(String name, String value) {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
- @Override
- public void setIntHeader(String name, int value) {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
- @Override
- public void addIntHeader(String name, int value) {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
- @Override
- public void setStatus(int sc) {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
- @Override
- public void setStatus(int sc, String sm) {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
- @Override
- public String getCharacterEncoding() {
- return response.getCharacterEncoding();
- }
-
- @Override
- public String getContentType() {
- return response.getContentType();
- }
-
- @Override
- public ServletOutputStream getOutputStream() throws IOException {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
- @Override
- public PrintWriter getWriter() throws IOException {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
- @Override
- public void setCharacterEncoding(String charset) {
- response.setCharacterEncoding(charset);
- }
-
- @Override
- public void setContentLength(int len) {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
- @Override
- public void setContentType(String type) {
- response.setContentType(type);
- }
-
- @Override
- public void setBufferSize(int size) {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
- @Override
- public int getBufferSize() {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
- @Override
- public void flushBuffer() throws IOException {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
- @Override
- public void resetBuffer() {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
- @Override
- public boolean isCommitted() {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
- @Override
- public void reset() {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
- @Override
- public void setLocale(Locale loc) {
- response.setLocale(loc);
- }
-
- @Override
- public Locale getLocale() {
- return response.getLocale();
- }
- }
-}
--- /dev/null
+package de.halbekunst.juplo.cachecontrol;
+
+/**
+ *
+ * @author kai
+ */
+public abstract class HeaderNames {
+
+ public static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding";
+ public static final String HEADER_CACHE_CONTROL = "Cache-Control";
+ public static final String HEADER_CONTENT_ENCODING = "Content-Encoding";
+ public static final String HEADER_DATE = "Date";
+ public static final String HEADER_ETAG = "ETag";
+ public static final String HEADER_EXPIRES = "Expires";
+ public static final String HEADER_IF_MODIFIED_SINCE = "If-Modified-Since";
+ public static final String HEADER_IF_NONE_MATCH = "If-None-Match";
+ public static final String HEADER_LAST_MODIFIED = "Last-Modified";
+ public static final String HEADER_PRAGMA = "Pragma";
+ public static final String HEADER_RANGE = "Range";
+
+}