Example usage for io.netty.buffer CompositeByteBuf writerIndex

List of usage examples for io.netty.buffer CompositeByteBuf writerIndex

Introduction

In this page you can find the example usage for io.netty.buffer CompositeByteBuf writerIndex.

Prototype

@Override
    public CompositeByteBuf writerIndex(int writerIndex) 

Source Link

Usage

From source file:com.uber.tchannel.codecs.TFrameCodec.java

License:Open Source License

public static ByteBuf encode(ByteBufAllocator allocator, TFrame frame) {
    ByteBuf buffer = allocator.buffer(TFrame.FRAME_HEADER_LENGTH, TFrame.FRAME_HEADER_LENGTH);

    // size:2/*from w  w  w  .ja  va 2 s . co  m*/
    buffer.writeShort(frame.size + TFrame.FRAME_HEADER_LENGTH);

    // type:1
    buffer.writeByte(frame.type);

    // reserved:1
    buffer.writeZero(1);

    // id:4
    buffer.writeInt((int) frame.id);

    // reserved:8
    buffer.writeZero(8);

    // TODO: refactor
    if (frame.payload instanceof CompositeByteBuf) {
        CompositeByteBuf cbf = (CompositeByteBuf) frame.payload;
        cbf.addComponent(0, buffer);
        cbf.writerIndex(cbf.writerIndex() + TFrame.FRAME_HEADER_LENGTH);
        return cbf;
    }

    return Unpooled.wrappedBuffer(buffer, frame.payload);
}

From source file:com.whizzosoftware.wzwave.codec.ZWaveFrameDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (logger.isDebugEnabled()) {
        logger.debug("RCVD: {}", ByteUtil.createString(in));
    }/*from   w w  w  .  ja  v a 2 s  .  co  m*/

    ByteBuf data;

    // if there was data left from the last decode call, create a composite ByteBuf that contains both
    // previous and new data
    if (previousBuf != null) {
        CompositeByteBuf cbuf = Unpooled.compositeBuffer(2);
        cbuf.addComponent(previousBuf.copy());
        cbuf.addComponent(in);
        cbuf.writerIndex(previousBuf.readableBytes() + in.readableBytes());
        data = cbuf;
        // release the data from the previous decode call
        previousBuf.release();
        previousBuf = null;
    } else {
        data = in;
    }

    while (data.isReadable()) {
        // check for single ACK/NAK/CAN
        if (data.readableBytes() == 1 && isSingleByteFrame(data, data.readerIndex())) {
            out.add(createSingleByteFrame(data));
        } else {
            boolean foundFrame = false;
            // search for a valid frame in the data
            for (int searchStartIx = data.readerIndex(); searchStartIx < data.readerIndex()
                    + data.readableBytes(); searchStartIx++) {
                if (data.getByte(searchStartIx) == DataFrame.START_OF_FRAME) {
                    int frameEndIx = scanForFrame(data, searchStartIx);
                    if (frameEndIx > 0) {
                        if (searchStartIx > data.readerIndex() && isSingleByteFrame(data, searchStartIx - 1)) {
                            data.readerIndex(searchStartIx - 1);
                            out.add(createSingleByteFrame(data));
                        } else if (searchStartIx > data.readerIndex()) {
                            data.readerIndex(searchStartIx);
                        }
                        DataFrame df = createDataFrame(data);
                        if (df != null) {
                            out.add(df);
                            data.readByte(); // discard checksum
                            foundFrame = true;
                        } else {
                            logger.debug("Unable to determine frame type");
                        }
                    }
                }
            }
            if (!foundFrame) {
                previousBuf = data.copy();
                break;
            }
        }
    }

    // make sure we read from the input ByteBuf so Netty doesn't throw an exception
    in.readBytes(in.readableBytes());

    logger.trace("Done processing received data: {}", out);
}

From source file:divconq.http.multipart.AbstractMemoryHttpData.java

License:Apache License

@Override
public void addContent(ByteBuf buffer, boolean last) throws IOException {
    if (buffer != null) {
        long localsize = buffer.readableBytes();
        checkSize(size + localsize);//  w  ww. java 2s. c om
        if (definedSize > 0 && definedSize < size + localsize) {
            throw new IOException("Out of size: " + (size + localsize) + " > " + definedSize);
        }
        size += localsize;
        if (byteBuf == null) {
            byteBuf = buffer;
        } else if (byteBuf instanceof CompositeByteBuf) {
            CompositeByteBuf cbb = (CompositeByteBuf) byteBuf;
            cbb.addComponent(buffer);
            cbb.writerIndex(cbb.writerIndex() + buffer.readableBytes());
        } else {
            CompositeByteBuf cbb = compositeBuffer(Integer.MAX_VALUE);
            cbb.addComponents(byteBuf, buffer);
            cbb.writerIndex(byteBuf.readableBytes() + buffer.readableBytes());
            byteBuf = cbb;
        }
    }
    if (last) {
        setCompleted();
    } else {
        if (buffer == null) {
            throw new NullPointerException("buffer");
        }
    }
}

From source file:eu.stratosphere.runtime.io.network.netty.InboundEnvelopeDecoderTest.java

License:Apache License

private static ByteBuf encode(EmbeddedChannel ch, Envelope... envelopes) {
    for (Envelope env : envelopes) {
        ch.writeOutbound(env);/*from   w  ww .  j  a v  a2  s  . c o m*/

        if (env.getBuffer() != null) {
            verify(env.getBuffer(), times(1)).recycleBuffer();
        }
    }

    CompositeByteBuf encodedEnvelopes = new CompositeByteBuf(ByteBufAllocator.DEFAULT, false, envelopes.length);

    ByteBuf buf;
    while ((buf = (ByteBuf) ch.readOutbound()) != null) {
        encodedEnvelopes.addComponent(buf);
    }

    return encodedEnvelopes.writerIndex(encodedEnvelopes.capacity());
}

From source file:io.grpc.alts.internal.BufUnwrapperTest.java

License:Apache License

@Test
public void writableNioBuffers_worksWithComposite() {
    CompositeByteBuf buf = alloc.compositeBuffer();
    buf.addComponent(alloc.buffer(1));/*w ww . j a  va 2 s.c  o  m*/
    buf.capacity(1);
    try (BufUnwrapper unwrapper = new BufUnwrapper()) {
        ByteBuffer[] internalBufs = unwrapper.writableNioBuffers(buf);
        Truth.assertThat(internalBufs).hasLength(1);

        internalBufs[0].put((byte) 'a');

        buf.writerIndex(1);
        assertEquals('a', buf.readByte());
    } finally {
        buf.release();
    }
}

From source file:io.grpc.netty.NettyHandlerTestBase.java

License:Apache License

protected final ByteBuf captureWrite(ChannelHandlerContext ctx) {
    ArgumentCaptor<ByteBuf> captor = ArgumentCaptor.forClass(ByteBuf.class);
    verify(ctx, atLeastOnce()).write(captor.capture(), any(ChannelPromise.class));
    CompositeByteBuf composite = Unpooled.compositeBuffer();
    for (ByteBuf buf : captor.getAllValues()) {
        composite.addComponent(buf);/*  w  w  w.j  a  va2  s  .c  o m*/
        composite.writerIndex(composite.writerIndex() + buf.readableBytes());
    }
    return composite;
}

From source file:io.scalecube.socketio.serialization.PacketEncoder.java

License:Apache License

public static ByteBuf encodePacket(final Packet packet) throws IOException {
    ByteBuf dataBytes = packet.getData();
    boolean hasData = dataBytes != null;

    CompositeByteBuf compositeByteBuf = PooledByteBufAllocator.DEFAULT.compositeBuffer(hasData ? 1 : 2);

    byte[] typeBytes = packet.getType().getValueAsBytes();
    int headerCapacity = typeBytes.length + DELIMITER_LENGTH + DELIMITER_LENGTH
            + (hasData ? DELIMITER_LENGTH : 0);
    ByteBuf headerByteBuf = PooledByteBufAllocator.DEFAULT.buffer(headerCapacity, headerCapacity);
    headerByteBuf.writeBytes(typeBytes);
    headerByteBuf.writeBytes(DELIMITER_BYTES);
    headerByteBuf.writeBytes(DELIMITER_BYTES);
    if (hasData) {
        headerByteBuf.writeBytes(DELIMITER_BYTES);
    }//from   www  . ja v a 2s .  co m
    compositeByteBuf.addComponent(headerByteBuf);
    int compositeReadableBytes = headerByteBuf.readableBytes();

    if (hasData) {
        compositeByteBuf.addComponent(dataBytes);
        compositeReadableBytes += dataBytes.readableBytes();
    }

    compositeByteBuf.writerIndex(compositeReadableBytes);
    return compositeByteBuf;
}

From source file:io.scalecube.socketio.serialization.PacketFramer.java

License:Apache License

public static ByteBuf encodePacketsFrame(final PacketsFrame packetsFrame) throws IOException {
    List<Packet> packets = packetsFrame.getPackets();
    if (packets.size() == 1) {
        Packet packet = packets.get(0);//  w  w  w .  j av a2s.  c o m
        return PacketEncoder.encodePacket(packet);
    } else {
        CompositeByteBuf compositeByteBuf = PooledByteBufAllocator.DEFAULT.compositeBuffer(packets.size() * 2);
        int compositeReadableBytes = 0;

        for (Packet packet : packets) {
            // Decode packet
            ByteBuf packetByteBuf = PacketEncoder.encodePacket(packet);

            // Prepare length prepender
            int packetLength = getUtf8CharCountByByteCount(packetByteBuf, 0, packetByteBuf.readableBytes());
            byte[] packetLengthBytes = String.valueOf(packetLength).getBytes(CharsetUtil.UTF_8);
            int packetLengthPrependerCapacity = packetLengthBytes.length + DELIMITER_BYTES_SIZE
                    + DELIMITER_BYTES_SIZE;
            ByteBuf packetLengthPrependerByteBuf = PooledByteBufAllocator.DEFAULT
                    .buffer(packetLengthPrependerCapacity, packetLengthPrependerCapacity);
            packetLengthPrependerByteBuf.writeBytes(DELIMITER_BYTES);
            packetLengthPrependerByteBuf.writeBytes(packetLengthBytes);
            packetLengthPrependerByteBuf.writeBytes(DELIMITER_BYTES);

            // Update composite byte buffer
            compositeByteBuf.addComponent(packetLengthPrependerByteBuf);
            compositeByteBuf.addComponent(packetByteBuf);
            compositeReadableBytes += packetLengthPrependerByteBuf.readableBytes()
                    + packetByteBuf.readableBytes();
        }

        compositeByteBuf.writerIndex(compositeReadableBytes);
        return compositeByteBuf;
    }
}

From source file:openbns.commons.net.codec.sts.HttpObjectAggregator.java

License:Apache License

@Override
protected void decode(final ChannelHandlerContext ctx, StsObject msg, List<Object> out) throws Exception {
    FullStsMessage currentMessage = this.currentMessage;

    if (msg instanceof StsMessage) {
        tooLongFrameFound = false;// w w w.j ava2s  .  c o m
        assert currentMessage == null;

        StsMessage m = (StsMessage) msg;

        if (!m.getDecoderResult().isSuccess()) {
            this.currentMessage = null;
            out.add(ReferenceCountUtil.retain(m));
            return;
        }
        if (msg instanceof StsRequest) {
            StsRequest header = (StsRequest) msg;
            this.currentMessage = currentMessage = new DefaultFullStsRequest(header.getProtocolVersion(),
                    header.getMethod(), header.getUri(),
                    Unpooled.compositeBuffer(maxCumulationBufferComponents));
        } else if (msg instanceof StsResponse) {
            StsResponse header = (StsResponse) msg;
            this.currentMessage = currentMessage = new DefaultFullStsResponse(header.getStatus(),
                    Unpooled.compositeBuffer(maxCumulationBufferComponents));
        } else {
            throw new Error();
        }

        currentMessage.headers().set(m.headers());
    } else if (msg instanceof StsContent) {
        if (tooLongFrameFound) {
            if (msg instanceof LastStsContent) {
                this.currentMessage = null;
            }
            // already detect the too long frame so just discard the content
            return;
        }
        assert currentMessage != null;

        // Merge the received chunk into the content of the current message.
        StsContent chunk = (StsContent) msg;
        CompositeByteBuf content = (CompositeByteBuf) currentMessage.content();

        if (content.readableBytes() > maxContentLength - chunk.content().readableBytes()) {
            tooLongFrameFound = true;

            // release current message to prevent leaks
            currentMessage.release();
            this.currentMessage = null;

            throw new TooLongFrameException("HTTP content length exceeded " + maxContentLength + " bytes.");
        }

        // Append the content of the chunk
        if (chunk.content().isReadable()) {
            chunk.retain();
            content.addComponent(chunk.content());
            content.writerIndex(content.writerIndex() + chunk.content().readableBytes());
        }

        final boolean last;
        if (!chunk.getDecoderResult().isSuccess()) {
            currentMessage.setDecoderResult(DecoderResult.failure(chunk.getDecoderResult().cause()));
            last = true;
        } else {
            last = chunk instanceof LastStsContent;
        }

        if (last) {
            this.currentMessage = null;

            // Merge trailing headers into the message.
            if (chunk instanceof LastStsContent) {
                LastStsContent trailer = (LastStsContent) chunk;
                currentMessage.headers().add(trailer.trailingHeaders());
            }

            // Set the 'Content-Length' header.
            currentMessage.headers().set(StsHeaders.Names.CONTENT_LENGTH,
                    String.valueOf(content.readableBytes()));

            // All done
            out.add(currentMessage);
        }
    } else {
        throw new Error();
    }
}

From source file:org.apache.drill.exec.rpc.ChunkCreationHandler.java

License:Apache License

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

    if (RpcConstants.EXTRA_DEBUGGING) {
        logger.debug("ChunkCreationHandler called with msg {} of size {} with chunkSize {}", msg,
                msg.readableBytes(), chunkSize);
    }/* ww w.  java2 s .c  o  m*/

    if (!ctx.channel().isOpen()) {
        logger.debug("Channel closed, skipping encode inside {}.", RpcConstants.CHUNK_CREATION_HANDLER);
        msg.release();
        return;
    }

    // Calculate the number of chunks based on configured chunk size and input msg size
    int numChunks = (int) Math.ceil((double) msg.readableBytes() / chunkSize);

    // Initialize a composite buffer to hold numChunks chunk.
    final CompositeByteBuf cbb = ctx.alloc().compositeBuffer(numChunks);

    int cbbWriteIndex = 0;
    int currentChunkLen = min(msg.readableBytes(), chunkSize);

    // Create slices of chunkSize from input msg and add it to the composite buffer.
    while (numChunks > 0) {
        final ByteBuf chunkBuf = msg.slice(msg.readerIndex(), currentChunkLen);
        chunkBuf.retain();
        cbb.addComponent(chunkBuf);
        cbbWriteIndex += currentChunkLen;
        msg.skipBytes(currentChunkLen);
        --numChunks;
        currentChunkLen = min(msg.readableBytes(), chunkSize);
    }

    // Update the writerIndex of composite byte buffer. Netty doesn't do it automatically.
    cbb.writerIndex(cbbWriteIndex);

    // Add the final composite bytebuf into output buffer.
    out.add(cbb);
}