Mercurial Hosting > luan
view src/goodjava/webserver/handlers/FileHandler.java @ 1640:570f3d483a31
host - move https.luan into src
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Tue, 21 Dec 2021 16:54:26 -0700 |
parents | fa066aaa068c |
children |
line wrap: on
line source
package goodjava.webserver.handlers; import java.io.File; import java.io.FileInputStream; 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.Status; public class FileHandler implements Handler { final File dir; public FileHandler() { this("."); } public FileHandler(String pathname) { this(new File(pathname)); } public FileHandler(File dir) { if( !dir.isDirectory() ) throw new RuntimeException("must be a directory"); this.dir = dir; } File file(Request request) { return new File(dir,request.path); } public Response handle(Request request) { try { 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; } return null; } catch(IOException e) { throw new RuntimeException(e); } } }