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:io.moquette.parser.netty.ConnectEncoderTest.java

License:Open Source License

@Test
public void testCompleteHeaderWIthUser_password() throws Exception {
    ConnectMessage msg = new ConnectMessage();
    msg.setUserFlag(true);/*from ww  w.  j a  v  a  2 s. co  m*/
    msg.setPasswordFlag(true);
    msg.setWillRetain(true);
    msg.setWillQos((byte) 2);
    msg.setWillFlag(true);
    msg.setCleanSession(true);
    msg.setKeepAlive(512);

    //variable part
    msg.setClientID("ABCDEF");
    msg.setWillTopic("Topic");
    msg.setWillMessage("Message".getBytes());
    msg.setUsername("Pablo");
    msg.setPassword("PBL".getBytes());

    ByteBuf out = Unpooled.buffer();

    //Exercise
    m_encoder.encode(m_mockedContext, msg, out);

    //Verify
    assertEquals(0x10, out.readByte()); //1 byte
    assertEquals(48, out.readByte()); //remaining length
    TestUtils.verifyString("MQIsdp", out);
    assertEquals(0x03, out.readByte()); //protocol version
    assertEquals((byte) 0xF6, (byte) out.readByte()); //flags
    assertEquals(2, out.readByte()); //keepAliveTimer msb
    assertEquals(0, out.readByte()); //keepAliveTimer lsb

    //Variable part
    TestUtils.verifyString("ABCDEF", out);
    TestUtils.verifyString("Topic", out);
    TestUtils.verifyString("Message", out);
    TestUtils.verifyString("Pablo", out);//username
    TestUtils.verifyString("PBL", out);//password
}

From source file:io.moquette.parser.netty.PubAckEncoderTest.java

License:Open Source License

@Test
public void testHeaderEncode() throws Exception {
    int messageID = 0xAABB;
    PubAckEncoder encoder = new PubAckEncoder();
    PubAckMessage msg = new PubAckMessage();
    msg.setMessageID(messageID);/*from   ww w . j a va2  s .c o m*/
    ByteBuf out = Unpooled.buffer();

    //Exercise
    encoder.encode(m_mockedContext, msg, out);

    //Verify
    assertEquals(0x40, out.readByte()); //1 byte
    assertEquals(0x02, out.readByte()); //2 byte, length
    assertEquals((byte) 0xAA, out.readByte());
    assertEquals((byte) 0xBB, out.readByte());
}

From source file:io.moquette.parser.netty.PublishDecoderTest.java

License:Open Source License

@Test
public void testBadClaimMoreData() throws Exception {
    byte[] rawMessage = new byte[] { 0x30, 0x17, 0x00, 0x06, 0x2f, (byte) 0x74, 0x6f, (byte) 0x70, 0x69, 0x63,
            0x54, 0x65, (byte) 0x73, 0x74, 0x20, 0x6d, (byte) 0x79, 0x20, (byte) 0x70, 0x61, (byte) 0x79, 0x6c,
            0x6f, 0x61, 0x64 };/*  ww w  .ja v a2 s.  c  om*/

    ByteBuf msgBuf = Unpooled.buffer(25);
    msgBuf.writeBytes(rawMessage);
    msgBuf.readByte(); //to simulate the reading of messageType done by MQTTDecoder dispatcher

    //Exercise
    m_msgdec.decode(m_attrMap, msgBuf, m_results);

    assertFalse(m_results.isEmpty());
    PublishMessage message = (PublishMessage) m_results.get(0);
    assertNotNull(message);
    assertEquals("/topic", message.getTopicName());
    //        assertEquals("Test my payload", new String(message.getPayload()));
    Buffer expectedPayload = ByteBuffer.allocate(15).put("Test my payload".getBytes()).flip();
    assertEquals(expectedPayload, message.getPayload());
}

From source file:io.moquette.parser.netty.PubRelEncoderTest.java

License:Open Source License

@Test
public void testHeaderEncode() throws Exception {
    int messageID = 0xAABB;
    PubRelEncoder encoder = new PubRelEncoder();
    PubRelMessage msg = new PubRelMessage();
    msg.setMessageID(messageID);/*from  w  w  w  . j  a va  2  s .  com*/
    ByteBuf out = Unpooled.buffer();

    //Exercise
    encoder.encode(m_mockedContext, msg, out);

    //Verify
    assertEquals(0x62, out.readByte()); //1 byte. See MQTT-3.6.1-1
    assertEquals(0x02, out.readByte()); //2 byte, length
    assertEquals((byte) 0xAA, out.readByte());
    assertEquals((byte) 0xBB, out.readByte());
}

From source file:io.netlibs.bgp.netty.codec.RouteRefreshPacketDecoder.java

License:Apache License

/**
 * decode the REFRESH network packet. The passed channel buffer MUST point to the first packet octet AFTER the type octet.
 * /*from   w  w w  .  jav  a 2  s  .c  o  m*/
 * @param buffer
 *          the buffer containing the data.
 * 
 * @return the decoded packet or null on decoding problems. Neither RFC2918 nor RFC5291 nor RFC4271 describe an error handling procedure,
 *         so best advise is to ignore invalid packets for now.
 */

public BGPv4Packet decodeRouteRefreshPacket(ByteBuf buffer) {

    RouteRefreshPacket packet = null;

    try {
        AddressFamily af = AddressFamily.fromCode(buffer.readUnsignedShort());

        buffer.readByte(); // swallow reserved octet

        SubsequentAddressFamily saf = SubsequentAddressFamily.fromCode(buffer.readUnsignedByte());

        packet = new RouteRefreshPacket(af, saf);

        if (buffer.isReadable()) {

            // we have outbound router filter rules here
            OutboundRouteFilter orf = new OutboundRouteFilter(af, saf);

            orf.setRefreshType(ORFRefreshType.fromCode(buffer.readUnsignedByte()));

            while (buffer.isReadable()) {
                ORFType orfType = ORFType.fromCode(buffer.readUnsignedByte());
                ByteBuf entriesBuffer = Unpooled.buffer(buffer.readUnsignedShort());

                buffer.readBytes(entriesBuffer);
                orf.addAllORFEntries(decodeORFEntries(entriesBuffer, orfType));
            }

            packet.setOutboundRouteFilter(orf);

        }

    } catch (Exception e) {
        log.error("cannot decode ROUTE_REFRESH packet, suppressing it from further processing", e);
        packet = null;
    }

    return packet;
}

From source file:io.netlibs.bgp.netty.codec.UpdatePacketDecoder.java

License:Apache License

private ExtendedCommunityPathAttribute decodeExtendedCommunityPathAttribute(final ByteBuf buffer) {
    final ExtendedCommunityPathAttribute attr = new ExtendedCommunityPathAttribute();

    if ((buffer.readableBytes() < 8) || ((buffer.readableBytes() % 8) != 0)) {
        throw new OptionalAttributeErrorException();
    }//from  w ww  .j  a  va2  s  .  c  om

    while (buffer.isReadable()) {
        AbstractExtendedCommunityInterface extcomm;
        // we need to check whether this is a transitive or non-transitive value
        // and then determine whether we need to red the lower type byte
        byte higherType = buffer.readByte();
        byte higherTypeCompare = (byte) (higherType & ~(1 << 6));
        if (((higherType >> 6) & 1) == 0) {
            // bit 7 is not set in the byte, therefore this is a transitive type
            // clear bit 8, not interested in this value
            TransitiveExtendedCommunityType transCommType = TransitiveExtendedCommunityType
                    .fromCode((byte) (higherType & (~(3 << 6))));

            switch (transCommType) {
            case TWO_OCTET_AS_SPECIFIC:
                TransitiveTwoOctetASSpecificExtCommSubTypes twoOctASNLowerType = TransitiveTwoOctetASSpecificExtCommSubTypes
                        .fromCode(buffer.readByte());
                switch (twoOctASNLowerType) {
                case ROUTE_TARGET:
                    extcomm = new TransitiveTwoByteASNFourByteAdministratorRT((int) buffer.readShort(),
                            (long) buffer.readInt());
                    break;
                default:
                    // all non-RT types are currently unimplemented
                    extcomm = new UnknownTransitiveTwoByteASNSpecificExtendedCommunity(transCommType,
                            twoOctASNLowerType, buffer.readBytes(6).array());
                }
                break;

            case TWO_OCTET_IPv4_ADDRESS_SPECIFIC:

                TransitiveIPv4AddressSpecificExtCommSubTypes ipv4LowerType = TransitiveIPv4AddressSpecificExtCommSubTypes
                        .fromCode(buffer.readByte());

                switch (ipv4LowerType) {
                case ROUTE_TARGET:
                    try {
                        extcomm = new TransitiveIPv4AddressTwoByteAdministratorRT(
                                (Inet4Address) InetAddresses
                                        .fromLittleEndianByteArray(buffer.readBytes(4).array()),
                                (int) buffer.readShort());
                    } catch (UnknownHostException e) {
                        ByteBuf data = Unpooled.buffer();
                        data.getByte(ipv4LowerType.toCode());
                        data.readBytes(buffer.readBytes(6));
                        extcomm = new UnknownTransitiveExtendedCommunity(transCommType, data.array());
                    }
                    break;

                default:

                    // all non-RT types are currently unimplemented
                    extcomm = new UnknownTransitiveIPv4AddressSpecificExtendedCommunity(transCommType,
                            ipv4LowerType, buffer.readBytes(6).array());
                    break;

                }
                break;

            default:
                // by default, just create an unknown type, reading the subsequent
                // 7 bytes (we have already read byte 1)
                extcomm = new UnknownTransitiveExtendedCommunity(transCommType, buffer.readBytes(7).array());
            }
        } else {
            // bit 7 is set, these are non-transitive
            NonTransitiveExtendedCommunityType nonTransCommType = NonTransitiveExtendedCommunityType
                    .fromCode((byte) (higherType & (~(3 << 6))));
            // all non-transitive types are currently unimplemented
            extcomm = new UnknownNonTransitiveExtendedCommunity(nonTransCommType, buffer.readBytes(7).array());
        }
        attr.getMembers().add(extcomm);
    }
    return attr;
}

From source file:io.netlibs.bgp.netty.codec.UpdatePacketDecoder.java

License:Apache License

private MultiProtocolReachableNLRI decodeMpReachNlriPathAttribute(final ByteBuf buffer) {
    final MultiProtocolReachableNLRI attr = new MultiProtocolReachableNLRI();

    try {/*w ww  .  ja  v a2  s. c  o  m*/
        attr.setAddressFamily(AddressFamily.fromCode(buffer.readUnsignedShort()));
        attr.setSubsequentAddressFamily(SubsequentAddressFamily.fromCode(buffer.readUnsignedByte()));

        final int nextHopLength = buffer.readUnsignedByte();

        if (nextHopLength > 0) {
            final byte[] nextHop = new byte[nextHopLength];

            buffer.readBytes(nextHop);
            attr.setNextHopAddress(nextHop);
        }

        buffer.readByte(); // reserved

        while (buffer.isReadable()) {
            attr.getNlris().add(NLRICodec.decodeNLRI(buffer));
        }
    } catch (final RuntimeException e) {
        throw new OptionalAttributeErrorException();
    }

    return attr;
}

From source file:io.netlibs.bgp.netty.protocol.open.CapabilityCodec.java

License:Apache License

private static Capability decodeOutboundRouteFilteringCapability(final ByteBuf buffer) {
    final OutboundRouteFilteringCapability cap = new OutboundRouteFilteringCapability();

    assertMinimalLength(buffer, 5); // 2 octest AFI + 1 octet reserved + 1 octet SAFI + 1 octet number of (ORF type, Send/Receive) tuples

    cap.setAddressFamily(AddressFamily.fromCode(buffer.readUnsignedShort()));
    buffer.readByte();
    cap.setSubsequentAddressFamily(SubsequentAddressFamily.fromCode(buffer.readUnsignedByte()));

    final int orfs = buffer.readUnsignedByte();

    if (buffer.readableBytes() != (2 * orfs)) {
        throw new UnspecificOpenPacketException(
                "Expected " + (2 * orfs) + " octets parameter, got " + buffer.readableBytes() + " octets");
    }/*from  w w w .j  a v a2  s . c  o m*/

    try {
        cap.getFilters().put(ORFType.fromCode(buffer.readUnsignedByte()),
                ORFSendReceive.fromCode(buffer.readUnsignedByte()));
    } catch (final IllegalArgumentException e) {
        throw new UnspecificOpenPacketException(e);
    }
    return cap;
}

From source file:io.netlibs.bgp.netty.protocol.open.CapabilityCodec.java

License:Apache License

private static Capability decodeMultiProtocolCapability(final ByteBuf buffer) {
    final MultiProtocolCapability cap = new MultiProtocolCapability();

    assertFixedLength(buffer, BGPv4Constants.BGP_CAPABILITY_LENGTH_MULTIPROTOCOL);

    cap.setAfi(AddressFamily.fromCode(buffer.readShort()));
    buffer.readByte(); // reserved

    int safiCode = Ints.fromBytes((byte) 0, (byte) 0, (byte) 0, buffer.readByte());
    cap.setSafi(SubsequentAddressFamily.fromCode(safiCode));

    return cap;//w  ww.java2  s  .c  o  m
}

From source file:io.nodyn.http.HTTPParser.java

License:Apache License

protected boolean readRequestLine() {
    ByteBuf line = readLine();
    if (line == null) {
        return false;
    }//from   w w  w.java  2s  .co  m

    int space = line.indexOf(line.readerIndex(), line.readerIndex() + line.readableBytes(), (byte) ' ');
    if (space < 0) {
        setError(Error.INVALID_METHOD);
        return false;
    }

    int len = space - line.readerIndex();

    ByteBuf methodBuf = line.readSlice(len);

    String methodName = methodBuf.toString(UTF8);
    for (int i = 0; i < METHODS.length; ++i) {
        if (METHODS[i].equals(methodName)) {
            this.method = i;
            break;
        }
    }

    if (this.method == null) {
        setError(Error.INVALID_METHOD);
        return false;
    }

    if ("CONNECT".equals(methodName)) {
        this.upgrade = true;
    }

    // skip the space
    line.readByte();

    space = line.indexOf(line.readerIndex(), line.readerIndex() + line.readableBytes(), (byte) ' ');

    ByteBuf urlBuf = null;
    ByteBuf versionBuf = null;
    if (space < 0) {
        // HTTP/1.0
        urlBuf = line.readSlice(line.readableBytes());
    } else {
        len = space - line.readerIndex();
        urlBuf = line.readSlice(len);
        versionBuf = line.readSlice(line.readableBytes());
    }

    this.url = urlBuf.toString(UTF8).trim();

    if (versionBuf != null) {
        if (!readVersion(versionBuf)) {
            setError(Error.INVALID_VERSION);
            return false;
        }
    } else {
        this.versionMajor = 1;
        this.versionMinor = 0;
    }
    return true;
}