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.atmosphere.nettosphere.BridgeRuntime.java

License:Apache License

private void handleHttp(final ChannelHandlerContext ctx, final Object messageEvent)
        throws URISyntaxException, IOException {

    boolean skipClose = false;
    AtmosphereResponse response = null;/* w  ww. j  a  va  2 s  . c o m*/
    AtmosphereRequest request = null;
    Action a = null;
    boolean resumeOnBroadcast = false;
    boolean keptOpen = false;
    ChannelWriter asyncWriter = null;
    String method = "GET";
    boolean writeHeader = false;
    boolean forceSuspend = false;
    boolean aggregateBodyInMemory = config.aggregateRequestBodyInMemory();

    try {
        if (messageEvent instanceof HttpRequest) {
            final HttpRequest hrequest = (HttpRequest) messageEvent;

            byte[] body = EMPTY;
            if (FullHttpRequest.class.isAssignableFrom(messageEvent.getClass())) {
                ByteBuf b = FullHttpRequest.class.cast(messageEvent).content();
                if (b.isReadable()) {
                    body = new byte[b.readableBytes()];
                    b.readBytes(body);
                }
            }

            // First let's try to see if it's a static resources
            if (!hrequest.getUri().contains(HeaderConfig.X_ATMOSPHERE)) {
                try {
                    hrequest.headers().add(STATIC_MAPPING, "true");
                    super.channelRead(ctx, messageEvent);

                    if (HttpHeaders.getHeader(hrequest, SERVICED) != null) {
                        return;
                    }
                } catch (Exception e) {
                    logger.debug("Unexpected State", e);
                } finally {
                    hrequest.headers().set(STATIC_MAPPING, "false");
                }
            }

            boolean ka = HttpHeaders.isKeepAlive(hrequest);
            asyncWriter = config.supportChunking() ? new ChunkedWriter(ctx.channel(), true, ka)
                    : new StreamWriter(ctx.channel(), true, ka);

            method = hrequest.getMethod().name();

            request = createAtmosphereRequest(ctx, hrequest, body);
            request.setAttribute(KEEP_ALIVE, new Boolean(ka));

            // Hacky. Is the POST doesn't contains a body, we must not close the connection yet.
            AtmosphereRequestImpl.Body b = request.body();
            if (!aggregateBodyInMemory && !hrequest.getMethod().equals(GET) && !b.isEmpty()
                    && (b.hasString() && b.asString().isEmpty()) || (b.hasBytes() && b.asBytes().length == 0)) {
                forceSuspend = true;
            }
        } else {
            request = State.class.cast(ctx.attr(ATTACHMENT).get()).request;
            boolean isLast = HttpChunkedInput.class.cast(messageEvent).isEndOfInput();
            Boolean ka = (Boolean) request.getAttribute(KEEP_ALIVE);

            asyncWriter = config.supportChunking() ? new ChunkedWriter(ctx.channel(), isLast, ka)
                    : new StreamWriter(ctx.channel(), isLast, ka);
            method = request.getMethod();
            ByteBuf internalBuffer = HttpChunkedInput.class.cast(messageEvent).readChunk(ctx).content();

            if (!aggregateBodyInMemory && internalBuffer.hasArray()) {
                request.body(internalBuffer.array());
            } else {
                logger.trace("Unable to read in memory the request's bytes. Using stream");
                request.body(new ByteBufInputStream(internalBuffer));
            }

            if (!isLast) {
                forceSuspend = true;
            }
        }

        response = new AtmosphereResponseImpl.Builder().asyncIOWriter(asyncWriter).writeHeader(writeHeader)
                .destroyable(false).header("Connection", "Keep-Alive").header("Server", "Nettosphere/3.0")
                .request(request).build();

        if (config.supportChunking()) {
            response.setHeader("Transfer-Encoding", "chunked");
        }

        a = framework.doCometSupport(request, response);
        if (forceSuspend) {
            a.type(Action.TYPE.SUSPEND);
            // leave the stream open
            keptOpen = true;
        }

        String transport = (String) request.getAttribute(FrameworkConfig.TRANSPORT_IN_USE);
        if (transport == null) {
            transport = request.getHeader(X_ATMOSPHERE_TRANSPORT);
        }

        if (a.type() == Action.TYPE.SUSPEND) {
            if (transport != null && (transport.equalsIgnoreCase(HeaderConfig.STREAMING_TRANSPORT)
                    || transport.equalsIgnoreCase(SSE_TRANSPORT))) {
                keptOpen = true;
            } else if (transport != null && (transport.equalsIgnoreCase(HeaderConfig.LONG_POLLING_TRANSPORT)
                    || transport.equalsIgnoreCase(HeaderConfig.JSONP_TRANSPORT))) {
                resumeOnBroadcast = true;
            }
        }

        final Action action = (Action) request.getAttribute(NettyCometSupport.SUSPEND);
        final State state = new State(request, action == null ? Action.CONTINUE : action);

        ctx.attr(ATTACHMENT).set(state);

        if (action != null && action.type() == Action.TYPE.SUSPEND) {
            if (action.timeout() != -1) {
                final AtomicReference<ChannelWriter> w = new AtomicReference<ChannelWriter>(asyncWriter);
                final AtomicReference<Future<?>> f = new AtomicReference<Future<?>>();
                f.set(suspendTimer.scheduleAtFixedRate(new Runnable() {
                    @Override
                    public void run() {
                        if (!w.get().isClosed()
                                && (System.currentTimeMillis() - w.get().lastTick()) > action.timeout()) {
                            AtmosphereResourceImpl impl = state.resource();
                            if (impl != null) {
                                asynchronousProcessor.endRequest(impl, false);
                                f.get().cancel(true);
                            }
                        }
                    }
                }, action.timeout(), action.timeout(), TimeUnit.MILLISECONDS));
            }
        } else if (action != null && action.type() == Action.TYPE.RESUME) {
            resumeOnBroadcast = false;
        }
    } catch (AtmosphereMappingException ex) {
        if (method.equalsIgnoreCase("GET")) {
            logger.trace("Unable to map the request {}, trying static file", messageEvent);
        }
    } catch (Throwable e) {
        logger.error("Unable to process request", e);
        throw new IOException(e);
    } finally {
        try {
            if (asyncWriter != null && !resumeOnBroadcast && !keptOpen) {
                if (!skipClose && response != null) {
                    asyncWriter.close(response);
                } else {
                    httpChannels.add(ctx.channel());
                }
            }
        } finally {
            if (request != null && a != null && a.type() != Action.TYPE.SUSPEND) {
                request.destroy();
                response.destroy();
                framework.notify(Action.TYPE.DESTROYED, request, response);
            }
        }
    }
}

From source file:org.atmosphere.nettosphere.BridgeRuntime.java

License:Apache License

@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    super.channelInactive(ctx);
    Object o = ctx.attr(ATTACHMENT).get();

    if (o == null)
        return;/*from   w  w w. jav  a  2s  . c  o  m*/

    if (WebSocket.class.isAssignableFrom(o.getClass())) {
        NettyWebSocket webSocket = NettyWebSocket.class.cast(o);
        logger.trace("Closing {}", webSocket.uuid());

        try {
            if (webSocket.closeFuture() != null) {
                webSocket.closeFuture().cancel(true);
            }

            webSocketProcessor.close(webSocket, 1005);
        } catch (Exception ex) {
            logger.error("{}", webSocket, ex);
        }
    } else if (State.class.isAssignableFrom(o.getClass())) {
        logger.trace("State {}", o);
        State s = State.class.cast(o);
        if (s.action.type() == Action.TYPE.SUSPEND) {
            asynchronousProcessor.endRequest(s.resource(), true);
        }
    } else {
        logger.error("Invalid state {} and Channel {}", o, ctx.channel());
    }
}

From source file:org.ebayopensource.scc.debug.DebugManager.java

License:Apache License

/**
 * Issue a debug request when debugging is enabled.
 *
 * @param httpObject      Http request of client
 * @param m_ctx           Netty context//w  ww. j  av a  2  s. com
 * @param fromDebugFilter Indicator shows if the request require to be forwarded
 * @return An indicator showing if debug manager consumes the request. If true, the caller needs to stop handling request.
 */
public void issueDebugRequest(FullHttpRequest httpObject, final ChannelHandlerContext m_ctx,
        boolean fromDebugFilter) {
    if (debugEnabled()) {
        final FullHttpRequest request = httpObject.copy();
        if (fromDebugFilter) {
            try {
                if (ssl(request)) {
                    Field field = ClientToProxyConnection.class.getDeclaredField("mitming");
                    field.setAccessible(true);
                    field.set(m_ctx.handler(), true);
                }
            } catch (Exception e) {
                LOGGER.error(e.getMessage());
            }
            String key = m_policyManager.generateCacheKey(request);
            FullHttpResponse cacheResponse = m_policyManager.getCacheManager().get(key);
            CacheResultVerifier verifier = new CacheResultVerifier(key, request, cacheResponse);
            Attribute<CacheResultVerifier> debugging = m_ctx.attr(DEBUG_RESULT);
            debugging.set(verifier);
        } else {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    forwardDebugRequest(request);
                }
            });
        }
    }
}

From source file:org.ebayopensource.scc.debug.DebugManager.java

License:Apache License

/**
 * Process response debug//from   w ww.  j  a  v a 2 s.c  om
 *
 * @param response Response Object
 * @param m_ctx    Netty Context
 * @return Return indicator shows if the response requires handling for debugging. If true, the caller needs to stop handling response
 */
public boolean debugResponse(FullHttpResponse response, ChannelHandlerContext m_ctx) {
    boolean consume = false;
    if (debugEnabled()) {
        Attribute<CacheResultVerifier> debugResult = m_ctx.attr(DEBUG_RESULT);
        if (debugResult.get() != null) {
            try {
                CacheVerifiedResult result = debugResult.get().fetchResult(response);
                m_cacheManager.getStats().addCacheVerifiedResult(result);
            } catch (Exception e) {
                LOGGER.error(e.getMessage());
            } finally {
                consume = true;
            }
        }
    }
    return consume;
}

From source file:org.ebayopensource.scc.debug.DebugManagerTest.java

License:Apache License

@Test
@SuppressWarnings("unchecked")
public void testIssueDebugRequest_fromDebugFilter() {
    Mockito.when(m_appConfiguration.getBoolean("debugManager.debugEnabled")).thenReturn(true);
    FullHttpRequest request = Mockito.mock(FullHttpRequest.class);
    FullHttpResponse cacheResponse = Mockito.mock(FullHttpResponse.class);
    ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class);
    Mockito.when(request.copy()).thenReturn(request);
    Mockito.when(m_cacheManager.get("test_req")).thenReturn(cacheResponse);
    Mockito.when(m_policyManager.generateCacheKey(request)).thenReturn("test_req");

    Attribute<CacheResultVerifier> debugging = Mockito.mock(Attribute.class);
    Mockito.when(ctx.attr(DebugManager.DEBUG_RESULT)).thenReturn(debugging);
    debugManager.issueDebugRequest(request, ctx, true);
    CacheResultVerifier verifier = new CacheResultVerifier("test_req", request, cacheResponse);
    Mockito.verify(debugging, Mockito.times(1)).set(Mockito.refEq(verifier));
}

From source file:org.ebayopensource.scc.debug.DebugManagerTest.java

License:Apache License

@Test
@SuppressWarnings("unchecked")
public void testIssueDebugRequest_sslFromDebugFilter() {
    Mockito.when(m_appConfiguration.getBoolean("debugManager.debugEnabled")).thenReturn(true);
    FullHttpRequest request = Mockito.mock(FullHttpRequest.class);
    FullHttpResponse cacheResponse = Mockito.mock(FullHttpResponse.class);
    ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class);
    Mockito.when(ctx.handler()).thenReturn(clientToProxyConnection);
    Mockito.when(request.copy()).thenReturn(request);
    String key = "https://serverHostAndPort=www.ebay.com:443";
    Mockito.when(m_cacheManager.get(key)).thenReturn(cacheResponse);
    Mockito.when(m_policyManager.generateCacheKey(request)).thenReturn(key);

    Attribute<CacheResultVerifier> debugging = Mockito.mock(Attribute.class);
    Mockito.when(ctx.attr(DebugManager.DEBUG_RESULT)).thenReturn(debugging);
    debugManager.issueDebugRequest(request, ctx, true);
    Assert.assertTrue((Boolean) readField(clientToProxyConnection, "mitming"));
    CacheResultVerifier verifier = new CacheResultVerifier(key, request, cacheResponse);
    Mockito.verify(debugging, Mockito.times(1)).set(Mockito.refEq(verifier));
}

From source file:org.ebayopensource.scc.debug.DebugManagerTest.java

License:Apache License

@Test
@SuppressWarnings("unchecked")
public void testDebugResponse_consume() {
    Mockito.when(m_appConfiguration.getBoolean("debugManager.debugEnabled")).thenReturn(true);
    FullHttpResponse actualResponse = Mockito.mock(FullHttpResponse.class);

    ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class);
    Attribute<CacheResultVerifier> debugging = Mockito.mock(Attribute.class);
    Mockito.when(ctx.attr(DebugManager.DEBUG_RESULT)).thenReturn(debugging);
    CacheResultVerifier verifier = Mockito.mock(CacheResultVerifier.class);
    CacheVerifiedResult result = new CacheVerifiedResult();
    result.key = "test_req";
    Mockito.when(verifier.fetchResult(actualResponse)).thenReturn(result);
    Mockito.when(debugging.get()).thenReturn(verifier);

    CacheStats cacheStats = Mockito.mock(CacheStats.class);
    Mockito.when(m_cacheManager.getStats()).thenReturn(cacheStats);
    debugManager.debugResponse(actualResponse, ctx);
    Mockito.verify(cacheStats, Mockito.times(1)).addCacheVerifiedResult(verifier.fetchResult(actualResponse));
}

From source file:org.ebayopensource.scc.filter.NettyRequestProxyFilter.java

License:Apache License

@Override
public HttpResponse filterRequest(HttpObject reqObject, ChannelHandlerContext reqCtx) {
    if (reqObject instanceof HttpRequest) {
        String uri = ((HttpRequest) reqObject).getUri();
        LOGGER.info("Received a request: " + uri);
        reqCtx.attr(REQUEST_URI).setIfAbsent(uri);
    }/*w  w w  .j a  va 2s.c  om*/

    if (reqObject instanceof FullHttpRequest) {
        FullHttpRequest req = (FullHttpRequest) reqObject;
        if (!isProxyRequest(req)) {
            return handleNonProxyRequest(req);
        }
        boolean isCachable = m_policyManager
                .cacheIsNeededFor(new CacheDecisionObject(req.getUri(), req.getMethod().name()));
        reqCtx.attr(IS_CACHABLE).setIfAbsent(isCachable);
        if (isCachable) {
            String key = m_policyManager.generateCacheKey(req);
            FullHttpResponse response = m_policyManager.getCacheManager().get(key);
            Attribute<String> attr = reqCtx.attr(CACHE_KEY);
            attr.set(key);
            debugRequestInfo(reqObject, key);
            if (response != null) {
                long bSize = 0;
                if (response.headers().contains(HttpHeaders.Names.CONTENT_LENGTH)) {
                    bSize = HttpHeaders.getContentLength(response);
                } else {
                    bSize = response.content().readableBytes();
                }

                if (bSize != 0) {
                    setBufferSizeIfConfigIsSocketChannelConfig(reqCtx.channel().config(), bSize);
                }
                LOGGER.info("HIT CACHE: " + key);
            }
            return response;
        }
    }
    debugRequestInfo(reqObject, null);
    return null;
}

From source file:org.ebayopensource.scc.filter.NettyRequestProxyFilterTest.java

License:Apache License

@Test
public void testFilterRequest() throws IOException {
    AppConfiguration appConfig = new AppConfiguration(new ConfigLoader(), null);
    appConfig.init();/*from  w w w.  j  av  a  2s  .c  o  m*/

    PolicyManager policyManager = mock(PolicyManager.class);
    NettyRequestProxyFilter filter = new NettyRequestProxyFilter(policyManager, appConfig);

    ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
    when(ctx.attr(any(AttributeKey.class))).thenReturn(mock(Attribute.class));
    assertNull(filter.filterRequest(mock(HttpRequest.class), ctx));

    DefaultFullHttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
            "http://test.ebay.com/s/");
    when(policyManager.cacheIsNeededFor(any(CacheDecisionObject.class))).thenReturn(false);
    assertNull(filter.filterRequest(req, ctx));

    when(policyManager.cacheIsNeededFor(any(CacheDecisionObject.class))).thenReturn(true);
    CacheManager cm = mock(CacheManager.class);
    when(policyManager.getCacheManager()).thenReturn(cm);
    assertNull(filter.filterRequest(req, ctx));

    FullHttpResponse resp = mock(FullHttpResponse.class);
    HttpHeaders respHeaders = mock(HttpHeaders.class);
    when(resp.headers()).thenReturn(respHeaders);
    when(respHeaders.get(any(CharSequence.class))).thenReturn("100");
    when(cm.get(anyString())).thenReturn(resp);
    Channel channel = mock(Channel.class);
    SocketChannelConfig config = mock(SocketChannelConfig.class);
    when(channel.config()).thenReturn(config);
    when(ctx.channel()).thenReturn(channel);
    req.headers().add("h1", "v1");

    when(resp.content()).thenReturn(new EmptyByteBuf(new PooledByteBufAllocator()))
            .thenReturn(Unpooled.copiedBuffer("Hello".getBytes()));
    assertEquals(resp, filter.filterRequest(req, ctx));
    assertEquals(resp, filter.filterRequest(req, ctx));
}

From source file:org.ebayopensource.scc.filter.NettyRequestProxyFilterTest.java

License:Apache License

@Test
public void testHandleNonProxyRequest() throws IOException {
    AppConfiguration appConfig = new AppConfiguration(new ConfigLoader(), null);
    appConfig.init();/*from   w  w w  .  j  a v a2  s  .  co  m*/
    PolicyManager policyManager = mock(PolicyManager.class);
    NettyRequestProxyFilter filter = new NettyRequestProxyFilter(policyManager, appConfig);

    ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
    when(ctx.attr(any(AttributeKey.class))).thenReturn(mock(Attribute.class));
    assertNull(filter.filterRequest(mock(HttpRequest.class), ctx));

    DefaultFullHttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/version");
    HttpHeaders.setHost(req, "localhost:32876");

    HttpResponse resp = filter.filterRequest(req, ctx);
    assertTrue(resp instanceof FullHttpResponse);
    FullHttpResponse response = (FullHttpResponse) resp;
    assertEquals("application/json", response.headers().get(HttpHeaders.Names.CONTENT_TYPE));
    assertTrue(HttpHeaders.getContentLength(response) > 0);
    assertEquals(HttpResponseStatus.OK, response.getStatus());

    req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/version");
    HttpHeaders.setHost(req, "127.0.0.1:32876");

    resp = filter.filterRequest(req, ctx);
    assertTrue(resp instanceof FullHttpResponse);
    response = (FullHttpResponse) resp;
    assertEquals(HttpResponseStatus.NOT_FOUND, response.getStatus());
    assertEquals(0, HttpHeaders.getContentLength(response));

    req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/NOTFOUND");
    HttpHeaders.setHost(req, "127.0.0.1:32876");

    resp = filter.filterRequest(req, ctx);
    assertTrue(resp instanceof FullHttpResponse);
    response = (FullHttpResponse) resp;
    assertEquals(HttpResponseStatus.NOT_FOUND, response.getStatus());
    assertEquals(0, HttpHeaders.getContentLength(response));
}