Example usage for io.netty.buffer ByteBuf getByte

List of usage examples for io.netty.buffer ByteBuf getByte

Introduction

In this page you can find the example usage for io.netty.buffer ByteBuf getByte.

Prototype

public abstract byte getByte(int index);

Source Link

Document

Gets a byte at the specified absolute index in this buffer.

Usage

From source file:org.traccar.protocol.TotemFrameDecoder.java

License:Apache License

@Override
protected Object decode(ChannelHandlerContext ctx, Channel channel, ByteBuf buf) throws Exception {

    if (buf.readableBytes() < 10) {
        return null;
    }//from w  ww  .  ja v a2  s  .  c  om

    int beginIndex = BufferUtil.indexOf("$$", buf);
    if (beginIndex == -1) {
        return null;
    } else if (beginIndex > buf.readerIndex()) {
        buf.readerIndex(beginIndex);
    }

    int length;

    if (buf.getByte(buf.readerIndex() + 2) == (byte) '0') {
        length = Integer.parseInt(buf.toString(buf.readerIndex() + 2, 4, StandardCharsets.US_ASCII));
    } else {
        length = Integer.parseInt(buf.toString(buf.readerIndex() + 2, 2, StandardCharsets.US_ASCII), 16);
    }

    if (length <= buf.readableBytes()) {
        return buf.readRetainedSlice(length);
    }

    return null;
}

From source file:org.traccar.protocol.UproProtocolDecoder.java

License:Apache License

@Override
protected Object decode(Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {

    ByteBuf buf = (ByteBuf) msg;

    if (buf.getByte(buf.readerIndex()) != '*') {
        return null;
    }/*from  ww w .java 2 s .  c o m*/

    int headerIndex = buf.indexOf(buf.readerIndex(), buf.writerIndex(), (byte) '&');
    if (headerIndex < 0) {
        headerIndex = buf.writerIndex();
    }
    String header = buf.readSlice(headerIndex - buf.readerIndex()).toString(StandardCharsets.US_ASCII);

    Parser parser = new Parser(PATTERN_HEADER, header);
    if (!parser.matches()) {
        return null;
    }

    String head = parser.next();
    boolean reply = parser.next().equals("1");

    DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, parser.next());
    if (deviceSession == null) {
        return null;
    }

    Position position = new Position(getProtocolName());
    position.setDeviceId(deviceSession.getDeviceId());

    String type = parser.next();
    String subtype = parser.next();

    if (reply && channel != null) {
        channel.writeAndFlush(new NetworkMessage("*" + head + "Y" + type + subtype + "#", remoteAddress));
    }

    while (buf.isReadable()) {

        buf.readByte(); // skip delimiter

        byte dataType = buf.readByte();

        int delimiterIndex = buf.indexOf(buf.readerIndex(), buf.writerIndex(), (byte) '&');
        if (delimiterIndex < 0) {
            delimiterIndex = buf.writerIndex();
        }

        ByteBuf data = buf.readSlice(delimiterIndex - buf.readerIndex());

        switch (dataType) {
        case 'A':
            decodeLocation(position, data.toString(StandardCharsets.US_ASCII));
            break;
        case 'B':
            position.set(Position.KEY_STATUS, data.toString(StandardCharsets.US_ASCII));
            break;
        case 'C':
            long odometer = 0;
            while (data.isReadable()) {
                odometer <<= 4;
                odometer += data.readByte() - (byte) '0';
            }
            position.set(Position.KEY_ODOMETER, odometer * 2 * 1852 / 3600);
            break;
        case 'F':
            position.setSpeed(Integer.parseInt(data.readSlice(4).toString(StandardCharsets.US_ASCII)) * 0.1);
            break;
        case 'K':
            position.set("statusExtended", data.toString(StandardCharsets.US_ASCII));
            break;
        case 'P':
            if (data.readableBytes() >= 16) {
                position.setNetwork(new Network(
                        CellTower.from(Integer.parseInt(data.readSlice(4).toString(StandardCharsets.US_ASCII)),
                                Integer.parseInt(data.readSlice(4).toString(StandardCharsets.US_ASCII)),
                                Integer.parseInt(data.readSlice(4).toString(StandardCharsets.US_ASCII), 16),
                                Integer.parseInt(data.readSlice(4).toString(StandardCharsets.US_ASCII), 16))));
            }
            break;
        case 'Q':
            position.set("obdPid", ByteBufUtil.hexDump(data));
            break;
        case 'R':
            if (head.startsWith("HQ")) {
                position.set(Position.KEY_RSSI,
                        Integer.parseInt(data.readSlice(2).toString(StandardCharsets.US_ASCII)));
                position.set(Position.KEY_SATELLITES,
                        Integer.parseInt(data.readSlice(2).toString(StandardCharsets.US_ASCII)));
            } else {
                position.set("odbTravel", ByteBufUtil.hexDump(data));
            }
            break;
        case 'S':
            position.set("obdTraffic", ByteBufUtil.hexDump(data));
            break;
        case 'T':
            position.set(Position.KEY_BATTERY_LEVEL,
                    Integer.parseInt(data.readSlice(2).toString(StandardCharsets.US_ASCII)));
            break;
        case 'V':
            position.set(Position.KEY_POWER,
                    Integer.parseInt(data.readSlice(4).toString(StandardCharsets.US_ASCII)) * 0.1);
            break;
        default:
            break;
        }

    }

    if (position.getLatitude() != 0 && position.getLongitude() != 0) {
        return position;
    }

    return null;
}

From source file:org.traccar.protocol.WatchProtocolDecoder.java

License:Apache License

@Override
protected Object decode(Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {

    ByteBuf buf = (ByteBuf) msg;

    buf.skipBytes(1); // '[' header
    manufacturer = buf.readSlice(2).toString(StandardCharsets.US_ASCII);
    buf.skipBytes(1); // '*' delimiter

    int idIndex = buf.indexOf(buf.readerIndex(), buf.writerIndex(), (byte) '*');
    String id = buf.readSlice(idIndex - buf.readerIndex()).toString(StandardCharsets.US_ASCII);
    DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, id);
    if (deviceSession == null) {
        return null;
    }/*from  www.  j a va  2s  .c  o m*/

    buf.skipBytes(1); // '*' delimiter

    String index = null;
    int contentIndex = buf.indexOf(buf.readerIndex(), buf.writerIndex(), (byte) '*');
    if (contentIndex + 5 < buf.writerIndex() && buf.getByte(contentIndex + 5) == '*'
            && buf.toString(contentIndex + 1, 4, StandardCharsets.US_ASCII).matches("\\p{XDigit}+")) {
        int indexLength = buf.indexOf(buf.readerIndex(), buf.writerIndex(), (byte) '*') - buf.readerIndex();
        hasIndex = true;
        index = buf.readSlice(indexLength).toString(StandardCharsets.US_ASCII);
        buf.skipBytes(1); // '*' delimiter
    }

    buf.skipBytes(4); // length
    buf.skipBytes(1); // '*' delimiter

    buf.writerIndex(buf.writerIndex() - 1); // ']' ignore ending

    contentIndex = buf.indexOf(buf.readerIndex(), buf.writerIndex(), (byte) ',');
    if (contentIndex < 0) {
        contentIndex = buf.writerIndex();
    }

    String type = buf.readSlice(contentIndex - buf.readerIndex()).toString(StandardCharsets.US_ASCII);

    if (contentIndex < buf.writerIndex()) {
        buf.readerIndex(contentIndex + 1);
    }

    if (type.equals("INIT")) {

        sendResponse(channel, id, index, "INIT,1");

    } else if (type.equals("LK")) {

        sendResponse(channel, id, index, "LK");

        if (buf.isReadable()) {
            String[] values = buf.toString(StandardCharsets.US_ASCII).split(",");
            if (values.length >= 3) {
                Position position = new Position(getProtocolName());
                position.setDeviceId(deviceSession.getDeviceId());

                getLastLocation(position, null);

                position.set(Position.KEY_BATTERY_LEVEL, Integer.parseInt(values[2]));

                return position;
            }
        }

    } else if (type.equals("UD") || type.equals("UD2") || type.equals("UD3") || type.equals("AL")
            || type.equals("WT")) {

        Position position = decodePosition(deviceSession, buf.toString(StandardCharsets.US_ASCII));

        if (type.equals("AL")) {
            if (position != null) {
                position.set(Position.KEY_ALARM, Position.ALARM_SOS);
            }
            sendResponse(channel, id, index, "AL");
        }

        return position;

    } else if (type.equals("TKQ")) {

        sendResponse(channel, id, index, "TKQ");

    } else if (type.equals("PULSE") || type.equals("heart") || type.equals("bphrt")) {

        if (buf.isReadable()) {

            Position position = new Position(getProtocolName());
            position.setDeviceId(deviceSession.getDeviceId());

            getLastLocation(position, new Date());

            String[] values = buf.toString(StandardCharsets.US_ASCII).split(",");
            int valueIndex = 0;

            if (type.equals("bphrt")) {
                position.set("pressureHigh", values[valueIndex++]);
                position.set("pressureLow", values[valueIndex++]);
            }
            position.set(Position.KEY_HEART_RATE, Integer.parseInt(values[valueIndex]));

            return position;

        }

    } else if (type.equals("img")) {

        Position position = new Position(getProtocolName());
        position.setDeviceId(deviceSession.getDeviceId());

        getLastLocation(position, null);

        int timeIndex = buf.indexOf(buf.readerIndex(), buf.writerIndex(), (byte) ',');
        buf.readerIndex(timeIndex + 12 + 2);
        position.set(Position.KEY_IMAGE, Context.getMediaManager().writeFile(id, buf, "jpg"));

        return position;

    } else if (type.equals("TK")) {

        if (buf.readableBytes() == 1) {
            byte result = buf.readByte();
            if (result != '1') {
                LOGGER.warn(type + "," + result);
            }
            return null;
        }

        Position position = new Position(getProtocolName());
        position.setDeviceId(deviceSession.getDeviceId());

        getLastLocation(position, null);

        position.set(Position.KEY_AUDIO, Context.getMediaManager().writeFile(id, buf, "amr"));

        return position;

    }

    return null;
}

From source file:ratpack.sse.internal.ServerSentEventDecoder.java

License:Apache License

/**
 * This code tries to eliminate the need of creating a string from the ByteBuf as the field names are very
 * constrained. The algorithm is as follows:
 *
 * -- Scan the bytes in the buffer./*from  w  w w . ja v a2s.  co  m*/
 * -- If the first byte matches the expected field names then use the matching field name char array to verify
 * the rest of the field name.
 * -- If the first byte does not match, reject the field name.
 * -- After the first byte, exact match the rest of the field name with the expected field name, byte by byte.
 * -- If the name does not exactly match the expected value, then reject the field name.
 */
private static FieldName readCurrentFieldTypeFromBuffer(final ByteBuf fieldNameBuffer) {

    FieldName toReturn = FieldName.Data;
    int readableBytes = fieldNameBuffer.readableBytes();
    final int readerIndexAtStart = fieldNameBuffer.readerIndex();
    char[] fieldNameToVerify = DATA_FIELD_NAME;
    boolean verified = false;
    int actualFieldNameIndexToCheck = 0; // Starts with 1 as the first char is validated by equality.
    for (int i = readerIndexAtStart; i < readableBytes; i++) {
        final char charAtI = (char) fieldNameBuffer.getByte(i);
        if (i == readerIndexAtStart) {
            switch (charAtI) { // See which among the known field names this buffer belongs.
            case 'e':
                fieldNameToVerify = EVENT_ID_FIELD_NAME;
                toReturn = FieldName.Event;
                break;
            case 'd':
                fieldNameToVerify = DATA_FIELD_NAME;
                toReturn = FieldName.Data;
                break;
            case 'i':
                fieldNameToVerify = ID_FIELD_NAME;
                toReturn = FieldName.Id;
                break;
            default:
                return null;
            }
        } else {
            if (++actualFieldNameIndexToCheck >= fieldNameToVerify.length
                    || charAtI != fieldNameToVerify[actualFieldNameIndexToCheck]) {
                // If the character does not match or the buffer is bigger than the expected name, then discard.
                verified = false;
                break;
            } else {
                // Verified till now. If all characters are matching then this stays as verified, else changed to false.
                verified = true;
            }
        }
    }
    if (verified) {
        return toReturn;
    } else {
        return null;
    }
}

From source file:ru.jts_dev.gameserver.util.Encoder.java

License:Open Source License

@Transformer
public ByteBuf decrypt(ByteBuf data, @Header(CONNECTION_ID) String connectionId) {
    GameSession gameSession = sessionService.getSessionBy(connectionId);

    assert gameSession != null : "GameSession for " + connectionId + " does not exist";

    ByteBuf key = gameSession.getDecryptKey();

    int temp = 0;
    for (int i = 0; i < data.readableBytes(); i++) {
        final int temp2 = data.getUnsignedByte(i);
        data.setByte(i, (byte) (temp2 ^ key.getByte(i & 15) ^ temp));
        temp = temp2;/*ww  w. ja  v  a  2 s .  c  o m*/
    }

    int old = key.getInt(8);
    old += data.readableBytes();

    key.setInt(8, old);

    return data;
}

From source file:ru.jts_dev.gameserver.util.Encoder.java

License:Open Source License

@Transformer
public ByteBuf encrypt(ByteBuf data, @Header(CONNECTION_ID) String connectionId) {
    GameSession gameSession = sessionService.getSessionBy(connectionId);

    assert gameSession != null : "GameSession for " + connectionId + " does not exist";

    ByteBuf key = gameSession.getEncryptKey();

    int temp = 0;
    for (int i = 0; i < data.readableBytes(); i++) {
        int temp2 = data.getUnsignedByte(data.readerIndex() + i);
        temp = temp2 ^ key.getByte(i & 15) ^ temp;
        data.setByte(data.readerIndex() + i, (byte) temp);
    }/*  w  w  w.j ava 2s. c  o m*/

    int old = key.getInt(8);
    old += data.readableBytes();

    key.setInt(8, old);

    return data;
}

From source file:sailfish.remoting.codec.DefaultRemotingCodec.java

License:Apache License

@Override
public Protocol decode(ByteBuf buffer) throws SailfishException {
    short magic = buffer.readShort();
    if (RemotingConstants.SAILFISH_MAGIC != magic) {
        throw new SailfishException(ExceptionCode.BAD_PACKAGE,
                "bad packet, expected magic:" + RemotingConstants.SAILFISH_MAGIC + ", but actual:" + magic
                        + ", current channel will be closed!");
    }/*from www . jav a2s.c o  m*/

    int totalLength = buffer.readInt();
    byte compactByte = buffer.getByte(buffer.readerIndex());
    boolean request = ((compactByte & RequestProtocol.REQUEST_FLAG) != 0);

    Protocol protocol;
    //recycle Protocol
    if (request) {//request
        protocol = RequestProtocol.newInstance();
    } else {//response
        protocol = ResponseProtocol.newInstance();
    }
    protocol.deserialize(buffer, totalLength);
    return protocol;
}

From source file:starnubserver.servers.starbound.TCPProxyServerPacketDecoder.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override//from   ww  w. j  a v  a  2 s  .c  o m
public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    switch (state()) {
    case READ_PACKET_ID: {
        packetIDIndex = in.readerIndex();
        byte packetId = in.getByte(packetIDIndex);
        packet = PACKET_POOL.get(packetId);
        checkpoint(DecoderState.READ_VLQ);
    }
    case READ_VLQ: {
        clearVLQ();
        int tempIndexMarker = packetIDIndex + 1;
        while (vlqLength <= 10) {
            int tmpByte = in.getByte(tempIndexMarker);
            payloadLength = (payloadLength << 7) | (tmpByte & 0x7f);
            vlqLength++;
            if ((tmpByte & 0x80) == 0) {
                break;
            }
            tempIndexMarker++;
        }
        if ((payloadLength & 1) == 0x00) {
            payloadLength = payloadLength >> 1;
        } else {
            payloadLength = -((payloadLength >> 1) + 1);
        }
        compressed = payloadLength < 0;
        if (compressed) {
            payloadLength = -payloadLength;
        }
        checkpoint(DecoderState.READ_PAYLOAD);
    }
    case READ_PAYLOAD: {
        if (packet != null) {
            HashSet<EventSubscription> hashSet = PACKET_EVENT_ROUTER.getEVENT_SUBSCRIPTION_MAP()
                    .get(packet.getClass());
            /* Handle Packet if there is an events handler for it, else do not create objects */
            if (hashSet != null) {
                in.skipBytes(1 + vlqLength);
                if (compressed) {
                    packet.read(Unpooled.wrappedBuffer(1, decompress(in.readBytes(payloadLength).array())));
                } else {
                    packet.read(in.readBytes(payloadLength));
                }
                for (EventSubscription<Packet> packetEventSubscription : hashSet) {
                    if (packet.isRecycle()) {
                        break;
                    }
                    packetEventSubscription.getEVENT_HANDLER().onEvent(packet);
                }
                /* Write packet out, if not recycling */
                if (!packet.isRecycle()) {
                    packet.routeToDestination();
                } else {
                    packet.resetRecycle();
                }
            } else {
                destinationCTX.writeAndFlush(in.readSlice(1 + vlqLength + payloadLength).retain(),
                        destinationCTX.voidPromise());
            }
        } else {
            destinationCTX.writeAndFlush(in.readSlice(1 + vlqLength + payloadLength).retain(),
                    destinationCTX.voidPromise());
        }
        checkpoint(DecoderState.READ_PACKET_ID);
        break;
    }
    default:
        throw new Error("Error Decoding - Reached the unreachable void.");
    }
}

From source file:tonivade.redis.protocol.RedisDecoder.java

License:Open Source License

private static int findEndOfLine(final ByteBuf buffer) {
    int i = buffer.forEachByte(ByteBufProcessor.FIND_LF);
    if (i > 0 && buffer.getByte(i - 1) == '\r') {
        i--;/*ww  w.jav a2s .c  om*/
    }
    return i;
}

From source file:whitespell.net.websockets.socketio.parser.Decoder.java

License:Apache License

private Packet decodePacket(ByteBuf buffer, UUID uuid) throws IOException {
    if (buffer.readableBytes() < 3) {
        throw new DecoderException("Can't parse " + buffer.toString(CharsetUtil.UTF_8));
    }/*from  ww w  . j  av  a2s. co m*/
    PacketType type = getType(buffer);

    int readerIndex = buffer.readerIndex() + 1;
    // 'null' to avoid unnecessary StringBuilder creation
    boolean hasData = false;
    StringBuilder messageId = null;
    for (readerIndex += 1; readerIndex < buffer.readableBytes(); readerIndex++) {
        if (messageId == null) {
            messageId = new StringBuilder(4);
        }
        byte msg = buffer.getByte(readerIndex);
        if (msg == Packet.SEPARATOR) {
            break;
        }
        if (msg != (byte) '+') {
            messageId.append((char) msg);
        } else {
            hasData = true;
        }
    }
    Long id = null;
    if (messageId != null && messageId.length() > 0) {
        id = Long.valueOf(messageId.toString());
    }

    // 'null' to avoid unnecessary StringBuilder creation
    StringBuilder endpointBuffer = null;
    for (readerIndex += 1; readerIndex < buffer.readableBytes(); readerIndex++) {
        if (endpointBuffer == null) {
            endpointBuffer = new StringBuilder();
        }
        byte msg = buffer.getByte(readerIndex);
        if (msg == Packet.SEPARATOR) {
            break;
        }
        endpointBuffer.append((char) msg);
    }

    String endpoint = Namespace.DEFAULT_NAME;
    if (endpointBuffer != null && endpointBuffer.length() > 0) {
        endpoint = endpointBuffer.toString();
    }

    if (buffer.readableBytes() == readerIndex) {
        buffer.readerIndex(buffer.readableBytes());
    } else {
        readerIndex += 1;
        buffer.readerIndex(readerIndex);
    }

    Packet packet = new Packet(type);
    packet.setEndpoint(endpoint);
    if (id != null) {
        packet.setId(id);
        if (hasData) {
            packet.setAck(Packet.ACK_DATA);
        } else {
            packet.setAck(true);
        }
    }

    switch (type) {
    case ERROR: {
        if (!buffer.isReadable()) {
            break;
        }
        String[] pieces = buffer.toString(CharsetUtil.UTF_8).split("\\+");
        if (pieces.length > 0 && pieces[0].trim().length() > 0) {
            ErrorReason reason = ErrorReason.valueOf(Integer.valueOf(pieces[0]));
            packet.setReason(reason);
            if (pieces.length > 1) {
                ErrorAdvice advice = ErrorAdvice.valueOf(Integer.valueOf(pieces[1]));
                packet.setAdvice(advice);
            }
        }
        break;
    }

    case MESSAGE: {
        if (buffer.isReadable()) {
            packet.setData(buffer.toString(CharsetUtil.UTF_8));
        } else {
            packet.setData("");
        }
        break;
    }

    case EVENT: {
        ByteBufInputStream in = new ByteBufInputStream(buffer);
        Event event = jsonSupport.readValue(in, Event.class);
        packet.setName(event.getName());
        if (event.getArgs() != null) {
            packet.setArgs(event.getArgs());
        }
        break;
    }

    case JSON: {
        ByteBufInputStream in = new ByteBufInputStream(buffer);
        JsonObject obj = jsonSupport.readValue(in, JsonObject.class);
        if (obj != null) {
            packet.setData(obj.getObject());
        } else {
            in.reset();
            Object object = jsonSupport.readValue(in, Object.class);
            packet.setData(object);
        }
        break;
    }

    case CONNECT: {
        if (buffer.isReadable()) {
            packet.setQs(buffer.toString(CharsetUtil.UTF_8));
        }
        break;
    }

    case ACK: {
        if (!buffer.isReadable()) {
            break;
        }
        boolean validFormat = true;
        int plusIndex = -1;
        for (int i = buffer.readerIndex(); i < buffer.readerIndex() + buffer.readableBytes(); i++) {
            byte dataChar = buffer.getByte(i);
            if (!Character.isDigit(dataChar)) {
                if (dataChar == '+') {
                    plusIndex = i;
                    break;
                } else {
                    validFormat = false;
                    break;
                }
            }
        }
        if (!validFormat) {
            break;
        }

        if (plusIndex == -1) {
            packet.setAckId(parseLong(buffer));
            break;
        } else {
            packet.setAckId(parseLong(buffer, plusIndex));
            buffer.readerIndex(plusIndex + 1);

            ByteBufInputStream in = new ByteBufInputStream(buffer);
            AckCallback<?> callback = ackManager.getCallback(uuid, packet.getAckId());
            AckArgs args = jsonSupport.readAckArgs(in, callback.getResultClass());
            packet.setArgs(args.getArgs());
        }
        break;
    }

    case DISCONNECT:
    case HEARTBEAT:
    case NOOP:
        break;
    }

    buffer.readerIndex(buffer.readerIndex() + buffer.readableBytes());
    return packet;
}