Example usage for io.netty.buffer CompositeByteBuf addComponent

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

Introduction

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

Prototype

public CompositeByteBuf addComponent(ByteBuf buffer) 

Source Link

Document

Add the given ByteBuf .

Usage

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));
    }/*w  w  w.j  a  v  a 2 s .  c o 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 w w .  j av  a 2 s.  c o m
        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);// www .ja va  2 s  .  co  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.advantageous.conekt.http.impl.HttpClientRequestImpl.java

License:Open Source License

private void write(ByteBuf buff, boolean end) {
    int readableBytes = buff.readableBytes();
    if (readableBytes == 0 && !end) {
        // nothing to write to the connection just return
        return;/* w w w . j a  v  a2s.  c om*/
    }

    if (end) {
        completed = true;
    }
    if (!end && !chunked && !contentLengthSet()) {
        throw new IllegalStateException(
                "You must set the Content-Length header to be the total size of the message "
                        + "body BEFORE sending any data if you are not using HTTP chunked encoding.");
    }

    written += buff.readableBytes();
    if (conn == null) {
        if (pendingChunks == null) {
            pendingChunks = buff;
        } else {
            CompositeByteBuf pending;
            if (pendingChunks instanceof CompositeByteBuf) {
                pending = (CompositeByteBuf) pendingChunks;
            } else {
                pending = Unpooled.compositeBuffer();
                pending.addComponent(pendingChunks).writerIndex(pendingChunks.writerIndex());
                pendingChunks = pending;
            }
            pending.addComponent(buff).writerIndex(pending.writerIndex() + buff.writerIndex());
        }
        connect();
    } else {
        if (!headWritten) {
            writeHeadWithContent(buff, end);
        } else {
            if (end) {
                if (buff.isReadable()) {
                    conn.writeToChannel(new DefaultLastHttpContent(buff, false));
                } else {
                    conn.writeToChannel(LastHttpContent.EMPTY_LAST_CONTENT);
                }
            } else {
                conn.writeToChannel(new DefaultHttpContent(buff));
            }
        }
        if (end) {
            conn.reportBytesWritten(written);

            if (respHandler != null) {
                conn.endRequest();
            }
        }
    }
}

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));
    buf.capacity(1);/*from   w  ww .  ja v  a  2s  .c om*/
    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);
        composite.writerIndex(composite.writerIndex() + buf.readableBytes());
    }/*from   w  w w.  j  a  v  a 2  s.  c o  m*/
    return composite;
}

From source file:io.jsync.http.impl.DefaultHttpClientRequest.java

License:Open Source License

private synchronized DefaultHttpClientRequest write(ByteBuf buff, boolean end) {
    int readableBytes = buff.readableBytes();
    if (readableBytes == 0 && !end) {
        // nothing to write to the connection just return
        return this;
    }/*from w w w.  ja  v  a 2s  .c  o  m*/

    if (end) {
        completed = true;
    }

    written += buff.readableBytes();

    if (!end && !raw && !chunked && !contentLengthSet()) {
        throw new IllegalStateException(
                "You must set the Content-Length header to be the total size of the message "
                        + "body BEFORE sending any data if you are not using HTTP chunked encoding.");
    }

    if (conn == null) {
        if (pendingChunks == null) {
            pendingChunks = buff;
        } else {
            CompositeByteBuf pending;
            if (pendingChunks instanceof CompositeByteBuf) {
                pending = (CompositeByteBuf) pendingChunks;
            } else {
                pending = Unpooled.compositeBuffer();
                pending.addComponent(pendingChunks).writerIndex(pendingChunks.writerIndex());
                pendingChunks = pending;
            }
            pending.addComponent(buff).writerIndex(pending.writerIndex() + buff.writerIndex());
        }
        connect();
    } else {
        if (!headWritten) {
            writeHeadWithContent(buff, end);
        } else {
            if (end) {
                writeEndChunk(buff);
            } else {
                sendChunk(buff);
            }
        }
        if (end) {
            conn.endRequest();
        }
    }
    return this;
}

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 ww w .ja  v a 2  s  .  c o 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  . ja v  a  2 s  .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:io.vertx.core.http.impl.HttpClientRequestImpl.java

License:Open Source License

private void write(ByteBuf buff, boolean end) {
    if (buff == null && !end) {
        // nothing to write to the connection just return
        return;//from   w ww  . j  ava  2  s. co  m
    }

    if (end) {
        if (buff != null && !chunked && !contentLengthSet()) {
            headers().set(CONTENT_LENGTH, String.valueOf(buff.writerIndex()));
        }
    } else {
        if (!chunked && !contentLengthSet()) {
            throw new IllegalStateException(
                    "You must set the Content-Length header to be the total size of the message "
                            + "body BEFORE sending any data if you are not using HTTP chunked encoding.");
        }
    }

    if (buff != null) {
        written += buff.readableBytes();
        if (followRedirects > 0) {
            if (cachedChunks == null) {
                cachedChunks = Unpooled.compositeBuffer();
            }
            cachedChunks.addComponent(buff).writerIndex(cachedChunks.writerIndex() + buff.writerIndex());
        }
    }

    if (stream == null) {
        if (buff != null) {
            if (pendingChunks == null) {
                pendingChunks = buff;
            } else {
                CompositeByteBuf pending;
                if (pendingChunks instanceof CompositeByteBuf) {
                    pending = (CompositeByteBuf) pendingChunks;
                } else {
                    pending = Unpooled.compositeBuffer();
                    pending.addComponent(pendingChunks).writerIndex(pendingChunks.writerIndex());
                    pendingChunks = pending;
                }
                pending.addComponent(buff).writerIndex(pending.writerIndex() + buff.writerIndex());
            }
        }
        connect(null);
    } else {
        if (!headWritten) {
            writeHeadWithContent(buff, end);
        } else {
            stream.writeBuffer(buff, end);
        }
        if (end) {
            stream.connection().reportBytesWritten(written);
            if (respHandler != null) {
                stream.endRequest();
            }
        }
    }

    if (end) {
        completed = true;
        if (completionHandler != null) {
            completionHandler.handle(null);
        }
    }
}