-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathStompAdapter.java
77 lines (70 loc) · 2.45 KB
/
StompAdapter.java
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
package karate;
import com.intuit.karate.Json;
import io.karatelabs.websocket.WebsocketAdapter;
import io.karatelabs.websocket.WebsocketConsumer;
import java.util.LinkedHashMap;
import java.util.Map;
public class StompAdapter implements WebsocketAdapter<Map<String, Object>, String> {
@Override
public void onMessage(WebsocketConsumer client, Map<String, Object> msg) {
client.receive(msg);
}
@SuppressWarnings("unchecked")
@Override
public String toWire(Map<String, Object> map) {
String command = (String) map.get("command");
Map<String, Object> headers = (Map<String, Object>) map.get("headers");
Object body = map.get("body");
if (body instanceof Map) {
body = Json.of(body).toString();
}
StringBuilder sb = new StringBuilder();
sb.append(command).append('\n');
if (headers != null) {
headers.forEach((k, v) -> {
sb.append(k).append(':').append(v).append('\n');
});
}
sb.append('\n');
if (body != null) {
sb.append(body);
}
sb.append('\0');
return sb.toString();
}
@Override
public Map<String, Object> fromWire(String text) {
Map<String, Object> map = new LinkedHashMap<>();
String[] lines = text.split("\\R");
Map<String, String> headers = new LinkedHashMap<>();
boolean headersDone = false;
for (String line : lines) {
if (map.isEmpty()) {
map.put("command", line);
} else if (line.isEmpty()) {
map.put("headers", headers);
headersDone = true;
} else if ("\0".equals(line)) {
continue;
} else {
if (headersDone) {
line = line.trim();
if (line.charAt(0) == '{') {
map.put("body", Json.of(line).asMap());
} else {
map.put("body", line);
}
} else {
int pos = line.indexOf(':');
if (pos == -1) {
throw new RuntimeException("unexpected header: " + line);
}
String key = line.substring(0, pos);
String value = line.substring(pos + 1);
headers.put(key, value);
}
}
}
return map;
}
}