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:com.mastfrog.scamper.InboundBytesDecoder.java

License:Open Source License

@Override
protected void messageReceived(ChannelHandlerContext ctx, ByteBuf sctpMsg) throws Exception {
    assoc.ensureRegistered(ctx);//from   www .  j  a  v a 2s. co  m
    int sctpChannel = ctx.attr(InboundSctpMessageToByteBufDecoder.SCTP_CHANNEL_KEY).get();
    MessageTypeAndBuffer decoded = codec.decode(sctpMsg, ctx, sctpChannel);
    ctx.fireChannelRead(decoded);
}

From source file:com.ning.http.client.providers.netty_4.NettyAsyncHttpProvider.java

License:Apache License

public void close() {
    isClose.set(true);/*  w w  w  .  j a v a2  s . c  o m*/
    try {
        connectionsPool.destroy();
        openChannels.close();

        for (Channel channel : openChannels) {
            ChannelHandlerContext ctx = channel.pipeline().context(NettyAsyncHttpProvider.class);
            if (ctx.attr(DEFAULT_ATTRIBUTE).get() instanceof NettyResponseFuture<?>) {
                NettyResponseFuture<?> future = (NettyResponseFuture<?>) ctx.attr(DEFAULT_ATTRIBUTE).get();
                future.setReaperFuture(null);
            }
        }

        config.executorService().shutdown();
        config.reaper().shutdown();
        if (this.allowReleaseSocketChannelFactory) {
            eventLoop.shutdown();
        }
    } catch (Throwable t) {
        log.warn("Unexpected error on close", t);
    }
}

From source file:com.ning.http.client.providers.netty_4.NettyAsyncHttpProvider.java

License:Apache License

private void finishChannel(final ChannelHandlerContext ctx) {
    ctx.attr(DEFAULT_ATTRIBUTE).set(new DiscardEvent());

    // The channel may have already been removed if a timeout occurred, and this method may be called just after.
    if (ctx.channel() == null) {
        return;//  w ww.  j  a  v a2  s. c o  m
    }

    log.debug("Closing Channel {} ", ctx.channel());

    try {
        ctx.channel().close();
    } catch (Throwable t) {
        log.debug("Error closing a connection", t);
    }

    if (ctx.channel() != null) {
        openChannels.remove(ctx.channel());
    }

}

From source file:com.ning.http.client.providers.netty_4.NettyAsyncHttpProvider.java

License:Apache License

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) throws Exception {
    Channel channel = ctx.channel();
    Throwable cause = e.getCause();
    NettyResponseFuture<?> future = null;

    /** Issue 81//w w  w. j av a 2s . c o  m
    if (e.getCause() != null && e.getCause().getClass().isAssignableFrom(PrematureChannelClosureException.class)) {
    return;
    }
    */
    if (e.getCause() != null
            && e.getCause().getClass().getSimpleName().equals("PrematureChannelClosureException")) {
        return;
    }

    if (log.isDebugEnabled()) {
        log.debug("Unexpected I/O exception on channel {}", channel, cause);
    }

    try {

        if (cause != null && ClosedChannelException.class.isAssignableFrom(cause.getClass())) {
            return;
        }

        if (ctx.attr(DEFAULT_ATTRIBUTE).get() instanceof NettyResponseFuture<?>) {
            future = (NettyResponseFuture<?>) ctx.attr(DEFAULT_ATTRIBUTE).get();
            future.attachChannel(null, false);
            future.touch();

            if (IOException.class.isAssignableFrom(cause.getClass())) {

                if (config.getIOExceptionFilters().size() > 0) {
                    FilterContext<?> fc = new FilterContext.FilterContextBuilder()
                            .asyncHandler(future.getAsyncHandler()).request(future.getRequest())
                            .ioException(new IOException("Channel Closed")).build();
                    fc = handleIoException(fc, future);

                    if (fc.replayRequest()) {
                        replayRequest(future, fc, null, ctx);
                        return;
                    }
                } else {
                    // Close the channel so the recovering can occurs.
                    try {
                        ctx.channel().close();
                    } catch (Throwable t) {
                        ; // Swallow.
                    }
                    return;
                }
            }

            if (abortOnReadCloseException(cause) || abortOnWriteCloseException(cause)) {
                log.debug("Trying to recover from dead Channel: {}", channel);
                return;
            }
        } else if (ctx.attr(DEFAULT_ATTRIBUTE).get() instanceof AsyncCallable) {
            future = ((AsyncCallable) ctx.attr(DEFAULT_ATTRIBUTE).get()).future();
        }
    } catch (Throwable t) {
        cause = t;
    }

    if (future != null) {
        try {
            log.debug("Was unable to recover Future: {}", future);
            abort(future, cause);
        } catch (Throwable t) {
            log.error(t.getMessage(), t);
        }
    }

    Protocol p = (ctx.pipeline().get(HttpClientCodec.class) != null ? httpProtocol : webSocketProtocol);
    p.onError(ctx, e);

    closeChannel(ctx);
    ctx.sendUpstream(e);
}

From source file:com.ning.http.client.providers.netty_4.NettyAsyncHttpProvider.java

License:Apache License

private boolean redirect(Request request, NettyResponseFuture<?> future, HttpResponse response,
        final ChannelHandlerContext ctx) throws Exception {

    int statusCode = response.getStatus().code();
    boolean redirectEnabled = request.isRedirectOverrideSet() ? request.isRedirectEnabled()
            : config.isRedirectEnabled();
    if (redirectEnabled && (statusCode == 302 || statusCode == 301 || statusCode == 303 || statusCode == 307)) {

        if (future.incrementAndGetCurrentRedirectCount() < config.getMaxRedirects()) {
            // We must allow 401 handling again.
            future.getAndSetAuth(false);

            String location = response.headers().get(HttpHeaders.Names.LOCATION);
            URI uri = AsyncHttpProviderUtils.getRedirectUri(future.getURI(), location);
            boolean stripQueryString = config.isRemoveQueryParamOnRedirect();
            if (!uri.toString().equals(future.getURI().toString())) {
                final RequestBuilder nBuilder = stripQueryString
                        ? new RequestBuilder(future.getRequest()).setQueryParameters(null)
                        : new RequestBuilder(future.getRequest());

                if (!(statusCode < 302 || statusCode > 303)
                        && !(statusCode == 302 && config.isStrict302Handling())) {
                    nBuilder.setMethod("GET");
                }/*  w ww.j  a va2 s .com*/
                final boolean initialConnectionKeepAlive = future.isKeepAlive();
                final String initialPoolKey = getPoolKey(future);
                future.setURI(uri);
                String newUrl = uri.toString();
                if (request.getUrl().startsWith(WEBSOCKET)) {
                    newUrl = newUrl.replace(HTTP, WEBSOCKET);
                }

                log.debug("Redirecting to {}", newUrl);
                for (String cookieStr : future.getHttpResponse().headers()
                        .getAll(HttpHeaders.Names.SET_COOKIE)) {
                    Cookie c = AsyncHttpProviderUtils.parseCookie(cookieStr);
                    nBuilder.addOrReplaceCookie(c);
                }

                for (String cookieStr : future.getHttpResponse().headers()
                        .getAll(HttpHeaders.Names.SET_COOKIE2)) {
                    Cookie c = AsyncHttpProviderUtils.parseCookie(cookieStr);
                    nBuilder.addOrReplaceCookie(c);
                }

                AsyncCallable ac = new AsyncCallable(future) {
                    public Object call() throws Exception {
                        if (initialConnectionKeepAlive && ctx.channel().isReadable()
                                && connectionsPool.offer(initialPoolKey, ctx.channel())) {
                            return null;
                        }
                        finishChannel(ctx);
                        return null;
                    }
                };

                if (response.isChunked()) {
                    // We must make sure there is no bytes left before executing the next request.
                    ctx.attr(DEFAULT_ATTRIBUTE).set(ac);
                } else {
                    ac.call();
                }
                nextRequest(nBuilder.setUrl(newUrl).build(), future);
                return true;
            }
        } else {
            throw new MaxRedirectException("Maximum redirect reached: " + config.getMaxRedirects());
        }
    }
    return false;
}

From source file:com.seventh_root.ld33.server.network.LD33ServerHandler.java

License:Apache License

private void sendUnits(ChannelHandlerContext ctx) {
    for (int x = 0; x < server.getWorld().getWidth(); x++) {
        for (int y = 0; y < server.getWorld().getHeight(); y++) {
            Tile tile = server.getWorld().getTileAt(x, y);
            if (tile != null) {
                Unit unit = tile.getUnit();
                if (unit != null) {
                    try {
                        ctx.writeAndFlush(new UnitSpawnClientBoundPacket(unit));
                    } catch (SQLException exception) {
                        server.getLogger().log(SEVERE, "Failed to send unit " + unit.getUUID().toString()
                                + " to " + ctx.attr(PLAYER).get().getName(), exception);
                    }//from w  w  w .  j a v a2  s .c  om
                }
            }
        }
    }
}

From source file:com.tesora.dve.db.mysql.MyLoadDataInfileContext.java

License:Open Source License

public static MyLoadDataInfileContext getOrCreateLoadDataInfileContextFromChannel(ChannelHandlerContext ctx) {
    MyLoadDataInfileContext loadDataInfileCtx = getLoadDataInfileContextFromChannel(ctx);
    if (loadDataInfileCtx == null) {
        loadDataInfileCtx = new MyLoadDataInfileContext();
        ctx.attr(MyLoadDataInfileContext.LOAD_DATA_INFILE_CONTEXT_KEY).set(loadDataInfileCtx);
    }//from   w  ww  .j a v a  2 s  .c o  m
    return loadDataInfileCtx;
}

From source file:com.tesora.dve.db.mysql.MyLoadDataInfileContext.java

License:Open Source License

public static MyLoadDataInfileContext getLoadDataInfileContextFromChannel(ChannelHandlerContext ctx) {
    return ctx.attr(MyLoadDataInfileContext.LOAD_DATA_INFILE_CONTEXT_KEY).get();
}

From source file:com.tesora.dve.db.mysql.MyLoadDataInfileContext.java

License:Open Source License

public static void setLoadDataInfileContextOnChannel(ChannelHandlerContext ctx,
        MyLoadDataInfileContext loadDataInfileCtx) {
    ctx.attr(MyLoadDataInfileContext.LOAD_DATA_INFILE_CONTEXT_KEY).set(loadDataInfileCtx);
}

From source file:com.tesora.dve.db.mysql.MyLoadDataInfileContext.java

License:Open Source License

public MyPrepStmtConnectionContext getOrCreatePrepStmtContextFromChannel(SSConnection ssCon,
        ChannelHandlerContext ctx) {
    MyPrepStmtConnectionContext mpscc = ctx.attr(MyPrepStmtConnectionContext.PSTMT_CONTEXT_KEY).get();

    if (mpscc == null) {
        mpscc = new MyPrepStmtConnectionContext(ssCon);
        ctx.attr(MyPrepStmtConnectionContext.PSTMT_CONTEXT_KEY).set(mpscc);
    }/*  www. j a va 2s.co  m*/

    return mpscc;
}