Packet.java
3.17 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/*
* Decompiled with CFR 0_118.
*
* Could not load the following classes:
* org.apache.sling.commons.json.JSONArray
* org.apache.sling.commons.json.JSONException
* org.slf4j.Logger
* org.slf4j.LoggerFactory
*/
package com.adobe.granite.socketio.impl;
import com.adobe.granite.socketio.impl.PacketType;
import org.apache.sling.commons.json.JSONArray;
import org.apache.sling.commons.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Packet {
private static final Logger log = LoggerFactory.getLogger(Packet.class);
public final PacketType type;
public final String nsp;
public final long id;
public final JSONArray data;
public final int attachments;
public Packet(PacketType type, String nsp, long id, JSONArray data, int attachments) {
this.type = type;
this.nsp = nsp == null ? "/" : nsp;
this.id = id;
this.data = data;
this.attachments = attachments;
}
public String encode() {
if (this.type == PacketType.BINARY_EVENT || this.type == PacketType.BINARY_ACK) {
throw new UnsupportedOperationException("binary packets not supported yet.");
}
StringBuilder str = new StringBuilder();
boolean hasNsp = false;
str.append(this.type.code);
if (!"/".equals(this.nsp)) {
str.append(this.nsp);
hasNsp = true;
}
if (this.id >= 0) {
if (hasNsp) {
str.append(",");
hasNsp = false;
}
str.append(this.id);
}
if (this.data != null) {
if (hasNsp) {
str.append(",");
}
str.append(this.data.toString());
}
return str.toString();
}
public static Packet decode(String str) {
PacketType type;
int d;
int idx;
int numAttachments = 0;
int i = 0;
if (((type = PacketType.valueOf(str.charAt(i++))) == PacketType.BINARY_EVENT || type == PacketType.BINARY_ACK) && (idx = str.indexOf(45)) > 0) {
numAttachments = Integer.valueOf(str.substring(1, idx));
i = idx + 1;
}
if (i == str.length()) {
return new Packet(type, "/", -1, null, 0);
}
String nsp = "/";
if ('/' == str.charAt(i)) {
int idx2 = str.indexOf(44, i);
if (idx2 < 0) {
idx2 = str.length();
}
nsp = str.substring(i, idx2);
i = idx2 + 1;
}
long id = -1;
while (i < str.length() && (d = Character.digit(str.charAt(i), 10)) >= 0) {
id = id < 0 ? (long)d : id * 10 + (long)d;
++i;
}
if (i < str.length() && str.charAt(i) == ',') {
++i;
}
JSONArray data = null;
if (i < str.length()) {
try {
data = new JSONArray(str.substring(i));
}
catch (JSONException e) {
log.error("Error decoding packet", (Throwable)e);
type = PacketType.PARSER_ERROR;
}
}
return new Packet(type, nsp, id, data, numAttachments);
}
}