diff src/goodjava/webserver/handlers/FileHandler.java @ 1604:8a7519dee55c

FileHandler handles if-modified-since
author Franklin Schmidt <fschmidt@gmail.com>
date Fri, 16 Apr 2021 19:19:39 -0600
parents 27efb1fcbcb5
children fa066aaa068c
line wrap: on
line diff
--- a/src/goodjava/webserver/handlers/FileHandler.java	Sun Apr 11 14:45:03 2021 -0600
+++ b/src/goodjava/webserver/handlers/FileHandler.java	Fri Apr 16 19:19:39 2021 -0600
@@ -2,16 +2,16 @@
 
 import java.io.File;
 import java.io.FileInputStream;
-import java.io.Writer;
-import java.io.OutputStreamWriter;
 import java.io.IOException;
 import java.text.DateFormat;
 import java.text.SimpleDateFormat;
+import java.text.ParseException;
 import java.util.Date;
+import java.util.TimeZone;
 import goodjava.webserver.Handler;
 import goodjava.webserver.Request;
 import goodjava.webserver.Response;
-import goodjava.webserver.ResponseOutputStream;
+import goodjava.webserver.Status;
 
 
 public class FileHandler implements Handler {
@@ -40,6 +40,23 @@
 			File file = file(request);
 			if( file.isFile() ) {
 				Response response = new Response();
+
+				DateFormat fmt = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
+				fmt.setTimeZone(TimeZone.getTimeZone("GMT"));
+				String lastModified = fmt.format(new Date(file.lastModified()));
+				String ifMod = (String)request.headers.get("if-modified-since");
+				if( ifMod != null ) {
+					try {
+						Date ifModDate = fmt.parse(ifMod);
+						if( ifModDate != null && ifModDate.getTime() >= fmt.parse(lastModified).getTime() ) {
+							response.status = Status.NOT_MODIFIED;
+							return response;
+						}
+
+					} catch(ParseException e) {}
+				}
+				response.headers.put("last-modified",lastModified);
+
 				response.body = new Response.Body( file.length(), new FileInputStream(file) );
 				return response;
 			}