Example usage for io.netty.buffer ByteBuf readByte

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

Introduction

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

Prototype

public abstract byte readByte();

Source Link

Document

Gets a byte at the current readerIndex and increases the readerIndex by 1 in this buffer.

Usage

From source file:com.phei.netty.protocol.netty.codec.NettyMessageDecoder.java

License:Apache License

@Override
protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
    //LengthFieldBasedFrameDecoder??
    //???//from  w w  w .  j a  v  a 2 s  .  c o m
    //i/o????
    ByteBuf frame = (ByteBuf) super.decode(ctx, in);
    if (frame == null) {
        return null;
    }

    NettyMessage message = new NettyMessage();
    Header header = new Header();
    header.setCrcCode(frame.readInt());
    header.setLength(frame.readInt());
    header.setSessionID(frame.readLong());
    header.setType(frame.readByte());
    header.setPriority(frame.readByte());

    int size = frame.readInt();
    if (size > 0) {
        Map<String, Object> attch = new HashMap<String, Object>(size);
        int keySize = 0;
        byte[] keyArray = null;
        String key = null;
        for (int i = 0; i < size; i++) {
            keySize = frame.readInt();
            keyArray = new byte[keySize];
            frame.readBytes(keyArray);
            key = new String(keyArray, "UTF-8");
            attch.put(key, marshallingDecoder.decode(frame));
        }
        keyArray = null;
        key = null;
        header.setAttachment(attch);
    }
    //body??body
    if (frame.readableBytes() > 4) {
        message.setBody(marshallingDecoder.decode(frame));
    }
    message.setHeader(header);
    return message;
}

From source file:com.projectzed.mod.handler.message.MessageTileEntityFluidTank.java

License:Open Source License

@Override
public void fromBytes(ByteBuf buf) {
    this.x = buf.readInt();
    this.y = buf.readInt();
    this.z = buf.readInt();
    this.tier = buf.readByte();
    this.fluidAmount = buf.readInt();
    this.fluidID = buf.readInt();
}

From source file:com.pubkit.platform.messaging.protocol.mqtt.proto.parser.ConnectDecoder.java

License:Open Source License

@Override
public AbstractMessage decode(AttributeMap ctx, ByteBuf in) throws UnsupportedEncodingException {
    in.resetReaderIndex();//from   w w w .java  2 s.c  om
    //Common decoding part
    ConnectMessage message = new ConnectMessage();
    if (!decodeCommonHeader(message, 0x00, in)) {
        in.resetReaderIndex();
        return null;
    }
    int remainingLength = message.getRemainingLength();
    int start = in.readerIndex();

    int protocolNameLen = in.readUnsignedShort();
    byte[] encProtoName;
    String protoName;
    Attribute<Integer> versionAttr = ctx.attr(MQTTDecoder.PROTOCOL_VERSION);
    switch (protocolNameLen) {
    case 6:
        //MQTT version 3.1 "MQIsdp"
        //ProtocolName 8 bytes or 6 bytes
        if (in.readableBytes() < 10) {
            in.resetReaderIndex();
            return null;
        }

        encProtoName = new byte[6];
        in.readBytes(encProtoName);
        protoName = new String(encProtoName, "UTF-8");
        if (!"MQIsdp".equals(protoName)) {
            in.resetReaderIndex();
            throw new CorruptedFrameException("Invalid protoName: " + protoName);
        }
        message.setProtocolName(protoName);

        versionAttr.set((int) VERSION_3_1);
        break;
    case 4:
        //MQTT version 3.1.1 "MQTT"
        //ProtocolName 6 bytes
        if (in.readableBytes() < 8) {
            in.resetReaderIndex();
            return null;
        }
        encProtoName = new byte[4];
        in.readBytes(encProtoName);
        protoName = new String(encProtoName, "UTF-8");
        if (!"MQTT".equals(protoName)) {
            in.resetReaderIndex();
            throw new CorruptedFrameException("Invalid protoName: " + protoName);
        }
        message.setProtocolName(protoName);
        versionAttr.set((int) VERSION_3_1_1);
        break;
    default:
        //protocol broken
        throw new CorruptedFrameException("Invalid protoName size: " + protocolNameLen);
    }

    //ProtocolVersion 1 byte (value 0x03 for 3.1, 0x04 for 3.1.1)
    message.setProcotolVersion(in.readByte());
    if (message.getProcotolVersion() == VERSION_3_1_1) {
        //if 3.1.1, check the flags (dup, retain and qos == 0)
        if (message.isDupFlag() || message.isRetainFlag()
                || message.getQos() != AbstractMessage.QOSType.MOST_ONE) {
            throw new CorruptedFrameException("Received a CONNECT with fixed header flags != 0");
        }

        //check if this is another connect from the same client on the same session
        Attribute<Boolean> connectAttr = ctx.attr(ConnectDecoder.CONNECT_STATUS);
        Boolean alreadyConnected = connectAttr.get();
        if (alreadyConnected == null) {
            //never set
            connectAttr.set(true);
        } else if (alreadyConnected) {
            throw new CorruptedFrameException("Received a second CONNECT on the same network connection");
        }
    }

    //PKMPConnection flag
    byte connFlags = in.readByte();
    if (message.getProcotolVersion() == VERSION_3_1_1) {
        if ((connFlags & 0x01) != 0) { //bit(0) of connection flags is != 0
            throw new CorruptedFrameException("Received a CONNECT with connectionFlags[0(bit)] != 0");
        }
    }

    boolean cleanSession = ((connFlags & 0x02) >> 1) == 1;
    boolean willFlag = ((connFlags & 0x04) >> 2) == 1;
    byte willQos = (byte) ((connFlags & 0x18) >> 3);
    if (willQos > 2) {
        in.resetReaderIndex();
        throw new CorruptedFrameException("Expected will QoS in range 0..2 but found: " + willQos);
    }
    boolean willRetain = ((connFlags & 0x20) >> 5) == 1;
    boolean passwordFlag = ((connFlags & 0x40) >> 6) == 1;
    boolean userFlag = ((connFlags & 0x80) >> 7) == 1;
    //a password is true iff user is true.
    if (!userFlag && passwordFlag) {
        in.resetReaderIndex();
        throw new CorruptedFrameException(
                "Expected password flag to true if the user flag is true but was: " + passwordFlag);
    }
    message.setCleanSession(cleanSession);
    message.setWillFlag(willFlag);
    message.setWillQos(willQos);
    message.setWillRetain(willRetain);
    message.setPasswordFlag(passwordFlag);
    message.setUserFlag(userFlag);

    //Keep Alive timer 2 bytes
    //int keepAlive = Utils.readWord(in);
    int keepAlive = in.readUnsignedShort();
    message.setKeepAlive(keepAlive);

    if ((remainingLength == 12 && message.getProcotolVersion() == VERSION_3_1)
            || (remainingLength == 10 && message.getProcotolVersion() == VERSION_3_1_1)) {
        return message;
    }

    //Decode the ClientID
    String clientID = Utils.decodeString(in);
    if (clientID == null) {
        in.resetReaderIndex();
        return null;
    }
    message.setClientID(clientID);

    //Decode willTopic
    if (willFlag) {
        String willTopic = Utils.decodeString(in);
        if (willTopic == null) {
            in.resetReaderIndex();
            return null;
        }
        message.setWillTopic(willTopic);
    }

    //Decode willMessage
    if (willFlag) {
        String willMessage = Utils.decodeString(in);
        if (willMessage == null) {
            in.resetReaderIndex();
            return null;
        }
        message.setWillMessage(willMessage);
    }

    //Compatibility check with v3.0, remaining length has precedence over
    //the user and password flags
    int readed = in.readerIndex() - start;
    if (readed == remainingLength) {
        return message;
    }

    //Decode username
    if (userFlag) {
        String userName = Utils.decodeString(in);
        if (userName == null) {
            in.resetReaderIndex();
            return null;
        }
        message.setUsername(userName);
    }

    readed = in.readerIndex() - start;
    if (readed == remainingLength) {
        return message;
    }

    //Decode password
    if (passwordFlag) {
        String password = Utils.decodeString(in);
        if (password == null) {
            in.resetReaderIndex();
            return null;
        }
        message.setPassword(password);
    }
    return message;
}

From source file:com.pubkit.platform.messaging.protocol.mqtt.proto.parser.DemuxDecoder.java

License:Open Source License

private boolean genericDecodeCommonHeader(AbstractMessage message, Integer expectedFlagsOpt, ByteBuf in) {
    //Common decoding part
    if (in.readableBytes() < 2) {
        return false;
    }/*from  www  .j  a  va  2  s  .  co  m*/
    byte h1 = in.readByte();
    byte messageType = (byte) ((h1 & 0x00F0) >> 4);

    byte flags = (byte) (h1 & 0x0F);
    if (expectedFlagsOpt != null) {
        int expectedFlags = expectedFlagsOpt;
        if ((byte) expectedFlags != flags) {
            String hexExpected = Integer.toHexString(expectedFlags);
            String hexReceived = Integer.toHexString(flags);
            throw new CorruptedFrameException(
                    String.format("Received a message with fixed header flags (%s) != expected (%s)",
                            hexReceived, hexExpected));
        }
    }

    boolean dupFlag = ((byte) ((h1 & 0x0008) >> 3) == 1);
    byte qosLevel = (byte) ((h1 & 0x0006) >> 1);
    boolean retainFlag = ((byte) (h1 & 0x0001) == 1);
    int remainingLength = Utils.decodeRemainingLenght(in);
    if (remainingLength == -1) {
        return false;
    }

    message.setMessageType(messageType);
    message.setDupFlag(dupFlag);
    message.setQos(AbstractMessage.QOSType.values()[qosLevel]);
    message.setRetainFlag(retainFlag);
    message.setRemainingLength(remainingLength);
    return true;
}

From source file:com.pubkit.platform.messaging.protocol.mqtt.proto.parser.SubAckDecoder.java

License:Open Source License

@Override
void decode(AttributeMap ctx, ByteBuf in, List<Object> out) throws Exception {
    //Common decoding part
    in.resetReaderIndex();/*from w w w  . j a  va  2 s  . c  o  m*/
    SubAckMessage message = new SubAckMessage();
    if (!decodeCommonHeader(message, 0x00, in)) {
        in.resetReaderIndex();
        return;
    }
    int remainingLength = message.getRemainingLength();

    //MessageID
    message.setMessageID(in.readUnsignedShort());
    remainingLength -= 2;

    //Qos array
    if (in.readableBytes() < remainingLength) {
        in.resetReaderIndex();
        return;
    }
    for (int i = 0; i < remainingLength; i++) {
        byte qos = in.readByte();
        message.addType(AbstractMessage.QOSType.values()[qos]);
    }

    out.add(message);
}

From source file:com.pubkit.platform.messaging.protocol.mqtt.proto.parser.SubscribeDecoder.java

License:Open Source License

/**
 * Populate the message with couple of Qos, topic
 *///from w  w  w . j  a  v a 2 s  . co  m
private void decodeSubscription(ByteBuf in, SubscribeMessage message) throws UnsupportedEncodingException {
    String topic = Utils.decodeString(in);
    byte qosByte = in.readByte();
    if ((qosByte & 0xFC) > 0) { //the first 6 bits is reserved => has to be 0
        throw new CorruptedFrameException(
                "subscribe MUST have QoS byte with reserved buts to 0, found " + Integer.toHexString(qosByte));
    }
    byte qos = (byte) (qosByte & 0x03);
    //TODO check qos id 000000xx
    message.addSubscription(new SubscribeMessage.Couple(qos, topic));
}

From source file:com.quavo.osrs.game.model.entity.actor.player.info.MachineInformation.java

License:Open Source License

/**
 * Decodes the machine information of the user during the {@link WorldLoginDecoder}.
 * /*  w w w  .  j  a v a2  s .  co m*/
 * @param buffer The {@link ByteBuf}.
 * @return The created machine information.
 */
public static MachineInformation decode(ByteBuf buffer) {
    buffer.readByte();
    int osArch = buffer.readByte();
    boolean is64Bit = buffer.readByte() == 1;
    int osBuild = buffer.readByte();
    int vendor = buffer.readByte();
    buffer.readByte();
    buffer.readByte();
    buffer.readByte();
    buffer.readByte();
    buffer.readShort();
    buffer.readByte();
    buffer.readMedium();
    buffer.readShort();
    ByteBufUtils.readJagString(buffer);
    ByteBufUtils.readJagString(buffer);
    ByteBufUtils.readJagString(buffer);
    ByteBufUtils.readJagString(buffer);
    buffer.readByte();
    buffer.readShort();
    ByteBufUtils.readJagString(buffer);
    ByteBufUtils.readJagString(buffer);
    buffer.readByte();
    buffer.readByte();
    return new MachineInformation(osArch, is64Bit, osBuild, vendor);
}

From source file:com.quavo.osrs.network.protocol.codec.login.LoginDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (!in.isReadable() || in.readableBytes() < 8) {
        return;// w  ww . ja v a2 s  . c om
    }

    LoginType.getType(in.readByte()).filter(a -> in.readShort() == in.readableBytes())
            .ifPresent(a -> out.add(new LoginRequest(this, a, in.readInt())));
}

From source file:com.quavo.osrs.network.protocol.codec.login.world.WorldLoginDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (!in.isReadable()) {
        return;//  ww w .j  a va  2s .c om
    }

    ByteBuf buffer = ByteBufUtils.encipherRSA(in, EXPONENT, MODULUS);
    int id = buffer.readByte();
    if (id != 1) {
        return;
    }
    int clearanceId = buffer.readByte();
    int[] clientKeys = new int[4];
    for (int index = 0; index < clientKeys.length; index++) {
        clientKeys[index] = buffer.readInt();
    }
    LoginClearance clearance = LoginClearance.getType(clearanceId).get().read(buffer);
    String password = ByteBufUtils.readString(buffer);
    buffer = ByteBufUtils.decipherXTEA(in, clientKeys);
    String username = ByteBufUtils.readString(buffer);
    DisplayMode mode = DisplayMode.getDisplayMode(buffer.readByte()).get();
    int width = buffer.readShort();
    int height = buffer.readShort();
    DisplayInformation display = new DisplayInformation(mode, width, height);
    buffer.skipBytes(24);
    String token = ByteBufUtils.readString(buffer);
    buffer.readInt();
    MachineInformation machineInformation = MachineInformation.decode(buffer);
    buffer.readInt();
    buffer.readInt();
    buffer.readInt();
    buffer.readInt();
    buffer.readByte();
    int[] crc = new int[16];
    for (int index = 0; index < crc.length; index++) {
        crc[index] = buffer.readInt();
    }
    int[] serverKeys = new int[4];
    for (int index = 0; index < serverKeys.length; index++) {
        serverKeys[index] = clientKeys[index] + 50;
    }
    IsaacRandomPair isaacPair = new IsaacRandomPair(new IsaacRandom(serverKeys), new IsaacRandom(clientKeys));

    out.add(new WorldLoginRequest(this, type, username, password, clearance, display, machineInformation, crc,
            token, isaacPair));
}

From source file:com.quavo.util.buf.ByteBufUtils.java

License:Open Source License

/**
 * Converts data from a {@link ByteBuf} into a readable string.
 *
 * @param buffer The {@link ByteBuf}./*w  w  w .j a  v  a2  s. c  o  m*/
 * @return The string.
 */
public static String readString(ByteBuf buffer) {
    StringBuilder bldr = new StringBuilder();
    byte b;
    while (buffer.isReadable() && (b = buffer.readByte()) != STRING_TERMINATOR) {
        bldr.append((char) b);
    }
    return bldr.toString();
}