Example usage for io.netty.buffer ByteBuf readUnsignedByte

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

Introduction

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

Prototype

public abstract short readUnsignedByte();

Source Link

Document

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

Usage

From source file:com.friz.update.network.codec.UpdateDecoder.java

License:Open Source License

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

    int opcode = buffer.readUnsignedByte();
    if (opcode == 0 || opcode == 1) {
        int type = buffer.readUnsignedByte();
        int file = buffer.readInt();
        out.add(new FileRequestEvent(opcode == 1, type, file));
    } else if (opcode == 4) {
        int key = buffer.readUnsignedByte();
        buffer.readerIndex(buffer.readerIndex() + 4);
        out.add(new XorRequestEvent(key));
    } else {
        buffer.readerIndex(buffer.readerIndex() + 5);
    }
}

From source file:com.friz.update.network.codec.UpdateInitDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) throws Exception {
    int type = buf.readUnsignedByte();
    int size = buf.readUnsignedByte();

    if (!buf.isReadable(size))
        return;//from  w  ww.  j  a  v a 2  s.  c  o m

    int version = buf.readInt();
    int subVersion = buf.readInt();
    String key = BufferUtils.getString(buf);
    int langId = buf.readUnsignedByte();
    out.add(new UpdateRequestEvent(type, version, subVersion, key, langId));
}

From source file:com.friz.update.network.codec.XorEncoder.java

License:Open Source License

@Override
protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception {
    while (msg.isReadable()) {
        out.writeByte(msg.readUnsignedByte() ^ key);
    }/*w  w  w .j a v a  2s. co m*/
}

From source file:com.ghrum.common.protocol.ProtocolReplayingDecoder.java

License:Apache License

/**
 * {@inheritDoc}//from  w  w  w  . j  a  va  2 s.  c o  m
 */
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    switch (state) {
    case READ_ID:
        id = in.readUnsignedByte();
        checkpoint(DecoderState.READ_LENGTH);
        break;
    case READ_LENGTH:
        length = in.readUnsignedShort();
        checkpoint(DecoderState.READ_CONTENT);
        break;
    case READ_CONTENT:
        out.add(service.decode(id, in.readBytes(length)));
        checkpoint(DecoderState.READ_ID);
    }
}

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;
        }/*from   ww  w .j a  v  a  2s.c  o  m*/
    }

    // 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 w w w  . j  av a  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.l2jmobius.commons.network.codecs.PacketDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
    if ((in == null) || !in.isReadable()) {
        return;/*w ww .  j av  a2 s .  co  m*/
    }

    if (in.order() != _byteOrder) {
        in = in.order(_byteOrder);
    }

    try {
        final short packetId = in.readUnsignedByte();
        if (packetId >= _incomingPackets.length) {
            LOGGER.finer("Unknown packet: " + Integer.toHexString(packetId));
            return;
        }

        final IIncomingPackets<T> incomingPacket = _incomingPackets[packetId];
        if (incomingPacket == null) {
            LOGGER.finer("Unknown packet: " + Integer.toHexString(packetId));
            return;
        }

        final IConnectionState connectionState = ctx.channel().attr(IConnectionState.ATTRIBUTE_KEY).get();
        if ((connectionState == null) || !incomingPacket.getConnectionStates().contains(connectionState)) {
            // LOGGER.warning(incomingPacket + ": Connection at invalid state: " + connectionState + " Required States: " + incomingPacket.getConnectionStates());
            return;
        }

        final IIncomingPacket<T> packet = incomingPacket.newIncomingPacket();
        if ((packet != null) && packet.read(_client, new PacketReader(in))) {
            out.add(packet);
        }
    } finally {
        // We always consider that we read whole packet.
        in.readerIndex(in.writerIndex());
    }
}

From source file:com.linecorp.armeria.client.endpoint.dns.DnsTextEndpointGroup.java

License:Apache License

@Override
ImmutableSortedSet<Endpoint> onDnsRecords(List<DnsRecord> records, int ttl) throws Exception {
    final ImmutableSortedSet.Builder<Endpoint> builder = ImmutableSortedSet.naturalOrder();
    for (DnsRecord r : records) {
        if (!(r instanceof DnsRawRecord) || r.type() != DnsRecordType.TXT) {
            continue;
        }/* w  w w . j a va2  s  .co  m*/

        final ByteBuf content = ((ByteBufHolder) r).content();
        if (!content.isReadable()) { // Missing length octet
            warnInvalidRecord(DnsRecordType.TXT, content);
            continue;
        }

        content.markReaderIndex();
        final int txtLen = content.readUnsignedByte();
        if (txtLen == 0) { // Empty content
            continue;
        }

        if (content.readableBytes() != txtLen) { // Mismatching number of octets
            content.resetReaderIndex();
            warnInvalidRecord(DnsRecordType.TXT, content);
            continue;
        }

        final byte[] txt = new byte[txtLen];
        content.readBytes(txt);

        final Endpoint endpoint;
        try {
            endpoint = mapping.apply(txt);
        } catch (Exception e) {
            content.resetReaderIndex();
            warnInvalidRecord(DnsRecordType.TXT, content);
            continue;
        }

        if (endpoint != null) {
            if (endpoint.isGroup()) {
                logger().warn("{} Ignoring group endpoint: {}", logPrefix(), endpoint);
            } else {
                builder.add(endpoint);
            }
        }
    }

    final ImmutableSortedSet<Endpoint> endpoints = builder.build();
    if (logger().isDebugEnabled()) {
        logger().debug("{} Resolved: {} (TTL: {})", logPrefix(),
                endpoints.stream().map(Object::toString).collect(Collectors.joining(", ")), ttl);
    }

    return endpoints;
}

From source file:com.linecorp.armeria.internal.grpc.ArmeriaMessageDeframer.java

License:Apache License

/**
 * Processes the gRPC compression header which is composed of the compression flag and the outer
 * frame length./*from w  w w  .  j av  a  2 s  .com*/
 */
private void readHeader() {
    final ByteBuf buf = readableBuf();
    final int type = buf.readUnsignedByte();
    if ((type & RESERVED_MASK) != 0) {
        throw Status.INTERNAL.withDescription(DEBUG_STRING + ": Frame header malformed: reserved bits not zero")
                .asRuntimeException();
    }
    compressedFlag = (type & COMPRESSED_FLAG_MASK) != 0;

    // Update the required length to include the length of the frame.
    requiredLength = buf.readInt();
    if (requiredLength < 0 || requiredLength > maxMessageSizeBytes) {
        throw Status.RESOURCE_EXHAUSTED.withDescription(String.format("%s: Frame size %d exceeds maximum: %d. ",
                DEBUG_STRING, requiredLength, maxMessageSizeBytes)).asRuntimeException();
    }

    // Continue reading the frame body.
    state = State.BODY;
}

From source file:com.mobius.software.android.iotbroker.mqtt.parser.MQParser.java

License:Open Source License

public static MQMessage decode(ByteBuf buf) throws MalformedMessageException, UnsupportedEncodingException {
    MQMessage header = null;/*  w ww.  j a v a2s. co m*/

    byte fixedHeader = buf.readByte();

    LengthDetails length = decodeLength(buf);

    MessageType type = MessageType.valueOf((fixedHeader >> 4) & 0xf);
    switch (type) {
    case CONNECT:

        byte[] nameValue = new byte[buf.readUnsignedShort()];
        buf.readBytes(nameValue, 0, nameValue.length);
        String name = new String(nameValue, "UTF-8");
        if (!name.equals("MQTT"))
            throw new MalformedMessageException("CONNECT, protocol-name set to " + name);

        int protocolLevel = buf.readUnsignedByte();

        byte contentFlags = buf.readByte();

        boolean userNameFlag = (((contentFlags >> 7) & 1) == 1) ? true : false;
        boolean userPassFlag = (((contentFlags >> 6) & 1) == 1) ? true : false;
        boolean willRetain = (((contentFlags >> 5) & 1) == 1) ? true : false;
        QoS willQos = QoS.valueOf(((contentFlags & 0x1f) >> 3) & 3);
        if (willQos == null)
            throw new MalformedMessageException("CONNECT, will QoS set to " + willQos);
        boolean willFlag = (((contentFlags >> 2) & 1) == 1) ? true : false;

        if (willQos.getValue() > 0 && !willFlag)
            throw new MalformedMessageException("CONNECT, will QoS set to " + willQos + ", willFlag not set");

        if (willRetain && !willFlag)
            throw new MalformedMessageException("CONNECT, will retain set, willFlag not set");

        boolean cleanSession = (((contentFlags >> 1) & 1) == 1) ? true : false;

        boolean reservedFlag = ((contentFlags & 1) == 1) ? true : false;
        if (reservedFlag)
            throw new MalformedMessageException("CONNECT, reserved flag set to true");

        int keepalive = buf.readUnsignedShort();

        byte[] clientIdValue = new byte[buf.readUnsignedShort()];
        buf.readBytes(clientIdValue, 0, clientIdValue.length);
        String clientID = new String(clientIdValue, "UTF-8");
        if (!StringVerifier.verify(clientID))
            throw new MalformedMessageException(
                    "ClientID contains restricted characters: U+0000, U+D000-U+DFFF");

        Text willTopic = null;
        byte[] willMessage = null;
        String username = null;
        String password = null;

        Will will = null;
        if (willFlag) {
            if (buf.readableBytes() < 2)
                throw new MalformedMessageException("Invalid encoding will/username/password");

            byte[] willTopicValue = new byte[buf.readUnsignedShort()];
            if (buf.readableBytes() < willTopicValue.length)
                throw new MalformedMessageException("Invalid encoding will/username/password");

            buf.readBytes(willTopicValue, 0, willTopicValue.length);

            String willTopicName = new String(willTopicValue, "UTF-8");
            if (!StringVerifier.verify(willTopicName))
                throw new MalformedMessageException(
                        "WillTopic contains one or more restricted characters: U+0000, U+D000-U+DFFF");
            willTopic = new Text(willTopicName);

            if (buf.readableBytes() < 2)
                throw new MalformedMessageException("Invalid encoding will/username/password");

            willMessage = new byte[buf.readUnsignedShort()];
            if (buf.readableBytes() < willMessage.length)
                throw new MalformedMessageException("Invalid encoding will/username/password");

            buf.readBytes(willMessage, 0, willMessage.length);
            if (willTopic.length() == 0)
                throw new MalformedMessageException("invalid will encoding");
            will = new Will(new Topic(willTopic, willQos), willMessage, willRetain);
            if (!will.isValid())
                throw new MalformedMessageException("invalid will encoding");
        }

        if (userNameFlag) {
            if (buf.readableBytes() < 2)
                throw new MalformedMessageException("Invalid encoding will/username/password");

            byte[] userNameValue = new byte[buf.readUnsignedShort()];
            if (buf.readableBytes() < userNameValue.length)
                throw new MalformedMessageException("Invalid encoding will/username/password");

            buf.readBytes(userNameValue, 0, userNameValue.length);
            username = new String(userNameValue, "UTF-8");
            if (!StringVerifier.verify(username))
                throw new MalformedMessageException(
                        "Username contains one or more restricted characters: U+0000, U+D000-U+DFFF");
        }

        if (userPassFlag) {
            if (buf.readableBytes() < 2)
                throw new MalformedMessageException("Invalid encoding will/username/password");

            byte[] userPassValue = new byte[buf.readUnsignedShort()];
            if (buf.readableBytes() < userPassValue.length)
                throw new MalformedMessageException("Invalid encoding will/username/password");

            buf.readBytes(userPassValue, 0, userPassValue.length);
            password = new String(userPassValue, "UTF-8");
            if (!StringVerifier.verify(password))
                throw new MalformedMessageException(
                        "Password contains one or more restricted characters: U+0000, U+D000-U+DFFF");
        }

        if (buf.readableBytes() > 0)
            throw new MalformedMessageException("Invalid encoding will/username/password");

        Connect connect = new Connect(username, password, clientID, cleanSession, keepalive, will);
        if (protocolLevel != 4)
            connect.setProtocolLevel(protocolLevel);
        header = connect;
        break;

    case CONNACK:
        byte sessionPresentValue = buf.readByte();
        if (sessionPresentValue != 0 && sessionPresentValue != 1)
            throw new MalformedMessageException(
                    String.format("CONNACK, session-present set to %d", sessionPresentValue & 0xff));
        boolean isPresent = sessionPresentValue == 1 ? true : false;

        short connackByte = buf.readUnsignedByte();
        ConnackCode connackCode = ConnackCode.valueOf(connackByte);
        if (connackCode == null)
            throw new MalformedMessageException("Invalid connack code: " + connackByte);
        header = new Connack(isPresent, connackCode);
        break;

    case PUBLISH:
        int dataLength = length.getLength();
        fixedHeader &= 0xf;

        boolean dup = (((fixedHeader >> 3) & 1) == 1) ? true : false;

        QoS qos = QoS.valueOf((fixedHeader & 0x07) >> 1);
        if (qos == null)
            throw new MalformedMessageException("invalid QoS value");
        if (dup && qos == QoS.AT_MOST_ONCE)
            throw new MalformedMessageException("PUBLISH, QoS-0 dup flag present");

        boolean retain = ((fixedHeader & 1) == 1) ? true : false;

        byte[] topicNameValue = new byte[buf.readUnsignedShort()];
        buf.readBytes(topicNameValue, 0, topicNameValue.length);
        String topicName = new String(topicNameValue, "UTF-8");
        if (!StringVerifier.verify(topicName))
            throw new MalformedMessageException(
                    "Publish-topic contains one or more restricted characters: U+0000, U+D000-U+DFFF");
        dataLength -= topicName.length() + 2;

        Integer packetID = null;
        if (qos != QoS.AT_MOST_ONCE) {
            packetID = buf.readUnsignedShort();
            if (packetID < 0 || packetID > 65535)
                throw new MalformedMessageException("Invalid PUBLISH packetID encoding");
            dataLength -= 2;
        }
        byte[] data = new byte[dataLength];
        if (dataLength > 0)
            buf.readBytes(data, 0, data.length);
        header = new Publish(packetID, new Topic(new Text(topicName), qos), data, retain, dup);
        break;

    case PUBACK:
        header = new Puback(buf.readUnsignedShort());
        break;

    case PUBREC:
        header = new Pubrec(buf.readUnsignedShort());
        break;

    case PUBREL:
        header = new Pubrel(buf.readUnsignedShort());
        break;

    case PUBCOMP:
        header = new Pubcomp(buf.readUnsignedShort());
        break;

    case SUBSCRIBE:
        Integer subID = buf.readUnsignedShort();
        List<Topic> subscriptions = new ArrayList<Topic>();
        while (buf.isReadable()) {
            byte[] value = new byte[buf.readUnsignedShort()];
            buf.readBytes(value, 0, value.length);
            QoS requestedQos = QoS.valueOf(buf.readByte());
            if (requestedQos == null)
                throw new MalformedMessageException(
                        "Subscribe qos must be in range from 0 to 2: " + requestedQos);
            String topic = new String(value, "UTF-8");
            if (!StringVerifier.verify(topic))
                throw new MalformedMessageException(
                        "Subscribe topic contains one or more restricted characters: U+0000, U+D000-U+DFFF");
            Topic subscription = new Topic(new Text(topic), requestedQos);
            subscriptions.add(subscription);
        }
        if (subscriptions.isEmpty())
            throw new MalformedMessageException("Subscribe with 0 topics");

        header = new Subscribe(subID, subscriptions.toArray(new Topic[subscriptions.size()]));
        break;

    case SUBACK:
        Integer subackID = buf.readUnsignedShort();
        List<SubackCode> subackCodes = new ArrayList<SubackCode>();
        while (buf.isReadable()) {
            short subackByte = buf.readUnsignedByte();
            SubackCode subackCode = SubackCode.valueOf(subackByte);
            if (subackCode == null)
                throw new MalformedMessageException("Invalid suback code: " + subackByte);
            subackCodes.add(subackCode);
        }
        if (subackCodes.isEmpty())
            throw new MalformedMessageException("Suback with 0 return-codes");

        header = new Suback(subackID, subackCodes);
        break;

    case UNSUBSCRIBE:
        Integer unsubID = buf.readUnsignedShort();
        List<Topic> unsubscribeTopics = new ArrayList<Topic>();
        while (buf.isReadable()) {
            byte[] value = new byte[buf.readUnsignedShort()];
            buf.readBytes(value, 0, value.length);
            String topic = new String(value, "UTF-8");
            if (!StringVerifier.verify(topic))
                throw new MalformedMessageException(
                        "Unsubscribe topic contains one or more restricted characters: U+0000, U+D000-U+DFFF");
            Topic subscription = new Topic(new Text(topic), QoS.AT_MOST_ONCE);
            unsubscribeTopics.add(subscription);
        }
        if (unsubscribeTopics.isEmpty())
            throw new MalformedMessageException("Unsubscribe with 0 topics");

        header = new Unsubscribe(unsubID, unsubscribeTopics.toArray(new Topic[unsubscribeTopics.size()]));
        break;

    case UNSUBACK:
        header = new Unsuback(buf.readUnsignedShort());
        break;

    case PINGREQ:
        header = new Pingreq();
        break;
    case PINGRESP:
        header = new Pingresp();
        break;
    case DISCONNECT:
        header = new Disconnect();
        break;

    default:
        throw new MalformedMessageException("Invalid header type: " + type);
    }

    if (buf.isReadable())
        throw new MalformedMessageException("unexpected bytes in content");

    if (length.getLength() != header.getLength())
        throw new MalformedMessageException(String.format("Invalid length. Encoded: %d, actual: %d",
                length.getLength(), header.getLength()));

    return header;
}