public static void decodePayload(byte[] data, DecodePayloadCallback callback) { ByteBuffer bufferTail = ByteBuffer.wrap(data); List<Object> buffers = new ArrayList<Object>(); while (bufferTail.capacity() > 0) { StringBuilder strLen = new StringBuilder(); boolean isString = (bufferTail.get(0) & 0xFF) == 0; boolean numberTooLong = false; for (int i = 1; ; i++) { int b = bufferTail.get(i) & 0xFF; if (b == 255) break; // supports only integer if (strLen.length() > MAX_INT_CHAR_LENGTH) { numberTooLong = true; break; } strLen.append(b); } if (numberTooLong) { @SuppressWarnings("unchecked") DecodePayloadCallback<String> tempCallback = callback; tempCallback.call(err, 0, 1); return; } bufferTail.position(strLen.length() + 1); bufferTail = bufferTail.slice(); int msgLength = Integer.parseInt(strLen.toString()); bufferTail.position(1); bufferTail.limit(msgLength + 1); byte[] msg = new byte[bufferTail.remaining()]; bufferTail.get(msg); if (isString) { buffers.add(byteArrayToString(msg)); } else { buffers.add(msg); } bufferTail.clear(); bufferTail.position(msgLength + 1); bufferTail = bufferTail.slice(); } int total = buffers.size(); for (int i = 0; i < total; i++) { Object buffer = buffers.get(i); if (buffer instanceof String) { @SuppressWarnings("unchecked") DecodePayloadCallback<String> tempCallback = callback; tempCallback.call(decodePacket((String) buffer, true), i, total); } else if (buffer instanceof byte[]) { @SuppressWarnings("unchecked") DecodePayloadCallback<byte[]> tempCallback = callback; tempCallback.call(decodePacket((byte[]) buffer), i, total); } } }
public static void decodePayload(String data, DecodePayloadCallback<String> callback) { if (data == null || data.length() == 0) { callback.call(err, 0, 1); return; } StringBuilder length = new StringBuilder(); for (int i = 0, l = data.length(); i < l; i++) { char chr = data.charAt(i); if (':' != chr) { length.append(chr); } else { int n; try { n = Integer.parseInt(length.toString()); } catch (NumberFormatException e) { callback.call(err, 0, 1); return; } String msg; try { msg = data.substring(i + 1, i + 1 + n); } catch (IndexOutOfBoundsException e) { callback.call(err, 0, 1); return; } if (msg.length() != 0) { Packet<String> packet = decodePacket(msg, true); if (err.type.equals(packet.type) && err.data.equals(packet.data)) { callback.call(err, 0, 1); return; } boolean ret = callback.call(packet, i + n, l); if (!ret) return; } i += n; length = new StringBuilder(); } } if (length.length() > 0) { callback.call(err, 0, 1); } }