-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBackendGossipHandler.java
More file actions
73 lines (63 loc) · 2.39 KB
/
BackendGossipHandler.java
File metadata and controls
73 lines (63 loc) · 2.39 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
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.MethodNotSupportedException;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
public class BackendGossipHandler implements HttpRequestHandler {
private static Logger log = Logger.getLogger(BackendGossipHandler.class);
public void handle(final HttpRequest request, final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
log.info("Backend: Handling StatusUpdate; Line = "
+ request.getRequestLine());
String method = request.getRequestLine().getMethod()
.toUpperCase(Locale.ENGLISH);
if (method.equals("POST")) {
final String target = request.getRequestLine().getUri();
Pattern p_uri = Pattern.compile("/data/gossip\\?s=(.*)$");
Pattern p_body = Pattern.compile("/data/gossip");
Matcher m_uri = p_uri.matcher(target);
Matcher m_body = p_body.matcher(target);
String message = null;
if (m_uri.find()) {
message = m_uri.group(1);
} else if (m_body.find()) {
HttpEntity entity = ((HttpEntityEnclosingRequest) request)
.getEntity();
String entityContent = EntityUtils.toString(entity);
Pattern p = Pattern.compile("s=(.*)$");
Matcher m = p.matcher(entityContent);
if (m.find()) {
message = m.group(1);
}
} else {
response.setStatusCode(HttpStatus.SC_BAD_REQUEST);
return;
}
if (message != null) {
JSONgossipMessage j = WebServer.g.fromJson(URLDecoder.decode(message, "UTF-8"), JSONgossipMessage.class);
ServerStateManager.mergeInfo(j.snapshot);
ServerStateManager.getSnapshot().get(j.myState.getID()).updateLastSeen();
if (j.tweets != null && j.tweets.size() > 0) {
BackendDataStorage bds = BackendDataStorage.getInstance();
bds.mergeTweets(j.tweets, j.myState.getClockVal());
}
} else {
response.setStatusCode(HttpStatus.SC_BAD_REQUEST);
}
} else {
throw new MethodNotSupportedException(method
+ " method not supported\n");
}
}
}