Skip to content

Commit fffdebf

Browse files
committed
updaterat i StaticFileHandler och skapat CacheFilter
1 parent 8e0ab50 commit fffdebf

File tree

2 files changed

+29
-21
lines changed

2 files changed

+29
-21
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package org.example;
2+
3+
import java.io.IOException;
4+
5+
public class CacheFilter {
6+
private final FileCache cache = new FileCache();
7+
8+
public byte[] getOrFetch(String uri, FileProvider provider) throws IOException {
9+
if (cache.contains(uri)) {
10+
System.out.println("✓ Cache hit for: " + uri);
11+
return cache.get(uri);
12+
}
13+
System.out.println("✗ Cache miss for: " + uri);
14+
byte[] fileBytes = provider.fetch(uri);
15+
cache.put(uri, fileBytes);
16+
return fileBytes;
17+
}
18+
19+
@FunctionalInterface
20+
public interface FileProvider {
21+
byte[] fetch(String uri) throws IOException;
22+
}
23+
}

src/main/java/org/example/StaticFileHandler.java

Lines changed: 6 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -11,32 +11,17 @@
1111

1212
public class StaticFileHandler {
1313
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();
1615

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+
3421
HttpResponseBuilder response = new HttpResponseBuilder();
3522
response.setHeaders(Map.of("Content-Type", "text/html; charset=utf-8"));
3623
response.setBody(fileBytes);
3724
PrintWriter writer = new PrintWriter(outputStream, true);
3825
writer.println(response.build());
39-
4026
}
41-
4227
}

0 commit comments

Comments
 (0)