Java 类io.netty.util.ReferenceCountUtil 实例源码

项目:AgentX    文件:XRelayHandler.java   
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (dstChannel.isActive()) {
        ByteBuf byteBuf = (ByteBuf) msg;
        try {
            if (!byteBuf.hasArray()) {
                byte[] bytes = new byte[byteBuf.readableBytes()];
                byteBuf.getBytes(0, bytes);
                if (uplink) {
                    dstChannel.writeAndFlush(Unpooled.wrappedBuffer(wrapper.wrap(bytes)));
                    log.info("\tClient ==========> Target \tSend [{} bytes]", bytes.length);
                } else {
                    bytes = wrapper.unwrap(bytes);
                    if (bytes != null) {
                        dstChannel.writeAndFlush(Unpooled.wrappedBuffer(bytes));
                        log.info("\tClient <========== Target \tGet [{} bytes]", bytes.length);
                    }
                }
            }
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }
}
项目:AgentX    文件:XRelayHandler.java   
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (dstChannel.isActive()) {
        ByteBuf byteBuf = (ByteBuf) msg;
        try {
            if (!byteBuf.hasArray()) {
                byte[] bytes = new byte[byteBuf.readableBytes()];
                byteBuf.getBytes(0, bytes);
                if (uplink) {
                    bytes = wrapper.unwrap(bytes);
                    if (bytes != null) {
                        dstChannel.writeAndFlush(Unpooled.wrappedBuffer(bytes));
                        log.info("\tClient ==========> Target \tSend [{} bytes]", bytes.length);
                    }
                } else {
                    dstChannel.writeAndFlush(Unpooled.wrappedBuffer(wrapper.wrap(bytes)));
                    log.info("\tClient <========== Target \tGet [{} bytes]", bytes.length);
                }
            }
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }
}
项目:proxyee    文件:HttpProxyClientHandle.java   
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  //客户端channel已关闭则不转发了
  if (!clientChannel.isOpen()) {
    ReferenceCountUtil.release(msg);
    return;
  }
  HttpProxyInterceptPipeline interceptPipeline = ((HttpProxyServerHandle) clientChannel.pipeline()
      .get("serverHandle")).getInterceptPipeline();
  if (msg instanceof HttpResponse) {
    interceptPipeline.afterResponse(clientChannel, ctx.channel(), (HttpResponse) msg);
  } else if (msg instanceof HttpContent) {
    interceptPipeline.afterResponse(clientChannel, ctx.channel(), (HttpContent) msg);
  } else {
    clientChannel.writeAndFlush(msg);
  }
}
项目:nitmproxy    文件:Http1FrontendHandler.java   
@Override
protected void channelRead0(ChannelHandlerContext ctx,
                            FullHttpRequest request) throws Exception {
    if (master.config().getProxyMode() == ProxyMode.HTTP && !tunneled) {
        if (request.method() == HttpMethod.CONNECT) {
            handleTunnelProxyConnection(ctx, request);
        } else {
            handleHttpProxyConnection(ctx, request);
        }
    } else {
        checkState(outboundChannel != null);
        LOGGER.info("[Client ({})] => [Server ({})] : {}",
                    connectionInfo.getClientAddr(), connectionInfo.getServerAddr(),
                    request);
        outboundChannel.writeAndFlush(ReferenceCountUtil.retain(request));
    }
}
项目:neoscada    文件:MessageChannel.java   
private ByteBuf encode ( final ChannelHandlerContext ctx, final Object msg )
{
    ByteBuf buf = ctx.alloc ().buffer ( 255 );
    try
    {
        this.manager.encodeMessage ( msg, buf );
        if ( buf.isReadable () )
        {
            // copy away the reference so it does not get released
            final ByteBuf buf2 = buf;
            buf = null;
            return buf2;
        }
    }
    finally
    {
        ReferenceCountUtil.release ( buf );
    }
    return null;
}
项目:neoscada    文件:APDUEncoder.java   
private void handleIFormat ( final InformationTransfer msg, ByteBuf out )
{
    final ByteBuf data = msg.getData ();
    try
    {
        out = out.order ( ByteOrder.LITTLE_ENDIAN );

        final int len = data.readableBytes ();

        if ( len > Constants.APCI_MAX_DATA_LENGTH )
        {
            throw new EncoderException ( String.format ( "Packet too big - %s bytes", len ) );
        }

        out.ensureWritable ( 6 + len );
        out.writeByte ( Constants.START_BYTE );
        out.writeByte ( 4 + len );
        out.writeShort ( msg.getSendSequenceNumber () << 1 );
        out.writeShort ( msg.getReceiveSequenceNumber () << 1 );
        out.writeBytes ( data );
    }
    finally
    {
        ReferenceCountUtil.release ( msg.getData () );
    }
}
项目:NSS    文件:OutRelayHandler.java   
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    try {
        if (relayChannel.isActive()) {
            ByteBuf bytebuff = (ByteBuf) msg;
            if (!bytebuff.hasArray()) {
                int len = bytebuff.readableBytes();
                byte[] arr = new byte[len];
                bytebuff.getBytes(0, arr);
                connectHandler.sendRemote(arr, arr.length, relayChannel);
            }
        }
    } catch (Exception e) {
        logger.error("send data to remoteServer error",e);
    } finally {
        ReferenceCountUtil.release(msg);
    }
}
项目:NSS    文件:InRelayHandler.java   
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    try {
        if (relayChannel.isActive()) {
            logger.debug("get remote message" + relayChannel);
            ByteBuf bytebuff = (ByteBuf) msg;
            if (!bytebuff.hasArray()) {
                int len = bytebuff.readableBytes();
                byte[] arr = new byte[len];
                bytebuff.getBytes(0, arr);
                connectHandler.sendLocal(arr, arr.length, relayChannel);
            }
        }
    } catch (Exception e) {
        logger.error("receive remoteServer data error", e);
    } finally {
        ReferenceCountUtil.release(msg);
    }
}
项目:NioSmtpClient    文件:DotStuffingChunkedStreamTest.java   
private String dotStuff(String testString, int chunkSize) throws Exception {
  ByteArrayInputStream stream = new ByteArrayInputStream(testString.getBytes(StandardCharsets.UTF_8));
  DotStuffingChunkedStream chunkedStream = new DotStuffingChunkedStream(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);

  ReferenceCountUtil.release(destBuffer);
  return new String(bytes, CharsetUtil.UTF_8);
}
项目:waterrower-core    文件:RxtxSerialHandler.java   
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    try {

        if (!(msg instanceof AbstractMessage)) {
            Log.warn(SERIAL, "Invalid message received! Message skipped.");
            return;
        }

        Log.debug(SERIAL, "Message received: " + msg);

        // Notify that a message was received.
        onMessageReceived((AbstractMessage) msg);

    } finally {
        ReferenceCountUtil.release(msg);
    }
}
项目:proxyee-down    文件:HttpDownSniffIntercept.java   
@Override
public void beforeRequest(Channel clientChannel, HttpContent httpContent,
    HttpProxyInterceptPipeline pipeline) throws Exception {
  if (content != null) {
    ByteBuf temp = httpContent.content().slice();
    content.writeBytes(temp);
    if (httpContent instanceof LastHttpContent) {
      try {
        byte[] contentBts = new byte[content.readableBytes()];
        content.readBytes(contentBts);
        ((HttpRequestInfo) pipeline.getHttpRequest()).setContent(contentBts);
      } finally {
        ReferenceCountUtil.release(content);
        content = null; //状态回归
      }
    }
  }
  pipeline.beforeRequest(clientChannel, httpContent);
}
项目:QuantBridge    文件:MessageServerHandler.java   
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    Message message = (Message) msg;
    try {
        if (Constants.COMMAND_REGISTER.equals(message.getCommand())) {
            Application.Connections.put(message.getContent(), ctx.channel());
            logger.debug("token " + message.getContent() + " ==> remote address " + ctx.channel().remoteAddress());
        } else if (!Application.clientIsOnline(ctx.channel())) {
            ctx.writeAndFlush(Constants.CONTENT_BYE);
            ctx.close();
        } else {
            if (Constants.COMMAND_PULSE.equals(message.getCommand())) {
            } else {
                ctx.writeAndFlush(Constants.CONTENT_BYE);
                ctx.close();
            }
        }
    } finally {
        ReferenceCountUtil.release(msg);
    }
}
项目:incubator-pulsar    文件:ProducerImpl.java   
/**
 * fail any pending batch messages that were enqueued, however batch was not closed out
 *
 */
private void failPendingBatchMessages(PulsarClientException ex) {
    if (batchMessageContainer.isEmpty()) {
        return;
    }
    int numMessagesInBatch = batchMessageContainer.numMessagesInBatch;
    semaphore.release(numMessagesInBatch);
    try {
        // Need to protect ourselves from any exception being thrown in the future handler from the application
        batchMessageContainer.firstCallback.sendComplete(ex);
    } catch (Throwable t) {
        log.warn("[{}] [{}] Got exception while completing the callback for msg {}:", topic, producerName,
                batchMessageContainer.sequenceId, t);
    }
    ReferenceCountUtil.safeRelease(batchMessageContainer.getBatchedSingleMessageMetadataAndPayload());
    batchMessageContainer.clear();
}
项目:LiteGraph    文件:AbstractGraphSONMessageSerializerV1d0.java   
@Override
public ByteBuf serializeResponseAsBinary(final ResponseMessage responseMessage, final ByteBufAllocator allocator) throws SerializationException {
    ByteBuf encodedMessage = null;
    try {
        final byte[] payload = mapper.writeValueAsBytes(responseMessage);
        encodedMessage = allocator.buffer(payload.length);
        encodedMessage.writeBytes(payload);

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

        logger.warn("Response [{}] could not be serialized by {}.", responseMessage.toString(), AbstractGraphSONMessageSerializerV1d0.class.getName());
        throw new SerializationException(ex);
    }
}
项目:LiteGraph    文件:AbstractGraphSONMessageSerializerV1d0.java   
@Override
public ByteBuf serializeRequestAsBinary(final RequestMessage requestMessage, final ByteBufAllocator allocator) throws SerializationException {
    ByteBuf encodedMessage = null;
    try {
        final byte[] header = obtainHeader();
        final byte[] payload = mapper.writeValueAsBytes(requestMessage);

        encodedMessage = allocator.buffer(header.length + payload.length);
        encodedMessage.writeBytes(header);
        encodedMessage.writeBytes(payload);

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

        logger.warn("Request [{}] could not be serialized by {}.", requestMessage.toString(), AbstractGraphSONMessageSerializerV1d0.class.getName());
        throw new SerializationException(ex);
    }
}
项目:LiteGraph    文件:OpExecutorHandler.java   
@Override
protected void channelRead0(final ChannelHandlerContext ctx, final Pair<RequestMessage, ThrowingConsumer<Context>> objects) throws Exception {
    final RequestMessage msg = objects.getValue0();
    final ThrowingConsumer<Context> op = objects.getValue1();
    final Context gremlinServerContext = new Context(msg, ctx,
            settings, graphManager, gremlinExecutor, scheduledExecutorService);

    try {
        op.accept(gremlinServerContext);
    } catch (OpProcessorException ope) {
        // Ops may choose to throw OpProcessorException or write the error ResponseMessage down the line
        // themselves
        logger.warn(ope.getMessage(), ope);
        ctx.writeAndFlush(ope.getResponseMessage());
    } catch (Exception ex) {
        // It is possible that an unplanned exception might raise out of an OpProcessor execution. Build a general
        // error to send back to the client
        logger.warn(ex.getMessage(), ex);
        ctx.writeAndFlush(ResponseMessage.build(msg)
                .code(ResponseStatusCode.SERVER_ERROR)
                .statusMessage(ex.getMessage()).create());
    } finally {
        ReferenceCountUtil.release(objects);
    }
}
项目:moonlight-ss    文件:ShadowSocksDecoder.java   
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf in = (ByteBuf) msg;
    if (!readIV) {
        if (in.readableBytes() < ivLength) {
            return;
        } else {
            readIV = true;
            byte[] ivbytes = new byte[ivLength];
            in.readBytes(ivbytes);
            this.decryptCipher = new ShadowSocksCipher(ivbytes, crypto, password, false);
        }
    }
    int length = in.readableBytes();
    if (length > 0) {
        ByteBuf out = ctx.alloc().buffer();
        BytebufCipherUtil.update(decryptCipher, in, out);//update decode
        ctx.fireChannelRead(out);
        ReferenceCountUtil.release(in);
    }
}
项目:milo    文件:ChunkEncoder.java   
private static void encode(
    AbstractEncoder encoder,
    SecureChannel channel,
    long requestId,
    ByteBuf messageBuffer,
    MessageType messageType,
    Callback callback) {

    List<ByteBuf> chunks = new ArrayList<>();

    try {
        encoder.encode(chunks, channel, requestId, messageBuffer, messageType, callback);
    } catch (UaException e) {
        callback.onEncodingError(e);

        chunks.forEach(ReferenceCountUtil::safeRelease);
    }
}
项目:milo    文件:UaTcpServerSymmetricHandler.java   
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    chunkBuffers.forEach(ReferenceCountUtil::safeRelease);
    chunkBuffers.clear();

    if (cause instanceof IOException) {
        ctx.close();
        logger.debug("[remote={}] IOException caught; channel closed");
    } else {
        ErrorMessage errorMessage = ExceptionHandler.sendErrorMessage(ctx, cause);

        if (cause instanceof UaException) {
            logger.debug("[remote={}] UaException caught; sent {}",
                ctx.channel().remoteAddress(), errorMessage, cause);
        } else {
            logger.error("[remote={}] Exception caught; sent {}",
                ctx.channel().remoteAddress(), errorMessage, cause);
        }
    }
}
项目:milo    文件:UaTcpServerAsymmetricHandler.java   
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    chunkBuffers.forEach(ReferenceCountUtil::safeRelease);
    chunkBuffers.clear();

    if (cause instanceof IOException) {
        ctx.close();
        logger.debug("[remote={}] IOException caught; channel closed");
    } else {
        ErrorMessage errorMessage = ExceptionHandler.sendErrorMessage(ctx, cause);

        if (cause instanceof UaException) {
            logger.debug("[remote={}] UaException caught; sent {}",
                ctx.channel().remoteAddress(), errorMessage, cause);
        } else {
            logger.error("[remote={}] Exception caught; sent {}",
                ctx.channel().remoteAddress(), errorMessage, cause);
        }
    }
}
项目:reactor-netty    文件:ChannelOperationsHandler.java   
void discard() {
    for (; ; ) {
        if (pendingWrites == null || pendingWrites.isEmpty()) {
            return;
        }

        ChannelPromise promise;
        Object v = pendingWrites.poll();

        try {
            promise = (ChannelPromise) v;
        }
        catch (Throwable e) {
            ctx.fireExceptionCaught(e);
            return;
        }
        v = pendingWrites.poll();
        if (log.isDebugEnabled()) {
            log.debug("{} Terminated ChannelOperation. Dropping Pending Write: {}",
                    ctx.channel().toString(), v);
        }
        ReferenceCountUtil.release(v);
        promise.tryFailure(new AbortedException("Connection has been closed"));
    }
}
项目:SecureSmartHome    文件:SignerTest.java   
public void testRoundtrip() {
    ByteBuf buf = channel.alloc().buffer();
    for (int c : new int[]{1, 1, 5, 10, 50, 100, 500, 1000, 5000, 10000}) {
        buf.capacity(c);
        while (buf.writableBytes() > 0) {
            buf.writeByte(c);
        }

        channel.writeOutbound(buf.duplicate().retain());
        channel.runPendingTasks();
        for (Object msg; (msg = channel.readOutbound()) != null; ) {
            channel.writeInbound(msg);
        }
        assertEquals(buf, channel.readInbound());
    }
    ReferenceCountUtil.release(buf);
}
项目:SecureSmartHome    文件:CrypterTest.java   
public void testRoundtrip() {
    ByteBuf buf = channel.alloc().buffer();
    for (int c : new int[]{1, 1, 5, 10, 50, 100, 500, 1000, 5000, 10000}) {
        buf.capacity(c);
        while (buf.writableBytes() > 0) {
            buf.writeByte(c);
        }

        channel.writeOutbound(buf.duplicate().retain());
        for (ByteBuf msg; (msg = channel.readOutbound()) != null; ) {
            assertNotSame(buf, msg);
            channel.writeInbound(msg);
        }
        assertEquals(buf, channel.readInbound());
    }
    ReferenceCountUtil.release(buf);
}
项目:reactive-ipc-jvm    文件:ChannelToConnectionBridge.java   
@SuppressWarnings("unchecked")
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (null == conn || null == inputSubscriber) {
        logger.error("No connection input subscriber available. Disposing data.");
        ReferenceCountUtil.release(msg);
        return;
    }

    try {
        inputSubscriber.onNext((R) msg);
    } catch (ClassCastException e) {
        logger.error("Invalid message type read from the pipeline.", e);
        inputSubscriber.onError(e);
    }
}
项目:netty4.0.27Learn    文件:ByteToMessageDecoderTest.java   
/**
 * Verifies that internal buffer of the ByteToMessageDecoder is released once decoder is removed from pipeline. In
 * this case input is read fully.
 */
@Test
public void testInternalBufferClearReadAll() {
    final ByteBuf buf = ReferenceCountUtil.releaseLater(Unpooled.buffer().writeBytes(new byte[]{'a'}));
    EmbeddedChannel channel = new EmbeddedChannel(new ByteToMessageDecoder() {
        @Override
        protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
            ByteBuf byteBuf = internalBuffer();
            Assert.assertEquals(1, byteBuf.refCnt());
            in.readByte();
            // Removal from pipeline should clear internal buffer
            ctx.pipeline().remove(this);
            Assert.assertEquals(0, byteBuf.refCnt());
        }
    });
    Assert.assertFalse(channel.writeInbound(buf));
    Assert.assertFalse(channel.finish());
}
项目:coyote    文件:NettyInboundRoadRunnerMessage.java   
/**
 * Attempt to give the entire trailer to the read callback
 *
 * @param data last chunk of data
 * @return <tt>true</tt> if the callback was updated, <tt>false</tt> otherwise
 */
private boolean doFullRead(ByteBuf data) {
  // not reading the whole buffer at once or we haven't see all the data yet
  if (!readFully || trailerOutstanding > 0) {
    return false;
  }

  LOG.trace("Reading full trailer into callback");

  ByteBuf finalTrailer = buildFullTrailer(trailer, data);
  sendToReader(finalTrailer, true);

  // release all the trailers we've accumulated
  for (ByteBuf buf : trailer) {
    ReferenceCountUtil.release(buf);
  }
  return true;
}
项目:armeria    文件:AbstractStreamMessageDuplicator.java   
private int removeElements() {
    final int removalRequestedOffset = lastRemovalRequestedOffset;
    final int numElementsToBeRemoved = removalRequestedOffset - headOffset;
    final int bitMask = elements.length - 1;
    final int oldHead = head;
    int removedLength = 0;
    for (int numRemovals = 0; numRemovals < numElementsToBeRemoved; numRemovals++) {
        final int index = (oldHead + numRemovals) & bitMask;
        final Object o = elements[index];
        if (!(o instanceof CloseEvent)) {
            removedLength += signalLengthGetter.length(o);
        }
        ReferenceCountUtil.safeRelease(o);
        elements[index] = null;
    }
    head = (oldHead + numElementsToBeRemoved) & bitMask;
    headOffset = removalRequestedOffset;
    size = size - numElementsToBeRemoved;
    return removedLength;
}
项目:bridje-framework    文件:HttpWsSwitch.java   
@Override
protected void decode(ChannelHandlerContext ctx, HttpObject msg, List<Object> out)
{
    if(!added && msg instanceof HttpRequest)
    {
        String path = ((HttpRequest)msg).getUri();
        WsServerHandler handler = findHandler(path);
        if(handler != null)
        {
            ctx.pipeline().addAfter("switch", "aggregator", new HttpObjectAggregator(65536));
            ctx.pipeline().addAfter("aggregator", "wsprotocol", new WebSocketServerProtocolHandler(path, null, true));
            ctx.pipeline().addAfter("wsprotocol", "wshandler", new WsFrameHandler(handler));
            added = true;
        }
    }
    ReferenceCountUtil.retain(msg);
    out.add(msg);
}
项目:netty4.0.27Learn    文件:SpdyFrameDecoderTest.java   
@Test
public void testUnknownSpdyWindowUpdateFrameFlags() throws Exception {
    short type = 9;
    byte flags = (byte) 0xFF; // undefined flags
    int length = 8;
    int streamId = RANDOM.nextInt() & 0x7FFFFFFF;
    int deltaWindowSize = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;

    ByteBuf buf = ReferenceCountUtil.releaseLater(Unpooled.buffer(SPDY_HEADER_SIZE + length));
    encodeControlFrameHeader(buf, type, flags, length);
    buf.writeInt(streamId);
    buf.writeInt(deltaWindowSize);

    delegate.readWindowUpdateFrame(streamId, deltaWindowSize);
    replay(delegate);
    decoder.decode(buf);
    verify(delegate);
    assertFalse(buf.isReadable());
}
项目:ethernet-ip    文件:GetInstanceAttributeListService.java   
@Override
public List<SymbolInstance> decodeResponse(ByteBuf buffer) throws CipResponseException, PartialResponseException {
    MessageRouterResponse response = MessageRouterResponse.decode(buffer);

    int status = response.getGeneralStatus();
    ByteBuf data = response.getData();

    try {
        if (status == 0x00 || status == 0x06) {
            symbols.addAll(decode(data));

            if (status == 0x00) {
                return Lists.newArrayList(symbols);
            } else {
                instanceId = symbols.get(symbols.size() - 1).getInstanceId() + 1;

                throw PartialResponseException.INSTANCE;
            }
        } else {
            throw new CipResponseException(status, response.getAdditionalStatus());
        }
    } finally {
        ReferenceCountUtil.release(data);
    }
}
项目:netty4.0.27Learn    文件:SpdyFrameDecoderTest.java   
@Test
public void testInvalidSpdyWindowUpdateFrameLength() throws Exception {
    short type = 9;
    byte flags = 0;
    int length = 12; // invalid length
    int streamId = RANDOM.nextInt() & 0x7FFFFFFF;
    int deltaWindowSize = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;

    ByteBuf buf = ReferenceCountUtil.releaseLater(Unpooled.buffer(SPDY_HEADER_SIZE + length));
    encodeControlFrameHeader(buf, type, flags, length);
    buf.writeInt(streamId);
    buf.writeInt(deltaWindowSize);

    delegate.readFrameError((String) anyObject());
    replay(delegate);
    decoder.decode(buf);
    verify(delegate);
    assertFalse(buf.isReadable());
}
项目:blynk-server    文件:BaseSimpleChannelInboundHandler.java   
@Override
@SuppressWarnings("unchecked")
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (type.isInstance(msg)) {
        try {
            if (quotaMeter.getOneMinuteRate() > userQuotaLimit) {
                sendErrorResponseIfTicked();
                return;
            }
            quotaMeter.mark();
            messageReceived(ctx, (I) msg);
        } catch (BaseServerException bse) {
            handleBaseServerException(ctx, bse, getMsgId(msg));
        } catch (Exception e) {
            handleGeneralException(ctx, e);
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }
}
项目:jetstream    文件:HttpErrorRequest.java   
public void processRequest() {
    try {
        DefaultHttpServletResponse servletResponse = new DefaultHttpServletResponse(HttpVersion.HTTP_1_1, m_status, 0);
        servletResponse.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");

        try {
            servletResponse.flushBuffer();
            postResponse(m_channel, m_request, servletResponse.toNettyHttpResponse());

        } catch (Throwable e) {
            LOGGER.error( e.getMessage(), e);
        }
    } finally {
        ReferenceCountUtil.release(m_request);
    }
}
项目:blynk-server    文件:StaticFileHandler.java   
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (!(msg instanceof FullHttpRequest)) {
        return;
    }

    FullHttpRequest req = (FullHttpRequest) msg;

    StaticFile staticFile = getStaticPath(req.uri());
    if (staticFile != null) {
        try {
            serveStatic(ctx, req, staticFile);
        } finally {
            ReferenceCountUtil.release(req);
        }
        return;
    }

    ctx.fireChannelRead(req);
}
项目:netty4.0.27Learn    文件:SpdyFrameDecoderTest.java   
@Test
public void testInvalidSpdySettingsFrameLength() throws Exception {
    short type = 4;
    byte flags = 0;
    int numSettings = 2;
    int length = 8 * numSettings + 8; // invalid length
    byte idFlags = 0;
    int id = RANDOM.nextInt() & 0x00FFFFFF;
    int value = RANDOM.nextInt();

    ByteBuf buf = ReferenceCountUtil.releaseLater(Unpooled.buffer(SPDY_HEADER_SIZE + length));
    encodeControlFrameHeader(buf, type, flags, length);
    buf.writeInt(numSettings);
    for (int i = 0; i < numSettings; i++) {
        buf.writeByte(idFlags);
        buf.writeMedium(id);
        buf.writeInt(value);
    }

    delegate.readFrameError((String) anyObject());
    replay(delegate);
    decoder.decode(buf);
    verify(delegate);
    assertFalse(buf.isReadable());
}
项目:netty4.0.27Learn    文件:SpdyFrameDecoderTest.java   
@Test
public void testInvalidSpdyHeadersFrameStreamId() throws Exception {
    short type = 8;
    byte flags = 0;
    int length = 4;
    int streamId = 0; // invalid stream identifier

    ByteBuf buf = ReferenceCountUtil.releaseLater(Unpooled.buffer(SPDY_HEADER_SIZE + length));
    encodeControlFrameHeader(buf, type, flags, length);
    buf.writeInt(streamId);

    delegate.readFrameError((String) anyObject());
    replay(delegate);
    decoder.decode(buf);
    verify(delegate);
    assertFalse(buf.isReadable());
}
项目:netty4.0.27Learn    文件:HttpContentDecoderTest.java   
private void assertHasInboundMessages(EmbeddedChannel channel, boolean hasMessages) {
    Object o;
    if (hasMessages) {
        while (true) {
            o = channel.readInbound();
            assertNotNull(o);
            ReferenceCountUtil.release(o);
            if (o instanceof LastHttpContent) {
                break;
            }
        }
    } else {
        o = channel.readInbound();
        assertNull(o);
    }
}
项目:netty4.0.27Learn    文件:ByteToMessageDecoderTest.java   
/**
 * Verifies that internal buffer of the ByteToMessageDecoder is released once decoder is removed from pipeline. In
 * this case input was not fully read.
 */
@Test
public void testInternalBufferClearReadPartly() {
    final ByteBuf buf = ReferenceCountUtil.releaseLater(Unpooled.buffer().writeBytes(new byte[]{'a', 'b'}));
    EmbeddedChannel channel = new EmbeddedChannel(new ByteToMessageDecoder() {
        @Override
        protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
            ByteBuf byteBuf = internalBuffer();
            Assert.assertEquals(1, byteBuf.refCnt());
            in.readByte();
            // Removal from pipeline should clear internal buffer
            ctx.pipeline().remove(this);
            Assert.assertEquals(0, byteBuf.refCnt());
        }
    });
    Assert.assertTrue(channel.writeInbound(buf));
    Assert.assertTrue(channel.finish());
    Assert.assertEquals(channel.readInbound(), Unpooled.wrappedBuffer(new byte[] {'b'}));
    Assert.assertNull(channel.readInbound());
}
项目:netty4.0.27Learn    文件:ChannelOutboundBuffer.java   
/**
 * Will remove the current message, mark its {@link ChannelPromise} as success and return {@code true}. If no
 * flushed message exists at the time this method is called it will return {@code false} to signal that no more
 * messages are ready to be handled.
 */
public boolean remove() {
    Entry e = flushedEntry;
    if (e == null) {
        return false;
    }
    Object msg = e.msg;

    ChannelPromise promise = e.promise;
    int size = e.pendingSize;

    removeEntry(e);

    if (!e.cancelled) {
        // only release message, notify and decrement if it was not canceled before.
        ReferenceCountUtil.safeRelease(msg);
        safeSuccess(promise);
        decrementPendingOutboundBytes(size, false);
    }

    // recycle the entry
    e.recycle();

    return true;
}
项目:netty4.0.27Learn    文件:SpdyHeaderBlockRawDecoderTest.java   
@Test
public void testOneNameValuePair() throws Exception {
    ByteBuf headerBlock = ReferenceCountUtil.releaseLater(Unpooled.buffer(21));
    headerBlock.writeInt(1);
    headerBlock.writeInt(4);
    headerBlock.writeBytes(nameBytes);
    headerBlock.writeInt(5);
    headerBlock.writeBytes(valueBytes);
    decoder.decode(ByteBufAllocator.DEFAULT, headerBlock, frame);
    decoder.endHeaderBlock(frame);

    assertFalse(headerBlock.isReadable());
    assertFalse(frame.isInvalid());
    assertEquals(1, frame.headers().names().size());
    assertTrue(frame.headers().contains(name));
    assertEquals(1, frame.headers().getAll(name).size());
    assertEquals(value, frame.headers().get(name));
}