Example usage for io.netty.buffer ByteBuf readSlice

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

Introduction

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

Prototype

public abstract ByteBuf readSlice(int length);

Source Link

Document

Returns a new slice of this buffer's sub-region starting at the current readerIndex and increases the readerIndex by the size of the new slice (= length ).

Usage

From source file:netty.syslog.MessageFramer.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
    if (buffer.readableBytes() > 0) {
        // Decode the content length
        final int length = readDigit(buffer);
        expect(buffer, ' ');
        if (length > maxMessageSize) {
            throw new TooLongFrameException(
                    "Received a message of length " + length + ", maximum message length is " + maxMessageSize);
        }/*from w w  w.  j a  va2s  .  c  o m*/
        out.add(buffer.readSlice(length).retain());
    }
}

From source file:nl.thijsalders.spigotproxy.haproxy.HAProxyMessageDecoder.java

License:Apache License

/**
 * Create a frame out of the {@link ByteBuf} and return it.
 * Based on code from {@link LineBasedFrameDecoder#decode(ChannelHandlerContext, ByteBuf)}.
 *
 * @param ctx     the {@link ChannelHandlerContext} which this {@link HAProxyMessageDecoder} belongs to
 * @param buffer  the {@link ByteBuf} from which to read data
 * @return frame  the {@link ByteBuf} which represent the frame or {@code null} if no frame could
 *                be created//  www .j  ava2s.  com
 */
private ByteBuf decodeStruct(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
    final int eoh = findEndOfHeader(buffer);
    if (!discarding) {
        if (eoh >= 0) {
            final int length = eoh - buffer.readerIndex();
            if (length > v2MaxHeaderSize) {
                buffer.readerIndex(eoh);
                failOverLimit(ctx, length);
                return null;
            }
            return buffer.readSlice(length);
        } else {
            final int length = buffer.readableBytes();
            if (length > v2MaxHeaderSize) {
                discardedBytes = length;
                buffer.skipBytes(length);
                discarding = true;
                failOverLimit(ctx, "over " + discardedBytes);
            }
            return null;
        }
    } else {
        if (eoh >= 0) {
            buffer.readerIndex(eoh);
            discardedBytes = 0;
            discarding = false;
        } else {
            discardedBytes = buffer.readableBytes();
            buffer.skipBytes(discardedBytes);
        }
        return null;
    }
}

From source file:nl.thijsalders.spigotproxy.haproxy.HAProxyMessageDecoder.java

License:Apache License

/**
 * Create a frame out of the {@link ByteBuf} and return it.
 * Based on code from {@link LineBasedFrameDecoder#decode(ChannelHandlerContext, ByteBuf)}.
 *
 * @param ctx     the {@link ChannelHandlerContext} which this {@link HAProxyMessageDecoder} belongs to
 * @param buffer  the {@link ByteBuf} from which to read data
 * @return frame  the {@link ByteBuf} which represent the frame or {@code null} if no frame could
 *                be created//  ww  w .  ja va 2 s.c  o m
 */
private ByteBuf decodeLine(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
    final int eol = findEndOfLine(buffer);
    if (!discarding) {
        if (eol >= 0) {
            final int length = eol - buffer.readerIndex();
            if (length > V1_MAX_LENGTH) {
                buffer.readerIndex(eol + DELIMITER_LENGTH);
                failOverLimit(ctx, length);
                return null;
            }
            ByteBuf frame = buffer.readSlice(length);
            buffer.skipBytes(DELIMITER_LENGTH);
            return frame;
        } else {
            final int length = buffer.readableBytes();
            if (length > V1_MAX_LENGTH) {
                discardedBytes = length;
                buffer.skipBytes(length);
                discarding = true;
                failOverLimit(ctx, "over " + discardedBytes);
            }
            return null;
        }
    } else {
        if (eol >= 0) {
            final int delimLength = buffer.getByte(eol) == '\r' ? 2 : 1;
            buffer.readerIndex(eol + delimLength);
            discardedBytes = 0;
            discarding = false;
        } else {
            discardedBytes = buffer.readableBytes();
            buffer.skipBytes(discardedBytes);
        }
        return null;
    }
}

From source file:org.apache.cassandra.transport.CBUtil.java

License:Apache License

public static ByteBuffer readBoundValue(ByteBuf cb, int protocolVersion) {
    int length = cb.readInt();
    if (length < 0) {
        if (protocolVersion < 4) // backward compatibility for pre-version 4
            return null;
        if (length == -1)
            return null;
        else if (length == -2)
            return ByteBufferUtil.UNSET_BYTE_BUFFER;
        else/*from  www .  j ava  2s . c  o m*/
            throw new ProtocolException("Invalid ByteBuf length " + length);
    }
    ByteBuf slice = cb.readSlice(length);

    return ByteBuffer.wrap(readRawBytes(slice));
}

From source file:org.apache.spark.network.util.TransportFrameDecoderSuite.java

License:Apache License

@Test
public void testSplitLengthField() throws Exception {
    byte[] frame = new byte[1024 * (RND.nextInt(31) + 1)];
    ByteBuf buf = Unpooled.buffer(frame.length + 8);
    buf.writeLong(frame.length + 8);//  w w  w .ja  v a 2  s.c o m
    buf.writeBytes(frame);

    TransportFrameDecoder decoder = new TransportFrameDecoder();
    ChannelHandlerContext ctx = mockChannelHandlerContext();
    try {
        decoder.channelRead(ctx, buf.readSlice(RND.nextInt(7)).retain());
        verify(ctx, never()).fireChannelRead(any(ByteBuf.class));
        decoder.channelRead(ctx, buf);
        verify(ctx).fireChannelRead(any(ByteBuf.class));
        assertEquals(0, buf.refCnt());
    } finally {
        decoder.channelInactive(ctx);
        release(buf);
    }
}

From source file:org.apache.spark.network.util.TransportFrameDecoderSuite.java

License:Apache License

/**
 * Creates a number of randomly sized frames and feed them to the given decoder, verifying
 * that the frames were read.//from   w ww  .j  a v  a2  s.c om
 */
private ByteBuf createAndFeedFrames(int frameCount, TransportFrameDecoder decoder, ChannelHandlerContext ctx)
        throws Exception {
    ByteBuf data = Unpooled.buffer();
    for (int i = 0; i < frameCount; i++) {
        byte[] frame = new byte[1024 * (RND.nextInt(31) + 1)];
        data.writeLong(frame.length + 8);
        data.writeBytes(frame);
    }

    try {
        while (data.isReadable()) {
            int size = RND.nextInt(4 * 1024) + 256;
            decoder.channelRead(ctx, data.readSlice(Math.min(data.readableBytes(), size)).retain());
        }

        verify(ctx, times(frameCount)).fireChannelRead(any(ByteBuf.class));
    } catch (Exception e) {
        release(data);
        throw e;
    }
    return data;
}

From source file:org.bgp4j.netty.protocol.refresh.RouteRefreshPacketDecoder.java

License:Apache License

/**
 * decode the UPDATE network packet. The passed channel buffer MUST point to the first packet octet AFTER the type octet.
 * /*from w  w w. j  a  va2s . c om*/
 * @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 = buffer.readSlice(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:org.bgp4j.netty.protocol.update.UpdatePacketDecoder.java

License:Apache License

/**
 * decode the UPDATE network packet. The passed channel buffer MUST point to the first packet octet AFTER the type octet.
 * // w ww .j  a  v a 2  s .  co  m
 * @param buffer the buffer containing the data. 
 * @return
 */
public BGPv4Packet decodeUpdatePacket(ByteBuf buffer) {
    UpdatePacket packet = new UpdatePacket();

    ProtocolPacketUtils.verifyPacketSize(buffer, BGPv4Constants.BGP_PACKET_MIN_SIZE_UPDATE, -1);

    if (buffer.readableBytes() < 2)
        throw new MalformedAttributeListException();

    // handle withdrawn routes
    int withdrawnOctets = buffer.readUnsignedShort();

    // sanity checking
    if (withdrawnOctets > buffer.readableBytes())
        throw new MalformedAttributeListException();

    ByteBuf withdrawnBuffer = null;

    if (withdrawnOctets > 0) {
        withdrawnBuffer = buffer.readSlice(withdrawnOctets);
    }

    // sanity checking
    if (buffer.readableBytes() < 2)
        throw new MalformedAttributeListException();

    // handle path attributes
    int pathAttributeOctets = buffer.readUnsignedShort();

    // sanity checking
    if (pathAttributeOctets > buffer.readableBytes())
        throw new MalformedAttributeListException();

    ByteBuf pathAttributesBuffer = null;

    if (pathAttributeOctets > 0) {
        pathAttributesBuffer = buffer.readSlice(pathAttributeOctets);
    }

    if (withdrawnBuffer != null) {
        try {
            packet.getWithdrawnRoutes().addAll(decodeWithdrawnRoutes(withdrawnBuffer));
        } catch (IndexOutOfBoundsException e) {
            throw new MalformedAttributeListException();
        }
    }

    if (pathAttributesBuffer != null) {
        try {
            packet.getPathAttributes().addAll(decodePathAttributes(pathAttributesBuffer));
        } catch (IndexOutOfBoundsException ex) {
            throw new MalformedAttributeListException();
        }
    }

    // handle network layer reachability information
    if (buffer.readableBytes() > 0) {
        try {
            while (buffer.isReadable()) {
                packet.getNlris().add(NLRICodec.decodeNLRI(buffer));
            }
        } catch (IndexOutOfBoundsException e) {
            throw new InvalidNetworkFieldException();
        } catch (IllegalArgumentException e) {
            throw new InvalidNetworkFieldException();
        }
    }

    return packet;
}

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();// w  w w.  java  2  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.dcache.xrootd.core.XrootdDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
    int length = verifyMessageLength(in);

    if (length < 0) {
        ctx.channel().close();//from  w w w.java2 s.  c o m
        return;
    }

    if (length == 0) {
        return;
    }

    out.add(getRequest(in.readSlice(length)));
}