Java Code Examples for io.netty.util.ReferenceCountUtil#release()

The following examples show how to use io.netty.util.ReferenceCountUtil#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: AbstractChannelHandlerContext.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
    public ChannelFuture writeAndFlush(Object msg, ChannelPromise promise) {
//        校验消息是否合法
        if (msg == null) {
            throw new NullPointerException("msg");
        }

//        校验promise是否有效
        if (isNotValidPromise(promise, true)) {
            ReferenceCountUtil.release(msg);
            // cancelled
            return promise;
        }

        write(msg, true, promise);

        return promise;
    }
 
Example 2
Source File: BrpcHttpObjectDecoderTest.java    From brpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testDecode() throws Exception {
    BrpcHttpObjectDecoder decoder = BrpcHttpObjectDecoder.getDecoder(true);
    ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class);
    when(ctx.alloc()).thenReturn(alloc);
    ByteBuf buf = alloc.buffer(1024);
    String[] testRequest = new String[]{
            "GET / HTTP/1.1",
            "Host: localhost",
            "Content-Length: 10",
            "",
            "1234567890"
    }; // full request
    buf.writeBytes(StringUtils.join(testRequest, "\n\r").getBytes(Charset.forName("UTF-8")));
    Object message = decoder.decode(ctx, buf);
    assertThat(message).isNotNull();
    ReferenceCountUtil.release(buf);
    ReferenceCountUtil.release(message);
}
 
Example 3
Source File: WebSocketTestClient.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object o) throws Exception {

    Channel ch = ctx.channel();

    if (!handshaker.isHandshakeComplete()) {
        handshaker.finishHandshake(ch, (FullHttpResponse) o);
        // the handshake response was processed upgrade is complete
        handshakeLatch.countDown();
        ReferenceCountUtil.release(o);
        return;
    }

    if (o instanceof FullHttpResponse) {
        FullHttpResponse response = (FullHttpResponse) o;
        ReferenceCountUtil.release(o);
        throw new Exception("Unexpected HttpResponse (status=" + response.getStatus() + ", content="
                + response.content().toString(CharsetUtil.UTF_8) + ')');
    }
    ctx.fireChannelRead(o);
}
 
Example 4
Source File: MessageDuplexCodec.java    From r2dbc-mysql with Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof ByteBuf) {
        DecodeContext context = this.decodeContext;
        ServerMessage message = decoder.decode((ByteBuf) msg, this.context, context, this.linkableIdProvider);

        if (message != null) {
            handleDecoded(ctx, message);
        }
    } else if (msg instanceof ServerMessage) {
        ctx.fireChannelRead(msg);
    } else {
        if (logger.isWarnEnabled()) {
            logger.warn("Unknown message type {} on reading", msg.getClass());
        }
        ReferenceCountUtil.release(msg);
    }
}
 
Example 5
Source File: DisconnectHandler.java    From socketio with Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  if (msg instanceof HttpRequest) {
    final HttpRequest req = (HttpRequest) msg;
    final HttpMethod requestMethod = req.method();
    final QueryStringDecoder queryDecoder = new QueryStringDecoder(req.uri());
    final String requestPath = queryDecoder.path();

    boolean disconnect = queryDecoder.parameters().containsKey(DISCONNECT);
    if (disconnect) {
      if (log.isDebugEnabled())
        log.debug("Received HTTP disconnect request: {} {} from channel: {}", requestMethod, requestPath, ctx.channel());

      final String sessionId = PipelineUtils.getSessionId(requestPath);
      final Packet disconnectPacket = new Packet(PacketType.DISCONNECT, sessionId);
      disconnectPacket.setOrigin(PipelineUtils.getOrigin(req));
      ctx.fireChannelRead(disconnectPacket);
      ReferenceCountUtil.release(msg);
      return;
    }
  }
  ctx.fireChannelRead(msg);
}
 
Example 6
Source File: DefaultHttpClient.java    From krpc with Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
    String connId = getConnId(ctx.channel());
    ReqResInfo info = dataMap.get(connId);

    try {
        FullHttpResponse httpRes = (FullHttpResponse) msg;

        if (!httpRes.decoderResult().isSuccess()) {
            if (info != null) info.setRes(new HttpClientRes(RetCodes.HTTPCLIENT_RES_PARSE_ERROR));
            return;
        }

        HttpClientRes res = convertRes(httpRes);
        if (info != null) info.setRes(res);
    } finally {
        ReferenceCountUtil.release(msg);
    }

}
 
Example 7
Source File: AbstractPacketEncoder.java    From ProtocolSupportBungee with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void write(final ChannelHandlerContext ctx, final Object msgObject, final ChannelPromise promise) throws Exception {
	try {
		if (acceptOutboundMessage(msgObject)) {
			DefinedPacket msg = (DefinedPacket) msgObject;
			try {
				encode(ctx, msg, null);
			} finally {
				ReferenceCountUtil.release(msg);
			}
		} else {
			ctx.write(msgObject, promise);
		}
	} catch (EncoderException e) {
		throw e;
	} catch (Throwable e2) {
		throw new EncoderException(e2);
	}
}
 
Example 8
Source File: KeyValueAuthHandlerTest.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPickHighestMechIfNotForced() {
    KeyValueAuthHandler handler = new KeyValueAuthHandler("user", "pass", false);
    EmbeddedChannel channel = new EmbeddedChannel(handler);

    // Handler sends "list mechs"
    BinaryMemcacheRequest listMechsRequest = (BinaryMemcacheRequest) channel.readOutbound();
    assertEquals(KeyValueAuthHandler.SASL_LIST_MECHS_OPCODE, listMechsRequest.getOpcode());
    ReferenceCountUtil.release(listMechsRequest);

    // Server returns with a bunch of them
    FullBinaryMemcacheResponse listMechsResponse = new DefaultFullBinaryMemcacheResponse(
            new byte[] {},
            Unpooled.EMPTY_BUFFER,
            Unpooled.copiedBuffer("SCRAM-SHA1 CRAM-MD5 PLAIN", CharsetUtil.UTF_8)
    );
    listMechsResponse.setOpcode(KeyValueAuthHandler.SASL_LIST_MECHS_OPCODE);

    channel.writeInbound(listMechsResponse);

    // make sure it still picks only PLAIN
    FullBinaryMemcacheRequest initialRequest = (FullBinaryMemcacheRequest) channel.readOutbound();
    assertEquals("SCRAM-SHA1", new String(initialRequest.getKey()));
    ReferenceCountUtil.release(initialRequest);
}
 
Example 9
Source File: BaseHttpHandler.java    From blynk-server with GNU General Public License v3.0 6 votes vote down vote up
public boolean process(ChannelHandlerContext ctx, HttpRequest req) {
    HandlerHolder handlerHolder = lookupHandler(req);

    if (handlerHolder != null) {
        try {
            invokeHandler(ctx, req, handlerHolder.handler, handlerHolder.extractedParams);
        } catch (Exception e) {
            log.debug("Error processing http request.", e);
            ctx.writeAndFlush(serverError(e.getMessage()), ctx.voidPromise());
        } finally {
            ReferenceCountUtil.release(req);
        }
        return true;
    }

    return false;
}
 
Example 10
Source File: DFActorWrap.java    From dfactor with MIT License 6 votes vote down vote up
private void _release(){
	_lockQueueWrite.lock();
	try{
		for(int i=0; i<2; ++i){
			final LinkedList<DFActorMessage> q = _arrQueue[i];
			final Iterator<DFActorMessage> itMsg = q.iterator();
			while(itMsg.hasNext()){
				final DFActorMessage m = itMsg.next();
				final Object payload = m.payload;
				if(payload != null){ //
					if(payload instanceof DFHttpSvrReq){
						((DFHttpSvrReq)payload).release();
					}else if(payload instanceof DFHttpCliRsp){
						((DFHttpCliRsp)payload).release();
					}else if(payload instanceof ByteBuf){
						ReferenceCountUtil.release(payload);
					}
					m.payload = null;
				}
			}
			q.clear();
		}
	}finally{
		_lockQueueWrite.unlock();
	}
}
 
Example 11
Source File: HttpClient.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    try {
        if (msg instanceof HttpResponse && msg instanceof HttpContent) {
            responseStatus = ((HttpResponse) msg).status();
            responseContent = ((HttpContent) msg).content().toString(CharsetUtil.UTF_8);
        } else {
            exception =
                    new Exception("Unexpected response message class: " + msg.getClass());
        }
    } finally {
        ReferenceCountUtil.release(msg);
    }
}
 
Example 12
Source File: TcpServerInboundHandler.java    From netty-cookbook with Apache License 2.0 5 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
	try {
		System.out.println("TcpServerInboundHandler");
    	StringBuilder s = new StringBuilder();
    	s.append("Ok TCP client, TcpServerInboundHandler got your message \"").append(msg).append("\"");
        ctx.write(s);
	} finally {
		ReferenceCountUtil.release(msg);
	}
}
 
Example 13
Source File: AbstractGryoMessageSerializerV1d0.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
public ByteBuf serializeResponseAsBinary(final ResponseMessage responseMessage, final ByteBufAllocator allocator) throws SerializationException {
    ByteBuf encodedMessage = null;
    try {
        final Kryo kryo = kryoThreadLocal.get();
        try (final ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            final Output output = new Output(baos, bufferSize);

            // request id - if present
            kryo.writeObjectOrNull(output, responseMessage.getRequestId() != null ? responseMessage.getRequestId() : null, UUID.class);

            // status
            output.writeShort(responseMessage.getStatus().getCode().getValue());
            output.writeString(responseMessage.getStatus().getMessage());
            kryo.writeClassAndObject(output, responseMessage.getStatus().getAttributes());

            // result
            kryo.writeClassAndObject(output, serializeToString ? serializeResultToString(responseMessage) : responseMessage.getResult().getData());
            kryo.writeClassAndObject(output, responseMessage.getResult().getMeta());

            final long size = output.total();
            if (size > Integer.MAX_VALUE)
                throw new SerializationException(String.format("Message size of %s exceeds allocatable space", size));

            output.flush();
            encodedMessage = allocator.buffer((int) size);
            encodedMessage.writeBytes(baos.toByteArray());
        }

        return encodedMessage;
    } catch (Exception ex) {
        if (encodedMessage != null) ReferenceCountUtil.release(encodedMessage);

        logger.warn(String.format("Response [%s] could not be serialized by %s.", responseMessage, AbstractGryoMessageSerializerV1d0.class.getName()), ex);
        throw new SerializationException(ex);
    }
}
 
Example 14
Source File: AbstractChannel.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
        public final void write(Object msg, ChannelPromise promise) {
            assertEventLoop();

            ChannelOutboundBuffer outboundBuffer = this.outboundBuffer;
            if (outboundBuffer == null) {
                // If the outboundBuffer is null we know the channel was closed and so
                // need to fail the future right away. If it is not null the handling of the rest
                // will be done in flush0()//如果outboundBuffer为空,我们知道通道已经关闭
//必须马上放弃未来。如果它不是空的,处理其余的
//将在flush0()中完成
                // See https://github.com/netty/netty/issues/2362
                safeSetFailure(promise, WRITE_CLOSED_CHANNEL_EXCEPTION);
                // release message now to prevent resource-leak现在发布消息以防止资源泄漏
                ReferenceCountUtil.release(msg);
                return;
            }

            int size;
            try {
                msg = filterOutboundMessage(msg);
                size = pipeline.estimatorHandle().size(msg);
                if (size < 0) {
                    size = 0;
                }
            } catch (Throwable t) {
                safeSetFailure(promise, t);
                ReferenceCountUtil.release(msg);
                return;
            }

            outboundBuffer.addMessage(msg, size, promise);
        }
 
Example 15
Source File: RespConnectionHandler.java    From resp-server with MIT License 5 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  try {
    impl.receive(ctx, (RedisToken) msg);
  } finally {
    ReferenceCountUtil.release(msg);
  }
}
 
Example 16
Source File: NoMatchHandler.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    try {
        if (msg instanceof HttpRequest) {
            HttpRequest req = (HttpRequest) msg;
            log.debug("Error resolving url. No path found. {} : {}", req.method().name(), req.uri());
            if (ctx.channel().isWritable()) {
                ctx.writeAndFlush(Response.notFound(), ctx.voidPromise());
            }
        }
    } finally {
        ReferenceCountUtil.release(msg);
    }
}
 
Example 17
Source File: Http2MultiplexCodec.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private Http2StreamFrame validateStreamFrame(Http2StreamFrame frame) {
    if (frame.stream() != null && frame.stream() != stream) {
        String msgString = frame.toString();
        ReferenceCountUtil.release(frame);
        throw new IllegalArgumentException(
                "Stream " + frame.stream() + " must not be set on the frame: " + msgString);
    }
    return frame;
}
 
Example 18
Source File: EnvelopedRecordSetWriter.java    From distributedlog with Apache License 2.0 4 votes vote down vote up
@Override
public synchronized void abortTransmit(Throwable reason) {
    cancelPromises(reason);
    buffer.release();
    ReferenceCountUtil.release(recordSetBuffer);
}
 
Example 19
Source File: SerializationTest.java    From ethernet-ip with Apache License 2.0 4 votes vote down vote up
@AfterMethod
public void tearDown() {
    ReferenceCountUtil.release(buffer);
}
 
Example 20
Source File: HttpUtilTest.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
private static void run100ContinueTest(final HttpMessage message, final boolean expected) {
    assertEquals(expected, HttpUtil.is100ContinueExpected(message));
    ReferenceCountUtil.release(message);
}