44import org .example .filter .IpFilter ;
55import org .example .httpparser .HttpParser ;
66import org .example .httpparser .HttpRequest ;
7-
8- import java .io .File ;
9- import java .nio .file .Files ;
10- import java .nio .file .NoSuchFileException ;
117import java .util .ArrayList ;
128import java .util .List ;
139import org .example .filter .Filter ;
2117public class ConnectionHandler implements AutoCloseable {
2218 private final Socket client ;
2319 private final List <Filter > filters ;
24- String webRoot ;
20+ private final String webRoot ;
2521
2622 public ConnectionHandler (Socket client ) {
2723 this .client = client ;
24+ this .webRoot = "www" ;
2825 this .filters = buildFilters ();
29- this .webRoot = null ;
3026 }
3127
3228 public ConnectionHandler (Socket client , String webRoot ) {
@@ -46,14 +42,6 @@ private List<Filter> buildFilters() {
4642 }
4743
4844 public void runConnectionHandler () throws IOException {
49- StaticFileHandler sfh ;
50-
51- if (webRoot != null ) {
52- sfh = new StaticFileHandler (webRoot );
53- } else {
54- sfh = new StaticFileHandler ();
55- }
56-
5745 HttpParser parser = new HttpParser ();
5846 parser .setReader (client .getInputStream ());
5947 parser .parseRequest ();
@@ -83,41 +71,17 @@ public void runConnectionHandler() throws IOException {
8371 }
8472
8573 // Let StaticFileHandler handle everything
86- StaticFileHandler sfh = new StaticFileHandler ();
74+ StaticFileHandler sfh = new StaticFileHandler (webRoot );
8775 sfh .sendGetRequest (client .getOutputStream (), parser .getUri ());
8876 }
8977
90- private String sanitizeUri (String uri ) {
91- if (uri == null || uri .isEmpty ()) return "index.html" ;
92-
93- int endIndex = Math .min (
94- uri .indexOf ('?' ) < 0 ? uri .length () : uri .indexOf ('?' ),
95- uri .indexOf ('#' ) < 0 ? uri .length () : uri .indexOf ('#' )
96- );
97-
98- return uri .substring (0 , endIndex )
99- .replace ("\0 " , "" )
100- .replaceAll ("^/+" , "" )
101- .replaceAll ("^$" , "index.html" );
102- resolveTargetFile (parser .getUri ());
103- sfh .sendGetRequest (client .getOutputStream (), uri );
104- }
105-
10678 private HttpResponseBuilder applyFilters (HttpRequest request ) {
10779 HttpResponseBuilder response = new HttpResponseBuilder ();
10880 FilterChainImpl chain = new FilterChainImpl (filters );
10981 chain .doFilter (request , response );
11082 return response ;
11183 }
11284
113- private void resolveTargetFile (String uri ) {
114- if (uri == null || "/" .equals (uri )) {
115- this .uri = "index.html" ;
116- } else {
117- this .uri = uri .startsWith ("/" ) ? uri .substring (1 ) : uri ;
118- }
119- }
120-
12185 @ Override
12286 public void close () throws Exception {
12387 client .close ();
0 commit comments