List of usage examples for io.netty.util ReferenceCountUtil release
public static boolean release(Object msg)
From source file:com.bloom.zerofs.rest.NettyMultipartRequest.java
License:Open Source License
/** * {@inheritDoc}// w w w. j a va2s . c om * <p/> * Prepares the request for reading by decoding all the content added via {@link #addContent(HttpContent)}. * @throws RestServiceException if request channel is closed or if the request could not be decoded/prepared. */ @Override public void prepare() throws RestServiceException { if (!isOpen()) { nettyMetrics.multipartRequestAlreadyClosedError.inc(); throw new RestServiceException("Request is closed", RestServiceErrorCode.RequestChannelClosed); } else if (!readyForRead) { // make sure data is held in memory. HttpDataFactory httpDataFactory = new DefaultHttpDataFactory(false); HttpPostMultipartRequestDecoder postRequestDecoder = new HttpPostMultipartRequestDecoder( httpDataFactory, request); try { HttpContent httpContent = rawRequestContents.poll(); while (httpContent != null) { try { // if the request is also an instance of HttpContent, the HttpPostMultipartRequestDecoder does the offer // automatically at the time of construction. We should not add it again. if (httpContent != request) { postRequestDecoder.offer(httpContent); } } finally { ReferenceCountUtil.release(httpContent); } httpContent = rawRequestContents.poll(); } for (InterfaceHttpData part : postRequestDecoder.getBodyHttpDatas()) { processPart(part); } allArgsReadOnly = Collections.unmodifiableMap(allArgs); requestContents.add(LastHttpContent.EMPTY_LAST_CONTENT); readyForRead = true; } catch (HttpPostRequestDecoder.ErrorDataDecoderException e) { nettyMetrics.multipartRequestDecodeError.inc(); throw new RestServiceException("There was an error decoding the request", e, RestServiceErrorCode.MalformedRequest); } finally { postRequestDecoder.destroy(); } } }
From source file:com.bloom.zerofs.rest.NettyRequest.java
License:Open Source License
@Override public void close() { if (channelOpen.compareAndSet(true, false)) { contentLock.lock();//from ww w .j av a2 s. co 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.nioMetricsTracker.markRequestCompleted(); restRequestMetricsTracker.recordMetrics(); if (digestCalculationTimeInMs >= 0) { nettyMetrics.digestCalculationTimeInMs.update(digestCalculationTimeInMs); } if (callbackWrapper != null) { callbackWrapper.invokeCallback(channelException); } } } }
From source file:com.bloom.zerofs.rest.NettyRequest.java
License:Open Source License
@Override public Future<Long> readInto(AsyncWritableChannel asyncWritableChannel, Callback<Long> callback) { ReadIntoCallbackWrapper tempWrapper = new ReadIntoCallbackWrapper(callback); contentLock.lock();// w w w . ja va2s . c om try { if (!isOpen()) { nettyMetrics.requestAlreadyClosedError.inc(); tempWrapper.invokeCallback(new ClosedChannelException()); } else if (writeChannel != null) { throw new IllegalStateException("ReadableStreamChannel cannot be read more than once"); } HttpContent content = requestContents.poll(); while (content != null) { try { writeContent(asyncWritableChannel, tempWrapper, content); } finally { ReferenceCountUtil.release(content); } content = requestContents.poll(); } callbackWrapper = tempWrapper; writeChannel = asyncWritableChannel; } finally { contentLock.unlock(); } return tempWrapper.futureResult; }
From source file:com.bloom.zerofs.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 w w.j a va 2 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++) { if (digest != null) { long startTime = System.currentTimeMillis(); int savedPosition = contentBuffers[i].position(); digest.update(contentBuffers[i]); contentBuffers[i].position(savedPosition); digestCalculationTimeInMs += (System.currentTimeMillis() - startTime); } writeChannel.write(contentBuffers[i], writeCallbacks[i]); } asyncWritesCalled = true; } finally { if (retained && !asyncWritesCalled) { ReferenceCountUtil.release(httpContent); } } allContentReceived = isLast; }
From source file:com.bloom.zerofs.rest.NettyRequest.java
License:Open Source License
/** * Decreases reference counts of content if required, updates the number of bytes read and invokes * {@link ReadIntoCallbackWrapper#invokeCallback(Exception)} if {@code exception} is not {@code null} or if this is * the last piece of content in the request. * @param result The result of the request. This would be non null when the request executed successfully * @param exception The exception that was reported on execution of the request *//*from w w w. j a v a 2s .c o m*/ @Override public void onCompletion(Long result, Exception exception) { if (httpContent != null) { ReferenceCountUtil.release(httpContent); } callbackWrapper.updateBytesRead(result); if (exception != null || isLast) { callbackWrapper.invokeCallback(exception); } }
From source file:com.caocao.nio.server.CustomerInboundHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object o) { Msg msg = (Msg) o;/*from w w w . ja va2 s. com*/ /*switch (msg.cmd) { case MsgProtocol.CMD_HEART_BEAT:// ctx.write(o); break; case MsgProtocol.CMD_CONNECT:// ? if (!channels.containsKey(ctx.channel())) { String[] data = msg.content.split(":", 2); String userId = data[0]; //ctx.channel().pipeline().addLast(new Ch) } break; case MsgProtocol.CMD_RECONNECT:// ? break; case MsgProtocol.CMD_UPDATE_DRIVER_LOCATION:// ??? Driver driver = channels.get(ctx.channel()); String content = msg.content; break; }*/ ReferenceCountUtil.release(o); System.out.println("?:" + msg.toString()); // ctx.write(Unpooled.copiedBuffer("you are ok",CharsetUtil.UTF_8)); }
From source file:com.caricah.iotracah.server.netty.channelgroup.IotChannelGroup.java
License:Apache License
@Override public ChannelGroupFuture write(Object message, ChannelMatcher matcher) { if (message == null) { throw new NullPointerException("message"); }/* w ww .j a v a 2s .c o m*/ if (matcher == null) { throw new NullPointerException("matcher"); } Map<Channel, ChannelFuture> futures = new LinkedHashMap<>(size()); nonServerChannels.values().stream().filter(matcher::matches) .forEach(c -> futures.put(c, c.write(safeDuplicate(message)))); ReferenceCountUtil.release(message); return new IotChannelGroupFuture(this, futures, executor); }
From source file:com.caricah.iotracah.server.netty.channelgroup.IotChannelGroup.java
License:Apache License
@Override public ChannelGroupFuture writeAndFlush(Object message, ChannelMatcher matcher) { if (message == null) { throw new NullPointerException("message"); }/*from ww w . ja v a 2 s .c om*/ Map<Channel, ChannelFuture> futures = new LinkedHashMap<Channel, ChannelFuture>(size()); nonServerChannels.values().stream().filter(matcher::matches) .forEach(c -> futures.put(c, c.writeAndFlush(safeDuplicate(message)))); ReferenceCountUtil.release(message); return new IotChannelGroupFuture(this, futures, executor); }
From source file:com.chen.opensourceframework.netty.copy.DiscardServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { // (2) ByteBuf in = (ByteBuf) msg;//from www . ja v a 2 s.c o m try { while (in.isReadable()) { // (1) System.out.print((char) in.readByte()); System.out.flush(); } } finally { ReferenceCountUtil.release(msg); // (2) } // // System.out.println("?:..."); // ctx.write(msg); // (1) // ctx.flush(); // (2) }
From source file:com.chen.opensourceframework.netty.discard.DiscardServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { // discard/*from ww w . j av a 2 s . c o m*/ ByteBuf in = (ByteBuf) msg; try { while (in.isReadable()) { // (1) System.out.print((char) in.readChar()); System.out.flush(); } } finally { ReferenceCountUtil.release(msg); // (2) } }