Mercurial Hosting > luan
comparison src/goodjava/webserver/handlers/DirHandler.java @ 1402:27efb1fcbcb5
move luan.lib to goodjava
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Tue, 17 Sep 2019 01:35:01 -0400 |
parents | src/luan/lib/webserver/handlers/DirHandler.java@643cf1c37723 |
children | 55d7b60c074d |
comparison
equal
deleted
inserted
replaced
1401:ef1620aa99cb | 1402:27efb1fcbcb5 |
---|---|
1 package goodjava.webserver.handlers; | |
2 | |
3 import java.io.File; | |
4 import java.io.FileInputStream; | |
5 import java.io.Writer; | |
6 import java.io.OutputStreamWriter; | |
7 import java.io.IOException; | |
8 import java.text.DateFormat; | |
9 import java.text.SimpleDateFormat; | |
10 import java.util.Arrays; | |
11 import java.util.Comparator; | |
12 import java.util.Date; | |
13 import goodjava.webserver.Handler; | |
14 import goodjava.webserver.Request; | |
15 import goodjava.webserver.Response; | |
16 import goodjava.webserver.ResponseOutputStream; | |
17 | |
18 | |
19 public final class DirHandler implements Handler { | |
20 private final FileHandler fileHandler; | |
21 | |
22 public DirHandler(FileHandler fileHandler) { | |
23 this.fileHandler = fileHandler; | |
24 } | |
25 | |
26 private static final Comparator<File> sorter = new Comparator<File>() { | |
27 public int compare(File f1, File f2) { | |
28 return f1.getName().compareTo(f2.getName()); | |
29 } | |
30 }; | |
31 | |
32 public Response handle(Request request) { | |
33 try { | |
34 File file = fileHandler.file(request); | |
35 if( request.path.endsWith("/") && file.isDirectory() ) { | |
36 DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss zzz"); | |
37 Response response = new Response(); | |
38 response.headers.put( "content-type", "text/html; charset=utf-8" ); | |
39 Writer writer = new OutputStreamWriter( new ResponseOutputStream(response) ); | |
40 writer.write( "<!doctype html><html>" ); | |
41 writer.write( "<head><style>td{padding: 2px 8px}</style></head>" ); | |
42 writer.write( "<body>" ); | |
43 writer.write( "<h1>Directory: "+request.path+"</h1>" ); | |
44 writer.write( "<table border=0>" ); | |
45 File[] a = file.listFiles(); | |
46 Arrays.sort(a,sorter); | |
47 for( File child : a ) { | |
48 String name = child.getName(); | |
49 if( child.isDirectory() ) | |
50 name += '/'; | |
51 writer.write( "<tr>" ); | |
52 writer.write( "<td><a href='"+name+"'>"+name+"</a></td>" ); | |
53 writer.write( "<td>"+child.length()+" bytes</td>" ); | |
54 writer.write( "<td>"+fmt.format(new Date(child.lastModified()))+"</td>" ); | |
55 writer.write( "</tr>" ); | |
56 } | |
57 writer.write( "</table>" ); | |
58 writer.write( "</body>" ); | |
59 writer.write( "</html>" ); | |
60 writer.close(); | |
61 return response; | |
62 } | |
63 return null; | |
64 } catch(IOException e) { | |
65 throw new RuntimeException(e); | |
66 } | |
67 } | |
68 } |