-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFrontendDataCache.java
More file actions
86 lines (73 loc) · 2.36 KB
/
FrontendDataCache.java
File metadata and controls
86 lines (73 loc) · 2.36 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import com.google.gson.Gson;
public class FrontendDataCache {
//private static Logger log = Logger.getLogger(FrontendDataCache.class);
private static Gson g = new Gson();
private final HashMap<String, CacheNode> index;
private static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
private static FrontendDataCache instance;
private FrontendDataCache() {
index = new HashMap<String, CacheNode>();
}
public static FrontendDataCache getInstance() {
if (instance == null) {
synchronized (FrontendDataCache.class) {
if (instance == null) {
instance = new FrontendDataCache();
}
}
}
return instance;
}
public VectorClock getVersion(String hash) {
VectorClock retval = null;
CacheNode tweet = null;
lock.readLock().lock();
if ((tweet = index.get(hash)) != null) {
retval = tweet.getVersion();
}
lock.readLock().unlock();
if (retval == null) {
retval = new VectorClock();
}
return retval;
}
public String getTweets(String query, String entityContent) {
JSONbackendResponse backResp = g.fromJson(entityContent, JSONbackendResponse.class);
JSONfrontendResponse response = null;
lock.readLock().lock();
if (backResp.status.equals("ok")) {
response = new JSONfrontendResponse(query, "yes", index.get(query).getContent());
} else if (backResp.status.equals("updated")) {
index.put(query, new CacheNode(backResp.version, backResp.tweets));
response = new JSONfrontendResponse(query, "no", index.get(query).getContent());
} else {
ArrayList<String> temp = new ArrayList<String>();
temp.add("No content");
response = new JSONfrontendResponse(query, "no", temp);
}
lock.readLock().unlock();
return g.toJson(response, JSONfrontendResponse.class);
}
public void addTweet(String hash, VectorClock version, ArrayList<String> tweets) {
lock.writeLock().lock();
index.put(hash, new CacheNode(version, tweets));
lock.writeLock().unlock();
}
private class CacheNode {
private VectorClock version;
private ArrayList<String> content;
public CacheNode(VectorClock version, ArrayList<String> content) {
this.version = version;
this.content = content;
}
public VectorClock getVersion() {
return version;
}
public ArrayList<String> getContent() {
return content;
}
}
}