-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMemoryCache.java
More file actions
58 lines (47 loc) · 1.49 KB
/
MemoryCache.java
File metadata and controls
58 lines (47 loc) · 1.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.*;
public class MemoryCache extends ResponseCache {
private final Map<URI, SimpleCacheResponse> responses
= new ConcurrentHashMap<URI, SimpleCacheResponse>();
private final int maxEntries;
public MemoryCache() {
this(100);
}
public MemoryCache(int maxEntries) {
this.maxEntries = maxEntries;
}
@Override
public CacheRequest put(URI uri, URLConnection conn)
throws IOException {
if (responses.size() >= maxEntries) return null;
CacheControl control = new CacheControl(conn.getHeaderField("Cache-Control"));
if (control.noStore()) {
return null;
} else if (!conn.getHeaderField(0).startsWith("GET ")) {
// only cache GET
return null;
}
SimpleCacheRequest request = new SimpleCacheRequest();
SimpleCacheResponse response = new SimpleCacheResponse(request, conn, control);
responses.put(uri, response);
return request;
}
@Override
public CacheResponse get(URI uri, String requestMethod,
Map<String, List<String>> requestHeaders)
throws IOException {
if ("GET".equals(requestMethod)) {
SimpleCacheResponse response = responses.get(uri);
// check expiration date
if (response != null && response.isExpired()) {
responses.remove(response);
response = null;
}
return response;
} else {
return null;
}
}
}