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.gemstone.gemfire.internal.redis.ByteToCommandDecoder.java

License:Apache License

/**
 * Helper method that is called when the next characters are 
 * supposed to be "\r\n"/*from  w ww.  j av  a2s . com*/
 * 
 * @param buffer Buffer to read from
 * @throws RedisCommandParserException Thrown when the next two characters
 * are not "\r\n"
 */
private boolean parseRN(ByteBuf buffer) throws RedisCommandParserException {
    if (!buffer.isReadable(2))
        return false;
    byte b = buffer.readByte();
    if (b != rID)
        throw new RedisCommandParserException("expected \'" + (char) rID + "\', got \'" + (char) b + "\'");
    b = buffer.readByte();
    if (b != nID)
        throw new RedisCommandParserException("expected: \'" + (char) nID + "\', got \'" + (char) b + "\'");
    return true;
}

From source file:com.github.jrialland.ajpclient.impl.handlers.AjpMessagesHandler.java

License:Apache License

@Override
protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> _out)
        throws Exception {

    // read magic bytes
    for (final byte element : CONTAINER_MAGIC) {
        final byte b = in.readByte();
        if (b != element) {
            final String hex = "0" + Integer.toHexString(b);
            getLog().warn("skipping unexpected byte 0x" + hex.substring(hex.length() - 2));
            return;
        }//w  w w .  ja v a 2s . c  om
    }

    // read data length
    final int length = in.readUnsignedShort();

    // read message type prefix
    final int prefix = in.readUnsignedByte();
    final MessageType msgType = MessageType.forPrefix(prefix);
    if (msgType == null) {
        throw new IllegalStateException("unknown message prefix code : " + prefix);
    } else if (getLog().isDebugEnabled()) {
        final String type = MessageType.forPrefix(prefix).name().toUpperCase();
        getLog().debug(String.format("Received : %s (%s), payload size = %s bytes", type, prefix, length));
    }

    // CPONG
    if (prefix == PREFIX_CPONG) {
        getCallback(ctx.channel()).handleCPongMessage();
        return;
    }

    // SEND_HEADERS
    else if (prefix == PREFIX_SEND_HEADERS) {
        // store response status and content length;
        expectedBytes = readHeaders(ctx, in);
        return;
    }

    // SEND_BODY_CHUNK
    else if (prefix == PREFIX_SEND_BODY_CHUNK) {
        final int chunkLength = in.readUnsignedShort();
        if (chunkLength > 0) {
            getCallback(ctx.channel()).handleSendBodyChunkMessage(in.readBytes(chunkLength));

            // update expected bytes counter

            if (expectedBytes != null) {
                expectedBytes -= chunkLength;
            }
        }

        // consume an extra byte, as it seems that there is always a useless
        // 0x00 following data in these packets
        in.readByte();
        return;
    }

    // END_RESPONSE
    else if (prefix == PREFIX_END_RESPONSE) {
        final boolean reuse = in.readBoolean();
        getCallback(ctx.channel()).handleEndResponseMessage(reuse);
        return;
    }

    // GET_BODY_CHUNK
    else if (prefix == PREFIX_GET_BODY_CHUNK) {
        final int requestedLength = in.readUnsignedShort();
        getCallback(ctx.channel()).handleGetBodyChunkMessage(requestedLength);
        return;
    }
}

From source file:com.github.jrialland.ajpclient.impl.handlers.AjpMessagesHandler.java

License:Apache License

protected String readString(final ByteBuf in) {
    in.markReaderIndex();//from   www.j  a  va  2 s .c  o m
    final int b0 = in.readUnsignedByte();
    if (b0 == 0xff) {
        return null;
    }
    in.resetReaderIndex();
    final int length = in.readUnsignedShort();
    final byte[] data = new byte[length];
    in.readBytes(data);

    // skip trailing \0
    in.readByte();

    return new String(data);
}

From source file:com.github.milenkovicm.kafka.protocol.Convert.java

License:Apache License

public static byte decodeByte(ByteBuf buf) {
    return buf.readByte();
}

From source file:com.github.pgasync.impl.netty.ByteBufMessageDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (in.readableBytes() == 0) {
        return;//from w  w  w . j a  v  a  2s. c  o  m
    }

    byte id = in.readByte();
    int length = in.readInt();

    Decoder<?> decoder = DECODERS.get(id);
    try {
        if (decoder != null) {
            ByteBuffer buffer = in.nioBuffer();
            out.add(decoder.read(buffer));
            in.skipBytes(buffer.position());
        } else {
            in.skipBytes(length - 4);
        }
    } catch (Throwable t) {
        // broad catch as otherwise the exception is silently dropped
        ctx.fireExceptionCaught(t);
    }
}

From source file:com.github.pgasync.impl.netty.NettyPgProtocolStream.java

License:Apache License

ChannelHandler newSslInitiator() {
    return new ByteToMessageDecoder() {
        @Override/*from   w w w  . ja v a 2s  . c o m*/
        protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
            if (in.readableBytes() < 1) {
                return;
            }
            if ('S' != in.readByte()) {
                ctx.fireExceptionCaught(
                        new IllegalStateException("SSL required but not supported by backend server"));
                return;
            }
            ctx.pipeline().remove(this);
            ctx.pipeline().addFirst(SslContextBuilder.forClient()
                    .trustManager(InsecureTrustManagerFactory.INSTANCE).build().newHandler(ctx.alloc()));
        }
    };
}

From source file:com.github.sylvek.wsmqttfwd.decoder.ConnectDecoder.java

License:Open Source License

@Override
public ConnectMessage decode(AttributeMap ctx, ByteBuf in) throws UnsupportedEncodingException {
    in.resetReaderIndex();/*from  w w  w .  j av a 2s.c o  m*/
    //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(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) Utils.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) Utils.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.setProtocolVersion(in.readByte());
    if (message.getProtocolVersion() == Utils.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");
        }
    }

    //Connection flag
    byte connFlags = in.readByte();
    if (message.getProtocolVersion() == Utils.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.getProtocolVersion() == Utils.VERSION_3_1)
            || (remainingLength == 10 && message.getProtocolVersion() == Utils.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) {
        byte[] willMessage = Utils.readFixedLengthContent(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) {
        byte[] password = Utils.readFixedLengthContent(in);
        if (password == null) {
            in.resetReaderIndex();
            return null;
        }
        message.setPassword(password);
    }

    return message;
}

From source file:com.github.sylvek.wsmqttfwd.decoder.DemuxDecoder.java

License:Open Source License

private boolean genericDecodeCommonHeader(AbstractMessage message, Integer expectedFlagsOpt, ByteBuf in) {
    //Common decoding part
    if (in.readableBytes() < 2) {
        return false;
    }/*  ww  w  .j  av a  2 s . c o  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.decodeRemainingLength(in);
    if (remainingLength == -1) {
        return false;
    }

    message.setMessageType(messageType);
    message.setDupFlag(dupFlag);
    try {
        message.setQos(AbstractMessage.QOSType.valueOf(qosLevel));
    } catch (IllegalArgumentException e) {
        throw new CorruptedFrameException(String.format("Received an invalid QOS: %s", e.getMessage()), e);
    }
    message.setRetainFlag(retainFlag);
    message.setRemainingLength(remainingLength);
    return true;
}

From source file:com.github.sylvek.wsmqttfwd.decoder.Utils.java

License:Open Source License

public static byte readMessageType(ByteBuf in) {
    byte h1 = in.readByte();
    byte messageType = (byte) ((h1 & 0x00F0) >> 4);
    return messageType;
}

From source file:com.github.sylvek.wsmqttfwd.decoder.Utils.java

License:Open Source License

/**
 * Decode the variable remaining length as defined in MQTT v3.1 specification
 * (section 2.1)./*from ww  w  . j a  va 2 s  .  c o  m*/
 *
 * @return the decoded length or -1 if needed more data to decode the length field.
 */
static int decodeRemainingLength(ByteBuf in) {
    int multiplier = 1;
    int value = 0;
    byte digit;
    do {
        if (in.readableBytes() < 1) {
            return -1;
        }
        digit = in.readByte();
        value += (digit & 0x7F) * multiplier;
        multiplier *= 128;
    } while ((digit & 0x80) != 0);
    return value;
}