|
11 | 11 |
|
12 | 12 | public class StaticFileHandler { |
13 | 13 | private static final String WEB_ROOT = "www"; |
14 | | - private byte[] fileBytes; |
15 | | - private final FileCache cache = new FileCache(); |
| 14 | + private final CacheFilter cacheFilter = new CacheFilter(); |
16 | 15 |
|
17 | | - public StaticFileHandler(){} |
18 | | - |
19 | | - private void handleGetRequest(String uri) throws IOException { |
20 | | - if (cache.contains(uri)) { |
21 | | - System.out.println("✓ Cache hit for: " + uri); |
22 | | - fileBytes = cache.get(uri); |
23 | | - return; |
24 | | - } |
25 | | - System.out.println("✗ Cache miss for: " + uri); |
26 | | - File file = new File(WEB_ROOT, uri); |
27 | | - fileBytes = Files.readAllBytes(file.toPath()); |
28 | | - |
29 | | - cache.put(uri, fileBytes); |
30 | | - } |
31 | | - |
32 | | - public void sendGetRequest(OutputStream outputStream, String uri) throws IOException{ |
33 | | - handleGetRequest(uri); |
| 16 | + public void sendGetRequest(OutputStream outputStream, String uri) throws IOException { |
| 17 | + byte[] fileBytes = cacheFilter.getOrFetch(uri, |
| 18 | + path -> Files.readAllBytes(new File(WEB_ROOT, path).toPath()) |
| 19 | + ); |
| 20 | + |
34 | 21 | HttpResponseBuilder response = new HttpResponseBuilder(); |
35 | 22 | response.setHeaders(Map.of("Content-Type", "text/html; charset=utf-8")); |
36 | 23 | response.setBody(fileBytes); |
37 | 24 | PrintWriter writer = new PrintWriter(outputStream, true); |
38 | 25 | writer.println(response.build()); |
39 | | - |
40 | 26 | } |
41 | | - |
42 | 27 | } |
0 commit comments