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.tinkerpop.gremlin.server.handler.HttpBasicAuthenticationHandler.java

License:Apache License

private void sendError(final ChannelHandlerContext ctx, final Object msg) {
    // Close the connection as soon as the error message is sent.
    ctx.writeAndFlush(new DefaultFullHttpResponse(HTTP_1_1, UNAUTHORIZED))
            .addListener(ChannelFutureListener.CLOSE);
    ReferenceCountUtil.release(msg);
}

From source file:org.apache.tinkerpop.gremlin.server.handler.HttpGremlinEndpointHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
    if (msg instanceof FullHttpRequest) {
        final FullHttpRequest req = (FullHttpRequest) msg;

        if ("/favicon.ico".equals(req.getUri())) {
            sendError(ctx, NOT_FOUND, "Gremlin Server doesn't have a favicon.ico");
            ReferenceCountUtil.release(msg);
            return;
        }/*from  ww w  . j  a  v a2  s  . c o  m*/

        if (is100ContinueExpected(req)) {
            ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
        }

        if (req.getMethod() != GET && req.getMethod() != POST) {
            sendError(ctx, METHOD_NOT_ALLOWED, METHOD_NOT_ALLOWED.toString());
            ReferenceCountUtil.release(msg);
            return;
        }

        final Quartet<String, Map<String, Object>, String, Map<String, String>> requestArguments;
        try {
            requestArguments = getRequestArguments(req);
        } catch (IllegalArgumentException iae) {
            sendError(ctx, BAD_REQUEST, iae.getMessage());
            ReferenceCountUtil.release(msg);
            return;
        }

        final String acceptString = Optional.ofNullable(req.headers().get("Accept")).orElse("application/json");
        final Pair<String, MessageTextSerializer> serializer = chooseSerializer(acceptString);
        if (null == serializer) {
            sendError(ctx, BAD_REQUEST,
                    String.format("no serializer for requested Accept header: %s", acceptString));
            ReferenceCountUtil.release(msg);
            return;
        }

        final String origin = req.headers().get(ORIGIN);
        final boolean keepAlive = isKeepAlive(req);

        // not using the req any where below here - assume it is safe to release at this point.
        ReferenceCountUtil.release(msg);

        try {
            logger.debug("Processing request containing script [{}] and bindings of [{}] on {}",
                    requestArguments.getValue0(), requestArguments.getValue1(),
                    Thread.currentThread().getName());
            final ChannelPromise promise = ctx.channel().newPromise();
            final AtomicReference<Object> resultHolder = new AtomicReference<>();
            promise.addListener(future -> {
                // if failed then the error was already written back to the client as part of the eval future
                // processing of the exception
                if (future.isSuccess()) {
                    logger.debug(
                            "Preparing HTTP response for request with script [{}] and bindings of [{}] with result of [{}] on [{}]",
                            requestArguments.getValue0(), requestArguments.getValue1(), resultHolder.get(),
                            Thread.currentThread().getName());
                    final FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK,
                            (ByteBuf) resultHolder.get());
                    response.headers().set(CONTENT_TYPE, serializer.getValue0());
                    response.headers().set(CONTENT_LENGTH, response.content().readableBytes());

                    // handle cors business
                    if (origin != null)
                        response.headers().set(ACCESS_CONTROL_ALLOW_ORIGIN, origin);

                    if (!keepAlive) {
                        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
                    } else {
                        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
                        ctx.writeAndFlush(response);
                    }
                }
            });

            final Timer.Context timerContext = evalOpTimer.time();

            final Bindings bindings;
            try {
                bindings = createBindings(requestArguments.getValue1(), requestArguments.getValue3());
            } catch (IllegalStateException iae) {
                sendError(ctx, BAD_REQUEST, iae.getMessage());
                ReferenceCountUtil.release(msg);
                return;
            }

            // provide a transform function to serialize to message - this will force serialization to occur
            // in the same thread as the eval. after the CompletableFuture is returned from the eval the result
            // is ready to be written as a ByteBuf directly to the response.  nothing should be blocking here.
            final CompletableFuture<Object> evalFuture = gremlinExecutor.eval(requestArguments.getValue0(),
                    requestArguments.getValue2(), bindings, FunctionUtils.wrapFunction(o -> {
                        // stopping the timer here is roughly equivalent to where the timer would have been stopped for
                        // this metric in other contexts.  we just want to measure eval time not serialization time.
                        timerContext.stop();

                        logger.debug(
                                "Transforming result of request with script [{}] and bindings of [{}] with result of [{}] on [{}]",
                                requestArguments.getValue0(), requestArguments.getValue1(), o,
                                Thread.currentThread().getName());
                        final ResponseMessage responseMessage = ResponseMessage.build(UUID.randomUUID())
                                .code(ResponseStatusCode.SUCCESS).result(IteratorUtils.asList(o)).create();

                        // http server is sessionless and must handle commit on transactions. the commit occurs
                        // before serialization to be consistent with how things work for websocket based
                        // communication.  this means that failed serialization does not mean that you won't get
                        // a commit to the database
                        attemptCommit(requestArguments.getValue3(), graphManager,
                                settings.strictTransactionManagement);

                        try {
                            return Unpooled.wrappedBuffer(serializer.getValue1()
                                    .serializeResponseAsString(responseMessage).getBytes(UTF8));
                        } catch (Exception ex) {
                            logger.warn(String.format("Error during serialization for %s", responseMessage),
                                    ex);
                            throw ex;
                        }
                    }));

            evalFuture.exceptionally(t -> {
                if (t.getMessage() != null)
                    sendError(ctx, INTERNAL_SERVER_ERROR, t.getMessage(), Optional.of(t));
                else
                    sendError(ctx, INTERNAL_SERVER_ERROR, String
                            .format("Error encountered evaluating script: %s", requestArguments.getValue0()),
                            Optional.of(t));
                promise.setFailure(t);
                return null;
            });

            evalFuture.thenAcceptAsync(r -> {
                // now that the eval/serialization is done in the same thread - complete the promise so we can
                // write back the HTTP response on the same thread as the original request
                resultHolder.set(r);
                promise.setSuccess();
            }, gremlinExecutor.getExecutorService());
        } catch (Exception ex) {
            // tossed to exceptionCaught which delegates to sendError method
            final Throwable t = ExceptionUtils.getRootCause(ex);
            throw new RuntimeException(null == t ? ex : t);
        }
    }
}

From source file:org.apache.tinkerpop.gremlin.server.handler.IteratorHandler.java

License:Apache License

@Override
public void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise)
        throws Exception {
    if (msg instanceof Pair) {
        try {//from w w  w . j a v a 2 s  .  c  o  m
            final Pair pair = (Pair) msg;
            final Iterator itty = (Iterator) pair.getValue1();
            final RequestMessage requestMessage = (RequestMessage) pair.getValue0();

            // the batch size can be overriden by the request
            final int resultIterationBatchSize = (Integer) requestMessage.optionalArgs(Tokens.ARGS_BATCH_SIZE)
                    .orElse(settings.resultIterationBatchSize);

            // timer for the total serialization time
            final StopWatch stopWatch = new StopWatch();

            final EventExecutorGroup executorService = ctx.executor();
            final Future<?> iteration = executorService.submit((Callable<Void>) () -> {
                logger.debug("Preparing to iterate results from - {} - in thread [{}]", requestMessage,
                        Thread.currentThread().getName());

                stopWatch.start();

                List<Object> aggregate = new ArrayList<>(resultIterationBatchSize);
                while (itty.hasNext()) {
                    aggregate.add(itty.next());

                    // send back a page of results if batch size is met or if it's the end of the results being
                    // iterated
                    if (aggregate.size() == resultIterationBatchSize || !itty.hasNext()) {
                        final ResponseStatusCode code = itty.hasNext() ? ResponseStatusCode.PARTIAL_CONTENT
                                : ResponseStatusCode.SUCCESS;
                        ctx.writeAndFlush(
                                ResponseMessage.build(requestMessage).code(code).result(aggregate).create());
                        aggregate = new ArrayList<>(resultIterationBatchSize);
                    }

                    stopWatch.split();
                    if (stopWatch.getSplitTime() > settings.serializedResponseTimeout)
                        throw new TimeoutException(
                                "Serialization of the entire response exceeded the serializeResponseTimeout setting");

                    stopWatch.unsplit();
                }

                return null;
            });

            iteration.addListener(f -> {
                stopWatch.stop();

                if (!f.isSuccess()) {
                    final String errorMessage = String.format(
                            "Response iteration and serialization exceeded the configured threshold for request [%s] - %s",
                            msg, f.cause().getMessage());
                    logger.warn(errorMessage);
                    ctx.writeAndFlush(
                            ResponseMessage.build(requestMessage).code(ResponseStatusCode.SERVER_ERROR_TIMEOUT)
                                    .statusMessage(errorMessage).create());
                }
            });
        } finally {
            ReferenceCountUtil.release(msg);
        }

    } else {
        ctx.write(msg, promise);
    }
}

From source file:org.apache.tinkerpop.gremlin.server.handler.OpExecutorHandler.java

License:Apache License

@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);/*  w w  w  .java 2s.  c o m*/

    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);
    }
}

From source file:org.apache.zookeeper.server.NettyServerCnxn.java

License:Apache License

/**
 * Clean up queued buffer once it's no longer needed. This should only be
 * called from the event loop thread./* ww w  . j  a  v  a  2  s  . c  o m*/
 */
private void releaseQueuedBuffer() {
    assert channel.eventLoop().inEventLoop();
    if (queuedBuffer != null) {
        ReferenceCountUtil.release(queuedBuffer);
        queuedBuffer = null;
    }
}

From source file:org.asynchttpclient.netty.handler.AsyncHttpClientHandler.java

License:Open Source License

@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {

    Channel channel = ctx.channel();
    Object attribute = Channels.getAttribute(channel);

    try {/* w  w  w  .j av  a2  s .co m*/
        if (attribute instanceof Callback) {
            Callback ac = (Callback) attribute;
            if (msg instanceof LastHttpContent) {
                ac.call();
            } else if (!(msg instanceof HttpContent)) {
                logger.info("Received unexpected message while expecting a chunk: " + msg);
                ac.call();
                Channels.setDiscard(channel);
            }

        } else if (attribute instanceof NettyResponseFuture) {
            NettyResponseFuture<?> future = (NettyResponseFuture<?>) attribute;
            handleRead(channel, future, msg);

        } else if (attribute instanceof StreamedResponsePublisher) {

            StreamedResponsePublisher publisher = (StreamedResponsePublisher) attribute;

            if (msg instanceof HttpContent) {
                ByteBuf content = ((HttpContent) msg).content();
                // Republish as a HttpResponseBodyPart
                if (content.readableBytes() > 0) {
                    HttpResponseBodyPart part = config.getResponseBodyPartFactory().newResponseBodyPart(content,
                            false);
                    ctx.fireChannelRead(part);
                }
                if (msg instanceof LastHttpContent) {
                    // Remove the handler from the pipeline, this will trigger
                    // it to finish
                    ctx.pipeline().remove(publisher);
                    // Trigger a read, just in case the last read complete
                    // triggered no new read
                    ctx.read();
                    // Send the last content on to the protocol, so that it can
                    // conclude the cleanup
                    handleRead(channel, publisher.future(), msg);
                }
            } else {
                logger.info("Received unexpected message while expecting a chunk: " + msg);
                ctx.pipeline().remove(publisher);
                Channels.setDiscard(channel);
            }
        } else if (attribute != DiscardEvent.INSTANCE) {
            // unhandled message
            logger.debug("Orphan channel {} with attribute {} received message {}, closing", channel, attribute,
                    msg);
            Channels.silentlyCloseChannel(channel);
        }
    } finally {
        ReferenceCountUtil.release(msg);
    }
}

From source file:org.bermuda.cartilage.core.ConnectionController.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object message) {
    ByteBuf buffer = (ByteBuf) message;//from  ww  w  .  ja va 2  s .c  o m
    try {
        logger.info("Incoming message : " + buffer.readUnsignedInt());
    } finally {
        ReferenceCountUtil.release(message);
    }
}

From source file:org.dcache.xrootd.core.XrootdAuthenticationHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    /* Pass along any message that is not an xrootd requests.
     *//*from  w  w  w.  java  2  s . c  o  m*/
    if (!(msg instanceof XrootdRequest)) {
        super.channelRead(ctx, msg);
        return;
    }

    XrootdRequest request = (XrootdRequest) msg;
    int reqId = request.getRequestId();

    try {
        switch (reqId) {
        case kXR_login:
            try {
                if (_isInProgress.compareAndSet(false, true)) {
                    try {
                        _state = State.NO_LOGIN;
                        _session = new XrootdSession(_sessionId, ctx.channel(), (LoginRequest) request);
                        request.setSession(_session);
                        doOnLogin(ctx, (LoginRequest) request);
                        _sessions.put(_sessionId, _session);
                    } finally {
                        _isInProgress.set(false);
                    }
                } else {
                    throw new XrootdException(kXR_inProgress, "Login in progress");
                }
            } finally {
                ReferenceCountUtil.release(request);
            }
            break;
        case kXR_auth:
            try {
                if (_isInProgress.compareAndSet(false, true)) {
                    try {
                        switch (_state) {
                        case NO_LOGIN:
                            throw new XrootdException(kXR_NotAuthorized, "Login required");
                        case AUTH:
                            throw new XrootdException(kXR_InvalidRequest, "Already authenticated");
                        }
                        request.setSession(_session);
                        doOnAuthentication(ctx, (AuthenticationRequest) request);
                    } finally {
                        _isInProgress.set(false);
                    }
                } else {
                    throw new XrootdException(kXR_inProgress, "Login in progress");
                }
            } finally {
                ReferenceCountUtil.release(request);
            }
            break;
        case kXR_endsess:
            try {
                switch (_state) {
                case NO_LOGIN:
                    throw new XrootdException(kXR_NotAuthorized, "Login required");
                case NO_AUTH:
                    throw new XrootdException(kXR_NotAuthorized, "Authentication required");
                }
                request.setSession(_session);
                doOnEndSession(ctx, (EndSessionRequest) request);
            } finally {
                ReferenceCountUtil.release(request);
            }
            break;

        case kXR_bind:
        case kXR_protocol:
            request.setSession(_session);
            super.channelRead(ctx, msg);
            break;
        case kXR_ping:
            if (_state == State.NO_LOGIN) {
                ReferenceCountUtil.release(request);
                throw new XrootdException(kXR_NotAuthorized, "Login required");
            }
            request.setSession(_session);
            super.channelRead(ctx, msg);
            break;
        default:
            switch (_state) {
            case NO_LOGIN:
                ReferenceCountUtil.release(request);
                throw new XrootdException(kXR_NotAuthorized, "Login required");
            case NO_AUTH:
                ReferenceCountUtil.release(request);
                throw new XrootdException(kXR_NotAuthorized, "Authentication required");
            }
            request.setSession(_session);
            super.channelRead(ctx, msg);
            break;
        }
    } catch (XrootdException e) {
        ErrorResponse error = new ErrorResponse<>(request, e.getError(), e.getMessage());
        ctx.writeAndFlush(error);
    } catch (RuntimeException e) {
        _log.error(
                "xrootd server error while processing " + msg + " (please report this to support@dcache.org)",
                e);
        ErrorResponse error = new ErrorResponse<>(request, kXR_ServerError,
                String.format("Internal server error (%s)", e.getMessage()));
        ctx.writeAndFlush(error);
    }
}

From source file:org.dcache.xrootd.core.XrootdRequestHandler.java

License:Open Source License

protected void requestReceived(ChannelHandlerContext ctx, XrootdRequest req) {
    try {/* www  .  java  2  s  .  co  m*/
        Object response;
        switch (req.getRequestId()) {
        case kXR_auth:
            response = doOnAuthentication(ctx, (AuthenticationRequest) req);
            break;
        case kXR_login:
            response = doOnLogin(ctx, (LoginRequest) req);
            break;
        case kXR_open:
            response = doOnOpen(ctx, (OpenRequest) req);
            break;
        case kXR_stat:
            response = doOnStat(ctx, (StatRequest) req);
            break;
        case kXR_statx:
            response = doOnStatx(ctx, (StatxRequest) req);
            break;
        case kXR_read:
            response = doOnRead(ctx, (ReadRequest) req);
            break;
        case kXR_readv:
            response = doOnReadV(ctx, (ReadVRequest) req);
            break;
        case kXR_write:
            response = doOnWrite(ctx, (WriteRequest) req);
            break;
        case kXR_sync:
            response = doOnSync(ctx, (SyncRequest) req);
            break;
        case kXR_close:
            response = doOnClose(ctx, (CloseRequest) req);
            break;
        case kXR_protocol:
            response = doOnProtocolRequest(ctx, (ProtocolRequest) req);
            break;
        case kXR_rm:
            response = doOnRm(ctx, (RmRequest) req);
            break;
        case kXR_rmdir:
            response = doOnRmDir(ctx, (RmDirRequest) req);
            break;
        case kXR_mkdir:
            response = doOnMkDir(ctx, (MkDirRequest) req);
            break;
        case kXR_mv:
            response = doOnMv(ctx, (MvRequest) req);
            break;
        case kXR_dirlist:
            response = doOnDirList(ctx, (DirListRequest) req);
            break;
        case kXR_prepare:
            response = doOnPrepare(ctx, (PrepareRequest) req);
            break;
        case kXR_locate:
            response = doOnLocate(ctx, (LocateRequest) req);
            break;
        case kXR_query:
            response = doOnQuery(ctx, (QueryRequest) req);
            break;
        case kXR_set:
            response = doOnSet(ctx, (SetRequest) req);
            break;
        case kXR_endsess:
            response = doOnEndSession(ctx, (EndSessionRequest) req);
            break;
        default:
            response = unsupported(ctx, req);
            break;
        }
        if (response != null) {
            respond(ctx, response);
        } else {
            req = null; // Do not release reference
        }
    } catch (XrootdException e) {
        respond(ctx, withError(req, e.getError(), e.getMessage()));
    } catch (RuntimeException e) {
        _log.error(
                "xrootd server error while processing " + req + " (please report this to support@dcache.org)",
                e);
        respond(ctx,
                withError(req, kXR_ServerError, String.format("Internal server error (%s)", e.getMessage())));
    } finally {
        ReferenceCountUtil.release(req);
    }
}

From source file:org.dcache.xrootd.protocol.messages.AbstractXrootdResponse.java

License:Open Source License

@Override
public void writeTo(ChannelHandlerContext ctx, ChannelPromise promise) {
    int dlen = getDataLength();
    ByteBuf buffer = ctx.alloc().buffer(8 + dlen);
    try {//from  w w  w .  j  a  v a2 s.c o  m
        buffer.writeShort(request.getStreamId());
        buffer.writeShort(stat);
        buffer.writeInt(dlen);
        getBytes(buffer);
    } catch (Error | RuntimeException t) {
        promise.setFailure(t);
        buffer.release();
        return;
    } finally {
        ReferenceCountUtil.release(this);
    }
    ctx.write(buffer, promise);
}