-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMessageExchange.java
More file actions
62 lines (44 loc) · 1.86 KB
/
MessageExchange.java
File metadata and controls
62 lines (44 loc) · 1.86 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
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.*;
import java.util.List;
public class MessageExchange {
private JSONParser jsonParser = new JSONParser();
public String getToken(int index) {
Integer number = index * 8 + 11;
return "TN" + number + "EN";
}
public int getIndex(String token) {
return (Integer.valueOf(token.substring(2, token.length() - 2)) - 11) / 8;
}
public String getServerResponse(List<Message> messages, int index) {
List<Message> chunk = messages.subList(index, messages.size());
JSONObject jsonObject = new JSONObject();
jsonObject.put("messages", chunk);
jsonObject.put("token", getToken(messages.size()));
return jsonObject.toJSONString();
}
public Message getClientMessage(InputStream inputStream) throws Exception {
JSONObject json = getJSONObject(inputStreamToString(inputStream));
return new Message((String)json.get("id"), (String)json.get("message"), (String)json.get("user") );
}
public String getErrorMessage(String text) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("error", text);
return jsonObject.toJSONString();
}
public JSONObject getJSONObject(String json) throws ParseException {
return (JSONObject) jsonParser.parse(json.trim());
}
public String inputStreamToString(InputStream in) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length = 0;
while ((length = in.read(buffer)) != -1) {
baos.write(buffer, 0, length);
}
System.out.println("Input stream " + new String(baos.toByteArray()));
return new String(baos.toByteArray());
}
}