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

The following examples show how to use io.netty.util.ReferenceCountUtil#safeRelease() . 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: ProtocolMessageDecoder.java    From herddb with Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf in = (ByteBuf) msg;

    if (LOGGER.isLoggable(Level.FINEST)) {
        StringBuilder dumper = new StringBuilder();
        ByteBufUtil.appendPrettyHexDump(dumper, in);
        LOGGER.log(Level.FINEST, "Received from {}: {}", new Object[]{ctx.channel(), dumper});
    }

    try {
        Pdu pdu = PduCodec.decodePdu(in);
        ctx.fireChannelRead(pdu);
    } catch (Throwable err) {
        LOGGER.log(Level.SEVERE, "Error decoding PDU", err);
        ReferenceCountUtil.safeRelease(msg);
    }

}
 
Example 2
Source File: RSocketResponderHandler.java    From alibaba-rsocket-broker with Apache License 2.0 6 votes vote down vote up
@Override
@NotNull
public Mono<Void> fireAndForget(Payload payload) {
    RSocketCompositeMetadata compositeMetadata = RSocketCompositeMetadata.from(payload.metadata());
    GSVRoutingMetadata routingMetaData = getGsvRoutingMetadata(compositeMetadata);
    if (routingMetaData == null) {
        ReferenceCountUtil.safeRelease(payload);
        return Mono.error(new InvalidException(RsocketErrorCode.message("RST-600404")));
    }
    MessageMimeTypeMetadata dataEncodingMetadata = getDataEncodingMetadata(compositeMetadata);
    if (dataEncodingMetadata == null) {
        ReferenceCountUtil.safeRelease(payload);
        return Mono.error(new InvalidException(RsocketErrorCode.message("RST-700404")));
    }
    Mono<Void> result = localFireAndForget(routingMetaData, dataEncodingMetadata, payload);
    return injectTraceContext(result, compositeMetadata);
}
 
Example 3
Source File: UdpChannel.java    From UdpServerSocketChannel with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected void doWrite(ChannelOutboundBuffer buffer) throws Exception {
	final RecyclableArrayList list = RecyclableArrayList.newInstance();
	boolean freeList = true;
	try {
		ByteBuf buf = null;
		while ((buf = (ByteBuf) buffer.current()) != null) {
			list.add(buf.retain());
			buffer.remove();
		}
		freeList = false;
	} finally {
		if (freeList) {
			for (Object obj : list) {
				ReferenceCountUtil.safeRelease(obj);
			}
			list.recycle();
		}
	}
	serverChannel.doWrite(list, remote);
}
 
Example 4
Source File: RSocketResponderHandler.java    From alibaba-rsocket-broker with Apache License 2.0 6 votes vote down vote up
public Flux<Payload> requestChannel(Payload signal, Publisher<Payload> payloads) {
    RSocketCompositeMetadata compositeMetadata = RSocketCompositeMetadata.from(signal.metadata());
    GSVRoutingMetadata routingMetaData = getGsvRoutingMetadata(compositeMetadata);
    if (routingMetaData == null) {
        ReferenceCountUtil.safeRelease(signal);
        return Flux.error(new InvalidException(RsocketErrorCode.message("RST-600404")));
    }
    MessageMimeTypeMetadata dataEncodingMetadata = getDataEncodingMetadata(compositeMetadata);
    if (dataEncodingMetadata == null) {
        ReferenceCountUtil.safeRelease(signal);
        return Flux.error(new InvalidException(RsocketErrorCode.message("RST-700404")));
    }
    if (payloads instanceof Flux) {
        return localRequestChannel(routingMetaData, dataEncodingMetadata, compositeMetadata.getAcceptMimeTypesMetadata(), signal, ((Flux<Payload>) payloads).skip(1));
    } else {
        return localRequestChannel(routingMetaData, dataEncodingMetadata, compositeMetadata.getAcceptMimeTypesMetadata(), signal, Flux.from(payloads).skip(1));
    }
}
 
Example 5
Source File: PacketDataCodecImpl.java    From ProtocolSupport with GNU Affero General Public License v3.0 5 votes vote down vote up
protected void read0(PacketData<?> packetdata) {
	try {
		packetIdCodec.writeServerBoundPacketId(packetdata);
		transformerDecoderCtx.fireChannelRead(packetdata);
	} catch (Throwable t) {
		ReferenceCountUtil.safeRelease(packetdata);
		throw new EncoderException(t);
	}
}
 
Example 6
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 7
Source File: SpdyHttpDecoder.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    // Release any outstanding messages from the map
    for (Map.Entry<Integer, FullHttpMessage> entry : messageMap.entrySet()) {
        ReferenceCountUtil.safeRelease(entry.getValue());
    }
    messageMap.clear();
    super.channelInactive(ctx);
}
 
Example 8
Source File: ArmeriaServerHttpResponse.java    From armeria with Apache License 2.0 5 votes vote down vote up
private void releaseFirstContent() {
    if (state != PublishingState.FIRST_CONTENT_SENT &&
        firstContent instanceof ReferenceCounted) {
        logger.debug("Releasing the first cached content: {}", firstContent);
        ReferenceCountUtil.safeRelease(firstContent);
    }
}
 
Example 9
Source File: PulsarStats.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Override
public void close() {
    bufferLock.writeLock().lock();
    try {
        ReferenceCountUtil.safeRelease(topicStatsBuf);
        ReferenceCountUtil.safeRelease(tempTopicStatsBuf);
    } finally {
        bufferLock.writeLock().unlock();
    }
}
 
Example 10
Source File: WebsocketPingPongIntegrationTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  if (msg instanceof PongWebSocketFrame) {
    pong.onNext(((PongWebSocketFrame) msg).content().toString(StandardCharsets.UTF_8));
    ReferenceCountUtil.safeRelease(msg);
    ctx.read();
  } else {
    super.channelRead(ctx, msg);
  }
}
 
Example 11
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 12
Source File: RSocketResponderSupport.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
protected Flux<Payload> localRequestStream(GSVRoutingMetadata routing,
                                           MessageMimeTypeMetadata dataEncodingMetadata,
                                           @Nullable MessageAcceptMimeTypesMetadata messageAcceptMimeTypesMetadata,
                                           Payload payload) {
    try {
        ReactiveMethodHandler methodHandler = localServiceCaller.getInvokeMethod(routing.getService(), routing.getMethod());
        if (methodHandler != null) {
            Object result = invokeLocalService(methodHandler, dataEncodingMetadata, payload);
            Flux<Object> fluxResult;
            if (result instanceof Flux) {
                fluxResult = (Flux<Object>) result;
            } else {
                fluxResult = methodHandler.getReactiveAdapter().toFlux(result);
            }
            //composite data for return value
            RSocketMimeType resultEncodingType = resultEncodingType(messageAcceptMimeTypesMetadata, dataEncodingMetadata.getRSocketMimeType(), methodHandler);
            return fluxResult
                    .map(object -> encodingFacade.encodingResult(object, resultEncodingType))
                    .map(dataByteBuf -> ByteBufPayload.create(dataByteBuf, encodingFacade.getDefaultCompositeMetadataByteBuf(resultEncodingType).retainedDuplicate()));
        } else {
            ReferenceCountUtil.safeRelease(payload);
            return Flux.error(new InvalidException(RsocketErrorCode.message("RST-201404", routing.getService(), routing.getMethod())));
        }
    } catch (Exception e) {
        log.error(RsocketErrorCode.message("RST-200500"), e);
        ReferenceCountUtil.safeRelease(payload);
        return Flux.error(new InvalidException(RsocketErrorCode.message("RST-900500", e.getMessage())));
    }
}
 
Example 13
Source File: HttpRequestAggregator.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
protected void onData(HttpData data) {
    if (!trailers.isEmpty()) {
        ReferenceCountUtil.safeRelease(data);
        // Data can't come after trailers.
        // See https://tools.ietf.org/html/rfc7540#section-8.1
        return;
    }
    super.onData(data);
}
 
Example 14
Source File: ReactiveGrpcMethodMetadata.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
public ReactiveGrpcMethodMetadata(Method method, String group, String serviceName, String version) {
    this.serviceName = serviceName;
    this.name = method.getName();
    this.returnType = method.getReturnType();
    this.inferredClassForReturn = getInferredClassForGeneric(method.getGenericReturnType());
    Class<?> parameterType = method.getParameterTypes()[0];
    if (parameterType.isAssignableFrom(Mono.class) && returnType.isAssignableFrom(Mono.class)) {
        this.rpcType = UNARY;
    } else if (parameterType.isAssignableFrom(Mono.class) && returnType.isAssignableFrom(Flux.class)) {
        this.rpcType = SERVER_STREAMING;
    } else if (parameterType.isAssignableFrom(Flux.class) && returnType.isAssignableFrom(Mono.class)) {
        this.rpcType = CLIENT_STREAMING;
    } else if (parameterType.isAssignableFrom(Flux.class) && returnType.isAssignableFrom(Flux.class)) {
        this.rpcType = BIDIRECTIONAL_STREAMING;
    }
    this.serviceId = MurmurHash3.hash32(ServiceLocator.serviceId(group, serviceName, version));
    this.handlerId = MurmurHash3.hash32(serviceName + "." + name);
    GSVRoutingMetadata routingMetadata = new GSVRoutingMetadata(group, serviceName, this.name, version);
    //payload binary routing metadata
    BinaryRoutingMetadata binaryRoutingMetadata = new BinaryRoutingMetadata(this.serviceId, this.handlerId,
            routingMetadata.assembleRoutingKey().getBytes(StandardCharsets.UTF_8));
    //add param encoding
    MessageMimeTypeMetadata messageMimeTypeMetadata = new MessageMimeTypeMetadata(WellKnownMimeType.APPLICATION_PROTOBUF);
    RSocketCompositeMetadata compositeMetadata = RSocketCompositeMetadata.from(routingMetadata, messageMimeTypeMetadata);
    CompositeByteBuf compositeMetadataContent = (CompositeByteBuf) compositeMetadata.getContent();
    //add BinaryRoutingMetadata as first
    compositeMetadataContent.addComponent(true, 0, binaryRoutingMetadata.getHeaderAndContent());
    this.compositeMetadataByteBuf = Unpooled.copiedBuffer(compositeMetadataContent);
    ReferenceCountUtil.safeRelease(compositeMetadataContent);
}
 
Example 15
Source File: RejectionUtils.java    From zuul with Apache License 2.0 5 votes vote down vote up
/**
 * Throttle either by sending rejection response message, or by closing the connection now, or just drop the
 * message. Only call this if ThrottleResult.shouldThrottle() returned {@code true}.
 *
 * @param ctx the channel handler processing the request
 * @param msg the request that is being rejected.
 * @param rejectionType the type of rejection
 * @param nfStatus the status to use for metric reporting
 * @param reason the reason for rejecting the request.  This is not sent back to the client.
 * @param injectedLatencyMillis optional parameter to delay sending a response. The reject notification is still
 *                              sent up the pipeline.
 * @param rejectedCode the HTTP code to send back to the client.
 * @param rejectedBody the HTTP body to be sent back.  It is assumed to be of type text/plain.
 * @param rejectionHeaders additional HTTP headers to add to the rejection response
 */
public static void handleRejection(
        ChannelHandlerContext ctx, Object msg, RejectionType rejectionType, StatusCategory nfStatus, String reason,
        @Nullable Integer injectedLatencyMillis, HttpResponseStatus rejectedCode, String rejectedBody,
        Map<String, String> rejectionHeaders)
        throws Exception {

    boolean shouldDropMessage = false;
    if (rejectionType == RejectionType.REJECT || rejectionType == RejectionType.CLOSE) {
        shouldDropMessage = true;
    }

    boolean shouldRejectNow = false;
    if (rejectionType == RejectionType.REJECT && msg instanceof LastHttpContent) {
        shouldRejectNow = true;
    } else if (rejectionType == RejectionType.CLOSE && msg instanceof HttpRequest) {
        shouldRejectNow = true;
    } else if (rejectionType == RejectionType.ALLOW_THEN_CLOSE && msg instanceof HttpRequest) {
        shouldRejectNow = true;
    }

    if (shouldRejectNow) {
        // Send a rejection response.
        HttpRequest request = msg instanceof HttpRequest ? (HttpRequest) msg : null;
        reject(ctx, rejectionType, nfStatus, reason, request, injectedLatencyMillis, rejectedCode, rejectedBody,
                rejectionHeaders);
    }

    if (shouldDropMessage) {
        ReferenceCountUtil.safeRelease(msg);
    } else {
        ctx.fireChannelRead(msg);
    }
}
 
Example 16
Source File: DefaultStreamMessageDuplicator.java    From armeria with Apache License 2.0 5 votes vote down vote up
void clear() {
    final Object[] oldElements = elements;
    if (oldElements == null) {
        return; // Already cleared.
    }
    elements = null;
    final int t = tail;
    for (int i = head; i < t; i++) {
        ReferenceCountUtil.safeRelease(oldElements[i]);
    }
}
 
Example 17
Source File: ConnectionFactoryImplTest.java    From pravega with Apache License 2.0 5 votes vote down vote up
@After
public void tearDown() throws Exception {
    serverChannel.close().awaitUninterruptibly();
    bossGroup.shutdownGracefully().await();
    workerGroup.shutdownGracefully().await();
    if (sslCtx != null) {
        ReferenceCountUtil.safeRelease(sslCtx);
    }
}
 
Example 18
Source File: GatewayTransportHandler.java    From IOT-Technical-Guide with Apache License 2.0 5 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    try {
        if (msg instanceof MqttMessage) {
            processMqttMsg(ctx,(MqttMessage) msg);
        } else {
            ctx.close();
        }
    } finally {
        ReferenceCountUtil.safeRelease(msg);
    }
}
 
Example 19
Source File: LargeFieldReader.java    From r2dbc-mysql with Apache License 2.0 4 votes vote down vote up
@Override
protected void deallocate() {
    for (ByteBuf buffer : buffers) {
        ReferenceCountUtil.safeRelease(buffer);
    }
}
 
Example 20
Source File: ConsumerImpl.java    From pulsar with Apache License 2.0 4 votes vote down vote up
private ByteBuf processMessageChunk(ByteBuf compressedPayload, MessageMetadata msgMetadata, MessageIdImpl msgId,
        MessageIdData messageId, ClientCnx cnx) {

    // Lazy task scheduling to expire incomplete chunk message
    if (!expireChunkMessageTaskScheduled && expireTimeOfIncompleteChunkedMessageMillis > 0) {
        ((ScheduledExecutorService) listenerExecutor).scheduleAtFixedRate(() -> {
            removeExpireIncompleteChunkedMessages();
        }, expireTimeOfIncompleteChunkedMessageMillis, expireTimeOfIncompleteChunkedMessageMillis,
                TimeUnit.MILLISECONDS);
        expireChunkMessageTaskScheduled = true;
    }
    
    if (msgMetadata.getChunkId() == 0) {
        ByteBuf chunkedMsgBuffer = Unpooled.directBuffer(msgMetadata.getTotalChunkMsgSize(),
                msgMetadata.getTotalChunkMsgSize());
        int totalChunks = msgMetadata.getNumChunksFromMsg();
        chunkedMessagesMap.computeIfAbsent(msgMetadata.getUuid(),
                (key) -> ChunkedMessageCtx.get(totalChunks, chunkedMsgBuffer));
        pendingChunckedMessageCount++;
        if (maxPendingChuckedMessage > 0 && pendingChunckedMessageCount > maxPendingChuckedMessage) {
            removeOldestPendingChunkedMessage();
        }
        pendingChunckedMessageUuidQueue.add(msgMetadata.getUuid());
    }

    ChunkedMessageCtx chunkedMsgCtx = chunkedMessagesMap.get(msgMetadata.getUuid());
    // discard message if chunk is out-of-order
    if (chunkedMsgCtx == null || chunkedMsgCtx.chunkedMsgBuffer == null
            || msgMetadata.getChunkId() != (chunkedMsgCtx.lastChunkedMessageId + 1)
            || msgMetadata.getChunkId() >= msgMetadata.getTotalChunkMsgSize()) {
        // means we lost the first chunk: should never happen
        log.info("Received unexpected chunk messageId {}, last-chunk-id{}, chunkId = {}, total-chunks {}", msgId,
                (chunkedMsgCtx != null ? chunkedMsgCtx.lastChunkedMessageId : null), msgMetadata.getChunkId(),
                msgMetadata.getTotalChunkMsgSize());
        if (chunkedMsgCtx != null) {
            if (chunkedMsgCtx.chunkedMsgBuffer != null) {
                ReferenceCountUtil.safeRelease(chunkedMsgCtx.chunkedMsgBuffer);
            }
            chunkedMsgCtx.recycle();
        }
        chunkedMessagesMap.remove(msgMetadata.getUuid());
        compressedPayload.release();
        increaseAvailablePermits(cnx);
        if (expireTimeOfIncompleteChunkedMessageMillis > 0
                && System.currentTimeMillis() > (msgMetadata.getPublishTime()
                        + expireTimeOfIncompleteChunkedMessageMillis)) {
            doAcknowledge(msgId, AckType.Individual, Collections.emptyMap(), null);
        } else {
            trackMessage(msgId);
        }
        return null;
    }

    chunkedMsgCtx.chunkedMessageIds[msgMetadata.getChunkId()] = msgId;
    // append the chunked payload and update lastChunkedMessage-id
    chunkedMsgCtx.chunkedMsgBuffer.writeBytes(compressedPayload);
    chunkedMsgCtx.lastChunkedMessageId = msgMetadata.getChunkId();

    // if final chunk is not received yet then release payload and return
    if (msgMetadata.getChunkId() != (msgMetadata.getNumChunksFromMsg() - 1)) {
        compressedPayload.release();
        increaseAvailablePermits(cnx);
        return null;
    }

    // last chunk received: so, stitch chunked-messages and clear up chunkedMsgBuffer
    if (log.isDebugEnabled()) {
        log.debug("Chunked message completed chunkId {}, total-chunks {}, msgId {} sequenceId {}",
                msgMetadata.getChunkId(), msgMetadata.getNumChunksFromMsg(), msgId, msgMetadata.getSequenceId());
    }
    // remove buffer from the map, add chucked messageId to unack-message tracker, and reduce pending-chunked-message count
    chunkedMessagesMap.remove(msgMetadata.getUuid());
    unAckedChunckedMessageIdSequenceMap.put(msgId, chunkedMsgCtx.chunkedMessageIds);
    pendingChunckedMessageCount--;
    compressedPayload.release();
    compressedPayload = chunkedMsgCtx.chunkedMsgBuffer;
    chunkedMsgCtx.recycle();
    ByteBuf uncompressedPayload = uncompressPayloadIfNeeded(messageId, msgMetadata, compressedPayload, cnx, false);
    compressedPayload.release();
    return uncompressedPayload;
}