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:org.apache.giraph.comm.netty.handler.ResponseClientHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (!(msg instanceof ByteBuf)) {
        throw new IllegalStateException("messageReceived: Got a " + "non-ByteBuf message " + msg);
    }/*from w  w w.  jav a  2 s .  com*/

    ByteBuf buf = (ByteBuf) msg;
    int senderId = -1;
    long requestId = -1;
    int response = -1;
    try {
        senderId = buf.readInt();
        requestId = buf.readLong();
        response = buf.readByte();
    } catch (IndexOutOfBoundsException e) {
        throw new IllegalStateException("channelRead: Got IndexOutOfBoundsException ", e);
    }
    ReferenceCountUtil.release(buf);

    // Simulate a failed response on the first response (if desired)
    if (dropFirstResponse && !ALREADY_DROPPED_FIRST_RESPONSE) {
        LOG.info("messageReceived: Simulating dropped response " + response + " for request " + requestId);
        setAlreadyDroppedFirstResponse();
        synchronized (workerIdOutstandingRequestMap) {
            workerIdOutstandingRequestMap.notifyAll();
        }
        return;
    }

    if (response == 1) {
        LOG.info("messageReceived: Already completed request (taskId = " + senderId + ", requestId = "
                + requestId + ")");
    } else if (response != 0) {
        throw new IllegalStateException("messageReceived: Got illegal response " + response);
    }

    RequestInfo requestInfo = workerIdOutstandingRequestMap.remove(new ClientRequestId(senderId, requestId));
    if (requestInfo == null) {
        LOG.info("messageReceived: Already received response for (taskId = " + senderId + ", requestId = "
                + requestId + ")");
    } else {
        if (LOG.isDebugEnabled()) {
            LOG.debug("messageReceived: Completed (taskId = " + senderId + ")" + requestInfo + ".  Waiting on "
                    + workerIdOutstandingRequestMap.size() + " requests");
        }
    }

    // Help NettyClient#waitSomeRequests() to finish faster
    synchronized (workerIdOutstandingRequestMap) {
        workerIdOutstandingRequestMap.notifyAll();
    }
}

From source file:org.apache.giraph.comm.netty.handler.SaslClientHandler.java

License:Apache License

/**
 * Decode the message read by handler// w ww . j ava  2 s.co m
 *
 * @param ctx channel handler context
 * @param msg message to decode into a writable request
 * @return decoded writablerequest object
 * @throws Exception
 */
protected WritableRequest decode(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (!(msg instanceof ByteBuf)) {
        throw new IllegalStateException("decode: Got illegal message " + msg);
    }
    // Decode msg into an object whose class C implements WritableRequest:
    //  C will be either SaslTokenMessage or SaslComplete.
    //
    // 1. Convert message to a stream that can be decoded.
    ByteBuf buf = (ByteBuf) msg;
    ByteBufInputStream inputStream = new ByteBufInputStream(buf);
    // 2. Get first byte: message type:
    int enumValue = inputStream.readByte();
    RequestType type = RequestType.values()[enumValue];
    if (LOG.isDebugEnabled()) {
        LOG.debug("decode: Got a response of type " + type + " from server:" + ctx.channel().remoteAddress());
    }
    // 3. Create object of the type determined in step 2.
    Class<? extends WritableRequest> writableRequestClass = type.getRequestClass();
    WritableRequest serverResponse = ReflectionUtils.newInstance(writableRequestClass, conf);
    // 4. Deserialize the inputStream's contents into the newly-constructed
    // serverResponse object.
    try {
        serverResponse.readFields(inputStream);
    } catch (IOException e) {
        LOG.error("decode: Exception when trying to read server response: " + e);
    }
    ReferenceCountUtil.release(buf);
    // serverResponse can now be used in the next stage in pipeline.
    return serverResponse;
}

From source file:org.apache.hyracks.http.server.HttpRequestCapacityController.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (overloaded) {
        ReferenceCountUtil.release(msg);
        return;/* www.j a  v  a 2s.c  o  m*/
    }
    if (overloaded()) {
        ReferenceCountUtil.release(msg);
        reject(ctx);
        return;
    } else {
        super.channelRead(ctx, msg);
    }
}

From source file:org.apache.qpid.jms.provider.amqp.AmqpProvider.java

License:Apache License

@Override
public void onData(final ByteBuf input) {

    // We need to retain until the serializer gets around to processing it.
    ReferenceCountUtil.retain(input);//ww w  .j av  a 2 s  .  co  m

    serializer.execute(new Runnable() {

        @Override
        public void run() {
            try {
                if (isTraceBytes()) {
                    TRACE_BYTES.info("Received: {}", ByteBufUtil.hexDump(input));
                }

                ByteBuffer source = input.nioBuffer();

                do {
                    ByteBuffer buffer = protonTransport.getInputBuffer();
                    int limit = Math.min(buffer.remaining(), source.remaining());
                    ByteBuffer duplicate = source.duplicate();
                    duplicate.limit(source.position() + limit);
                    buffer.put(duplicate);
                    protonTransport.processInput().checkIsOk();
                    source.position(source.position() + limit);
                } while (source.hasRemaining());

                ReferenceCountUtil.release(input);

                // Process the state changes from the latest data and then answer back
                // any pending updates to the Broker.
                processUpdates();
                pumpToProtonTransport();
            } catch (Throwable t) {
                LOG.warn("Caught problem during data processing: {}", t.getMessage(), t);

                fireProviderException(t);
            }
        }
    });
}

From source file:org.apache.reef.wake.remote.transport.netty.NettyChannelHandler.java

License:Apache License

/**
 * Handle the incoming message: pass it to the listener.
 *
 * @param ctx the context object for this handler.
 * @param msg the message.//from   w ww . j  a  v a  2 s. c  o m
 * @throws Exception
 */
@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
    //LOG.log(Level.FINEST, "Read {0} {1}", new Object[]{ctx.channel(), msg});
    try {
        this.listener.channelRead(ctx, msg);
    } finally {
        ReferenceCountUtil.release(msg);
    }
}

From source file:org.apache.tajo.rpc.MonitorClientHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (enableMonitor && isPing(msg)) {
        //ignore ping response
        if (LOG.isDebugEnabled()) {
            LOG.debug("received ping " + ctx.channel());
        }//from   w ww .  j a  v  a 2s  .  com
        ReferenceCountUtil.release(msg);
    } else {
        super.channelRead(ctx, msg);
    }
}

From source file:org.apache.tajo.ws.rs.netty.NettyRestHandlerContainer.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    boolean needRelease = true;
    try {/*from ww w. java 2  s .  c o m*/
        if (msg instanceof FullHttpRequest) {
            FullHttpRequest request = (FullHttpRequest) msg;
            messageReceived(ctx, request);
        } else {
            needRelease = false;
            ctx.fireChannelRead(msg);
        }
    } finally {
        if (needRelease) {
            ReferenceCountUtil.release(msg);
        }
    }
}

From source file:org.apache.tinkerpop.gremlin.driver.handler.WebSocketGremlinResponseDecoder.java

License:Apache License

@Override
protected void decode(final ChannelHandlerContext channelHandlerContext, final WebSocketFrame webSocketFrame,
        final List<Object> objects) throws Exception {
    try {/*  w  w  w . j a  v  a2  s  . c  o  m*/
        if (webSocketFrame instanceof BinaryWebSocketFrame) {
            final BinaryWebSocketFrame tf = (BinaryWebSocketFrame) webSocketFrame;
            objects.add(serializer.deserializeResponse(tf.content()));
        } else if (webSocketFrame instanceof TextWebSocketFrame) {
            final TextWebSocketFrame tf = (TextWebSocketFrame) webSocketFrame;
            final MessageTextSerializer textSerializer = (MessageTextSerializer) serializer;
            objects.add(textSerializer.deserializeResponse(tf.text()));
        } else {
            throw new RuntimeException(
                    String.format("WebSocket channel does not handle this type of message: %s",
                            webSocketFrame.getClass().getName()));
        }
    } finally {
        ReferenceCountUtil.release(webSocketFrame);
    }
}

From source file:org.apache.tinkerpop.gremlin.driver.ser.AbstractGraphSONMessageSerializerV1d0.java

License:Apache License

@Override
public ByteBuf serializeResponseAsBinary(final ResponseMessage responseMessage,
        final ByteBufAllocator allocator) throws SerializationException {
    ByteBuf encodedMessage = null;//from  ww w. j  a  v a 2s  . c  o  m
    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);
    }
}

From source file:org.apache.tinkerpop.gremlin.driver.ser.AbstractGraphSONMessageSerializerV1d0.java

License:Apache License

@Override
public ByteBuf serializeRequestAsBinary(final RequestMessage requestMessage, final ByteBufAllocator allocator)
        throws SerializationException {
    ByteBuf encodedMessage = null;// w w w. j av  a  2 s  . c  om
    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);
    }
}