io.netty.buffer.CompositeByteBuf Java Examples

The following examples show how to use io.netty.buffer.CompositeByteBuf. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PacketEncoder.java    From socketio with Apache License 2.0 6 votes vote down vote up
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);
  }
  compositeByteBuf.addComponent(headerByteBuf);
  int compositeReadableBytes = headerByteBuf.readableBytes();

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

  compositeByteBuf.writerIndex(compositeReadableBytes);
  return compositeByteBuf;
}
 
Example #2
Source File: FileOperationEncoder.java    From azeroth with Apache License 2.0 6 votes vote down vote up
@Override
public List<Object> encode(ByteBufAllocator alloc) {
    ByteBuf meta = metadata(alloc);

    ByteBuf head = alloc.buffer(FDFS_HEAD_LEN);
    head.writeLong(meta.readableBytes() + size);
    head.writeByte(cmd());
    head.writeByte(ERRNO_OK);

    CompositeByteBuf cbb = alloc.compositeBuffer();
    cbb.addComponents(head, meta);
    cbb.writerIndex(head.readableBytes() + meta.readableBytes());

    List<Object> requests = new LinkedList<>();
    requests.add(cbb);
    requests.add(content);
    return requests;
}
 
Example #3
Source File: BufUnwrapperTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void writableNioBuffers_worksWithComposite() {
  CompositeByteBuf buf = alloc.compositeBuffer();
  buf.addComponent(alloc.buffer(1));
  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();
  }
}
 
Example #4
Source File: CompositeMetadataCodec.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
/**
 * Encode a new sub-metadata information into a composite metadata {@link CompositeByteBuf
 * buffer}, first verifying if the passed {@link String} matches a {@link WellKnownMimeType} (in
 * which case it will be encoded in a compressed fashion using the mime id of that type).
 *
 * <p>Prefer using {@link #encodeAndAddMetadata(CompositeByteBuf, ByteBufAllocator, String,
 * ByteBuf)} if you already know that the mime type is not a {@link WellKnownMimeType}.
 *
 * @param compositeMetaData the buffer that will hold all composite metadata information.
 * @param allocator the {@link ByteBufAllocator} to use to create intermediate buffers as needed.
 * @param mimeType the mime type to encode, as a {@link String}. well known mime types are
 *     compressed.
 * @param metadata the metadata value to encode.
 * @see #encodeAndAddMetadata(CompositeByteBuf, ByteBufAllocator, WellKnownMimeType, ByteBuf)
 */
// see #encodeMetadataHeader(ByteBufAllocator, String, int)
public static void encodeAndAddMetadataWithCompression(
    CompositeByteBuf compositeMetaData,
    ByteBufAllocator allocator,
    String mimeType,
    ByteBuf metadata) {
  WellKnownMimeType wkn = WellKnownMimeType.fromString(mimeType);
  if (wkn == WellKnownMimeType.UNPARSEABLE_MIME_TYPE) {
    compositeMetaData.addComponents(
        true, encodeMetadataHeader(allocator, mimeType, metadata.readableBytes()), metadata);
  } else {
    compositeMetaData.addComponents(
        true,
        encodeMetadataHeader(allocator, wkn.getIdentifier(), metadata.readableBytes()),
        metadata);
  }
}
 
Example #5
Source File: FrameReassembler.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
void cancelAssemble(int streamId) {
  ByteBuf header = removeHeader(streamId);
  CompositeByteBuf metadata = removeMetadata(streamId);
  CompositeByteBuf data = removeData(streamId);

  if (header != null) {
    ReferenceCountUtil.safeRelease(header);
  }

  if (metadata != null) {
    ReferenceCountUtil.safeRelease(metadata);
  }

  if (data != null) {
    ReferenceCountUtil.safeRelease(data);
  }
}
 
Example #6
Source File: InboundEnvelopeDecoderTest.java    From stratosphere with Apache License 2.0 6 votes vote down vote up
private static ByteBuf encode(EmbeddedChannel ch, Envelope... envelopes) {
	for (Envelope env : envelopes) {
		ch.writeOutbound(env);

		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());
}
 
Example #7
Source File: ByteBufDeserializerTest.java    From log4j2-elasticsearch with Apache License 2.0 6 votes vote down vote up
@Test
public void writesBytesIntoPooledBuffer() throws IOException {

    // given
    ByteBufDeserializer deserializer = spy(new ByteBufDeserializer());
    ByteBufAllocator allocator = mock(ByteBufAllocator.class);
    when(deserializer.allocator()).thenReturn(allocator);

    CompositeByteBuf byteBuf = mock(CompositeByteBuf.class);
    when(allocator.compositeBuffer(eq(2))).thenReturn(byteBuf);

    JsonParser jsonParser = mock(JsonParser.class);
    byte[] bytes = UUID.randomUUID().toString().getBytes();
    when(jsonParser.getBinaryValue()).thenReturn(bytes);

    // when
    deserializer.deserialize(jsonParser, null);

    // then
    verify(byteBuf).writeBytes(eq(bytes));

}
 
Example #8
Source File: FailedItemMarshallerTest.java    From log4j2-elasticsearch with Apache License 2.0 6 votes vote down vote up
@Test
public void jacksonInjectedReleaseCallbackDoesNotThrow() throws IOException {

    // given
    FailedItemMarshaller failedItemMarshaller = new FailedItemMarshaller();

    CompositeByteBuf byteBuf = new CompositeByteBuf(PooledByteBufAllocator.DEFAULT, false, 2).capacity(1024);
    ByteBufItemSource itemSource = new ByteBufItemSource(byteBuf, source -> {});
    FailedItemSource<ByteBuf> failedItemSource =
            new FailedItemSource<>(itemSource, new FailedItemInfo(UUID.randomUUID().toString()));

    ReusableByteBufOutputStream outputStream =
            new ReusableByteBufOutputStream(byteBuf);
    failedItemMarshaller.objectMapper().writeValue((OutputStream) outputStream, failedItemSource);

    Bytes<Object> in = mock(Bytes.class);
    ByteArrayInputStream inputStream = new ByteArrayInputStream(byteBuf.array());
    when(in.inputStream()).thenReturn(inputStream);

    FailedItemSource deserialized = (FailedItemSource) failedItemMarshaller.read(in, null);

    // when
    deserialized.release();

}
 
Example #9
Source File: SimpleTest.java    From x-pipe with Apache License 2.0 6 votes vote down vote up
@Test
public void testNetty(){

	CompositeByteBuf byteBuf = ByteBufAllocator.DEFAULT.compositeBuffer();
	byteBuf.addComponent(Unpooled.wrappedBuffer("12345".getBytes()));
	byteBuf.addComponent(Unpooled.wrappedBuffer("abcde".getBytes()));

	System.out.println(ByteBufUtils.readToString(byteBuf));

	ByteBuf buf = Unpooled.wrappedBuffer(Unpooled.wrappedBuffer("134".getBytes()), Unpooled.wrappedBuffer("abc".getBytes()));
	System.out.println(buf.readableBytes());
	byte []result = new byte[buf.readableBytes()];
	buf.readBytes(result);
	System.out.println(new String(result));

}
 
Example #10
Source File: SubMultiMutationRequest.java    From couchbase-jvm-core with Apache License 2.0 5 votes vote down vote up
private static ByteBuf encode(List<MutationCommand> commands) {
    //FIXME a way of using the pooled allocator?
    CompositeByteBuf compositeBuf = Unpooled.compositeBuffer(commands.size());
    for (MutationCommand command : commands) {
        byte[] pathBytes = command.path().getBytes(CharsetUtil.UTF_8);
        short pathLength = (short) pathBytes.length;

        ByteBuf commandBuf = Unpooled.buffer(4 + pathLength + command.fragment().readableBytes());
        commandBuf.writeByte(command.opCode());
        byte subdocFlags = 0;
        if (command.createIntermediaryPath()) {
            subdocFlags |= KeyValueHandler.SUBDOC_BITMASK_MKDIR_P;
        }
        if (command.xattr()) {
            subdocFlags |= KeyValueHandler.SUBDOC_FLAG_XATTR_PATH;
        }
        if (command.expandMacros()) {
            subdocFlags |= KeyValueHandler.SUBDOC_FLAG_EXPAND_MACROS;
        }
        commandBuf.writeByte(subdocFlags);
        commandBuf.writeShort(pathLength);
        commandBuf.writeInt(command.fragment().readableBytes());
        commandBuf.writeBytes(pathBytes);

        //copy the fragment but don't move indexes (in case it is retained and reused)
        commandBuf.writeBytes(command.fragment(), command.fragment().readerIndex(), command.fragment().readableBytes());
        //eagerly release the fragment once it's been copied
        command.fragment().release();

        //add the command to the composite buffer
        compositeBuf.addComponent(commandBuf);
        compositeBuf.writerIndex(compositeBuf.writerIndex() + commandBuf.readableBytes());
    }
    return compositeBuf;
}
 
Example #11
Source File: Http2FrameRoundtripTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private ByteBuf captureWrites() {
    ArgumentCaptor<ByteBuf> captor = ArgumentCaptor.forClass(ByteBuf.class);
    verify(ctx, atLeastOnce()).write(captor.capture(), isA(ChannelPromise.class));
    CompositeByteBuf composite = releaseLater(Unpooled.compositeBuffer());
    for (ByteBuf buf : captor.getAllValues()) {
        buf = releaseLater(buf.retain());
        composite.addComponent(true, buf);
    }
    return composite;
}
 
Example #12
Source File: DatagramUnicastTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
public void testSimpleSendCompositeHeapByteBuf(Bootstrap sb, Bootstrap cb) throws Throwable {
    CompositeByteBuf buf = Unpooled.compositeBuffer();
    buf.addComponent(true, Unpooled.buffer().writeBytes(BYTES, 0, 2));
    buf.addComponent(true, Unpooled.buffer().writeBytes(BYTES, 2, 2));
    testSimpleSend(sb, cb, buf, true, BYTES, 1);

    CompositeByteBuf buf2 = Unpooled.compositeBuffer();
    buf2.addComponent(true, Unpooled.buffer().writeBytes(BYTES, 0, 2));
    buf2.addComponent(true, Unpooled.buffer().writeBytes(BYTES, 2, 2));
    testSimpleSend(sb, cb, buf2, true, BYTES, 4);
}
 
Example #13
Source File: ArmeriaMessageFramer.java    From armeria with Apache License 2.0 5 votes vote down vote up
private ByteBuf write(ByteBuf message, boolean compressed) {
    final int messageLength = message.readableBytes();
    if (maxOutboundMessageSize >= 0 && messageLength > maxOutboundMessageSize) {
        message.release();
        throw new ArmeriaStatusException(
                StatusCodes.RESOURCE_EXHAUSTED,
                String.format("message too large %d > %d", messageLength,
                              maxOutboundMessageSize));
    }

    // Here comes some heuristics.
    // TODO(trustin): Consider making this configurable.
    if (messageLength <= 128) {
        // Frame is so small that the cost of composition outweighs.
        try {
            final ByteBuf buf = alloc.buffer(HEADER_LENGTH + messageLength);
            buf.writeByte(compressed ? COMPRESSED : UNCOMPRESSED);
            buf.writeInt(messageLength);
            buf.writeBytes(message);
            return buf;
        } finally {
            message.release();
        }
    }

    // Frame is fairly large that composition might reduce memory footprint.
    return new CompositeByteBuf(alloc, true, 2,
                                alloc.buffer(HEADER_LENGTH)
                                     .writeByte(compressed ? COMPRESSED : UNCOMPRESSED)
                                     .writeInt(messageLength),
                                message);
}
 
Example #14
Source File: SslHandler.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
protected ByteBuf composeFirst(ByteBufAllocator allocator, ByteBuf first) {
    if (first instanceof CompositeByteBuf) {
        CompositeByteBuf composite = (CompositeByteBuf) first;
        first = allocator.directBuffer(composite.readableBytes());
        try {
            first.writeBytes(composite);
        } catch (Throwable cause) {
            first.release();
            PlatformDependent.throwException(cause);
        }
        composite.release();
    }
    return first;
}
 
Example #15
Source File: HttpObjectAggregatorTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private static void checkContentBuffer(FullHttpRequest aggregatedMessage) {
    CompositeByteBuf buffer = (CompositeByteBuf) aggregatedMessage.content();
    assertEquals(2, buffer.numComponents());
    List<ByteBuf> buffers = buffer.decompose(0, buffer.capacity());
    assertEquals(2, buffers.size());
    for (ByteBuf buf: buffers) {
        // This should be false as we decompose the buffer before to not have deep hierarchy
        assertFalse(buf instanceof CompositeByteBuf);
    }
    aggregatedMessage.release();
}
 
Example #16
Source File: NettyDataBufferFactory.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 * <p>This implementation uses Netty's {@link CompositeByteBuf}.
 */
@Override
public DataBuffer join(List<? extends DataBuffer> dataBuffers) {
	Assert.notEmpty(dataBuffers, "DataBuffer List must not be empty");
	int bufferCount = dataBuffers.size();
	if (bufferCount == 1) {
		return dataBuffers.get(0);
	}
	CompositeByteBuf composite = this.byteBufAllocator.compositeBuffer(bufferCount);
	for (DataBuffer dataBuffer : dataBuffers) {
		Assert.isInstanceOf(NettyDataBuffer.class, dataBuffer);
		composite.addComponent(true, ((NettyDataBuffer) dataBuffer).getNativeBuffer());
	}
	return new NettyDataBuffer(composite, this);
}
 
Example #17
Source File: IdentityCompressionCodec.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
@Override
public ByteBuf compress(ByteBuf uncompressed, int headerLen) {
    checkNotNull(uncompressed);
    checkArgument(uncompressed.readableBytes() >= 0);
    if (headerLen == 0) {
        return uncompressed.retain();
    } else {
        CompositeByteBuf composited = PooledByteBufAllocator.DEFAULT.compositeBuffer(2);
        composited.addComponent(PooledByteBufAllocator.DEFAULT.buffer(headerLen, headerLen));
        composited.addComponent(uncompressed.retain());
        return composited;
    }
}
 
Example #18
Source File: ByteBufJoiner.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
static ByteBufJoiner wrapped() {
    return (parts) -> {
        int size = parts.size();

        switch (size) {
            case 0:
                throw new IllegalStateException("No buffer available");
            case 1:
                try {
                    return parts.get(0);
                } finally {
                    parts.clear();
                }
            default:
                CompositeByteBuf composite = null;

                try {
                    composite = parts.get(0).alloc().compositeBuffer(size);
                    // Auto-releasing failed parts
                    return composite.addComponents(true, parts);
                } catch (Throwable e) {
                    if (composite == null) {
                        // Alloc failed, release parts.
                        for (ByteBuf part : parts) {
                            ReferenceCountUtil.safeRelease(part);
                        }
                    } else {
                        // Also release success parts.
                        composite.release();
                    }
                    throw e;
                } finally {
                    parts.clear();
                }
        }
    };
}
 
Example #19
Source File: LargeFieldReader.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
private static ByteBuf retainedMerge(ByteBufAllocator allocator, List<ByteBuf> parts) {
    int i;
    int successSentinel = 0;
    int size = parts.size();
    CompositeByteBuf byteBuf = allocator.compositeBuffer(size);

    try {
        for (i = 0; i < size; ++i) {
            parts.get(i).retain();
            successSentinel = i + 1;
        }

        // Auto-releasing failed Buffer if addComponents called.
        return byteBuf.addComponents(true, parts);
    } catch (Throwable e) {
        // Also release components which append succeed.
        ReferenceCountUtil.safeRelease(byteBuf);

        if (successSentinel < size) {
            // Retains failed, even not call addComponents.
            // So release all retained buffers.
            // Of course, this still does not solve call-stack
            // overflow when calling addComponents.
            for (i = 0; i < successSentinel; ++i) {
                ReferenceCountUtil.safeRelease(parts.get(i));
            }
        }

        throw e;
    }
}
 
Example #20
Source File: RequestsToOriginMetricsCollectorTest.java    From styx with Apache License 2.0 5 votes vote down vote up
/**
 * Concatenates result of outbound Netty pipeline into an ByteBuf object.
 * <p/>
 * The optional byte buffer is returned only if a pipeline processing
 * resulted in outgoing bytes. Otherwise optional return value is absent.
 */
private static Optional<ByteBuf> grabSentBytes(EmbeddedChannel channel) {
    CompositeByteBuf outboundBytes = Unpooled.compositeBuffer();

    Object result = channel.readOutbound();
    while (result != null) {
        outboundBytes.addComponent((ByteBuf) result);
        result = channel.readOutbound();
    }

    if (outboundBytes.numComponents() > 0) {
        return Optional.of((ByteBuf) outboundBytes);
    }
    return Optional.empty();
}
 
Example #21
Source File: HCRequestFactoryTest.java    From log4j2-elasticsearch with Apache License 2.0 5 votes vote down vote up
@Test
public void createsEntityUsingGivenSource() throws IOException {

    // given
    HCRequestFactory factory = createDefaultTestObject();
    String expectedUrl = UUID.randomUUID().toString();
    Request request = createDefaultMockRequest(expectedUrl, "POST");

    ByteBuf byteBuf = new CompositeByteBuf(UnpooledByteBufAllocator.DEFAULT, false, 2);
    byte[] expectedBytes = UUID.randomUUID().toString().getBytes();
    byteBuf.writeBytes(expectedBytes);

    ItemSource<ByteBuf> itemSource = mock(ItemSource.class);
    when(itemSource.getSource()).thenReturn(byteBuf);

    when(request.serialize()).thenReturn(itemSource);

    // when
    HttpEntityEnclosingRequest result = (HttpEntityEnclosingRequest) factory.create(expectedUrl, request);

    // then
    assertEquals(expectedBytes.length, result.getEntity().getContentLength());
    ByteBuf source = (ByteBuf) request.serialize().getSource();
    source.readBytes(new byte[source.writerIndex()]);

    InputStream inputStream = result.getEntity().getContent();
    assertEquals(0, inputStream.available());

}
 
Example #22
Source File: CompositeBufferGatheringWriteTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private static ByteBuf newCompositeBuffer(ByteBufAllocator alloc) {
    CompositeByteBuf compositeByteBuf = alloc.compositeBuffer();
    compositeByteBuf.addComponent(true, alloc.directBuffer(4).writeInt(100));
    compositeByteBuf.addComponent(true, alloc.directBuffer(8).writeLong(123));
    compositeByteBuf.addComponent(true, alloc.directBuffer(8).writeLong(456));
    assertEquals(EXPECTED_BYTES, compositeByteBuf.readableBytes());
    return compositeByteBuf;
}
 
Example #23
Source File: SSLEngineTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
public CompositeByteBuf compositeBuffer() {
    switch (type) {
        case Direct:
            return allocator.compositeDirectBuffer();
        case Heap:
            return allocator.compositeHeapBuffer();
        case Mixed:
            return PlatformDependent.threadLocalRandom().nextBoolean() ?
                    allocator.compositeDirectBuffer() :
                    allocator.compositeHeapBuffer();
        default:
            throw new Error();
    }
}
 
Example #24
Source File: RetainingAsyncWritableChannelTest.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * Test that {@link RetainingAsyncWritableChannel} behaves as expected: chunks are copied, callback completed
 * immediately after {@link RetainingAsyncWritableChannel#write} method completes.
 */
@Test
public void basicsTestWithNettyByteBuf() throws Exception {
  for (boolean useCompositeByteBuf : Arrays.asList(false, true)) {
    List<byte[]> inputBuffers = getBuffers(1000, 20, 201, 0, 79, 1005);
    RetainingAsyncWritableChannel channel = new RetainingAsyncWritableChannel();
    for (int i = 0; i < inputBuffers.size(); i++) {
      byte[] data = inputBuffers.get(i);
      ByteBuf chunk;
      if (data.length == 0) {
        chunk = Unpooled.wrappedBuffer(data);
      } else if (!useCompositeByteBuf) {
        chunk = ByteBufAllocator.DEFAULT.heapBuffer(data.length);
        chunk.writeBytes(data);
      } else {
        CompositeByteBuf composite = ByteBufAllocator.DEFAULT.compositeHeapBuffer(100);
        ByteBuf c = ByteBufAllocator.DEFAULT.heapBuffer(data.length / 2);
        c.writeBytes(data, 0, data.length / 2);
        composite.addComponent(true, c);
        c = ByteBufAllocator.DEFAULT.heapBuffer(data.length - data.length / 2);
        c.writeBytes(data, data.length / 2, data.length - data.length / 2);
        composite.addComponent(true, c);
        chunk = composite;
      }
      writeAndCheckCallback(chunk, channel, chunk.readableBytes(), null, null);
    }
    checkStream(inputBuffers, channel);
    channel.close();
    writeAndCheckCallback(ByteBuffer.allocate(0), channel, 0, ClosedChannelException.class, null);
  }
}
 
Example #25
Source File: ChannelOutboundBufferTest.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Test
public void testNioBuffersExpand2() {
    TestChannel channel = new TestChannel();

    ChannelOutboundBuffer buffer = new ChannelOutboundBuffer(channel);

    CompositeByteBuf comp = compositeBuffer(256);
    ByteBuf buf = directBuffer().writeBytes("buf1".getBytes(CharsetUtil.US_ASCII));
    for (int i = 0; i < 65; i++) {
        comp.addComponent(buf.copy()).writerIndex(comp.writerIndex() + buf.readableBytes());
    }
    buffer.addMessage(comp, comp.readableBytes(), channel.voidPromise());

    assertEquals("Should still be 0 as not flushed yet", 0, buffer.nioBufferCount());
    buffer.addFlush();
    ByteBuffer[] buffers = buffer.nioBuffers();
    assertEquals(65, buffer.nioBufferCount());
    for (int i = 0;  i < buffer.nioBufferCount(); i++) {
        if (i < 65) {
            assertEquals(buffers[i], buf.internalNioBuffer(0, buf.readableBytes()));
        } else {
            assertNull(buffers[i]);
        }
    }
    release(buffer);
    buf.release();
}
 
Example #26
Source File: AbstractCoalescingBufferQueue.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
/**
 * Compose {@code cumulation} and {@code next} into a new {@link CompositeByteBuf}.
 */
protected final ByteBuf composeIntoComposite(ByteBufAllocator alloc, ByteBuf cumulation, ByteBuf next) {
    // Create a composite buffer to accumulate this pair and potentially all the buffers
    // in the queue. Using +2 as we have already dequeued current and next.
    CompositeByteBuf composite = alloc.compositeBuffer(size() + 2);
    try {
        composite.addComponent(true, cumulation);
        composite.addComponent(true, next);
    } catch (Throwable cause) {
        composite.release();
        safeRelease(next);
        throwException(cause);
    }
    return composite;
}
 
Example #27
Source File: CoalescingBufferQueue.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
protected ByteBuf compose(ByteBufAllocator alloc, ByteBuf cumulation, ByteBuf next) {
    if (cumulation instanceof CompositeByteBuf) {
        CompositeByteBuf composite = (CompositeByteBuf) cumulation;
        composite.addComponent(true, next);
        return composite;
    }
    return composeIntoComposite(alloc, cumulation, next);
}
 
Example #28
Source File: DatagramUnicastTest.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
public void testSimpleSendCompositeMixedByteBuf(Bootstrap sb, Bootstrap cb) throws Throwable {
    CompositeByteBuf buf = Unpooled.compositeBuffer();
    buf.addComponent(Unpooled.directBuffer().writeBytes(BYTES, 0, 2));
    buf.addComponent(Unpooled.buffer().writeBytes(BYTES, 2, 2));
    buf.writerIndex(4);
    testSimpleSend0(sb, cb, buf, true, BYTES, 1);

    CompositeByteBuf buf2 = Unpooled.compositeBuffer();
    buf2.addComponent(Unpooled.directBuffer().writeBytes(BYTES, 0, 2));
    buf2.addComponent(Unpooled.buffer().writeBytes(BYTES, 2, 2));
    buf2.writerIndex(4);
    testSimpleSend0(sb, cb, buf2, true, BYTES, 4);
}
 
Example #29
Source File: CrlfTerminatingChunkedStreamTest.java    From NioSmtpClient with Apache License 2.0 5 votes vote down vote up
private String terminate(String testString, int chunkSize) throws Exception {
  ByteArrayInputStream stream = new ByteArrayInputStream(testString.getBytes(StandardCharsets.UTF_8));
  CrlfTerminatingChunkedStream chunkedStream = new CrlfTerminatingChunkedStream(stream, chunkSize);

  CompositeByteBuf destBuffer = ALLOCATOR.compositeBuffer();
  while (!chunkedStream.isEndOfInput()) {
    destBuffer.addComponent(true, chunkedStream.readChunk(ALLOCATOR));
  }

  byte[] bytes = new byte[destBuffer.readableBytes()];
  destBuffer.getBytes(0, bytes);
  destBuffer.release();
  return new String(bytes, CharsetUtil.UTF_8);
}
 
Example #30
Source File: SnappyFrameEncoderTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Test
public void testStreamStartIsOnlyWrittenOnce() throws Exception {
    ByteBuf in = Unpooled.wrappedBuffer(new byte[] {
        'n', 'e', 't', 't', 'y'
    });

    channel.writeOutbound(in.retain());
    in.resetReaderIndex(); // rewind the buffer to write the same data
    channel.writeOutbound(in);
    assertTrue(channel.finish());

    ByteBuf expected = Unpooled.wrappedBuffer(new byte[] {
        (byte) 0xff, 0x06, 0x00, 0x00, 0x73, 0x4e, 0x61, 0x50, 0x70, 0x59,
         0x01, 0x09, 0x00, 0x00, 0x6f, -0x68, -0x7e, -0x5e, 'n', 'e', 't', 't', 'y',
         0x01, 0x09, 0x00, 0x00, 0x6f, -0x68, -0x7e, -0x5e, 'n', 'e', 't', 't', 'y',
    });

    CompositeByteBuf actual = Unpooled.compositeBuffer();
    for (;;) {
        ByteBuf m = channel.readOutbound();
        if (m == null) {
            break;
        }
        actual.addComponent(true, m);
    }
    assertEquals(expected, actual);

    expected.release();
    actual.release();
}