Example usage for io.netty.buffer ByteBuf slice

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

Introduction

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

Prototype

public abstract ByteBuf slice();

Source Link

Document

Returns a slice of this buffer's readable bytes.

Usage

From source file:org.apache.distributedlog.tests.CompressionBenchmark.java

License:Apache License

private void testDecompress(CompressionCodec codec, ByteBuf compressed) {
    ByteBuf decompressed = codec.decompress(compressed.slice(), size);
    decompressed.release();
}

From source file:org.apache.pulsar.compaction.CompactorTest.java

License:Apache License

public ByteBuf extractPayload(RawMessage m) throws Exception {
    ByteBuf payloadAndMetadata = m.getHeadersAndPayload();
    Commands.skipChecksumIfPresent(payloadAndMetadata);
    int metadataSize = payloadAndMetadata.readInt(); // metadata size
    byte[] metadata = new byte[metadataSize];
    payloadAndMetadata.readBytes(metadata);
    return payloadAndMetadata.slice();
}

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);//from   w w  w  .  j  a  va  2s .co  m
        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.OFVersionDetector.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext chc, ByteBuf bb, List<Object> list) throws Exception {
    if (bb.readableBytes() == 0) {
        LOGGER.debug("not enough data");
        bb.release();/*from   w  w  w .j av a  2s.c  o  m*/
        return;
    }
    byte version = bb.readByte();
    if ((version == OF13_VERSION_ID) || (version == OF10_VERSION_ID)) {
        LOGGER.debug("detected version: " + version);
    } else {
        LOGGER.warn("detected version: " + version + " - currently not supported");
        bb.skipBytes(bb.readableBytes());
        return;
    }

    ByteBuf messageBuffer = bb.slice();
    list.add(new VersionMessageWrapper(version, messageBuffer));
    messageBuffer.retain();
    bb.skipBytes(bb.readableBytes());
}

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

License:Open Source License

private static org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.NodeIdentifier parseLink(
        final CLinkstateDestinationBuilder builder, final ByteBuf buffer,
        final LocalNodeDescriptors localDescriptors) throws BGPParsingException {
    final int type = buffer.readUnsignedShort();
    final int length = buffer.readUnsignedShort();
    final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.NodeIdentifier remote = null;
    RemoteNodeDescriptors remoteDescriptors = null;
    if (type == REMOTE_NODE_DESCRIPTORS_TYPE) {
        remoteDescriptors = (RemoteNodeDescriptors) NodeNlriParser
                .parseNodeDescriptors(buffer.readSlice(length), NlriType.Link, false);
    }//from  w  ww.jav  a2  s  . c o m
    builder.setObjectType(new LinkCaseBuilder().setLocalNodeDescriptors(localDescriptors)
            .setRemoteNodeDescriptors(remoteDescriptors)
            .setLinkDescriptors(LinkNlriParser.parseLinkDescriptors(buffer.slice())).build());
    return remote;
}

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

License:Open Source License

/**
 * Parses given byte array to BGP Open message
 *
 * @param body byte array representing BGP Open message, without header
 * @param messageLength the length of the message
 * @return {@link Open} BGP Open Message
 * @throws BGPDocumentedException if the parsing was unsuccessful
 *//*from ww w  .j  a v a  2  s. co  m*/
@Override
public Open parseMessageBody(final ByteBuf body, final int messageLength) throws BGPDocumentedException {
    Preconditions.checkArgument(body != null, "Buffer cannot be null.");

    if (body.readableBytes() < MIN_MSG_LENGTH) {
        throw BGPDocumentedException.badMessageLength("Open message too small.", messageLength);
    }
    final int version = body.readUnsignedByte();
    if (version != BGP_VERSION) {
        throw new BGPDocumentedException("BGP Protocol version " + version + " not supported.",
                BGPError.VERSION_NOT_SUPPORTED);
    }
    final AsNumber as = new AsNumber((long) body.readUnsignedShort());
    final int holdTime = body.readUnsignedShort();
    if (holdTime == 1 || holdTime == 2) {
        throw new BGPDocumentedException("Hold time value not acceptable.", BGPError.HOLD_TIME_NOT_ACC);
    }
    Ipv4Address bgpId = null;
    try {
        bgpId = Ipv4Util.addressForByteBuf(body);
    } catch (final IllegalArgumentException e) {
        throw new BGPDocumentedException("BGP Identifier is not a valid IPv4 Address", BGPError.BAD_BGP_ID, e);
    }
    final int optLength = body.readUnsignedByte();

    final List<BgpParameters> optParams = new ArrayList<>();
    if (optLength > 0) {
        fillParams(body.slice(), optParams);
    }
    LOG.debug("BGP Open message was parsed: AS = {}, holdTimer = {}, bgpId = {}, optParams = {}", as, holdTime,
            bgpId, optParams);
    return new OpenBuilder().setMyAsNumber(as.getValue().intValue()).setHoldTimer(holdTime)
            .setBgpIdentifier(bgpId).setBgpParameters(optParams).build();
}

From source file:org.opendaylight.protocol.bgp.parser.spi.pojo.SimpleNlriRegistry.java

License:Open Source License

@Override
public MpUnreachNlri parseMpUnreach(final ByteBuf buffer, final PeerSpecificParserConstraint constraint)
        throws BGPParsingException {
    final MpUnreachNlriBuilder builder = new MpUnreachNlriBuilder();
    builder.setAfi(getAfi(buffer));/*from   w w  w .  ja v a 2 s.c  o  m*/
    builder.setSafi(getSafi(buffer));

    final ByteBuf nlri = buffer.slice();
    final BgpTableType key = createKey(builder.getAfi(), builder.getSafi());
    final NlriParser parser = this.handlers.get(key);
    if (parser == null) {
        LOG.warn(PARSER_NOT_FOUND, key);
    } else {
        parser.parseNlri(nlri, builder, constraint);
    }
    return builder.build();
}

From source file:org.opendaylight.protocol.bgp.parser.spi.pojo.SimpleNlriRegistry.java

License:Open Source License

@Override
public MpReachNlri parseMpReach(final ByteBuf buffer, final PeerSpecificParserConstraint constraint)
        throws BGPParsingException {
    final MpReachNlriBuilder builder = new MpReachNlriBuilder();
    final Class<? extends AddressFamily> afi = getAfi(buffer);
    final Class<? extends SubsequentAddressFamily> safi = getSafi(buffer);
    builder.setAfi(afi);/*from   w  w  w  . jav  a2  s .  com*/
    builder.setSafi(safi);

    final BgpTableType key = createKey(builder.getAfi(), builder.getSafi());

    final int nextHopLength = buffer.readUnsignedByte();
    if (nextHopLength != 0) {
        final NextHopParserSerializer nextHopParser = this.nextHopParsers.get(key);
        if (nextHopParser != null) {
            builder.setCNextHop(nextHopParser.parseNextHop(buffer.readSlice(nextHopLength)));
        } else {
            builder.setCNextHop(NextHopUtil.parseNextHop(buffer.readSlice(nextHopLength)));
            LOG.warn("NexHop Parser/Serializer for AFI/SAFI ({},{}) not bound", afi, safi);
        }
    }
    buffer.skipBytes(RESERVED);

    final ByteBuf nlri = buffer.slice();
    final NlriParser parser = this.handlers.get(key);
    if (parser == null) {
        LOG.warn(PARSER_NOT_FOUND, key);
    } else {
        parser.parseNlri(nlri, builder, constraint);
    }
    return builder.build();
}

From source file:org.opendaylight.protocol.bmp.spi.parser.AbstractBmpPerPeerMessageParser.java

License:Open Source License

protected final PeerHeader parsePerPeerHeader(final ByteBuf bytes) {
    Preconditions.checkArgument(bytes.readableBytes() >= PER_PEER_HEADER_SIZE);
    final PeerHeaderBuilder phBuilder = new PeerHeaderBuilder();
    final PeerType peerType = PeerType.forValue(bytes.readByte());
    phBuilder.setType(peerType);//from  www .  j  a v a  2  s  .  c  om
    final BitArray flags = BitArray.valueOf(bytes, FLAGS_SIZE);
    phBuilder.setAdjRibInType(AdjRibInType.forValue(flags.get(L_FLAG_POS) ? 1 : 0));
    phBuilder.setIpv4(!flags.get(V_FLAG_POS));
    switch (peerType) {
    case L3vpn:
        phBuilder.setDistinguisher(PeerDistinguisherUtil.parsePeerDistingisher(bytes.slice()));
        phBuilder.setPeerDistinguisher(
                new PeerDistinguisher(RouteDistinguisherUtil.parseRouteDistinguisher(bytes)));
        break;
    case Local:
        phBuilder.setPeerDistinguisher(
                new PeerDistinguisher(ByteArray.readBytes(bytes, PEER_DISTINGUISHER_SIZE)));
        break;
    case Global:
    default:
        bytes.skipBytes(PEER_DISTINGUISHER_SIZE);
        break;
    }
    if (phBuilder.isIpv4()) {
        bytes.skipBytes(Ipv6Util.IPV6_LENGTH - Ipv4Util.IP4_LENGTH);
        phBuilder.setAddress(new IpAddress(Ipv4Util.addressForByteBuf(bytes)));
    } else {
        phBuilder.setAddress(new IpAddress(Ipv6Util.addressForByteBuf(bytes)));
    }
    phBuilder.setAs(new AsNumber(bytes.readUnsignedInt()));
    phBuilder.setBgpId(Ipv4Util.addressForByteBuf(bytes));
    phBuilder.setTimestampSec(new Timestamp(bytes.readUnsignedInt()));
    phBuilder.setTimestampMicro(new Timestamp(bytes.readUnsignedInt()));
    return phBuilder.build();
}

From source file:org.opendaylight.protocol.pcep.ietf.stateful07.Stateful07LspObjectParser.java

License:Open Source License

@Override
public Lsp parseObject(final ObjectHeader header, final ByteBuf bytes) throws PCEPDeserializerException {
    Preconditions.checkArgument(bytes != null && bytes.isReadable(),
            "Array of bytes is mandatory. Can't be null or empty.");
    final LspBuilder builder = new LspBuilder();
    builder.setIgnore(header.isIgnore());
    builder.setProcessingRule(header.isProcessingRule());
    final int[] plspIdRaw = new int[] { bytes.readUnsignedByte(), bytes.readUnsignedByte(),
            bytes.getUnsignedByte(2), };
    builder.setPlspId(new PlspId((long) ((plspIdRaw[0] << FLAGS_SIZE) | (plspIdRaw[1] << FOUR_BITS_SHIFT)
            | (plspIdRaw[2] >> FOUR_BITS_SHIFT))));
    parseFlags(builder, bytes);//from w  w  w .  j av a  2s . c  om
    final TlvsBuilder b = new TlvsBuilder();
    parseTlvs(b, bytes.slice());
    builder.setTlvs(b.build());
    return builder.build();
}