Example usage for io.netty.buffer ByteBuf getByte

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

Introduction

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

Prototype

public abstract byte getByte(int index);

Source Link

Document

Gets a byte at the specified absolute index in this buffer.

Usage

From source file:org.opendaylight.openflowjava.protocol.impl.clients.UdpSimpleClientFramer.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext chc, DatagramPacket msg, List<Object> list) throws Exception {
    ByteBuf bb = msg.content();
    if (bb.readableBytes() < LENGTH_OF_HEADER) {
        LOG.debug("skipping bb - too few data for header: {}", bb.readableBytes());
        return;/* w  w w  .ja  va  2  s.  co  m*/
    }

    int length = bb.getUnsignedShort(bb.readerIndex() + LENGTH_INDEX_IN_HEADER);
    if (bb.readableBytes() < length) {
        LOG.debug("skipping bb - too few data for msg: {} < {}", bb.readableBytes(), length);
        return;
    }
    LOG.debug("OF Protocol message received, type:{}", bb.getByte(bb.readerIndex() + 1));

    ByteBuf messageBuffer = bb.slice(bb.readerIndex(), length);
    list.add(messageBuffer);
    messageBuffer.retain();
    bb.skipBytes(length);
}

From source file:org.opendaylight.openflowjava.protocol.impl.core.OFDatagramPacketHandler.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, DatagramPacket msg, List<Object> out) throws Exception {
    LOG.debug("OFDatagramPacketFramer");
    MessageConsumer consumer = UdpConnectionMap.getMessageConsumer(msg.sender());
    if (consumer == null) {
        ConnectionFacade connectionFacade = adapterFactory.createConnectionFacade(ctx.channel(), msg.sender(),
                false);/* www.j av  a  2  s  .  c om*/
        connectionHandler.onSwitchConnected(connectionFacade);
        connectionFacade.checkListeners();
        UdpConnectionMap.addConnection(msg.sender(), connectionFacade);
    }
    ByteBuf bb = msg.content();
    int readableBytes = bb.readableBytes();
    if (readableBytes < LENGTH_OF_HEADER) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("skipping bytebuf - too few bytes for header: {} < {}", readableBytes, LENGTH_OF_HEADER);
            LOG.debug("bb: {}", ByteBufUtils.byteBufToHexString(bb));
        }
        return;
    }

    int length = bb.getUnsignedShort(bb.readerIndex() + LENGTH_INDEX_IN_HEADER);
    LOG.debug("length of actual message: {}", length);

    if (readableBytes < length) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("skipping bytebuf - too few bytes for msg: {} < {}", readableBytes, length);
            LOG.debug("bytebuffer: {}", ByteBufUtils.byteBufToHexString(bb));
        }
        return;
    }
    LOG.debug("OF Protocol message received, type:{}", bb.getByte(bb.readerIndex() + 1));

    byte version = bb.readByte();
    if ((version == EncodeConstants.OF13_VERSION_ID) || (version == EncodeConstants.OF10_VERSION_ID)) {
        LOG.debug("detected version: {}", version);
        ByteBuf messageBuffer = bb.slice();
        out.add(new VersionMessageUdpWrapper(version, messageBuffer, msg.sender()));
        messageBuffer.retain();
    } else {
        LOG.warn("detected version: {} - currently not supported", version);
    }
    bb.skipBytes(bb.readableBytes());
}

From source file:org.opendaylight.openflowjava.protocol.impl.core.OFFrameDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext chc, ByteBuf bb, List<Object> list) throws Exception {
    int readableBytes = bb.readableBytes();
    if (readableBytes < LENGTH_OF_HEADER) {
        LOGGER.debug("skipping bb - too few data for header: " + readableBytes);
        return;/*from w  w w  .ja  va2 s  .  c  o m*/
    }

    int length = bb.getUnsignedShort(bb.readerIndex() + LENGTH_INDEX_IN_HEADER);
    LOGGER.debug("length of actual message: {}", length);

    if (readableBytes < length) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("skipping bb - too few data for msg: " + readableBytes + " < " + length);
            LOGGER.debug("bb: " + ByteBufUtils.byteBufToHexString(bb));
        }
        return;
    }
    LOGGER.debug("OF Protocol message received, type:{}", bb.getByte(bb.readerIndex() + 1));

    ByteBuf messageBuffer = bb.slice(bb.readerIndex(), length);
    list.add(messageBuffer);
    messageBuffer.retain();
    bb.skipBytes(length);
}

From source file:org.opendaylight.ovsdb.lib.jsonrpc.JsonRpcDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) throws Exception {

    logger.trace("readable bytes {}, records read {}, incomplete record bytes {}", buf.readableBytes(),
            recordsRead, lastRecordBytes);

    if (lastRecordBytes == 0) {
        if (buf.readableBytes() < 4) {
            return; //wait for more data
        }/*from   w  w w .j  a v a  2  s  . c o m*/

        skipSpaces(buf);

        byte[] buff = new byte[4];
        buf.getBytes(buf.readerIndex(), buff);
        ByteSourceJsonBootstrapper strapper = new ByteSourceJsonBootstrapper(jacksonIOContext, buff, 0, 4);
        JsonEncoding jsonEncoding = strapper.detectEncoding();
        if (!JsonEncoding.UTF8.equals(jsonEncoding)) {
            throw new InvalidEncodingException(jsonEncoding.getJavaName(), "currently only UTF-8 is supported");
        }
    }

    int index = lastRecordBytes + buf.readerIndex();

    for (; index < buf.writerIndex(); index++) {
        switch (buf.getByte(index)) {
        case '{':
            if (!inS) {
                leftCurlies++;
            }
            break;
        case '}':
            if (!inS) {
                rightCurlies++;
            }
            break;
        case '"':
            if (buf.getByte(index - 1) != '\\') {
                inS = !inS;
            }
            break;
        default:
            break;
        }

        if (leftCurlies != 0 && leftCurlies == rightCurlies && !inS) {
            ByteBuf slice = buf.readSlice(1 + index - buf.readerIndex());
            JsonParser jp = jacksonJsonFactory.createParser(new ByteBufInputStream(slice));
            JsonNode root = jp.readValueAsTree();
            out.add(root);
            leftCurlies = rightCurlies = lastRecordBytes = 0;
            recordsRead++;
            break;
        }

        if (index - buf.readerIndex() >= maxFrameLength) {
            fail(ctx, index - buf.readerIndex());
        }
    }

    // end of stream, save the incomplete record index to avoid reexamining the whole on next run
    if (index >= buf.writerIndex()) {
        lastRecordBytes = buf.readableBytes();
        return;
    }
}

From source file:org.opendaylight.ovsdb.lib.jsonrpc.JsonRpcDecoder.java

License:Open Source License

private static void skipSpaces(ByteBuf byteBuf) throws IOException {
    while (byteBuf.isReadable()) {
        int ch = byteBuf.getByte(byteBuf.readerIndex()) & 0xFF;
        if (!(ch == ' ' || ch == '\r' || ch == '\n' || ch == '\t')) {
            return;
        } else {/* www .  j av  a 2s.c  o  m*/
            byteBuf.readByte(); //move the read index
        }
    }
}

From source file:org.opendaylight.protocol.bgp.linkstate.impl.tlvs.RouterIdTlvParser.java

License:Open Source License

@Override
public CRouterIdentifier parseTlvBody(final ByteBuf value) {
    if (value.readableBytes() == ISO_SYSTEM_ID_LENGTH
            || (value.readableBytes() == ISO_SYSTEM_ID_LENGTH + PSN_LENGTH
                    && value.getByte(ISO_SYSTEM_ID_LENGTH) == 0)) {
        return new IsisNodeCaseBuilder().setIsisNode(new IsisNodeBuilder()
                .setIsoSystemId(new IsoSystemIdentifier(ByteArray.readBytes(value, ISO_SYSTEM_ID_LENGTH)))
                .build()).build();//from   www.jav  a 2 s .c om
    }
    if (value.readableBytes() == ISO_SYSTEM_ID_LENGTH + PSN_LENGTH) {
        final IsIsRouterIdentifier iri = new IsIsRouterIdentifierBuilder()
                .setIsoSystemId(new IsoSystemIdentifier(ByteArray.readBytes(value, ISO_SYSTEM_ID_LENGTH)))
                .build();
        return new IsisPseudonodeCaseBuilder().setIsisPseudonode(new IsisPseudonodeBuilder()
                .setIsIsRouterIdentifier(iri).setPsn((short) value.readByte()).build()).build();
    }
    if (value.readableBytes() == OSPF_ROUTER_ID_LENGTH) {
        return new OspfNodeCaseBuilder()
                .setOspfNode(new OspfNodeBuilder().setOspfRouterId(value.readUnsignedInt()).build()).build();

    }
    if (value.readableBytes() == OSPF_PSEUDONODE_ROUTER_ID_LENGTH) {
        return new OspfPseudonodeCaseBuilder()
                .setOspfPseudonode(new OspfPseudonodeBuilder().setOspfRouterId(value.readUnsignedInt())
                        .setLanInterface(new OspfInterfaceIdentifier(value.readUnsignedInt())).build())
                .build();
    }
    return null;
}

From source file:org.opendaylight.protocol.bgp.linkstate.nlri.NodeNlriParser.java

License:Open Source License

private static CRouterIdentifier parseRouterId(final ByteBuf value) throws BGPParsingException {
    if (value.readableBytes() == ISO_SYSTEM_ID_LENGTH
            || (value.readableBytes() == ISO_SYSTEM_ID_LENGTH + PSN_LENGTH
                    && value.getByte(ISO_SYSTEM_ID_LENGTH) == 0)) {
        return new IsisNodeCaseBuilder().setIsisNode(new IsisNodeBuilder()
                .setIsoSystemId(new IsoSystemIdentifier(ByteArray.readBytes(value, ISO_SYSTEM_ID_LENGTH)))
                .build()).build();/*from   ww  w . j  ava2s  . co m*/
    }
    if (value.readableBytes() == ISO_SYSTEM_ID_LENGTH + PSN_LENGTH) {
        final IsIsRouterIdentifier iri = new IsIsRouterIdentifierBuilder()
                .setIsoSystemId(new IsoSystemIdentifier(ByteArray.readBytes(value, ISO_SYSTEM_ID_LENGTH)))
                .build();
        return new IsisPseudonodeCaseBuilder().setIsisPseudonode(new IsisPseudonodeBuilder()
                .setIsIsRouterIdentifier(iri).setPsn((short) value.readByte()).build()).build();
    }
    if (value.readableBytes() == OSPF_ROUTER_ID_LENGTH) {
        return new OspfNodeCaseBuilder()
                .setOspfNode(new OspfNodeBuilder().setOspfRouterId(value.readUnsignedInt()).build()).build();
    }
    if (value.readableBytes() == OSPF_PSEUDONODE_ROUTER_ID_LENGTH) {
        return new OspfPseudonodeCaseBuilder()
                .setOspfPseudonode(new OspfPseudonodeBuilder().setOspfRouterId(value.readUnsignedInt())
                        .setLanInterface(new OspfInterfaceIdentifier(value.readUnsignedInt())).build())
                .build();
    }
    throw new BGPParsingException("Router Id of invalid length " + value.readableBytes());
}

From source file:org.opendaylight.protocol.bgp.parser.impl.message.open.GracefulCapabilityHandler.java

License:Open Source License

@Override
public CParameters parseCapability(final ByteBuf buffer) throws BGPDocumentedException, BGPParsingException {
    final GracefulRestartCapabilityBuilder cb = new GracefulRestartCapabilityBuilder();

    final int flagBits = (buffer.getByte(0) >> RESTART_FLAGS_SIZE);
    cb.setRestartFlags(new RestartFlags((flagBits & Byte.SIZE) != 0));

    final int timer = ((buffer.readUnsignedByte() & TIMER_TOPBITS_MASK) << Byte.SIZE)
            + buffer.readUnsignedByte();
    cb.setRestartTime(timer);//from www  . j a va 2  s . c  o m

    final List<Tables> tables = new ArrayList<>();
    while (buffer.readableBytes() != 0) {
        final int afiVal = buffer.readShort();
        final Class<? extends AddressFamily> afi = this.afiReg.classForFamily(afiVal);
        if (afi == null) {
            LOG.debug("Ignoring GR capability for unknown address family {}", afiVal);
            buffer.skipBytes(PER_AFI_SAFI_SIZE - 2);
            continue;
        }
        final int safiVal = buffer.readUnsignedByte();
        final Class<? extends SubsequentAddressFamily> safi = this.safiReg.classForFamily(safiVal);
        if (safi == null) {
            LOG.debug("Ignoring GR capability for unknown subsequent address family {}", safiVal);
            buffer.skipBytes(1);
            continue;
        }
        final int flags = buffer.readUnsignedByte();
        tables.add(new TablesBuilder().setAfi(afi).setSafi(safi)
                .setAfiFlags(new AfiFlags((flags & AFI_FLAG_FORWARDING_STATE) != 0)).build());
    }
    cb.setTables(tables);
    return new CParametersBuilder().addAugmentation(CParameters1.class,
            new CParameters1Builder().setGracefulRestartCapability(cb.build()).build()).build();
}

From source file:org.opendaylight.protocol.pcep.impl.subobject.EROExplicitExclusionRouteSubobjectParser.java

License:Open Source License

private List<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.exclude.route.object.xro.Subobject> parseSubobject(
        final ByteBuf buffer) throws PCEPDeserializerException {
    Preconditions.checkArgument(buffer != null && buffer.isReadable(),
            "Array of bytes is mandatory. Can't be null or empty.");
    final List<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.exclude.route.object.xro.Subobject> subs = new ArrayList<>();
    while (buffer.isReadable()) {
        final boolean mandatory = ((buffer.getByte(buffer.readerIndex()) & (1 << Values.FIRST_BIT_OFFSET)) != 0)
                ? true//from   w  w w  . j  a v a 2 s.  c o m
                : false;
        final int type = (buffer.readUnsignedByte() & Values.BYTE_MAX_VALUE_BYTES)
                & ~(1 << Values.FIRST_BIT_OFFSET);
        final int length = buffer.readUnsignedByte() - HEADER_LENGTH;
        if (length > buffer.readableBytes()) {
            throw new PCEPDeserializerException(
                    "Wrong length specified. Passed: " + length + "; Expected: <= " + buffer.readableBytes());
        }
        subs.add(this.registry.parseSubobject(type, buffer.readSlice(length), mandatory));
    }
    return subs;
}

From source file:org.opendaylight.protocol.rsvp.parser.impl.subobject.ero.EROExplicitExclusionRouteSubobjectParser.java

License:Open Source License

private List<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rsvp.rev150820.exclude.route.object.exclude.route.object.SubobjectContainer> parseSubobject(
        final ByteBuf buffer) throws RSVPParsingException {
    Preconditions.checkArgument(buffer != null && buffer.isReadable(),
            "Array of bytes is mandatory. Can't be null or empty.");
    final List<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rsvp.rev150820.exclude.route.object.exclude.route.object.SubobjectContainer> subs = new ArrayList<>();
    while (buffer.isReadable()) {
        final boolean mandatory = ((buffer.getByte(buffer.readerIndex()) & (1 << Values.FIRST_BIT_OFFSET)) != 0)
                ? true// w  ww. j av  a  2  s . c o m
                : false;
        final int type = (buffer.readUnsignedByte() & Values.BYTE_MAX_VALUE_BYTES)
                & ~(1 << Values.FIRST_BIT_OFFSET);
        final int length = buffer.readUnsignedByte() - HEADER_LENGTH;
        if (length > buffer.readableBytes()) {
            throw new RSVPParsingException(
                    "Wrong length specified. Passed: " + length + "; Expected: <= " + buffer.readableBytes());
        }
        subs.add(this.registry.parseSubobject(type, buffer.readSlice(length), mandatory));
    }
    return subs;
}