Example usage for io.netty.channel ChannelHandlerContext attr

List of usage examples for io.netty.channel ChannelHandlerContext attr

Introduction

In this page you can find the example usage for io.netty.channel ChannelHandlerContext attr.

Prototype

@Deprecated
@Override
<T> Attribute<T> attr(AttributeKey<T> key);

Source Link

Usage

From source file:org.restexpress.pipeline.DefaultRequestHandler.java

License:Apache License

private void handleRestExpressException(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    MessageContext context = (MessageContext) ctx.attr(CONTEXT_KEY).get();
    Throwable rootCause = mapServiceException(cause);

    if (rootCause != null) // was/is a ServiceException
    {/*from  w  w  w  . j  a va2 s.co  m*/
        context.setHttpStatus(((ServiceException) rootCause).getHttpStatus());

        if (ServiceException.class.isAssignableFrom(rootCause.getClass())) {
            ((ServiceException) rootCause).augmentResponse(context.getResponse());
        }
    } else {
        rootCause = ExceptionUtils.findRootCause(cause);
        context.setHttpStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
    }

    context.setException(rootCause);
    notifyException(context);
    serializeResponse(context, true);
    invokeFinallyProcessors(finallyProcessors, context.getRequest(), context.getResponse());
    writeResponse(ctx, context);
}

From source file:org.restexpress.pipeline.DefaultRequestHandler.java

License:Apache License

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable throwable) throws Exception {
    try {/*from ww w. j  ava2 s  .c  o  m*/
        MessageContext messageContext = (MessageContext) ctx.attr(CONTEXT_KEY).get();

        if (messageContext != null) {
            messageContext.setException(throwable.getCause() != null ? throwable.getCause() : throwable);
            notifyException(messageContext);
        }
    } catch (Throwable t) {
        System.err.print("DefaultRequestHandler.exceptionCaught() threw an exception.");
        t.printStackTrace();
    } finally {
        ctx.channel().close();
    }
}

From source file:org.restexpress.pipeline.DefaultRequestHandler.java

License:Apache License

private MessageContext createInitialContext(ChannelHandlerContext ctx, FullHttpRequest httpRequest) {
    Request request = createRequest(httpRequest, ctx);
    Response response = createResponse();
    MessageContext context = new MessageContext(request, response);
    ctx.attr(CONTEXT_KEY).set(context);
    return context;
}

From source file:org.skfiy.typhon.net.Netty4EndpointHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    Netty4Session session = new Netty4Session(ctx);
    ctx.attr(SESSION_KEY).set(session);

    super.channelActive(ctx);
}

From source file:org.skfiy.typhon.net.Netty4EndpointHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf buf = (ByteBuf) msg;//  w w w. ja  v  a  2s  .  co m
    Netty4Session session = ctx.attr(SESSION_KEY).get();

    // ?
    session.updateLastAccessedTime();

    // read namespace
    int len = buf.indexOf(0, 32, AbstractSession.NS_SEPARTOR);
    if (len <= 0) {
        return;
    }

    byte[] nsBytes = new byte[len];
    buf.readBytes(nsBytes, 0, nsBytes.length);
    buf.skipBytes(1);
    byte[] dataBytes = new byte[buf.readableBytes()];
    buf.readBytes(dataBytes, 0, dataBytes.length);

    protocolHandler.handle(session, nsBytes, dataBytes);
}

From source file:org.skfiy.typhon.net.Netty4EndpointHandler.java

License:Apache License

private void sendLogout(ChannelHandlerContext ctx) {
    // /*  w ww.j a  va2 s. c om*/
    Netty4Session session = ctx.attr(SESSION_KEY).get();
    if (StringUtils.isNotEmpty(session.getAuthType())) {
        protocolHandler.handle(session, Namespaces.LOGOUT.getBytes(), "{}".getBytes());
    }
}

From source file:org.wso2.carbon.mss.internal.router.RequestRouter.java

License:Open Source License

private boolean handleRequest(HttpRequest httpRequest, Channel channel, ChannelHandlerContext ctx)
        throws HandlerException {
    httpMethodInfoBuilder = httpMethodHandler.getDestinationMethod(httpRequest,
            new BasicHttpResponder(channel, HttpHeaders.isKeepAlive(httpRequest)));
    ctx.attr(AttributeKey.valueOf(METHOD_INFO_BUILDER)).set(httpMethodInfoBuilder);
    return httpMethodInfoBuilder != null;
}

From source file:ratpack.server.internal.NettyHandlerAdapter.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext channelHandlerContext, Object msg) throws Exception {
    if (!(msg instanceof FullHttpRequest)) {
        Action<Object> subscriber = channelHandlerContext.attr(CHANNEL_SUBSCRIBER_ATTRIBUTE_KEY).get();
        if (subscriber != null) {
            subscriber.execute(msg);//from w  w  w  . j  a v  a2s.com
            return;
        }
    }
    super.channelRead(channelHandlerContext, msg);
}

From source file:ratpack.server.internal.NettyHandlerAdapter.java

License:Apache License

public void channelRead0(final ChannelHandlerContext ctx, final FullHttpRequest nettyRequest) throws Exception {
    if (!nettyRequest.decoderResult().isSuccess()) {
        sendError(ctx, HttpResponseStatus.BAD_REQUEST);
        nettyRequest.release();//  w  w w  . j  a v  a2s . c  om
        return;
    }

    final Channel channel = ctx.channel();
    InetSocketAddress remoteAddress = (InetSocketAddress) channel.remoteAddress();
    InetSocketAddress socketAddress = (InetSocketAddress) channel.localAddress();

    final ServerConfig serverConfig = rootRegistry.get(ServerConfig.class);
    final Request request = new DefaultRequest(new NettyHeadersBackedHeaders(nettyRequest.headers()),
            nettyRequest.method(), nettyRequest.uri(), remoteAddress, socketAddress, nettyRequest.content());
    final HttpHeaders nettyHeaders = new DefaultHttpHeaders(false);
    final MutableHeaders responseHeaders = new NettyHeadersBackedMutableHeaders(nettyHeaders);
    final DefaultEventController<RequestOutcome> requestOutcomeEventController = new DefaultEventController<>();
    final AtomicBoolean transmitted = new AtomicBoolean(false);

    final DefaultResponseTransmitter responseTransmitter = new DefaultResponseTransmitter(transmitted,
            execControl, channel, nettyRequest, request, nettyHeaders, requestOutcomeEventController);

    ctx.attr(RESPONSE_TRANSMITTER_ATTRIBUTE_KEY).set(responseTransmitter);

    Action<Action<Object>> subscribeHandler = thing -> {
        transmitted.set(true);
        ctx.attr(CHANNEL_SUBSCRIBER_ATTRIBUTE_KEY).set(thing);
    };

    final DirectChannelAccess directChannelAccess = new DefaultDirectChannelAccess(channel, subscribeHandler);

    final DefaultContext.RequestConstants requestConstants = new DefaultContext.RequestConstants(
            applicationConstants, request, directChannelAccess, requestOutcomeEventController.getRegistry());

    final Response response = new DefaultResponse(execControl, responseHeaders, ctx.alloc(),
            responseTransmitter, requestConstants);
    requestConstants.response = response;

    DefaultContext.start(channel.eventLoop(), execController.getControl(), requestConstants, rootRegistry,
            handlers, execution -> {
                if (!transmitted.get()) {
                    Handler lastHandler = requestConstants.handler;
                    StringBuilder description = new StringBuilder();
                    description.append("No response sent for ").append(request.getMethod().getName())
                            .append(" request to ").append(request.getUri()).append(" (last handler: ");

                    if (lastHandler instanceof DescribingHandler) {
                        ((DescribingHandler) lastHandler).describeTo(description);
                    } else {
                        DescribingHandlers.describeTo(lastHandler, description);
                    }

                    description.append(")");
                    String message = description.toString();
                    LOGGER.warn(message);

                    response.status(500);

                    if (serverConfig.isDevelopment()) {
                        response.send(message);
                    } else {
                        response.send();
                    }
                }
            });
}

From source file:ratpack.server.internal.NettyHandlerAdapter.java

License:Apache License

@Override
public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
    ctx.attr(RESPONSE_TRANSMITTER_ATTRIBUTE_KEY).get().writabilityChanged();
}