Example usage for io.netty.channel.socket SocketChannel attr

List of usage examples for io.netty.channel.socket SocketChannel attr

Introduction

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

Prototype

<T> Attribute<T> attr(AttributeKey<T> key);

Source Link

Document

Get the Attribute for the given AttributeKey .

Usage

From source file:com.chenyang.proxy.http.HttpRemoteForwardChannelInitializer.java

License:Apache License

@Override
public void initChannel(SocketChannel channel) throws Exception {

    channel.attr(HttpConnectionAttribute.ATTRIBUTE_KEY)
            .set(uaChannel.attr(HttpConnectionAttribute.ATTRIBUTE_KEY).get());

    ChannelPipeline pipeline = channel.pipeline();

    // pipeline.addLast("idlestate", new IdleStateHandler(0, 0, 3,
    // TimeUnit.MINUTES));
    // pipeline.addLast("idlehandler", new ProxyIdleHandler());

    pipeline.addLast("codec", new HttpClientCodec());

    pipeline.addLast(HttpRemoteForwardHandler.HANDLER_NAME,
            new HttpRemoteForwardHandler(uaChannel, remoteChannelInactiveCallback));

}

From source file:com.chenyang.proxy.http.HttpTunnelChannelInitializer.java

License:Apache License

/**
 * @see io.netty.channel.ChannelInitializer#initChannel(io.netty.channel.Channel)
 *//*w w w .  ja  v a 2 s .  c o  m*/
@Override
protected void initChannel(SocketChannel channel) throws Exception {
    com.chenyang.proxy.common.HttpRemote apnProxyRemote = uaChannel
            .attr(com.chenyang.proxy.common.HttpConnectionAttribute.ATTRIBUTE_KEY).get().getRemote();

    channel.attr(com.chenyang.proxy.common.HttpConnectionAttribute.ATTRIBUTE_KEY)
            .set(uaChannel.attr(com.chenyang.proxy.common.HttpConnectionAttribute.ATTRIBUTE_KEY).get());

    ChannelPipeline pipeline = channel.pipeline();

    // pipeline.addLast("idlestate", new IdleStateHandler(0, 0, 3,
    // TimeUnit.MINUTES));
    // pipeline.addLast("idlehandler", new ProxyIdleHandler());

    pipeline.addLast(new com.chenyang.proxy.http.HttpRelayHandler(apnProxyRemote.getRemoteAddr() + " --> UA",
            uaChannel));

}

From source file:com.turo.pushy.apns.ApnsChannelFactory.java

License:Open Source License

ApnsChannelFactory(final SslContext sslContext, final ApnsSigningKey signingKey,
        final ProxyHandlerFactory proxyHandlerFactory, final int connectTimeoutMillis,
        final long idlePingIntervalMillis, final long gracefulShutdownTimeoutMillis,
        final Http2FrameLogger frameLogger, final InetSocketAddress apnsServerAddress,
        final EventLoopGroup eventLoopGroup) {

    this.sslContext = sslContext;

    if (this.sslContext instanceof ReferenceCounted) {
        ((ReferenceCounted) this.sslContext).retain();
    }/*from w w  w .  j av a  2  s.c om*/

    this.addressResolverGroup = proxyHandlerFactory == null
            ? new RoundRobinDnsAddressResolverGroup(
                    ClientChannelClassUtil.getDatagramChannelClass(eventLoopGroup),
                    DefaultDnsServerAddressStreamProvider.INSTANCE)
            : NoopAddressResolverGroup.INSTANCE;

    this.bootstrapTemplate = new Bootstrap();
    this.bootstrapTemplate.group(eventLoopGroup);
    this.bootstrapTemplate.option(ChannelOption.TCP_NODELAY, true);
    this.bootstrapTemplate.remoteAddress(apnsServerAddress);
    this.bootstrapTemplate.resolver(this.addressResolverGroup);

    if (connectTimeoutMillis > 0) {
        this.bootstrapTemplate.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMillis);
    }

    this.bootstrapTemplate.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(final SocketChannel channel) {
            final ChannelPipeline pipeline = channel.pipeline();

            if (proxyHandlerFactory != null) {
                pipeline.addFirst(proxyHandlerFactory.createProxyHandler());
            }

            final SslHandler sslHandler = sslContext.newHandler(channel.alloc());

            sslHandler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() {
                @Override
                public void operationComplete(final Future<Channel> handshakeFuture) {
                    if (handshakeFuture.isSuccess()) {
                        final String authority = channel.remoteAddress().getHostName();

                        final ApnsClientHandler.ApnsClientHandlerBuilder clientHandlerBuilder;

                        if (signingKey != null) {
                            clientHandlerBuilder = new TokenAuthenticationApnsClientHandler.TokenAuthenticationApnsClientHandlerBuilder()
                                    .signingKey(signingKey).authority(authority)
                                    .idlePingIntervalMillis(idlePingIntervalMillis);
                        } else {
                            clientHandlerBuilder = new ApnsClientHandler.ApnsClientHandlerBuilder()
                                    .authority(authority).idlePingIntervalMillis(idlePingIntervalMillis);
                        }

                        if (frameLogger != null) {
                            clientHandlerBuilder.frameLogger(frameLogger);
                        }

                        final ApnsClientHandler apnsClientHandler = clientHandlerBuilder.build();

                        if (gracefulShutdownTimeoutMillis > 0) {
                            apnsClientHandler.gracefulShutdownTimeoutMillis(gracefulShutdownTimeoutMillis);
                        }

                        // TODO Use a named constant when https://github.com/netty/netty/pull/8683 is available
                        pipeline.addLast(new FlushConsolidationHandler(256, true));
                        pipeline.addLast(
                                new IdleStateHandler(idlePingIntervalMillis, 0, 0, TimeUnit.MILLISECONDS));
                        pipeline.addLast(apnsClientHandler);
                        pipeline.remove(ConnectionNegotiationErrorHandler.INSTANCE);

                        channel.attr(CHANNEL_READY_PROMISE_ATTRIBUTE_KEY).get().trySuccess(channel);
                    } else {
                        tryFailureAndLogRejectedCause(channel.attr(CHANNEL_READY_PROMISE_ATTRIBUTE_KEY).get(),
                                handshakeFuture.cause());
                    }
                }
            });

            pipeline.addLast(sslHandler);
            pipeline.addLast(ConnectionNegotiationErrorHandler.INSTANCE);
        }
    });
}

From source file:com.vmware.xenon.common.http.netty.NettyHttpClientRequestInitializer.java

License:Open Source License

/**
 * initChannel is called by Netty when a channel is first used.
 *//*from w  ww  .j ava2 s. c  o m*/
@Override
public void initChannel(SocketChannel ch) {
    ChannelPipeline p = ch.pipeline();
    ch.config().setAllocator(NettyChannelContext.ALLOCATOR);
    ch.config().setSendBufferSize(NettyChannelContext.BUFFER_SIZE);
    ch.config().setReceiveBufferSize(NettyChannelContext.BUFFER_SIZE);
    if (this.pool.getSSLContext() != null) {
        if (this.isHttp2Only) {
            throw new IllegalArgumentException("HTTP/2 with SSL is not supported");
        }
        SSLEngine engine = this.pool.getSSLContext().createSSLEngine();
        engine.setUseClientMode(true);
        p.addLast(SSL_HANDLER, new SslHandler(engine));
    }

    HttpClientCodec http1_codec = new HttpClientCodec(NettyChannelContext.MAX_INITIAL_LINE_LENGTH,
            NettyChannelContext.MAX_HEADER_SIZE, NettyChannelContext.MAX_CHUNK_SIZE, false, false);

    // The HttpClientCodec combines the HttpRequestEncoder and the HttpResponseDecoder, and it
    // also provides a method for upgrading the protocol, which we use to support HTTP/2.
    p.addLast(HTTP1_CODEC, http1_codec);

    if (this.isHttp2Only) {
        try {
            NettyHttpToHttp2Handler connectionHandler = makeHttp2ConnectionHandler();
            Http2ClientUpgradeCodec upgradeCodec = new Http2ClientUpgradeCodec(connectionHandler);
            HttpClientUpgradeHandler upgradeHandler = new HttpClientUpgradeHandler(http1_codec, upgradeCodec,
                    this.requestPayloadSizeLimit);

            p.addLast(UPGRADE_HANDLER, upgradeHandler);
            p.addLast(UPGRADE_REQUEST, new UpgradeRequestHandler());

            // This promise will be triggered when we negotiate the settings.
            // That's important because we can't send user data until the negotiation is done
            ChannelPromise settingsPromise = ch.newPromise();
            p.addLast("settings-handler", new Http2SettingsHandler(settingsPromise));
            ch.attr(NettyChannelContext.SETTINGS_PROMISE_KEY).set(settingsPromise);
            p.addLast(EVENT_LOGGER, new NettyHttp2UserEventLogger(this.debugLogging));
        } catch (Throwable ex) {
            Utils.log(NettyHttpClientRequestInitializer.class,
                    NettyHttpClientRequestInitializer.class.getSimpleName(), Level.WARNING,
                    "Channel Initializer exception: %s", ex);
            throw ex;
        }
    } else {
        // The HttpObjectAggregator is not needed for HTTP/2. For HTTP/1.1 it
        // aggregates the HttpMessage and HttpContent into the FullHttpResponse
        p.addLast(AGGREGATOR_HANDLER, new HttpObjectAggregator(this.requestPayloadSizeLimit));
    }
    p.addLast(XENON_HANDLER, new NettyHttpServerResponseHandler(this.pool));
}

From source file:com.xx_dev.apn.proxy.ApnProxyRemoteForwardChannelInitializer.java

License:Apache License

@Override
public void initChannel(SocketChannel channel) throws Exception {

    ApnProxyRemote apnProxyRemote = uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY).get().getRemote();

    channel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY)
            .set(uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY).get());

    ChannelPipeline pipeline = channel.pipeline();

    pipeline.addLast("idlestate", new IdleStateHandler(0, 0, 3, TimeUnit.MINUTES));
    pipeline.addLast("idlehandler", new ApnProxyIdleHandler());

    if (apnProxyRemote.getRemoteListenType() == ApnProxyListenType.SSL) {
        SSLEngine engine = ApnProxySSLContextFactory.createClientSSLEnginForRemoteAddress(
                apnProxyRemote.getRemoteHost(), apnProxyRemote.getRemotePort());
        engine.setUseClientMode(true);/*from   w  w  w .ja va 2 s.c  o  m*/

        pipeline.addLast("ssl", new SslHandler(engine));
    } else if (apnProxyRemote.getRemoteListenType() == ApnProxyListenType.AES) {
        byte[] key = ((ApnProxyAESRemote) apnProxyRemote).getKey();
        byte[] iv = ((ApnProxyAESRemote) apnProxyRemote).getIv();

        pipeline.addLast("apnproxy.encrypt", new ApnProxyAESEncoder(key, iv));
        pipeline.addLast("apnproxy.decrypt", new ApnProxyAESDecoder(key, iv));
    }

    pipeline.addLast("codec", new HttpClientCodec());

    pipeline.addLast(ApnProxyRemoteForwardHandler.HANDLER_NAME,
            new ApnProxyRemoteForwardHandler(uaChannel, remoteChannelInactiveCallback));

}

From source file:com.xx_dev.apn.proxy.ApnProxyTunnelChannelInitializer.java

License:Apache License

/**
 * @see io.netty.channel.ChannelInitializer#initChannel(io.netty.channel.Channel)
 *///from  w  w w  .j  ava  2 s  .  co m
@Override
protected void initChannel(SocketChannel channel) throws Exception {
    ApnProxyRemote apnProxyRemote = uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY).get().getRemote();

    channel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY)
            .set(uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY).get());

    ChannelPipeline pipeline = channel.pipeline();

    pipeline.addLast("idlestate", new IdleStateHandler(0, 0, 3, TimeUnit.MINUTES));
    pipeline.addLast("idlehandler", new ApnProxyIdleHandler());

    if (apnProxyRemote.getRemoteListenType() == ApnProxyListenType.SSL) {
        SSLEngine engine = ApnProxySSLContextFactory.createClientSSLEnginForRemoteAddress(
                apnProxyRemote.getRemoteHost(), apnProxyRemote.getRemotePort());
        engine.setUseClientMode(true);

        pipeline.addLast("ssl", new SslHandler(engine));
    } else if (apnProxyRemote.getRemoteListenType() == ApnProxyListenType.AES) {
        byte[] key = ((ApnProxyAESRemote) apnProxyRemote).getKey();
        byte[] iv = ((ApnProxyAESRemote) apnProxyRemote).getIv();

        pipeline.addLast("apnproxy.encrypt", new ApnProxyAESEncoder(key, iv));
        pipeline.addLast("apnproxy.decrypt", new ApnProxyAESDecoder(key, iv));
    }

    if (apnProxyRemote.getRemoteListenType() == ApnProxyListenType.PLAIN) {
        // nothing to do
    }

    pipeline.addLast(new ApnProxyRelayHandler(apnProxyRemote.getRemoteAddr() + " --> UA", uaChannel));

}

From source file:eu.matejkormuth.rpgdavid.starving.remote.ServerChannelInitializer.java

License:Open Source License

@Override
protected void initChannel0(SocketChannel ch) {
    ch.pipeline().addLast(new DefaultPacketChannelInHandler());
    ch.attr(HANDSHAKED).set(false);
}

From source file:org.kaaproject.kaa.server.transports.http.transport.netty.DefaultHttpServerInitializer.java

License:Apache License

@Override
protected void initChannel(SocketChannel ch) throws Exception {
    final ChannelPipeline p = ch.pipeline();

    final UUID uuid = UUID.randomUUID();

    LOG.info("DefaultServerInitializer Initializing Channel {} connection from {}:{}", uuid,
            ch.remoteAddress().getAddress().toString(), ch.remoteAddress().getPort());

    Attribute<UUID> uuidAttr = ch.attr(AbstractNettyServer.UUID_KEY);
    uuidAttr.set(uuid);//  w  ww .j  av a 2s . c  om

    p.addLast("httpDecoder", new HttpRequestDecoder());
    p.addLast("httpAggregator", new HttpObjectAggregator(getClientMaxBodySize()));
    p.addLast("httpDecoderAux", getRequestDecoder());
    p.addLast("httpEncoder", new HttpResponseEncoder());
    p.addLast("httpEncoderAux", new ResponseEncoder());
    p.addLast("handler", getMainHandler(uuid));
    p.addLast("httpExceptionHandler", new DefaultExceptionHandler());
}

From source file:org.kaaproject.kaa.server.transports.tcp.transport.netty.AbstractKaaTcpServerInitializer.java

License:Apache License

@Override
protected void initChannel(SocketChannel ch) throws Exception {
    final ChannelPipeline p = ch.pipeline();

    final UUID uuid = UUID.randomUUID();

    LOG.debug("KaaTcpServerInitializer Initializing Channel {} connection from {}:{}", uuid,
            ch.remoteAddress().getAddress().toString(), ch.remoteAddress().getPort());

    Attribute<UUID> uuidAttr = ch.attr(AbstractNettyServer.UUID_KEY);
    uuidAttr.set(uuid);//from  ww  w . j a v a2s  . c o  m

    p.addLast("binaryDecoder", new ByteArrayDecoder());
    p.addLast("kaaTcpDecoder", getDecoder());
    p.addLast("binaryEncoder", new ByteArrayEncoder());
    p.addLast("kaaTcpEncoder", new KaaTcpEncoder());
    p.addLast("mainHandler", getMainHandler(uuid));
    p.addLast("kaaTcpExceptionHandler", new KaaTcpExceptionHandler());
}

From source file:sailfish.remoting.channel.AbstractConfigurableExchangeChannelGroup.java

License:Apache License

private ChannelInitializer<SocketChannel> newChannelInitializer(final NegotiateConfig config,
        final ExchangeChannelGroup channelGroup, final EventExecutorGroup executorGroup) {
    return new ChannelInitializer<SocketChannel>() {
        @Override//from w  w w  .  jav  a 2s  . c  o  m
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            ch.attr(ChannelAttrKeys.maxIdleTimeout).set(config.maxIdleTimeout());
            ch.attr(ChannelAttrKeys.channelGroup).set(channelGroup);
            ch.attr(ChannelAttrKeys.clientSide).set(true);
            ch.attr(OneTime.awaitNegotiate).set(new CountDownLatch(1));
            ch.attr(OneTime.channelConfig).set(config);
            // TODO should increase ioRatio when every ChannelHandler bind to executorGroup?
            pipeline.addLast(executorGroup, RemotingEncoder.INSTANCE, new RemotingDecoder(),
                    new IdleStateHandler(config.idleTimeout(), 0, 0), HeartbeatChannelHandler.INSTANCE,
                    NegotiateChannelHandler.INSTANCE, ConcreteRequestHandler.INSTANCE);
        }
    };
}