comparison 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
comparison
equal deleted inserted replaced
1603:bd125ee375d2 1604:8a7519dee55c
1 package goodjava.webserver.handlers; 1 package goodjava.webserver.handlers;
2 2
3 import java.io.File; 3 import java.io.File;
4 import java.io.FileInputStream; 4 import java.io.FileInputStream;
5 import java.io.Writer;
6 import java.io.OutputStreamWriter;
7 import java.io.IOException; 5 import java.io.IOException;
8 import java.text.DateFormat; 6 import java.text.DateFormat;
9 import java.text.SimpleDateFormat; 7 import java.text.SimpleDateFormat;
8 import java.text.ParseException;
10 import java.util.Date; 9 import java.util.Date;
10 import java.util.TimeZone;
11 import goodjava.webserver.Handler; 11 import goodjava.webserver.Handler;
12 import goodjava.webserver.Request; 12 import goodjava.webserver.Request;
13 import goodjava.webserver.Response; 13 import goodjava.webserver.Response;
14 import goodjava.webserver.ResponseOutputStream; 14 import goodjava.webserver.Status;
15 15
16 16
17 public class FileHandler implements Handler { 17 public class FileHandler implements Handler {
18 final File dir; 18 final File dir;
19 19
38 public Response handle(Request request) { 38 public Response handle(Request request) {
39 try { 39 try {
40 File file = file(request); 40 File file = file(request);
41 if( file.isFile() ) { 41 if( file.isFile() ) {
42 Response response = new Response(); 42 Response response = new Response();
43
44 DateFormat fmt = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
45 fmt.setTimeZone(TimeZone.getTimeZone("GMT"));
46 String lastModified = fmt.format(new Date(file.lastModified()));
47 String ifMod = (String)request.headers.get("if-modified-since");
48 if( ifMod != null ) {
49 try {
50 Date ifModDate = fmt.parse(ifMod);
51 if( ifModDate != null && ifModDate.getTime() >= fmt.parse(lastModified).getTime() ) {
52 response.status = Status.NOT_MODIFIED;
53 return response;
54 }
55
56 } catch(ParseException e) {}
57 }
58 response.headers.put("last-modified",lastModified);
59
43 response.body = new Response.Body( file.length(), new FileInputStream(file) ); 60 response.body = new Response.Body( file.length(), new FileInputStream(file) );
44 return response; 61 return response;
45 } 62 }
46 return null; 63 return null;
47 } catch(IOException e) { 64 } catch(IOException e) {