Example usage for io.netty.util ReferenceCountUtil release

List of usage examples for io.netty.util ReferenceCountUtil release

Introduction

In this page you can find the example usage for io.netty.util ReferenceCountUtil release.

Prototype

public static boolean release(Object msg) 

Source Link

Document

Try to call ReferenceCounted#release() if the specified message implements ReferenceCounted .

Usage

From source file:com.github.ambry.frontend.FrontendIntegrationTest.java

License:Open Source License

/**
 * Discards all the content in {@code contents}.
 * @param contents the content to discard.
 * @param expectedDiscardCount the number of {@link HttpObject}s that are expected to discarded.
 *///from  w  w  w . ja  va2 s  .c o m
private void discardContent(Queue<HttpObject> contents, int expectedDiscardCount) {
    assertEquals("Objects that will be discarded differ from expected", expectedDiscardCount, contents.size());
    boolean endMarkerFound = false;
    for (HttpObject object : contents) {
        assertFalse("There should have been no more data after the end marker was found", endMarkerFound);
        endMarkerFound = object instanceof LastHttpContent;
        ReferenceCountUtil.release(object);
    }
    assertTrue("There should have been an end marker", endMarkerFound);
}

From source file:com.github.ambry.rest.NettyRequest.java

License:Open Source License

@Override
public void close() {
    if (channelOpen.compareAndSet(true, false)) {
        contentLock.lock();/*from   w w  w . j  a  v a 2 s .  c o m*/
        try {
            logger.trace("Closing NettyRequest {} with {} content chunks unread", getUri(),
                    requestContents.size());
            // For non-POST we usually have one content chunk unread - this the LastHttpContent chunk. This is OK.
            HttpContent content = requestContents.poll();
            while (content != null) {
                ReferenceCountUtil.release(content);
                content = requestContents.poll();
            }
        } finally {
            contentLock.unlock();
            restRequestMetricsTracker.recordMetrics();
            if (callbackWrapper != null) {
                callbackWrapper.invokeCallback(channelException);
            }
        }
    }
}

From source file:com.github.ambry.rest.NettyRequest.java

License:Open Source License

/**
 * Writes the data in the provided {@code httpContent} to the given {@code writeChannel}.
 * @param writeChannel the {@link AsyncWritableChannel} to write the data of {@code httpContent} to.
 * @param callbackWrapper the {@link ReadIntoCallbackWrapper} for the read operation.
 * @param httpContent the piece of {@link HttpContent} that needs to be written to the {@code writeChannel}.
 *//*from w  ww.  ja va2 s  .c  om*/
protected void writeContent(AsyncWritableChannel writeChannel, ReadIntoCallbackWrapper callbackWrapper,
        HttpContent httpContent) {
    boolean retained = false;
    ByteBuffer[] contentBuffers;
    Callback<Long>[] writeCallbacks;
    // LastHttpContent in the end marker in netty http world.
    boolean isLast = httpContent instanceof LastHttpContent;
    if (httpContent.content().nioBufferCount() > 0) {
        // not a copy.
        httpContent = ReferenceCountUtil.retain(httpContent);
        retained = true;
        contentBuffers = httpContent.content().nioBuffers();
        writeCallbacks = new ContentWriteCallback[contentBuffers.length];
        int i = 0;
        for (; i < contentBuffers.length - 1; i++) {
            writeCallbacks[i] = new ContentWriteCallback(null, false, callbackWrapper);
        }
        writeCallbacks[i] = new ContentWriteCallback(httpContent, isLast, callbackWrapper);
    } else {
        // this will not happen (looking at current implementations of ByteBuf in Netty), but if it does, we cannot avoid
        // a copy (or we can introduce a read(GatheringByteChannel) method in ReadableStreamChannel if required).
        nettyMetrics.contentCopyCount.inc();
        logger.warn("HttpContent had to be copied because ByteBuf did not have a backing ByteBuffer");
        ByteBuffer contentBuffer = ByteBuffer.allocate(httpContent.content().readableBytes());
        httpContent.content().readBytes(contentBuffer);
        // no need to retain httpContent since we have a copy.
        ContentWriteCallback writeCallback = new ContentWriteCallback(null, isLast, callbackWrapper);
        contentBuffers = new ByteBuffer[] { contentBuffer };
        writeCallbacks = new ContentWriteCallback[] { writeCallback };
    }
    boolean asyncWritesCalled = false;
    try {
        for (int i = 0; i < contentBuffers.length; i++) {
            writeChannel.write(contentBuffers[i], writeCallbacks[i]);
        }
        asyncWritesCalled = true;
    } finally {
        if (retained && !asyncWritesCalled) {
            ReferenceCountUtil.release(httpContent);
        }
    }
}

From source file:com.github.sinsinpub.pero.backend.RelayTrafficHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (relayChannel.isActive()) {
        int size = estimatorHandle(relayChannel).size(msg);
        readBytes.addAndGet(size);//w  w  w . j a v a  2s. co m
        relayChannel.writeAndFlush(msg);
    } else {
        ReferenceCountUtil.release(msg);
    }
}

From source file:com.github.sparkfy.network.protocol.MessageWithHeader.java

License:Apache License

@Override
protected void deallocate() {
    header.release();
    ReferenceCountUtil.release(body);
    if (managedBuffer != null) {
        managedBuffer.release();
    }
}

From source file:com.github.vitrifiedcode.javautilities.netty.DiscardServerHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    ByteBuf in = (ByteBuf) msg;/*  w w w.  j ava 2s  .  c o m*/
    try {
        while (in.isReadable()) {
            System.out.print((char) in.readByte());
            System.out.flush();
        }
    } finally {
        ReferenceCountUtil.release(msg);
    }
}

From source file:com.gxkj.demo.netty.socksproxy.RelayHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (relayChannel.isActive()) {
        relayChannel.writeAndFlush(msg);
    } else {//from  w  ww. j a  v a2 s .  co m
        ReferenceCountUtil.release(msg);
    }
}

From source file:com.ibasco.agql.protocols.valve.source.query.handlers.SourceQueryPacketAssembler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    log.trace("SourcePacketHandler.channelRead() : START");

    try {/*from  w w w  . j  ava2 s.  c  om*/
        //Make sure we are only receiving an instance of DatagramPacket
        if (!(msg instanceof DatagramPacket)) {
            return;
        }

        final DatagramPacket packet = (DatagramPacket) msg;
        final ByteBuf data = ((DatagramPacket) msg).content();

        //Verify size
        if (data.readableBytes() <= 5) {
            log.debug(
                    "Not a valid datagram for processing. Size getTotalRequests needs to be at least more than or equal to 5 bytes. Discarding. (Readable Bytes: {})",
                    data.readableBytes());
            return;
        }

        //Try to read protocol header, determine if its a single packet or a split-packet
        int protocolHeader = data.readIntLE();

        //If the packet arrived is single type, we can already forward it to the next handler
        if (protocolHeader == 0xFFFFFFFF) {
            //Pass the message to the succeeding handlers
            ctx.fireChannelRead(packet.retain());
            return;
        }
        //If the packet is a split type...we need to process each succeeding read until we have a complete packet
        else if (protocolHeader == 0xFFFFFFFE) {
            final ByteBuf reassembledPacket = processSplitPackets(data, ctx.channel().alloc(), packet.sender());
            //Check if we already have a reassembled packet
            if (reassembledPacket != null) {
                ctx.fireChannelRead(packet.replace(reassembledPacket));
                return;
            }
        }
        //Packet is not being handled by any of our processors, discard
        else {
            log.debug("Not a valid protocol header. Discarding. (Header Received: Dec = {}, Hex = {})",
                    protocolHeader, Integer.toHexString(protocolHeader));
            return;
        }
    } catch (Exception e) {
        log.error(String.format("Error while processing packet for %s", ((DatagramPacket) msg).sender()), e);
        throw e;
    } finally {
        //Release the message
        ReferenceCountUtil.release(msg);
    }
    log.trace("SourcePacketHandler.channelRead() : END");
}

From source file:com.kingmed.dp.lisclient.demo.DiscardServerHandler.java

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf in = (ByteBuf) msg;/*from   w  w  w . j a  v  a2s  .  com*/
    try {
        while (in.isReadable()) {
            System.out.println((char) in.readByte());
            System.out.flush();
        }
    } finally {
        ReferenceCountUtil.release(msg);
    }
}

From source file:com.linecorp.armeria.client.http.Http1ResponseDecoder.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (!(msg instanceof HttpObject)) {
        ctx.fireChannelRead(msg);//from  www .  ja  va2s  .  c  om
        return;
    }

    try {
        switch (state) {
        case NEED_HEADERS:
            if (msg instanceof HttpResponse) {
                final HttpResponse nettyRes = (HttpResponse) msg;
                final DecoderResult decoderResult = nettyRes.decoderResult();
                if (!decoderResult.isSuccess()) {
                    fail(ctx, new ProtocolViolationException(decoderResult.cause()));
                    return;
                }

                if (!HttpUtil.isKeepAlive(nettyRes)) {
                    disconnectWhenFinished();
                }

                final HttpResponseWrapper res = getResponse(resId);
                assert res != null;
                this.res = res;

                if (nettyRes.status().codeClass() == HttpStatusClass.INFORMATIONAL) {
                    state = State.NEED_INFORMATIONAL_DATA;
                } else {
                    state = State.NEED_DATA_OR_TRAILING_HEADERS;
                    res.scheduleTimeout(ctx);
                }

                res.write(ArmeriaHttpUtil.toArmeria(nettyRes));
            } else {
                failWithUnexpectedMessageType(ctx, msg);
            }
            break;
        case NEED_INFORMATIONAL_DATA:
            if (msg instanceof LastHttpContent) {
                state = State.NEED_HEADERS;
            } else {
                failWithUnexpectedMessageType(ctx, msg);
            }
            break;
        case NEED_DATA_OR_TRAILING_HEADERS:
            if (msg instanceof HttpContent) {
                final HttpContent content = (HttpContent) msg;
                final DecoderResult decoderResult = content.decoderResult();
                if (!decoderResult.isSuccess()) {
                    fail(ctx, new ProtocolViolationException(decoderResult.cause()));
                    return;
                }

                final ByteBuf data = content.content();
                final int dataLength = data.readableBytes();
                if (dataLength > 0) {
                    final long maxContentLength = res.maxContentLength();
                    if (maxContentLength > 0 && res.writtenBytes() > maxContentLength - dataLength) {
                        fail(ctx, ContentTooLargeException.get());
                        return;
                    } else {
                        res.write(HttpData.of(data));
                    }
                }

                if (msg instanceof LastHttpContent) {
                    final HttpResponseWriter res = removeResponse(resId++);
                    assert this.res == res;
                    this.res = null;

                    state = State.NEED_HEADERS;

                    final HttpHeaders trailingHeaders = ((LastHttpContent) msg).trailingHeaders();
                    if (!trailingHeaders.isEmpty()) {
                        res.write(ArmeriaHttpUtil.toArmeria(trailingHeaders));
                    }

                    res.close();

                    if (needsToDisconnect()) {
                        ctx.close();
                    }
                }
            } else {
                failWithUnexpectedMessageType(ctx, msg);
            }
            break;
        case DISCARD:
            break;
        }
    } finally {
        ReferenceCountUtil.release(msg);
    }
}