Java Code Examples for io.netty.buffer.ByteBuf#release()
The following examples show how to use
io.netty.buffer.ByteBuf#release() .
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: DefaultHttp2ConnectionDecoderTest.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
@Test public void dataReadForUnknownStreamShouldApplyFlowControl() throws Exception { when(connection.stream(STREAM_ID)).thenReturn(null); final ByteBuf data = dummyData(); int padding = 10; int processedBytes = data.readableBytes() + padding; try { try { decode().onDataRead(ctx, STREAM_ID, data, padding, true); fail(); } catch (Http2Exception e) { verify(localFlow) .receiveFlowControlledFrame(eq((Http2Stream) null), eq(data), eq(padding), eq(true)); verify(localFlow).consumeBytes(eq((Http2Stream) null), eq(processedBytes)); verify(localFlow).frameWriter(any(Http2FrameWriter.class)); verifyNoMoreInteractions(localFlow); // Verify that the event was absorbed and not propagated to the observer. verify(listener, never()).onDataRead(eq(ctx), anyInt(), any(ByteBuf.class), anyInt(), anyBoolean()); } } finally { data.release(); } }
Example 2
Source File: DelimiterBasedFrameDecoderTest.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
@Test public void testFailFastTooLongFrameRecovery() throws Exception { EmbeddedChannel ch = new EmbeddedChannel( new DelimiterBasedFrameDecoder(1, Delimiters.nulDelimiter())); for (int i = 0; i < 2; i ++) { try { assertTrue(ch.writeInbound(Unpooled.wrappedBuffer(new byte[] { 1, 2 }))); fail(DecoderException.class.getSimpleName() + " must be raised."); } catch (TooLongFrameException e) { // Expected } ch.writeInbound(Unpooled.wrappedBuffer(new byte[] { 0, 'A', 0 })); ByteBuf buf = ch.readInbound(); assertEquals("A", buf.toString(CharsetUtil.ISO_8859_1)); buf.release(); } }
Example 3
Source File: ReplayingDecoderTest.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
@Test public void testRemoveItselfWithReplayError() { EmbeddedChannel channel = new EmbeddedChannel(new ReplayingDecoder() { private boolean removed; @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { assertFalse(removed); ctx.pipeline().remove(this); in.readBytes(1000); removed = true; } }); ByteBuf buf = Unpooled.wrappedBuffer(new byte[] {'a', 'b', 'c'}); channel.writeInbound(buf.copy()); ByteBuf b = channel.readInbound(); assertEquals("Expect to have still all bytes in the buffer", b, buf); b.release(); buf.release(); }
Example 4
Source File: ProtobufVarint32FrameDecoderTest.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
@Test public void testTinyDecode() { byte[] b = { 4, 1, 1, 1, 1 }; assertFalse(ch.writeInbound(wrappedBuffer(b, 0, 1))); assertThat(ch.readInbound(), is(nullValue())); assertFalse(ch.writeInbound(wrappedBuffer(b, 1, 2))); assertThat(ch.readInbound(), is(nullValue())); assertTrue(ch.writeInbound(wrappedBuffer(b, 3, b.length - 3))); ByteBuf expected = wrappedBuffer(new byte[] { 1, 1, 1, 1 }); ByteBuf actual = ch.readInbound(); assertThat(expected, is(actual)); assertFalse(ch.finish()); expected.release(); actual.release(); }
Example 5
Source File: RemotingDecoder.java From sailfish with Apache License 2.0 | 6 votes |
@Override protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception { ByteBuf buffer = (ByteBuf) super.decode(ctx, in); if (null == buffer) { return null; } try { return DefaultRemotingCodec.INSTANCE.decode(buffer); } catch (SailfishException cause) { if (cause.code() == ExceptionCode.BAD_PACKAGE) { String log = String.format("packet invalid, begin to close channel[{}], detail msg: {}", ctx.channel().toString(), cause.getMessage()); logger.error(log); ChannelUtil.closeChannel(ctx.channel()); return null; } throw cause; } finally { buffer.release(); } }
Example 6
Source File: BufUnwrapperTest.java From grpc-nebula-java with Apache License 2.0 | 6 votes |
@Test public void closeEmptiesBuffers() { BufUnwrapper unwrapper = new BufUnwrapper(); ByteBuf buf = alloc.buffer(); try { ByteBuffer[] readableBufs = unwrapper.readableNioBuffers(buf); ByteBuffer[] writableBufs = unwrapper.writableNioBuffers(buf); Truth.assertThat(readableBufs).hasLength(1); Truth.assertThat(readableBufs[0]).isNotNull(); Truth.assertThat(writableBufs).hasLength(1); Truth.assertThat(writableBufs[0]).isNotNull(); unwrapper.close(); Truth.assertThat(readableBufs[0]).isNull(); Truth.assertThat(writableBufs[0]).isNull(); } finally { buf.release(); } }
Example 7
Source File: LineBasedFrameDecoderTest.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
@Test public void testTooLongLine2() throws Exception { EmbeddedChannel ch = new EmbeddedChannel(new LineBasedFrameDecoder(16, false, false)); assertFalse(ch.writeInbound(copiedBuffer("12345678901234567", CharsetUtil.US_ASCII))); try { ch.writeInbound(copiedBuffer("890\r\nfirst\r\n", CharsetUtil.US_ASCII)); fail(); } catch (Exception e) { assertThat(e, is(instanceOf(TooLongFrameException.class))); } ByteBuf buf = ch.readInbound(); ByteBuf buf2 = copiedBuffer("first\r\n", CharsetUtil.US_ASCII); assertThat(buf, is(buf2)); assertThat(ch.finish(), is(false)); buf.release(); buf2.release(); }
Example 8
Source File: ChannelOutboundBufferTest.java From netty4.0.27Learn with Apache License 2.0 | 6 votes |
@Test public void testNioBuffersExpand() { TestChannel channel = new TestChannel(); ChannelOutboundBuffer buffer = new ChannelOutboundBuffer(channel); ByteBuf buf = directBuffer().writeBytes("buf1".getBytes(CharsetUtil.US_ASCII)); for (int i = 0; i < 64; i++) { buffer.addMessage(buf.copy(), buf.readableBytes(), channel.voidPromise()); } assertEquals("Should still be 0 as not flushed yet", 0, buffer.nioBufferCount()); buffer.addFlush(); ByteBuffer[] buffers = buffer.nioBuffers(); assertEquals(64, buffer.nioBufferCount()); for (int i = 0; i < buffer.nioBufferCount(); i++) { assertEquals(buffers[i], buf.internalNioBuffer(0, buf.readableBytes())); } release(buffer); buf.release(); }
Example 9
Source File: LargeMessageSlicer.java From r2dbc-mysql with Apache License 2.0 | 5 votes |
@Override public void onNext(ByteBuf buf) { if (!buf.isReadable()) { // Ignore empty buffer. buf.release(); return; } if (now == null) { onNullNext(buf); } else { int needBytes = Envelopes.MAX_ENVELOPE_SIZE - nowBytes; if (buf.readableBytes() < needBytes) { // Must less than sliceBytes nowBytes += buf.readableBytes(); now.add(buf); } else { now.add(buf.readRetainedSlice(needBytes)); sink.next(mergeNow()); now = null; nowBytes = 0; onNullNext(buf); } } }
Example 10
Source File: SpdyHeaderBlockZlibDecoderTest.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
@Test public void testLargeHeaderValue() throws Exception { ByteBuf headerBlock = Unpooled.buffer(8220); headerBlock.writeBytes(zlibHeader); headerBlock.writeByte(0); // Non-compressed block headerBlock.writeByte(0x0c); // little-endian length (8204) headerBlock.writeByte(0x20); // little-endian length (8204) headerBlock.writeByte(0xf3); // one's compliment of length headerBlock.writeByte(0xdf); // one's compliment of length headerBlock.writeInt(1); // number of Name/Value pairs headerBlock.writeInt(1); // length of name headerBlock.writeByte('n'); headerBlock.writeInt(8191); // length of value for (int i = 0; i < 8191; i++) { headerBlock.writeByte('v'); } headerBlock.writeBytes(zlibSyncFlush); decoder.decode(ByteBufAllocator.DEFAULT, headerBlock, frame); decoder.endHeaderBlock(frame); assertFalse(headerBlock.isReadable()); assertFalse(frame.isInvalid()); assertFalse(frame.isTruncated()); assertEquals(1, frame.headers().names().size()); assertEquals(8191, frame.headers().get("n").length()); headerBlock.release(); }
Example 11
Source File: PerFrameDeflateEncoderTest.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
@Test public void testCompressedFrame() { EmbeddedChannel encoderChannel = new EmbeddedChannel(new PerFrameDeflateEncoder(9, 15, false)); EmbeddedChannel decoderChannel = new EmbeddedChannel( ZlibCodecFactory.newZlibDecoder(ZlibWrapper.NONE)); // initialize byte[] payload = new byte[300]; random.nextBytes(payload); BinaryWebSocketFrame frame = new BinaryWebSocketFrame(true, WebSocketExtension.RSV3, Unpooled.wrappedBuffer(payload)); // execute encoderChannel.writeOutbound(frame); BinaryWebSocketFrame compressedFrame = encoderChannel.readOutbound(); // test assertNotNull(compressedFrame); assertNotNull(compressedFrame.content()); assertTrue(compressedFrame instanceof BinaryWebSocketFrame); assertEquals(WebSocketExtension.RSV1 | WebSocketExtension.RSV3, compressedFrame.rsv()); decoderChannel.writeInbound(compressedFrame.content()); decoderChannel.writeInbound(DeflateDecoder.FRAME_TAIL); ByteBuf uncompressedPayload = decoderChannel.readInbound(); assertEquals(300, uncompressedPayload.readableBytes()); byte[] finalPayload = new byte[300]; uncompressedPayload.readBytes(finalPayload); assertTrue(Arrays.equals(finalPayload, payload)); uncompressedPayload.release(); }
Example 12
Source File: RedissonSessionClient.java From redis-session-manager with Apache License 2.0 | 5 votes |
@Override public int getEncodedSize(Object obj) { ByteBuf buf = null; try { buf = redissonClient.getConfig().getCodec().getValueEncoder().encode(obj); return buf.readableBytes(); } catch (IOException e) { throw new IllegalArgumentException(e); // redisson style } finally { if (buf != null) { buf.release(); } } }
Example 13
Source File: StringDecoder.java From chuidiang-ejemplos with GNU Lesser General Public License v3.0 | 5 votes |
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buf =(ByteBuf)msg; String text = buf.toString(Charset.defaultCharset()); ctx.fireChannelRead(text); buf.release(); }
Example 14
Source File: TimestampZTypeTest.java From crate with Apache License 2.0 | 5 votes |
@Test public void testBinaryRoundtrip() { ByteBuf buffer = Unpooled.buffer(); try { long value = 1467072000000L; int written = pgType.writeAsBinary(buffer, value); int length = buffer.readInt(); assertThat(written - 4, is(length)); long readValue = (long) pgType.readBinaryValue(buffer, length); assertThat(readValue, is(value)); } finally { buffer.release(); } }
Example 15
Source File: DefaultHttp2FrameReaderTest.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
@Test(expected = Http2Exception.class) public void failedWhenAckSettingsFrameWithPayload() throws Http2Exception { ByteBuf input = Unpooled.buffer(); try { writeFrameHeader(input, 1, SETTINGS, new Http2Flags().ack(true), 0); input.writeByte(1); frameReader.readFrame(ctx, input, listener); } finally { input.release(); } }
Example 16
Source File: ExecToCoordTunnel.java From dremio-oss with Apache License 2.0 | 5 votes |
@Override public void connectionFailed(FailureType type, Throwable t) { for(ByteBuf buffer : batch.getBuffers()) { buffer.release(); } super.connectionFailed(type, t); }
Example 17
Source File: KeepaliveFrameFlyweightTest.java From rsocket-java with Apache License 2.0 | 5 votes |
@Test void canReadData() { ByteBuf data = Unpooled.wrappedBuffer(new byte[] {5, 4, 3}); ByteBuf frame = KeepAliveFrameCodec.encode(ByteBufAllocator.DEFAULT, true, 0, data); assertTrue(KeepAliveFrameCodec.respondFlag(frame)); assertEquals(data, KeepAliveFrameCodec.data(frame)); frame.release(); }
Example 18
Source File: ResumableDuplexConnection.java From rsocket-java with Apache License 2.0 | 5 votes |
private void sendFrame(ByteBuf f) { if (disposed.get()) { f.release(); return; } /*resuming from store so no need to save again*/ if (state != State.RESUME && isResumableFrame(f)) { resumeSaveFrames.onNext(f); } /*filter frames coming from upstream before actual resumption began, * to preserve frames ordering*/ if (state != State.RESUME_STARTED) { downStreamFrames.onNext(f); } }
Example 19
Source File: SubscribeEncoder.java From vertx-mqtt-broker with Apache License 2.0 | 4 votes |
@Override protected void encode(SubscribeMessage message, ByteBuf out) { if (message.subscriptions().isEmpty()) { throw new IllegalArgumentException("Found a subscribe message with empty topics"); } if (message.getQos() != AbstractMessage.QOSType.LEAST_ONE) { throw new IllegalArgumentException("Expected a message with QOS 1, found " + message.getQos()); } // ByteBuf variableHeaderBuff = chc.alloc().buffer(4); ByteBuf variableHeaderBuff = Buffer.buffer(4).getByteBuf(); ByteBuf buff = null; try { variableHeaderBuff.writeShort(message.getMessageID()); for (SubscribeMessage.Couple c : message.subscriptions()) { variableHeaderBuff.writeBytes(Utils.encodeString(c.getTopicFilter())); variableHeaderBuff.writeByte(c.getQos()); } int variableHeaderSize = variableHeaderBuff.readableBytes(); byte flags = Utils.encodeFlags(message); // buff = chc.alloc().buffer(2 + variableHeaderSize); buff = Buffer.buffer(2 + variableHeaderSize).getByteBuf(); buff.writeByte(AbstractMessage.SUBSCRIBE << 4 | flags); buff.writeBytes(Utils.encodeRemainingLength(variableHeaderSize)); buff.writeBytes(variableHeaderBuff); out.writeBytes(buff); } finally { variableHeaderBuff.release(); buff.release(); } if (message.subscriptions().isEmpty()) { throw new IllegalArgumentException("Found a subscribe message with empty topics"); } if (message.getQos() != AbstractMessage.QOSType.LEAST_ONE) { throw new IllegalArgumentException("Expected a message with QOS 1, found " + message.getQos()); } }
Example 20
Source File: KeyValueHandler.java From couchbase-jvm-core with Apache License 2.0 | 4 votes |
/** * Helper method to safely release the content. * * @param content the content to safely release if needed. */ private static void releaseContent(ByteBuf content) { if (content != null && content.refCnt() > 0) { content.release(); } }