55import java .io .File ;
66import java .io .IOException ;
77import java .io .OutputStream ;
8+ import java .io .PrintWriter ;
89import java .nio .file .Files ;
10+ import java .util .Map ;
911
1012public class StaticFileHandler {
11- private final String WEB_ROOT ;
13+ private static final String WEB_ROOT = "www" ;
1214 private byte [] fileBytes ;
13- private int statusCode ;
1415
15- // Constructor for production
16- public StaticFileHandler () {
17- WEB_ROOT = "www" ;
18- }
19-
20- // Constructor for tests, otherwise the www folder won't be seen
21- public StaticFileHandler (String webRoot ) {
22- WEB_ROOT = webRoot ;
23- }
16+ public StaticFileHandler (){}
2417
2518 private void handleGetRequest (String uri ) throws IOException {
26- // Sanitize URI
27- int q = uri .indexOf ('?' );
28- if (q >= 0 ) uri = uri .substring (0 , q );
29- int h = uri .indexOf ('#' );
30- if (h >= 0 ) uri = uri .substring (0 , h );
31- uri = uri .replace ("\0 " , "" );
32- if (uri .startsWith ("/" )) uri = uri .substring (1 );
3319
34- // Path traversal check
35- File root = new File (WEB_ROOT ).getCanonicalFile ();
36- File file = new File (root , uri ).getCanonicalFile ();
37- if (!file .toPath ().startsWith (root .toPath ())) {
38- fileBytes = "403 Forbidden" .getBytes (java .nio .charset .StandardCharsets .UTF_8 );
39- statusCode = 403 ;
40- return ;
41- }
20+ File file = new File (WEB_ROOT , uri );
21+ fileBytes = Files .readAllBytes (file .toPath ());
4222
43- // Read file
44- if (file .isFile ()) {
45- fileBytes = Files .readAllBytes (file .toPath ());
46- statusCode = 200 ;
47- } else {
48- File errorFile = new File (WEB_ROOT , "pageNotFound.html" );
49- if (errorFile .isFile ()) {
50- fileBytes = Files .readAllBytes (errorFile .toPath ());
51- } else {
52- fileBytes = "404 Not Found" .getBytes (java .nio .charset .StandardCharsets .UTF_8 );
53- }
54- statusCode = 404 ;
55- }
5623 }
5724
58- public void sendGetRequest (OutputStream outputStream , String uri ) throws IOException {
25+ public void sendGetRequest (OutputStream outputStream , String uri ) throws IOException {
5926 handleGetRequest (uri );
6027 HttpResponseBuilder response = new HttpResponseBuilder ();
61- response .setStatusCode (statusCode );
62- // Use MimeTypeDetector instead of hardcoded text/html
63- response .setContentTypeFromFilename (uri );
28+ response .setHeaders (Map .of ("Content-Type" , "text/html; charset=utf-8" ));
6429 response .setBody (fileBytes );
65- outputStream .write (response .build ());
66- outputStream .flush ();
30+ PrintWriter writer = new PrintWriter (outputStream , true );
31+ writer .println (response .build ());
32+
6733 }
68- }
34+
35+ }
0 commit comments