io.socket.parser.Parser Maven / Gradle / Ivy
package io.socket.parser;
import io.socket.emitter.Emitter;
import org.json.JSONException;
import org.json.JSONTokener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Parser {
private static final Logger logger = Logger.getLogger(Parser.class.getName());
/**
* Packet type `connect`.
*/
public static final int CONNECT = 0;
/**
* Packet type `disconnect`.
*/
public static final int DISCONNECT = 1;
/**
* Packet type `event`.
*/
public static final int EVENT = 2;
/**
* Packet type `ack`.
*/
public static final int ACK = 3;
/**
* Packet type `error`.
*/
public static final int ERROR = 4;
/**
* Packet type `binary event`.
*/
public static final int BINARY_EVENT = 5;
/**
* Packet type `binary ack`.
*/
public static final int BINARY_ACK = 6;
public static int protocol = 4;
/**
* Packet types.
*/
public static String[] types = new String[] {
"CONNECT",
"DISCONNECT",
"EVENT",
"ACK",
"ERROR",
"BINARY_EVENT",
"BINARY_ACK"
};
private Parser() {}
private static Packet error() {
return new Packet(ERROR, "parser error");
}
public static class Encoder {
public Encoder() {}
public void encode(Packet obj, Callback callback) {
logger.fine(String.format("encoding packet %s", obj));
if (BINARY_EVENT == obj.type || BINARY_ACK == obj.type) {
encodeAsBinary(obj, callback);
} else {
String encoding = encodeAsString(obj);
callback.call(new String[] {encoding});
}
}
private String encodeAsString(Packet obj) {
StringBuilder str = new StringBuilder();
boolean nsp = false;
str.append(obj.type);
if (BINARY_EVENT == obj.type || BINARY_ACK == obj.type) {
str.append(obj.attachments);
str.append("-");
}
if (obj.nsp != null && obj.nsp.length() != 0 && !"/".equals(obj.nsp)) {
nsp = true;
str.append(obj.nsp);
}
if (obj.id >= 0) {
if (nsp) {
str.append(",");
nsp = false;
}
str.append(obj.id);
}
if (obj.data != null) {
if (nsp) str.append(",");
str.append(obj.data);
}
logger.fine(String.format("encoded %s as %s", obj, str));
return str.toString();
}
private void encodeAsBinary(Packet obj, Callback callback) {
Binary.DeconstructedPacket deconstruction = Binary.deconstructPacket(obj);
String pack = encodeAsString(deconstruction.packet);
List