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(int index, int length);

Source Link

Document

Returns a slice of this buffer's sub-region.

Usage

From source file:org.opendaylight.protocol.pcep.pcecc.PceccObjectParserTest.java

License:Open Source License

@Test
public void testPceccFecIpv4ObjectParser() throws PCEPDeserializerException {
    final PceccFecIpv4ObjectParser parser = new PceccFecIpv4ObjectParser();

    final FecBuilder builder = new FecBuilder();
    builder.setProcessingRule(false);//from   w  w w.  j a va  2  s .  c  o m
    builder.setIgnore(false);

    builder.setFec(new Ipv4NodeIdCaseBuilder().setNodeId(new Ipv4Address("255.144.0.1")).build());
    final ByteBuf result = Unpooled.wrappedBuffer(PceccFecObjectBytes);
    assertEquals(builder.build(), parser.parseObject(new ObjectHeaderImpl(false, false),
            result.slice(4, result.readableBytes() - 4)));
    final ByteBuf buffer = Unpooled.buffer();
    parser.serializeObject(builder.build(), buffer);
    assertArrayEquals(PceccFecObjectBytes, ByteArray.getAllBytes(buffer));
}

From source file:org.opendaylight.protocol.pcep.pcecc.PceccObjectParserTest.java

License:Open Source License

@Test
public void testPceccFecObjectParserIpv4NodeId() throws PCEPDeserializerException {
    final PceccFecObjectParser parser = new PceccFecObjectParser();

    final FecBuilder builder = new FecBuilder();
    builder.setProcessingRule(false);/*from  w  w  w  .  j ava  2  s  . c om*/
    builder.setIgnore(false);
    builder.setFec(new Ipv4NodeIdCaseBuilder().setNodeId(new Ipv4Address("255.144.0.1")).build());
    /*only for parser coverage*/
    final ByteBuf result = Unpooled.wrappedBuffer(PceccFecObjectBytes);
    parser.parseObject(new ObjectHeaderImpl(false, false), result.slice(4, result.readableBytes() - 4));

    final ByteBuf buffer = Unpooled.buffer();
    parser.serializeObject(builder.build(), buffer);
    assertArrayEquals(PceccFecObjectBytes, ByteArray.getAllBytes(buffer));
}

From source file:org.opendaylight.protocol.pcep.pcecc.PceccObjectParserTest.java

License:Open Source License

@Test
public void testPceccFecIpv4AdjacencyObjectParser() throws PCEPDeserializerException {
    final PceccFecIpv4AdjacencyObjectParser parser = new PceccFecIpv4AdjacencyObjectParser();

    final FecBuilder builder = new FecBuilder();
    builder.setProcessingRule(false);/*from  w  ww.j a v  a 2 s .  c  o m*/
    builder.setIgnore(false);
    builder.setFec(new Ipv4AdjacencyCaseBuilder().setLocalIpAddress(new Ipv4Address("254.144.0.0"))
            .setRemoteIpAddress(new Ipv4Address("254.144.0.0")).build()).build();

    final ByteBuf result = Unpooled.wrappedBuffer(PceccFecAdjacencyObjectBytes);
    assertEquals(builder.build(), parser.parseObject(new ObjectHeaderImpl(false, false),
            result.slice(4, result.readableBytes() - 4)));
    final ByteBuf buffer = Unpooled.buffer();
    parser.serializeObject(builder.build(), buffer);
    assertArrayEquals(PceccFecAdjacencyObjectBytes, ByteArray.getAllBytes(buffer));
}

From source file:org.opendaylight.protocol.pcep.pcecc.PceccObjectParserTest.java

License:Open Source License

@Test
public void testPceccLabelObjectParserWithAddressLabelTLV() throws PCEPDeserializerException {
    final PceccLabelObjectParser parser = new PceccLabelObjectParser(this.tlvRegistry, this.viTlvRegistry);

    final LabelBuilder builder = new LabelBuilder();
    builder.setProcessingRule(false);/*from   w w w .j  a  v a 2s  . c o  m*/
    builder.setIgnore(false);
    builder.setLabelNum(new LabelNumber(5001L));
    builder.setOutLabel(false);

    org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.pcecc.rev160225.label.object.label.TlvsBuilder tlvBuilder = new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.pcecc.rev160225.label.object.label.TlvsBuilder();

    AddressBuilder addressBuilder = new AddressBuilder();
    Ipv4Builder ipv4 = new Ipv4Builder();
    ipv4.setIpv4Address(new Ipv4Address("1.1.1.1")).build();
    addressBuilder.setAddressFamily(new Ipv4CaseBuilder().setIpv4(ipv4.build()).build());

    builder.setTlvs(tlvBuilder.setAddress(addressBuilder.build()).build());

    final ByteBuf result = Unpooled.wrappedBuffer(PceccLabelObjectwithAddressTlvBytes);
    assertEquals(builder.build(), parser.parseObject(new ObjectHeaderImpl(false, false),
            result.slice(4, result.readableBytes() - 4)));
    final ByteBuf buffer = Unpooled.buffer();
    parser.serializeObject(builder.build(), buffer);
    assertArrayEquals(PceccLabelObjectwithAddressTlvBytes, ByteArray.getAllBytes(buffer));
}

From source file:org.opendaylight.protocol.pcep.segment.routing.SrObjectParserTest.java

License:Open Source License

@Test
public void testOpenObjectWithSpcTlv() throws PCEPDeserializerException {
    final PcepOpenObjectWithSpcTlvParser parser = new PcepOpenObjectWithSpcTlvParser(this.tlvRegistry,
            this.viTlvRegistry);

    final OpenBuilder builder = new OpenBuilder();
    builder.setProcessingRule(false);// www  .  ja  v  a 2 s.  c  o  m
    builder.setIgnore(false);
    builder.setVersion(new ProtocolVersion((short) 1));
    builder.setKeepalive((short) 30);
    builder.setDeadTimer((short) 120);
    builder.setSessionId((short) 1);

    final Tlvs1 tlv = new Tlvs1Builder()
            .setSrPceCapability(new SrPceCapabilityBuilder().setMsd((short) 1).build()).build();
    builder.setTlvs(new TlvsBuilder().addAugmentation(
            org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.Tlvs1.class,
            new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.Tlvs1Builder()
                    .build())
            .addAugmentation(Tlvs1.class, tlv).addAugmentation(Tlvs3.class, new Tlvs3Builder().build())
            .build());

    final ByteBuf result = Unpooled.wrappedBuffer(openObjectBytes);
    assertEquals(builder.build(), parser.parseObject(new ObjectHeaderImpl(false, false),
            result.slice(4, result.readableBytes() - 4)));
    final ByteBuf buffer = Unpooled.buffer();
    parser.serializeObject(builder.build(), buffer);
    parser.serializeTlvs(null, Unpooled.EMPTY_BUFFER);
    parser.serializeTlvs(new TlvsBuilder().build(), Unpooled.EMPTY_BUFFER);
    assertArrayEquals(openObjectBytes, ByteArray.getAllBytes(buffer));
}

From source file:org.opendaylight.protocol.pcep.segment.routing.SrObjectParserTest.java

License:Open Source License

@Test
public void testSrEroObjectWithSubobjects() throws PCEPDeserializerException {
    final PCEPExplicitRouteObjectParser parser = new PCEPExplicitRouteObjectParser(
            this.ctx.getEROSubobjectHandlerRegistry());

    final EroBuilder builder = new EroBuilder();
    builder.setProcessingRule(false);/*from   w w  w. j  a  va  2s . co m*/
    builder.setIgnore(false);
    final List<Subobject> subobjects = Lists.newArrayList();

    final SrEroTypeBuilder srEroSubBuilder = new SrEroTypeBuilder();
    srEroSubBuilder.setCFlag(false);
    srEroSubBuilder.setMFlag(false);
    srEroSubBuilder.setSidType(SidType.Ipv4NodeId);
    srEroSubBuilder.setSid(123456L);
    srEroSubBuilder
            .setNai(new IpNodeIdBuilder().setIpAddress(new IpAddress(new Ipv4Address("74.125.43.99"))).build());
    final SubobjectBuilder subobjBuilder = new SubobjectBuilder().setSubobjectType(srEroSubBuilder.build())
            .setLoose(false);
    subobjects.add(subobjBuilder.build());

    builder.setSubobject(subobjects);

    final ByteBuf result = Unpooled.wrappedBuffer(srEroObjectBytes);
    assertEquals(builder.build(), parser.parseObject(new ObjectHeaderImpl(false, false),
            result.slice(4, result.readableBytes() - 4)));
    final ByteBuf buffer = Unpooled.buffer();
    parser.serializeObject(builder.build(), buffer);
    assertArrayEquals(srEroObjectBytes, ByteArray.getAllBytes(buffer));
}

From source file:org.opendaylight.usc.plugin.UscFrameDecoderTcp.java

License:Open Source License

@Override
protected ByteBuf extractFrame(ChannelHandlerContext ctx, ByteBuf buffer, int index, int length) {
    // we avoid making a copy here since UscFrameDecoder already makes a
    // copy of the data
    return buffer.slice(index, length);
}

From source file:org.rzo.netty.mcast.MulticastEndpoint.java

License:Apache License

public ByteBuf getMessage(ByteBuf e) {
    if (checkMessage(e)) {
        return e.slice(id.length, e.readableBytes() - id.length);
    }/*from w ww . j  a v  a  2  s  . c  o m*/
    return null;
}

From source file:org.springframework.core.codec.support.JsonObjectDecoder.java

License:Apache License

@Override
public Flux<DataBuffer> decode(Publisher<DataBuffer> inputStream, ResolvableType type, MimeType mimeType,
        Object... hints) {/* w  w  w .  j a  va  2s  .c o  m*/

    return Flux.from(inputStream).flatMap(new Function<DataBuffer, Publisher<? extends DataBuffer>>() {

        int openBraces;
        int index;
        int state;
        boolean insideString;
        ByteBuf input;
        Integer writerIndex;

        @Override
        public Publisher<? extends DataBuffer> apply(DataBuffer b) {
            List<DataBuffer> chunks = new ArrayList<>();
            if (this.input == null) {
                this.input = Unpooled.copiedBuffer(b.asByteBuffer());
                this.writerIndex = this.input.writerIndex();
            } else {
                this.input = Unpooled.copiedBuffer(this.input, Unpooled.copiedBuffer(b.asByteBuffer()));
                this.writerIndex = this.input.writerIndex();
            }
            if (this.state == ST_CORRUPTED) {
                this.input.skipBytes(this.input.readableBytes());
                return Flux.error(new IllegalStateException("Corrupted stream"));
            }
            if (this.writerIndex > maxObjectLength) {
                // buffer size exceeded maxObjectLength; discarding the complete buffer.
                this.input.skipBytes(this.input.readableBytes());
                reset();
                return Flux.error(new IllegalStateException("object length exceeds " + maxObjectLength + ": "
                        + this.writerIndex + " bytes discarded"));
            }
            for (/* use current index */; this.index < this.writerIndex; this.index++) {
                byte c = this.input.getByte(this.index);
                if (this.state == ST_DECODING_NORMAL) {
                    decodeByte(c, this.input, this.index);

                    // All opening braces/brackets have been closed. That's enough to conclude
                    // that the JSON object/array is complete.
                    if (this.openBraces == 0) {
                        ByteBuf json = extractObject(this.input, this.input.readerIndex(),
                                this.index + 1 - this.input.readerIndex());
                        if (json != null) {
                            chunks.add(allocator.wrap(json.nioBuffer()));
                        }

                        // The JSON object/array was extracted => discard the bytes from
                        // the input buffer.
                        this.input.readerIndex(this.index + 1);
                        // Reset the object state to get ready for the next JSON object/text
                        // coming along the byte stream.
                        reset();
                    }
                } else if (this.state == ST_DECODING_ARRAY_STREAM) {
                    decodeByte(c, this.input, this.index);

                    if (!this.insideString
                            && (this.openBraces == 1 && c == ',' || this.openBraces == 0 && c == ']')) {
                        // skip leading spaces. No range check is needed and the loop will terminate
                        // because the byte at position index is not a whitespace.
                        for (int i = this.input.readerIndex(); Character
                                .isWhitespace(this.input.getByte(i)); i++) {
                            this.input.skipBytes(1);
                        }

                        // skip trailing spaces.
                        int idxNoSpaces = this.index - 1;
                        while (idxNoSpaces >= this.input.readerIndex()
                                && Character.isWhitespace(this.input.getByte(idxNoSpaces))) {

                            idxNoSpaces--;
                        }

                        ByteBuf json = extractObject(this.input, this.input.readerIndex(),
                                idxNoSpaces + 1 - this.input.readerIndex());

                        if (json != null) {
                            chunks.add(allocator.wrap(json.nioBuffer()));
                        }

                        this.input.readerIndex(this.index + 1);

                        if (c == ']') {
                            reset();
                        }
                    }
                    // JSON object/array detected. Accumulate bytes until all braces/brackets are closed.
                } else if (c == '{' || c == '[') {
                    initDecoding(c, streamArrayElements);

                    if (this.state == ST_DECODING_ARRAY_STREAM) {
                        // Discard the array bracket
                        this.input.skipBytes(1);
                    }
                    // Discard leading spaces in front of a JSON object/array.
                } else if (Character.isWhitespace(c)) {
                    this.input.skipBytes(1);
                } else {
                    this.state = ST_CORRUPTED;
                    return Flux.error(new IllegalStateException("invalid JSON received at byte position "
                            + this.index + ": " + ByteBufUtil.hexDump(this.input)));
                }
            }

            if (this.input.readableBytes() == 0) {
                this.index = 0;
            }
            return Flux.fromIterable(chunks);
        }

        /**
         * Override this method if you want to filter the json objects/arrays that
         * get passed through the pipeline.
         */
        @SuppressWarnings("UnusedParameters")
        protected ByteBuf extractObject(ByteBuf buffer, int index, int length) {
            return buffer.slice(index, length).retain();
        }

        private void decodeByte(byte c, ByteBuf input, int index) {
            if ((c == '{' || c == '[') && !this.insideString) {
                this.openBraces++;
            } else if ((c == '}' || c == ']') && !this.insideString) {
                this.openBraces--;
            } else if (c == '"') {
                // start of a new JSON string. It's necessary to detect strings as they may
                // also contain braces/brackets and that could lead to incorrect results.
                if (!this.insideString) {
                    this.insideString = true;
                    // If the double quote wasn't escaped then this is the end of a string.
                } else if (input.getByte(index - 1) != '\\') {
                    this.insideString = false;
                }
            }
        }

        private void initDecoding(byte openingBrace, boolean streamArrayElements) {
            this.openBraces = 1;
            if (openingBrace == '[' && streamArrayElements) {
                this.state = ST_DECODING_ARRAY_STREAM;
            } else {
                this.state = ST_DECODING_NORMAL;
            }
        }

        private void reset() {
            this.insideString = false;
            this.state = ST_INIT;
            this.openBraces = 0;
        }
    });
}

From source file:org.springframework.reactive.codec.decoder.JsonObjectDecoder.java

License:Apache License

@Override
public Publisher<ByteBuffer> decode(Publisher<ByteBuffer> inputStream, ResolvableType type, MediaType mediaType,
        Object... hints) {/*  w w w.  j  a  v a 2 s .co m*/

    return Streams.wrap(inputStream).flatMap(new Function<ByteBuffer, Publisher<? extends ByteBuffer>>() {

        int openBraces;
        int idx;
        int state;
        boolean insideString;
        ByteBuf in;
        Integer wrtIdx;

        @Override
        public Publisher<? extends ByteBuffer> apply(ByteBuffer b) {
            List<ByteBuffer> chunks = new ArrayList<>();

            if (in == null) {
                in = Unpooled.copiedBuffer(b);
                wrtIdx = in.writerIndex();
            } else {
                in = Unpooled.copiedBuffer(in, Unpooled.copiedBuffer(b));
                wrtIdx = in.writerIndex();
            }
            if (state == ST_CORRUPTED) {
                in.skipBytes(in.readableBytes());
                return Streams.fail(new IllegalStateException("Corrupted stream"));
            }

            if (wrtIdx > maxObjectLength) {
                // buffer size exceeded maxObjectLength; discarding the complete buffer.
                in.skipBytes(in.readableBytes());
                reset();
                return Streams.fail(new IllegalStateException(
                        "object length exceeds " + maxObjectLength + ": " + wrtIdx + " bytes discarded"));
            }

            for (/* use current idx */; idx < wrtIdx; idx++) {
                byte c = in.getByte(idx);
                if (state == ST_DECODING_NORMAL) {
                    decodeByte(c, in, idx);

                    // All opening braces/brackets have been closed. That's enough to conclude
                    // that the JSON object/array is complete.
                    if (openBraces == 0) {
                        ByteBuf json = extractObject(in, in.readerIndex(), idx + 1 - in.readerIndex());
                        if (json != null) {
                            chunks.add(json.nioBuffer());
                        }

                        // The JSON object/array was extracted => discard the bytes from
                        // the input buffer.
                        in.readerIndex(idx + 1);
                        // Reset the object state to get ready for the next JSON object/text
                        // coming along the byte stream.
                        reset();
                    }
                } else if (state == ST_DECODING_ARRAY_STREAM) {
                    decodeByte(c, in, idx);

                    if (!insideString && (openBraces == 1 && c == ',' || openBraces == 0 && c == ']')) {
                        // skip leading spaces. No range check is needed and the loop will terminate
                        // because the byte at position idx is not a whitespace.
                        for (int i = in.readerIndex(); Character.isWhitespace(in.getByte(i)); i++) {
                            in.skipBytes(1);
                        }

                        // skip trailing spaces.
                        int idxNoSpaces = idx - 1;
                        while (idxNoSpaces >= in.readerIndex()
                                && Character.isWhitespace(in.getByte(idxNoSpaces))) {
                            idxNoSpaces--;
                        }

                        ByteBuf json = extractObject(in, in.readerIndex(), idxNoSpaces + 1 - in.readerIndex());
                        if (json != null) {
                            chunks.add(json.nioBuffer());
                        }

                        in.readerIndex(idx + 1);

                        if (c == ']') {
                            reset();
                        }
                    }
                    // JSON object/array detected. Accumulate bytes until all braces/brackets are closed.
                } else if (c == '{' || c == '[') {
                    initDecoding(c, streamArrayElements);

                    if (state == ST_DECODING_ARRAY_STREAM) {
                        // Discard the array bracket
                        in.skipBytes(1);
                    }
                    // Discard leading spaces in front of a JSON object/array.
                } else if (Character.isWhitespace(c)) {
                    in.skipBytes(1);
                } else {
                    state = ST_CORRUPTED;
                    return Streams.fail(new IllegalStateException(
                            "invalid JSON received at byte position " + idx + ": " + ByteBufUtil.hexDump(in)));
                }
            }

            if (in.readableBytes() == 0) {
                idx = 0;
            }
            return Streams.from(chunks);
        }

        /**
         * Override this method if you want to filter the json objects/arrays that get passed through the pipeline.
         */
        @SuppressWarnings("UnusedParameters")
        protected ByteBuf extractObject(ByteBuf buffer, int index, int length) {
            return buffer.slice(index, length).retain();
        }

        private void decodeByte(byte c, ByteBuf in, int idx) {
            if ((c == '{' || c == '[') && !insideString) {
                openBraces++;
            } else if ((c == '}' || c == ']') && !insideString) {
                openBraces--;
            } else if (c == '"') {
                // start of a new JSON string. It's necessary to detect strings as they may
                // also contain braces/brackets and that could lead to incorrect results.
                if (!insideString) {
                    insideString = true;
                    // If the double quote wasn't escaped then this is the end of a string.
                } else if (in.getByte(idx - 1) != '\\') {
                    insideString = false;
                }
            }
        }

        private void initDecoding(byte openingBrace, boolean streamArrayElements) {
            openBraces = 1;
            if (openingBrace == '[' && streamArrayElements) {
                state = ST_DECODING_ARRAY_STREAM;
            } else {
                state = ST_DECODING_NORMAL;
            }
        }

        private void reset() {
            insideString = false;
            state = ST_INIT;
            openBraces = 0;
        }

    });
}