Example usage for io.netty.buffer ByteBuf resetReaderIndex

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

Introduction

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

Prototype

public abstract ByteBuf resetReaderIndex();

Source Link

Document

Repositions the current readerIndex to the marked readerIndex in this buffer.

Usage

From source file:org.apache.qpid.jms.provider.amqp.message.AmqpCodec.java

License:Apache License

/**
 * Given an encoded AMQP Section, decode the value previously written there.
 *
 * @param encoded//from w w  w .  j  a  v  a  2  s . c  o  m
 *      the AMQP Section value to decode.
 *
 * @return a Section object read from its encoded form.
 */
public static Section decode(ByteBuf encoded) {
    if (encoded == null || !encoded.isReadable()) {
        return null;
    }

    DecoderImpl decoder = TLS_CODEC.get().decoder;
    decoder.setByteBuffer(encoded.nioBuffer());
    Section result = (Section) decoder.readObject();
    decoder.setByteBuffer(null);
    encoded.resetReaderIndex();

    return result;
}

From source file:org.apache.qpid.jms.provider.amqp.message.AmqpCodec.java

License:Apache License

/**
 * Create a new JmsMessage and underlying JmsMessageFacade that represents the proper
 * message type for the incoming AMQP message.
 *
 * @param consumer/*from  w ww  .  j  av a 2 s  . c o m*/
 *        The AmqpConsumer instance that will be linked to the decoded message.
 * @param messageBytes
 *        The the raw bytes that compose the incoming message. (Read-Only)
 *
 * @return a AmqpJmsMessageFacade instance decoded from the message bytes.
 *
 * @throws IOException if an error occurs while creating the message objects.
 */
public static AmqpJmsMessageFacade decodeMessage(AmqpConsumer consumer, ByteBuf messageBytes)
        throws IOException {

    DecoderImpl decoder = getDecoder();
    ByteBuffer buffer = messageBytes.nioBuffer();
    decoder.setByteBuffer(buffer);

    Header header = null;
    DeliveryAnnotations deliveryAnnotations = null;
    MessageAnnotations messageAnnotations = null;
    Properties properties = null;
    ApplicationProperties applicationProperties = null;
    Section body = null;
    Footer footer = null;
    Section section = null;

    if (buffer.hasRemaining()) {
        section = (Section) decoder.readObject();
    }

    if (section instanceof Header) {
        header = (Header) section;
        if (buffer.hasRemaining()) {
            section = (Section) decoder.readObject();
        } else {
            section = null;
        }

    }
    if (section instanceof DeliveryAnnotations) {
        deliveryAnnotations = (DeliveryAnnotations) section;

        if (buffer.hasRemaining()) {
            section = (Section) decoder.readObject();
        } else {
            section = null;
        }

    }
    if (section instanceof MessageAnnotations) {
        messageAnnotations = (MessageAnnotations) section;

        if (buffer.hasRemaining()) {
            section = (Section) decoder.readObject();
        } else {
            section = null;
        }

    }
    if (section instanceof Properties) {
        properties = (Properties) section;

        if (buffer.hasRemaining()) {
            section = (Section) decoder.readObject();
        } else {
            section = null;
        }

    }
    if (section instanceof ApplicationProperties) {
        applicationProperties = (ApplicationProperties) section;

        if (buffer.hasRemaining()) {
            section = (Section) decoder.readObject();
        } else {
            section = null;
        }

    }
    if (section != null && !(section instanceof Footer)) {
        body = section;

        if (buffer.hasRemaining()) {
            section = (Section) decoder.readObject();
        } else {
            section = null;
        }

    }
    if (section instanceof Footer) {
        footer = (Footer) section;
    }

    decoder.setByteBuffer(null);
    messageBytes.resetReaderIndex();

    // First we try the easy way, if the annotation is there we don't have to work hard.
    AmqpJmsMessageFacade result = createFromMsgAnnotation(messageAnnotations);
    if (result == null) {
        // Next, match specific section structures and content types
        result = createWithoutAnnotation(body, properties);
    }

    if (result != null) {
        result.setHeader(header);
        result.setDeliveryAnnotations(deliveryAnnotations);
        result.setMessageAnnotations(messageAnnotations);
        result.setProperties(properties);
        result.setApplicationProperties(applicationProperties);
        result.setBody(body);
        result.setFooter(footer);
        result.initialize(consumer);

        return result;
    }

    throw new IOException("Could not create a JMS message from incoming message");
}

From source file:org.apache.spark.sql.hive.thriftserver.rsc.KryoMessageCodec.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (in.readableBytes() < 4) {
        return;/*from www  .  j a  v  a 2s.  co  m*/
    }

    in.markReaderIndex();
    int msgSize = in.readInt();
    checkSize(msgSize);

    if (in.readableBytes() < msgSize) {
        // Incomplete message in buffer.
        in.resetReaderIndex();
        return;
    }

    try {
        ByteBuffer nioBuffer = maybeDecrypt(in.nioBuffer(in.readerIndex(), msgSize));
        Object msg = serializer.deserialize(nioBuffer);
        LOG.info("Decoded message of type {} ({} bytes)", msg != null ? msg.getClass().getName() : msg,
                msgSize);
        out.add(msg);
    } catch (Exception e) {
        Throwable throwable = e;

        while (throwable != null) {
            LOG.info("tlitest cause: " + throwable.getCause());
            LOG.info("tlitest message: " + throwable.getMessage());

            StringBuilder builder = new StringBuilder();

            for (StackTraceElement elem : throwable.getStackTrace()) {
                builder.append(elem);
                builder.append("\n");
            }
            LOG.info(builder.toString());
            throwable = throwable.getCause();
        }

        throw e;
    } finally {
        in.skipBytes(msgSize);
    }
}

From source file:org.beaconmc.network.socket.pipeline.PacketFraming.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    in.markReaderIndex();//from w  ww.  ja  v  a2  s  . c  om
    if (!readableVarInt(in)) {
        return;
    }
    int length = readVarInt(in);
    if (in.readableBytes() < length) {
        in.resetReaderIndex();
        return;
    }
    ByteBuf buf = ctx.alloc().buffer(length);
    in.readBytes(buf, length);
    out.add(buf);
}

From source file:org.beaconmc.network.socket.pipeline.PacketLegacy.java

License:Open Source License

@Override
protected void messageReceived(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {

    byteBuf.markReaderIndex();/*from   ww  w . j a v  a  2 s  .c om*/
    boolean repliedPing = true;

    try {
        short packetId = byteBuf.readUnsignedByte();
        if (packetId == 254) {
            int length = byteBuf.readableBytes();
            AsyncServerPingEvent asyncServerPingEvent = EventFactory
                    .callAsyncServerPingEvent(this.server.createServerPing());
            if (asyncServerPingEvent.getPing() != null) {
                switch (length) {
                case 0:
                    this.sendPingAndClose(channelHandlerContext,
                            this.toArray(String.format("%s%d%d",
                                    asyncServerPingEvent.getPing().getDescription().getText(),
                                    asyncServerPingEvent.getPing().getPlayers().getOnline(),
                                    asyncServerPingEvent.getPing().getPlayers().getMax())));
                    break;
                case 1:
                    if (byteBuf.readUnsignedByte() != 1) {
                        return;
                    }
                    this.sendPingAndClose(channelHandlerContext,
                            this.toArray(String.format("1\0%d\0%s\0%s\0%d\0%d", 127,
                                    asyncServerPingEvent.getPing().getVersion().getName(),
                                    asyncServerPingEvent.getPing().getDescription().getText(),
                                    asyncServerPingEvent.getPing().getPlayers().getOnline(),
                                    asyncServerPingEvent.getPing().getPlayers().getMax())));
                    break;
                default:
                    boolean checkFlag = byteBuf.readUnsignedByte() == 1;
                    checkFlag &= byteBuf.readUnsignedByte() == 250;
                    checkFlag &= "MC|PingHost".equals(
                            new String(byteBuf.readBytes(byteBuf.readShort() * 2).array(), Charsets.UTF_16));

                    int checkShort = byteBuf.readShort();

                    checkFlag &= byteBuf.readUnsignedByte() >= 73;
                    checkFlag &= 3 + byteBuf.readBytes(byteBuf.readShort() * 2).array().length
                            + 4 == checkShort;
                    checkFlag &= byteBuf.readInt() <= '\uffff';
                    checkFlag &= byteBuf.readableBytes() == 0;

                    if (!checkFlag) {
                        return;
                    }

                    this.sendPingAndClose(channelHandlerContext,
                            this.toArray(String.format("1\0%d\0%s\0%s\0%d\0%d", 127,
                                    asyncServerPingEvent.getPing().getVersion().getName(),
                                    asyncServerPingEvent.getPing().getDescription().getText(),
                                    asyncServerPingEvent.getPing().getPlayers().getOnline(),
                                    asyncServerPingEvent.getPing().getPlayers().getMax())));
                    break;
                }
            } else {
                this.close(channelHandlerContext);
            }
            repliedPing = false;
        } else if (packetId == 0x02 && byteBuf.isReadable()) {
            this.sendPingAndClose(channelHandlerContext, this.toArray(ChatColor.RED + "Outdated Client"));
            repliedPing = false;
        }
    } catch (Exception e) {
        return;
    } finally {
        if (repliedPing) {
            byteBuf.resetReaderIndex();
            channelHandlerContext.channel().pipeline().remove("legacy_ping");
            channelHandlerContext.fireChannelRead(byteBuf.retain());
        }
    }
}

From source file:org.bgp4j.netty.protocol.open.CapabilityCodec.java

License:Apache License

public static Capability decodeCapability(ByteBuf buffer) {
    Capability cap = null;// w w  w  .  j a  v  a2s. com

    try {
        buffer.markReaderIndex();

        int type = buffer.readUnsignedByte();

        switch (type) {
        case BGPv4Constants.BGP_CAPABILITY_TYPE_MULTIPROTOCOL:
            cap = decodeMultiProtocolCapability(buffer);
            break;
        case BGPv4Constants.BGP_CAPABILITY_TYPE_ROUTE_REFRESH:
            cap = decodeRouteRefreshCapability(buffer);
            break;
        case BGPv4Constants.BGP_CAPABILITY_TYPE_AS4_NUMBERS:
            cap = decodeAutonomousSystem4Capability(buffer);
            break;
        case BGPv4Constants.BGP_CAPABILITY_TYPE_OUTBOUND_ROUTE_FILTERING:
            cap = decodeOutboundRouteFilteringCapability(buffer);
            break;
        default:
            cap = decodeUnknownCapability(type, buffer);
            break;
        }
    } catch (CapabilityException e) {
        buffer.resetReaderIndex();

        int type = buffer.readUnsignedByte();
        int capLength = buffer.readUnsignedByte();

        byte[] capPacket = new byte[capLength + 2];

        buffer.readBytes(capPacket, 2, capLength);
        capPacket[0] = (byte) type;
        capPacket[1] = (byte) capLength;

        e.setCapability(capPacket);
        throw e;
    }

    return cap;
}

From source file:org.bgp4j.netty.protocol.update.UpdatePacketDecoder.java

License:Apache License

private List<PathAttribute> decodePathAttributes(ByteBuf buffer) {
    List<PathAttribute> attributes = new LinkedList<PathAttribute>();

    while (buffer.isReadable()) {
        buffer.markReaderIndex();//from ww w. j  a v a2  s .  c  o m

        try {
            int flagsType = buffer.readUnsignedShort();
            boolean optional = ((flagsType & BGPv4Constants.BGP_PATH_ATTRIBUTE_OPTIONAL_BIT) != 0);
            boolean transitive = ((flagsType & BGPv4Constants.BGP_PATH_ATTRIBUTE_TRANSITIVE_BIT) != 0);
            boolean partial = ((flagsType & BGPv4Constants.BGP_PATH_ATTRIBUTE_PARTIAL_BIT) != 0);
            int typeCode = (flagsType & BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_MASK);
            int valueLength = 0;

            if ((flagsType & BGPv4Constants.BGP_PATH_ATTRIBUTE_EXTENDED_LENGTH_BIT) != 0)
                valueLength = buffer.readUnsignedShort();
            else
                valueLength = buffer.readUnsignedByte();

            ByteBuf valueBuffer = buffer.readSlice(valueLength);

            PathAttribute attr = null;

            switch (typeCode) {
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_AGGREGATOR:
                attr = decodeAggregatorPathAttribute(valueBuffer, ASType.AS_NUMBER_2OCTETS);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_AS4_AGGREGATOR:
                attr = decodeAggregatorPathAttribute(valueBuffer, ASType.AS_NUMBER_4OCTETS);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_AS4_PATH:
                attr = decodeASPathAttribute(valueBuffer, ASType.AS_NUMBER_4OCTETS);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_AS_PATH:
                attr = decodeASPathAttribute(valueBuffer, ASType.AS_NUMBER_2OCTETS);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_ATOMIC_AGGREGATE:
                attr = decodeAtomicAggregatePathAttribute(valueBuffer);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_COMMUNITIES:
                attr = decodeCommunityPathAttribute(valueBuffer);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_LOCAL_PREF:
                attr = decodeLocalPrefPathAttribute(valueBuffer);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_MULTI_EXIT_DISC:
                attr = decodeMultiExitDiscPathAttribute(valueBuffer);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_NEXT_HOP:
                attr = decodeNextHopPathAttribute(valueBuffer);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_ORIGIN:
                attr = decodeOriginPathAttribute(valueBuffer);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_MP_REACH_NLRI:
                attr = decodeMpReachNlriPathAttribute(valueBuffer);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_MP_UNREACH_NLRI:
                attr = decodeMpUnreachNlriPathAttribute(valueBuffer);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_ORIGINATOR_ID:
                attr = decodeOriginatorIDPathAttribute(valueBuffer);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_CLUSTER_LIST:
                attr = decodeClusterListPathAttribute(valueBuffer);
                break;
            default: {
                byte[] value = new byte[valueBuffer.readableBytes()];

                valueBuffer.readBytes(value);
                attr = new UnknownPathAttribute(typeCode, value);
            }
                break;
            }
            attr.setOptional(optional);
            attr.setTransitive(transitive);
            attr.setPartial(partial);

            attributes.add(attr);
        } catch (AttributeException ex) {
            int endReadIndex = buffer.readerIndex();

            buffer.resetReaderIndex();

            int attributeLength = endReadIndex - buffer.readerIndex();
            byte[] packet = new byte[attributeLength];

            buffer.readBytes(packet);
            ex.setOffendingAttribute(packet);

            throw ex;
        } catch (IndexOutOfBoundsException ex) {
            int endReadIndex = buffer.readerIndex();

            buffer.resetReaderIndex();

            int attributeLength = endReadIndex - buffer.readerIndex();
            byte[] packet = new byte[attributeLength];

            buffer.readBytes(packet);

            throw new AttributeLengthException(packet);
        }

    }

    return attributes;
}

From source file:org.clitherproject.clither.server.net.PacketDecoder.java

License:Open Source License

@SuppressWarnings("deprecation")
@Override/*from  www  .j  a  va  2s  . c o  m*/
protected void decode(ChannelHandlerContext ctx, WebSocketFrame frame, List<Object> out) throws Exception {
    ByteBuf buf = frame.content().order(ByteOrder.BIG_ENDIAN);
    if (buf.capacity() < 1) {
        // Discard empty messages
        return;
    }

    buf.resetReaderIndex();
    int packetId = buf.readUnsignedByte();
    Packet packet = PacketRegistry.SERVERBOUND.constructPacket(packetId);

    if (packet == null) {
        return;
    }

    ClitherServer.log.finest("Received packet " + " (" + packet.getClass().getSimpleName() + ") from "
            + ctx.channel().remoteAddress());

    packet.readData(buf);
    out.add(packet);
}

From source file:org.diorite.impl.connection.packets.PacketSizer.java

License:Open Source License

@Override
protected void decode(final ChannelHandlerContext context, final ByteBuf byteBuf, final List<Object> objects) {
    byteBuf.markReaderIndex();//from w  w w .  j a  v  a 2s .co m

    final byte[] arrayOfByte = new byte[3];
    for (int i = 0; i < arrayOfByte.length; i++) {
        if (!byteBuf.isReadable()) {
            byteBuf.resetReaderIndex();
            return;
        }
        arrayOfByte[i] = byteBuf.readByte();
        if (arrayOfByte[i] >= 0) {
            final PacketDataSerializer dataSerializer = new PacketDataSerializer(
                    Unpooled.wrappedBuffer(arrayOfByte));
            try {
                final int size = dataSerializer.readVarInt();
                if (byteBuf.readableBytes() < size) {
                    byteBuf.resetReaderIndex();
                    return;
                }
                objects.add(byteBuf.readBytes(size));
                return;
            } finally {
                dataSerializer.release();
            }
        }
    }
    throw new CorruptedFrameException("length wider than 21-bit");
}

From source file:org.dna.mqtt.moquette.parser.netty.ConnectDecoder.java

License:Open Source License

@Override
void decode(AttributeMap ctx, ByteBuf in, List<Object> out) throws UnsupportedEncodingException {
    in.resetReaderIndex();
    //Common decoding part
    ConnectMessage message = new ConnectMessage();
    if (!decodeCommonHeader(message, 0x00, in)) {
        in.resetReaderIndex();/*ww  w.ja v a2 s . c  om*/
        return;
    }
    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;
        }

        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;
        }
        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");
        }
    }

    //Connection 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)) {
        out.add(message);
        return;
    }

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

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

    //Decode willMessage
    if (willFlag) {
        String willMessage = Utils.decodeString(in);
        if (willMessage == null) {
            in.resetReaderIndex();
            return;
        }
        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) {
        out.add(message);
        return;
    }

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

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

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

    out.add(message);
}