From 60ef28853e4aca8b227f533c4b95c03de6574e02 Mon Sep 17 00:00:00 2001 From: Fredrik Tolf Date: Tue, 13 Oct 2009 06:48:20 +0200 Subject: [PATCH] Made cache checking easier. --- src/dolda/jsvc/util/Cache.java | 28 ++++++++++++++++++++++++++++ src/dolda/jsvc/util/Restarts.java | 7 +++++++ src/dolda/jsvc/util/StaticContent.java | 17 +---------------- 3 files changed, 36 insertions(+), 16 deletions(-) create mode 100644 src/dolda/jsvc/util/Cache.java diff --git a/src/dolda/jsvc/util/Cache.java b/src/dolda/jsvc/util/Cache.java new file mode 100644 index 0000000..6fd7d7a --- /dev/null +++ b/src/dolda/jsvc/util/Cache.java @@ -0,0 +1,28 @@ +package dolda.jsvc.util; + +import dolda.jsvc.*; +import java.util.*; + +public class Cache { + public static void checkmtime(Request req, long mtime) { + /* Since the HTTP time format is (reasonably enough) precise + * only to seconds, any extra milliseconds must be trimmed + * off, or the mtime will almost certainly not match. */ + Date mdate = new Date((mtime / 1000) * 1000); + String ims = req.inheaders().get("If-Modified-Since"); + if(ims != null) { + Date cldate; + try { + cldate = Http.parsedate(ims); + } catch(java.text.ParseException e) { + throw(Restarts.stdresponse(400, "The If-Modified-Since header is not parseable.")); + } + if(mdate.compareTo(cldate) <= 0) { + req.status(304); + req.outheaders().put("Content-Length", "0"); + throw(Restarts.done()); + } + } + req.outheaders().put("Last-Modified", Http.fmtdate(mdate)); + } +} diff --git a/src/dolda/jsvc/util/Restarts.java b/src/dolda/jsvc/util/Restarts.java index 7725f28..d4aab70 100644 --- a/src/dolda/jsvc/util/Restarts.java +++ b/src/dolda/jsvc/util/Restarts.java @@ -77,4 +77,11 @@ public class Restarts { public static RequestRestart stdresponse(int code) { return(stdresponse(code, "An error occurred", Misc.statustext(code))); } + + public static RequestRestart done() { + return(new RequestRestart() { + public void respond(Request req) { + } + }); + } } diff --git a/src/dolda/jsvc/util/StaticContent.java b/src/dolda/jsvc/util/StaticContent.java index 0d4208e..685669c 100644 --- a/src/dolda/jsvc/util/StaticContent.java +++ b/src/dolda/jsvc/util/StaticContent.java @@ -36,25 +36,10 @@ public class StaticContent implements Responder { } if(in == null) throw(Restarts.stdresponse(404)); - String ims = req.inheaders().get("If-Modified-Since"); - Date mtime = new Date((req.ctx().starttime() / 1000) * 1000); - if(ims != null) { - Date d; - try { - d = Http.parsedate(ims); - } catch(java.text.ParseException e) { - throw(Restarts.stdresponse(400)); - } - if(mtime.compareTo(d) <= 0) { - req.status(304); - req.outheaders().put("Content-Length", "0"); - return; - } - } + Cache.checkmtime(req, req.ctx().starttime()); try { try { req.outheaders().put("Content-Type", mimetype); - req.outheaders().put("Last-Modified", Http.fmtdate(mtime)); Misc.cpstream(in, req.output()); } finally { in.close(); -- 2.11.0