Example usage for io.netty.channel ChannelOption CONNECT_TIMEOUT_MILLIS

List of usage examples for io.netty.channel ChannelOption CONNECT_TIMEOUT_MILLIS

Introduction

In this page you can find the example usage for io.netty.channel ChannelOption CONNECT_TIMEOUT_MILLIS.

Prototype

ChannelOption CONNECT_TIMEOUT_MILLIS

To view the source code for io.netty.channel ChannelOption CONNECT_TIMEOUT_MILLIS.

Click Source Link

Usage

From source file:org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnector.java

License:Apache License

public synchronized void start() {
    if (channelClazz != null) {
        return;/*  ww  w .  ja  v  a2  s .c om*/
    }

    int threadsToUse;

    if (nioRemotingThreads == -1) {
        // Default to number of cores * 3

        threadsToUse = Runtime.getRuntime().availableProcessors() * 3;
    } else {
        threadsToUse = this.nioRemotingThreads;
    }

    if (useNioGlobalWorkerPool) {
        channelClazz = NioSocketChannel.class;
        group = SharedNioEventLoopGroup.getInstance(threadsToUse);
    } else {
        channelClazz = NioSocketChannel.class;
        group = new NioEventLoopGroup(threadsToUse);
    }
    // if we are a servlet wrap the socketChannelFactory

    bootstrap = new Bootstrap();
    bootstrap.channel(channelClazz);
    bootstrap.group(group);

    bootstrap.option(ChannelOption.TCP_NODELAY, tcpNoDelay);

    if (connectTimeoutMillis != -1) {
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMillis);
    }
    if (tcpReceiveBufferSize != -1) {
        bootstrap.option(ChannelOption.SO_RCVBUF, tcpReceiveBufferSize);
    }
    if (tcpSendBufferSize != -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, tcpSendBufferSize);
    }
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    bootstrap.option(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);
    channelGroup = new DefaultChannelGroup("activemq-connector", GlobalEventExecutor.INSTANCE);

    final SSLContext context;
    if (sslEnabled) {
        try {
            // HORNETQ-680 - override the server-side config if client-side system properties are set
            String realKeyStorePath = keyStorePath;
            String realKeyStoreProvider = keyStoreProvider;
            String realKeyStorePassword = keyStorePassword;
            if (System.getProperty(JAVAX_KEYSTORE_PATH_PROP_NAME) != null) {
                realKeyStorePath = System.getProperty(JAVAX_KEYSTORE_PATH_PROP_NAME);
            }
            if (System.getProperty(JAVAX_KEYSTORE_PASSWORD_PROP_NAME) != null) {
                realKeyStorePassword = System.getProperty(JAVAX_KEYSTORE_PASSWORD_PROP_NAME);
            }

            if (System.getProperty(ACTIVEMQ_KEYSTORE_PROVIDER_PROP_NAME) != null) {
                realKeyStoreProvider = System.getProperty(ACTIVEMQ_KEYSTORE_PROVIDER_PROP_NAME);
            }
            if (System.getProperty(ACTIVEMQ_KEYSTORE_PATH_PROP_NAME) != null) {
                realKeyStorePath = System.getProperty(ACTIVEMQ_KEYSTORE_PATH_PROP_NAME);
            }
            if (System.getProperty(ACTIVEMQ_KEYSTORE_PASSWORD_PROP_NAME) != null) {
                realKeyStorePassword = System.getProperty(ACTIVEMQ_KEYSTORE_PASSWORD_PROP_NAME);
            }

            String realTrustStorePath = trustStorePath;
            String realTrustStoreProvider = trustStoreProvider;
            String realTrustStorePassword = trustStorePassword;
            if (System.getProperty(JAVAX_TRUSTSTORE_PATH_PROP_NAME) != null) {
                realTrustStorePath = System.getProperty(JAVAX_TRUSTSTORE_PATH_PROP_NAME);
            }
            if (System.getProperty(JAVAX_TRUSTSTORE_PASSWORD_PROP_NAME) != null) {
                realTrustStorePassword = System.getProperty(JAVAX_TRUSTSTORE_PASSWORD_PROP_NAME);
            }

            if (System.getProperty(ACTIVEMQ_TRUSTSTORE_PROVIDER_PROP_NAME) != null) {
                realTrustStoreProvider = System.getProperty(ACTIVEMQ_TRUSTSTORE_PROVIDER_PROP_NAME);
            }
            if (System.getProperty(ACTIVEMQ_TRUSTSTORE_PATH_PROP_NAME) != null) {
                realTrustStorePath = System.getProperty(ACTIVEMQ_TRUSTSTORE_PATH_PROP_NAME);
            }
            if (System.getProperty(ACTIVEMQ_TRUSTSTORE_PASSWORD_PROP_NAME) != null) {
                realTrustStorePassword = System.getProperty(ACTIVEMQ_TRUSTSTORE_PASSWORD_PROP_NAME);
            }
            context = SSLSupport.createContext(realKeyStoreProvider, realKeyStorePath, realKeyStorePassword,
                    realTrustStoreProvider, realTrustStorePath, realTrustStorePassword);
        } catch (Exception e) {
            close();
            IllegalStateException ise = new IllegalStateException(
                    "Unable to create NettyConnector for " + host + ":" + port);
            ise.initCause(e);
            throw ise;
        }
    } else {
        context = null; // Unused
    }

    if (context != null && useServlet) {
        // TODO: Fix me
        //bootstrap.setOption("sslContext", context);
    }

    bootstrap.handler(new ChannelInitializer<Channel>() {
        public void initChannel(Channel channel) throws Exception {
            final ChannelPipeline pipeline = channel.pipeline();
            if (sslEnabled && !useServlet) {
                SSLEngine engine = context.createSSLEngine();

                engine.setUseClientMode(true);

                engine.setWantClientAuth(true);

                // setting the enabled cipher suites resets the enabled protocols so we need
                // to save the enabled protocols so that after the customer cipher suite is enabled
                // we can reset the enabled protocols if a customer protocol isn't specified
                String[] originalProtocols = engine.getEnabledProtocols();

                if (enabledCipherSuites != null) {
                    try {
                        engine.setEnabledCipherSuites(
                                SSLSupport.parseCommaSeparatedListIntoArray(enabledCipherSuites));
                    } catch (IllegalArgumentException e) {
                        ActiveMQClientLogger.LOGGER.invalidCipherSuite(SSLSupport
                                .parseArrayIntoCommandSeparatedList(engine.getSupportedCipherSuites()));
                        throw e;
                    }
                }

                if (enabledProtocols != null) {
                    try {
                        engine.setEnabledProtocols(
                                SSLSupport.parseCommaSeparatedListIntoArray(enabledProtocols));
                    } catch (IllegalArgumentException e) {
                        ActiveMQClientLogger.LOGGER.invalidProtocol(
                                SSLSupport.parseArrayIntoCommandSeparatedList(engine.getSupportedProtocols()));
                        throw e;
                    }
                } else {
                    engine.setEnabledProtocols(originalProtocols);
                }

                SslHandler handler = new SslHandler(engine);

                pipeline.addLast(handler);
            }

            if (httpEnabled) {
                pipeline.addLast(new HttpRequestEncoder());

                pipeline.addLast(new HttpResponseDecoder());

                pipeline.addLast(new HttpObjectAggregator(Integer.MAX_VALUE));

                pipeline.addLast(new HttpHandler());
            }

            if (httpUpgradeEnabled) {
                // prepare to handle a HTTP 101 response to upgrade the protocol.
                final HttpClientCodec httpClientCodec = new HttpClientCodec();
                pipeline.addLast(httpClientCodec);
                pipeline.addLast("http-upgrade", new HttpUpgradeHandler(pipeline, httpClientCodec));
            }

            protocolManager.addChannelHandlers(pipeline);

            pipeline.addLast(new ActiveMQClientChannelHandler(channelGroup, handler, new Listener()));
        }
    });

    if (batchDelay > 0) {
        flusher = new BatchFlusher();

        batchFlusherFuture = scheduledThreadPool.scheduleWithFixedDelay(flusher, batchDelay, batchDelay,
                TimeUnit.MILLISECONDS);
    }

    ActiveMQClientLogger.LOGGER.debug("Started Netty Connector version " + TransportConstants.NETTY_VERSION);
}

From source file:org.apache.activemq.core.remoting.impl.netty.NettyConnector.java

License:Apache License

public synchronized void start() {
    if (channelClazz != null) {
        return;/*w  w  w .  ja v  a2 s .c o m*/
    }

    int threadsToUse;

    if (nioRemotingThreads == -1) {
        // Default to number of cores * 3

        threadsToUse = Runtime.getRuntime().availableProcessors() * 3;
    } else {
        threadsToUse = this.nioRemotingThreads;
    }

    if (useNioGlobalWorkerPool) {
        channelClazz = NioSocketChannel.class;
        group = SharedNioEventLoopGroup.getInstance(threadsToUse);
    } else {
        channelClazz = NioSocketChannel.class;
        group = new NioEventLoopGroup(threadsToUse);
    }
    // if we are a servlet wrap the socketChannelFactory

    bootstrap = new Bootstrap();
    bootstrap.channel(channelClazz);
    bootstrap.group(group);

    bootstrap.option(ChannelOption.TCP_NODELAY, tcpNoDelay);

    if (connectTimeoutMillis != -1) {
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMillis);
    }
    if (tcpReceiveBufferSize != -1) {
        bootstrap.option(ChannelOption.SO_RCVBUF, tcpReceiveBufferSize);
    }
    if (tcpSendBufferSize != -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, tcpSendBufferSize);
    }
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    bootstrap.option(ChannelOption.ALLOCATOR, new UnpooledByteBufAllocator(false));
    channelGroup = new DefaultChannelGroup("activemq-connector", GlobalEventExecutor.INSTANCE);

    final SSLContext context;
    if (sslEnabled) {
        try {
            // HORNETQ-680 - override the server-side config if client-side system properties are set
            String realKeyStorePath = keyStorePath;
            String realKeyStoreProvider = keyStoreProvider;
            String realKeyStorePassword = keyStorePassword;
            if (System.getProperty(JAVAX_KEYSTORE_PATH_PROP_NAME) != null) {
                realKeyStorePath = System.getProperty(JAVAX_KEYSTORE_PATH_PROP_NAME);
            }
            if (System.getProperty(JAVAX_KEYSTORE_PASSWORD_PROP_NAME) != null) {
                realKeyStorePassword = System.getProperty(JAVAX_KEYSTORE_PASSWORD_PROP_NAME);
            }

            if (System.getProperty(ACTIVEMQ_KEYSTORE_PROVIDER_PROP_NAME) != null) {
                realKeyStoreProvider = System.getProperty(ACTIVEMQ_KEYSTORE_PROVIDER_PROP_NAME);
            }
            if (System.getProperty(ACTIVEMQ_KEYSTORE_PATH_PROP_NAME) != null) {
                realKeyStorePath = System.getProperty(ACTIVEMQ_KEYSTORE_PATH_PROP_NAME);
            }
            if (System.getProperty(ACTIVEMQ_KEYSTORE_PASSWORD_PROP_NAME) != null) {
                realKeyStorePassword = System.getProperty(ACTIVEMQ_KEYSTORE_PASSWORD_PROP_NAME);
            }

            String realTrustStorePath = trustStorePath;
            String realTrustStoreProvider = trustStoreProvider;
            String realTrustStorePassword = trustStorePassword;
            if (System.getProperty(JAVAX_TRUSTSTORE_PATH_PROP_NAME) != null) {
                realTrustStorePath = System.getProperty(JAVAX_TRUSTSTORE_PATH_PROP_NAME);
            }
            if (System.getProperty(JAVAX_TRUSTSTORE_PASSWORD_PROP_NAME) != null) {
                realTrustStorePassword = System.getProperty(JAVAX_TRUSTSTORE_PASSWORD_PROP_NAME);
            }

            if (System.getProperty(ACTIVEMQ_TRUSTSTORE_PROVIDER_PROP_NAME) != null) {
                realTrustStoreProvider = System.getProperty(ACTIVEMQ_TRUSTSTORE_PROVIDER_PROP_NAME);
            }
            if (System.getProperty(ACTIVEMQ_TRUSTSTORE_PATH_PROP_NAME) != null) {
                realTrustStorePath = System.getProperty(ACTIVEMQ_TRUSTSTORE_PATH_PROP_NAME);
            }
            if (System.getProperty(ACTIVEMQ_TRUSTSTORE_PASSWORD_PROP_NAME) != null) {
                realTrustStorePassword = System.getProperty(ACTIVEMQ_TRUSTSTORE_PASSWORD_PROP_NAME);
            }
            context = SSLSupport.createContext(realKeyStoreProvider, realKeyStorePath, realKeyStorePassword,
                    realTrustStoreProvider, realTrustStorePath, realTrustStorePassword);
        } catch (Exception e) {
            close();
            IllegalStateException ise = new IllegalStateException(
                    "Unable to create NettyConnector for " + host + ":" + port);
            ise.initCause(e);
            throw ise;
        }
    } else {
        context = null; // Unused
    }

    if (context != null && useServlet) {
        // TODO: Fix me
        //bootstrap.setOption("sslContext", context);
    }

    bootstrap.handler(new ChannelInitializer<Channel>() {
        public void initChannel(Channel channel) throws Exception {
            final ChannelPipeline pipeline = channel.pipeline();
            if (sslEnabled && !useServlet) {
                SSLEngine engine = context.createSSLEngine();

                engine.setUseClientMode(true);

                engine.setWantClientAuth(true);

                // setting the enabled cipher suites resets the enabled protocols so we need
                // to save the enabled protocols so that after the customer cipher suite is enabled
                // we can reset the enabled protocols if a customer protocol isn't specified
                String[] originalProtocols = engine.getEnabledProtocols();

                if (enabledCipherSuites != null) {
                    try {
                        engine.setEnabledCipherSuites(
                                SSLSupport.parseCommaSeparatedListIntoArray(enabledCipherSuites));
                    } catch (IllegalArgumentException e) {
                        ActiveMQClientLogger.LOGGER.invalidCipherSuite(SSLSupport
                                .parseArrayIntoCommandSeparatedList(engine.getSupportedCipherSuites()));
                        throw e;
                    }
                }

                if (enabledProtocols != null) {
                    try {
                        engine.setEnabledProtocols(
                                SSLSupport.parseCommaSeparatedListIntoArray(enabledProtocols));
                    } catch (IllegalArgumentException e) {
                        ActiveMQClientLogger.LOGGER.invalidProtocol(
                                SSLSupport.parseArrayIntoCommandSeparatedList(engine.getSupportedProtocols()));
                        throw e;
                    }
                } else {
                    engine.setEnabledProtocols(originalProtocols);
                }

                SslHandler handler = new SslHandler(engine);

                pipeline.addLast(handler);
            }

            if (httpEnabled) {
                pipeline.addLast(new HttpRequestEncoder());

                pipeline.addLast(new HttpResponseDecoder());

                pipeline.addLast(new HttpObjectAggregator(Integer.MAX_VALUE));

                pipeline.addLast(new HttpHandler());
            }

            if (httpUpgradeEnabled) {
                // prepare to handle a HTTP 101 response to upgrade the protocol.
                final HttpClientCodec httpClientCodec = new HttpClientCodec();
                pipeline.addLast(httpClientCodec);
                pipeline.addLast("http-upgrade", new HttpUpgradeHandler(pipeline, httpClientCodec));
            }

            protocolManager.addChannelHandlers(pipeline);

            pipeline.addLast(new ActiveMQClientChannelHandler(channelGroup, handler, new Listener()));
        }
    });

    if (batchDelay > 0) {
        flusher = new BatchFlusher();

        batchFlusherFuture = scheduledThreadPool.scheduleWithFixedDelay(flusher, batchDelay, batchDelay,
                TimeUnit.MILLISECONDS);
    }

    ActiveMQClientLogger.LOGGER.debug("Started Netty Connector version " + TransportConstants.NETTY_VERSION);
}

From source file:org.apache.activemq.transport.amqp.client.transport.NettyTcpTransport.java

License:Apache License

private void configureNetty(Bootstrap bootstrap, NettyTransportOptions options) {
    bootstrap.option(ChannelOption.TCP_NODELAY, options.isTcpNoDelay());
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, options.getConnectTimeout());
    bootstrap.option(ChannelOption.SO_KEEPALIVE, options.isTcpKeepAlive());
    bootstrap.option(ChannelOption.SO_LINGER, options.getSoLinger());
    bootstrap.option(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);

    if (options.getSendBufferSize() != -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, options.getSendBufferSize());
    }/*w w w . java 2 s.c  om*/

    if (options.getReceiveBufferSize() != -1) {
        bootstrap.option(ChannelOption.SO_RCVBUF, options.getReceiveBufferSize());
        bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR,
                new FixedRecvByteBufAllocator(options.getReceiveBufferSize()));
    }

    if (options.getTrafficClass() != -1) {
        bootstrap.option(ChannelOption.IP_TOS, options.getTrafficClass());
    }
}

From source file:org.apache.activemq.transport.netty.NettyTcpTransport.java

License:Apache License

private void configureNetty(Bootstrap bootstrap, NettyTransportOptions options) {
    bootstrap.option(ChannelOption.TCP_NODELAY, options.isTcpNoDelay());
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, options.getConnectTimeout());
    bootstrap.option(ChannelOption.SO_KEEPALIVE, options.isTcpKeepAlive());
    bootstrap.option(ChannelOption.SO_LINGER, options.getSoLinger());

    if (options.getSendBufferSize() != -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, options.getSendBufferSize());
    }/*from w  ww  .  j a v  a 2s . c  o  m*/

    if (options.getReceiveBufferSize() != -1) {
        bootstrap.option(ChannelOption.SO_RCVBUF, options.getReceiveBufferSize());
        bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR,
                new FixedRecvByteBufAllocator(options.getReceiveBufferSize()));
    }

    if (options.getTrafficClass() != -1) {
        bootstrap.option(ChannelOption.IP_TOS, options.getTrafficClass());
    }
}

From source file:org.apache.bookkeeper.proto.PerChannelBookieClient.java

License:Apache License

protected ChannelFuture connect() {
    final long startTime = MathUtils.nowInNano();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Connecting to bookie: {}", addr);
    }/*from   ww  w.  ja va  2 s  .  c  o  m*/

    // Set up the ClientBootStrap so we can create a new Channel connection to the bookie.
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(eventLoopGroup);
    if (eventLoopGroup instanceof EpollEventLoopGroup) {
        bootstrap.channel(EpollSocketChannel.class);
    } else if (eventLoopGroup instanceof DefaultEventLoopGroup) {
        bootstrap.channel(LocalChannel.class);
    } else {
        bootstrap.channel(NioSocketChannel.class);
    }

    bootstrap.option(ChannelOption.ALLOCATOR, this.allocator);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, conf.getClientConnectTimeoutMillis());
    bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(
            conf.getClientWriteBufferLowWaterMark(), conf.getClientWriteBufferHighWaterMark()));

    if (!(eventLoopGroup instanceof DefaultEventLoopGroup)) {
        bootstrap.option(ChannelOption.TCP_NODELAY, conf.getClientTcpNoDelay());
        bootstrap.option(ChannelOption.SO_KEEPALIVE, conf.getClientSockKeepalive());

        // if buffer sizes are 0, let OS auto-tune it
        if (conf.getClientSendBufferSize() > 0) {
            bootstrap.option(ChannelOption.SO_SNDBUF, conf.getClientSendBufferSize());
        }

        if (conf.getClientReceiveBufferSize() > 0) {
            bootstrap.option(ChannelOption.SO_RCVBUF, conf.getClientReceiveBufferSize());
        }
    }

    // In the netty pipeline, we need to split packets based on length, so we
    // use the {@link LengthFieldBasedFramDecoder}. Other than that all actions
    // are carried out in this class, e.g., making sense of received messages,
    // prepending the length to outgoing packets etc.
    bootstrap.handler(new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();

            pipeline.addLast("bytebufList", ByteBufList.ENCODER_WITH_SIZE);
            pipeline.addLast("lengthbasedframedecoder",
                    new LengthFieldBasedFrameDecoder(maxFrameSize, 0, 4, 0, 4));
            pipeline.addLast("lengthprepender", new LengthFieldPrepender(4));
            pipeline.addLast("bookieProtoEncoder", new BookieProtoEncoding.RequestEncoder(extRegistry));
            pipeline.addLast("bookieProtoDecoder",
                    new BookieProtoEncoding.ResponseDecoder(extRegistry, useV2WireProtocol));
            pipeline.addLast("authHandler", new AuthHandler.ClientSideHandler(authProviderFactory,
                    txnIdGenerator, connectionPeer, useV2WireProtocol));
            pipeline.addLast("mainhandler", PerChannelBookieClient.this);
        }
    });

    SocketAddress bookieAddr = addr.getSocketAddress();
    if (eventLoopGroup instanceof DefaultEventLoopGroup) {
        bookieAddr = addr.getLocalAddress();
    }

    ChannelFuture future = bootstrap.connect(bookieAddr);
    future.addListener(contextPreservingListener(new ConnectionFutureListener(startTime)));
    future.addListener(x -> makeWritable());
    return future;
}

From source file:org.apache.camel.component.netty4.ClientModeTCPNettyServerBootstrapFactory.java

License:Apache License

protected void startServerBootstrap() throws Exception {
    // prefer using explicit configured thread pools

    EventLoopGroup wg = configuration.getWorkerGroup();

    if (wg == null) {
        // create new pool which we should shutdown when stopping as its not shared
        workerGroup = new NettyWorkerPoolBuilder().withWorkerCount(configuration.getWorkerCount())
                .withName("NettyServerTCPWorker").build();
        wg = workerGroup;//from   w w  w.  ja v  a 2  s.  c  om
    }

    clientBootstrap = new Bootstrap();
    clientBootstrap.channel(NioSocketChannel.class);
    clientBootstrap.group(wg);
    clientBootstrap.option(ChannelOption.SO_KEEPALIVE, configuration.isKeepAlive());
    clientBootstrap.option(ChannelOption.TCP_NODELAY, configuration.isTcpNoDelay());
    clientBootstrap.option(ChannelOption.SO_REUSEADDR, configuration.isReuseAddress());
    clientBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, configuration.getConnectTimeout());

    LOG.debug("Created ClientBootstrap {}", clientBootstrap);
    clientBootstrap.handler(pipelineFactory);
    ChannelFuture channelFuture = clientBootstrap
            .connect(new InetSocketAddress(configuration.getHost(), configuration.getPort()));
    if (LOG.isDebugEnabled()) {
        LOG.debug("Created new TCP client bootstrap connecting to {}:{} with options: {}",
                new Object[] { configuration.getHost(), configuration.getPort(), clientBootstrap });
    }
    LOG.info("ClientModeServerBootstrap binding to {}:{}", configuration.getHost(), configuration.getPort());
    channel = openChannel(channelFuture);

}

From source file:org.apache.camel.component.netty4.NettyProducer.java

License:Apache License

protected ChannelFuture openConnection() throws Exception {
    ChannelFuture answer;/*from  w  w  w .j a v  a  2s  .  c o  m*/

    if (isTcp()) {
        // its okay to create a new bootstrap for each new channel
        Bootstrap clientBootstrap = new Bootstrap();
        clientBootstrap.channel(NioSocketChannel.class);
        clientBootstrap.group(getWorkerGroup());
        clientBootstrap.option(ChannelOption.SO_KEEPALIVE, configuration.isKeepAlive());
        clientBootstrap.option(ChannelOption.TCP_NODELAY, configuration.isTcpNoDelay());
        clientBootstrap.option(ChannelOption.SO_REUSEADDR, configuration.isReuseAddress());
        clientBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, configuration.getConnectTimeout());

        //TODO need to check it later
        // set any additional netty options
        /*
        if (configuration.getOptions() != null) {
        for (Map.Entry<String, Object> entry : configuration.getOptions().entrySet()) {
            clientBootstrap.setOption(entry.getKey(), entry.getValue());
        }
        }*/

        // set the pipeline factory, which creates the pipeline for each newly created channels
        clientBootstrap.handler(pipelineFactory);
        answer = clientBootstrap
                .connect(new InetSocketAddress(configuration.getHost(), configuration.getPort()));
        if (LOG.isDebugEnabled()) {
            LOG.debug("Created new TCP client bootstrap connecting to {}:{} with options: {}",
                    new Object[] { configuration.getHost(), configuration.getPort(), clientBootstrap });
        }
        return answer;
    } else {
        // its okay to create a new bootstrap for each new channel
        Bootstrap connectionlessClientBootstrap = new Bootstrap();
        connectionlessClientBootstrap.channel(NioDatagramChannel.class);
        connectionlessClientBootstrap.group(getWorkerGroup());
        connectionlessClientBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
                configuration.getConnectTimeout());
        connectionlessClientBootstrap.option(ChannelOption.SO_BROADCAST, configuration.isBroadcast());
        connectionlessClientBootstrap.option(ChannelOption.SO_SNDBUF, configuration.getSendBufferSize());
        connectionlessClientBootstrap.option(ChannelOption.SO_RCVBUF, configuration.getReceiveBufferSize());

        //TODO need to check it later
        // set any additional netty options
        /*
        if (configuration.getOptions() != null) {
        for (Map.Entry<String, Object> entry : configuration.getOptions().entrySet()) {
            connectionlessClientBootstrap.setOption(entry.getKey(), entry.getValue());
        }
        }*/

        // set the pipeline factory, which creates the pipeline for each newly created channels
        connectionlessClientBootstrap.handler(pipelineFactory);
        // bind and store channel so we can close it when stopping
        ChannelFuture channelFuture = connectionlessClientBootstrap.bind(new InetSocketAddress(0));
        channelFuture.awaitUninterruptibly();
        Channel channel = channelFuture.channel();
        allChannels.add(channel);
        answer = connectionlessClientBootstrap
                .connect(new InetSocketAddress(configuration.getHost(), configuration.getPort()));

        if (LOG.isDebugEnabled()) {
            LOG.debug("Created new UDP client bootstrap connecting to {}:{} with options: {}", new Object[] {
                    configuration.getHost(), configuration.getPort(), connectionlessClientBootstrap });
        }
        return answer;
    }
}

From source file:org.apache.camel.component.netty4.SingleTCPNettyServerBootstrapFactory.java

License:Apache License

protected void startServerBootstrap() {
    // prefer using explicit configured thread pools
    EventLoopGroup bg = configuration.getBossGroup();
    EventLoopGroup wg = configuration.getWorkerGroup();

    if (bg == null) {
        // create new pool which we should shutdown when stopping as its not shared
        bossGroup = new NettyServerBossPoolBuilder().withBossCount(configuration.getBossCount())
                .withName("NettyServerTCPBoss").build();
        bg = bossGroup;//from w  w w .  j a  va2  s  .c o  m
    }
    if (wg == null) {
        // create new pool which we should shutdown when stopping as its not shared
        workerGroup = new NettyWorkerPoolBuilder().withWorkerCount(configuration.getWorkerCount())
                .withName("NettyServerTCPWorker").build();
        wg = workerGroup;
    }

    //channelFactory = new NioServerSocketChannelFactory(bg, wg);

    serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(bg, wg).channel(NioServerSocketChannel.class);
    serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, configuration.isKeepAlive());
    serverBootstrap.childOption(ChannelOption.TCP_NODELAY, configuration.isTcpNoDelay());
    serverBootstrap.option(ChannelOption.SO_REUSEADDR, configuration.isReuseAddress());
    serverBootstrap.childOption(ChannelOption.SO_REUSEADDR, configuration.isReuseAddress());
    serverBootstrap.childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, configuration.getConnectTimeout());
    if (configuration.getBacklog() > 0) {
        serverBootstrap.option(ChannelOption.SO_BACKLOG, configuration.getBacklog());
    }

    // TODO set any additional netty options and child options
    /*if (configuration.getOptions() != null) {
    for (Map.Entry<String, Object> entry : configuration.getOptions().entrySet()) {
        serverBootstrap.setOption(entry.getKey(), entry.getValue());
    }
    }*/

    // set the pipeline factory, which creates the pipeline for each newly created channels
    serverBootstrap.childHandler(pipelineFactory);

    LOG.debug("Created ServerBootstrap {}", serverBootstrap);

    LOG.info("ServerBootstrap binding to {}:{}", configuration.getHost(), configuration.getPort());
    ChannelFuture channelFutrue = serverBootstrap
            .bind(new InetSocketAddress(configuration.getHost(), configuration.getPort()));
    channelFutrue.awaitUninterruptibly();
    channel = channelFutrue.channel();
    // to keep track of all channels in use
    allChannels.add(channel);
}

From source file:org.apache.camel.component.netty4.SingleUDPNettyServerBootstrapFactory.java

License:Apache License

protected void startServerBootstrap() throws Exception {
    // create non-shared worker pool
    EventLoopGroup wg = configuration.getWorkerGroup();
    if (wg == null) {
        // create new pool which we should shutdown when stopping as its not shared
        workerGroup = new NettyWorkerPoolBuilder().withWorkerCount(configuration.getWorkerCount())
                .withName("NettyServerTCPWorker").build();
        wg = workerGroup;/* w ww.  jav  a 2 s.  c  o  m*/
    }

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(wg).channel(NioDatagramChannel.class);
    // We cannot set the child option here      
    bootstrap.option(ChannelOption.SO_REUSEADDR, configuration.isReuseAddress());
    bootstrap.option(ChannelOption.SO_SNDBUF, configuration.getSendBufferSize());
    bootstrap.option(ChannelOption.SO_RCVBUF, configuration.getReceiveBufferSize());
    bootstrap.option(ChannelOption.SO_BROADCAST, configuration.isBroadcast());
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, configuration.getConnectTimeout());

    // TODO need to find the right setting of below option
    // only set this if user has specified
    /*
    if (configuration.getReceiveBufferSizePredictor() > 0) {
    bootstrap.setOption("receiveBufferSizePredictorFactory",
            new FixedReceiveBufferSizePredictorFactory(configuration.getReceiveBufferSizePredictor()));
    }*/

    if (configuration.getBacklog() > 0) {
        bootstrap.option(ChannelOption.SO_BACKLOG, configuration.getBacklog());
    }

    //TODO need to check the additional netty options
    /*
    if (configuration.getOptions() != null) {
    for (Map.Entry<String, Object> entry : configuration.getOptions().entrySet()) {
        connectionlessBootstrap.setOption(entry.getKey(), entry.getValue());
    }
    }*/

    LOG.debug("Created ConnectionlessBootstrap {}", bootstrap);

    // set the pipeline factory, which creates the pipeline for each newly created channels
    bootstrap.handler(pipelineFactory);

    InetSocketAddress hostAddress = new InetSocketAddress(configuration.getHost(), configuration.getPort());
    SubnetUtils multicastSubnet = new SubnetUtils(MULTICAST_SUBNET);

    if (multicastSubnet.getInfo().isInRange(configuration.getHost())) {
        ChannelFuture channelFuture = bootstrap.bind(hostAddress);
        channelFuture.awaitUninterruptibly();
        channel = channelFuture.channel();
        DatagramChannel datagramChannel = (DatagramChannel) channel;
        String networkInterface = configuration.getNetworkInterface() == null ? LOOPBACK_INTERFACE
                : configuration.getNetworkInterface();
        multicastNetworkInterface = NetworkInterface.getByName(networkInterface);
        ObjectHelper.notNull(multicastNetworkInterface,
                "No network interface found for '" + networkInterface + "'.");
        LOG.info("ConnectionlessBootstrap joining {}:{} using network interface: {}", new Object[] {
                configuration.getHost(), configuration.getPort(), multicastNetworkInterface.getName() });
        datagramChannel.joinGroup(hostAddress, multicastNetworkInterface).syncUninterruptibly();
        allChannels.add(datagramChannel);
    } else {
        LOG.info("ConnectionlessBootstrap binding to {}:{}", configuration.getHost(), configuration.getPort());
        ChannelFuture channelFuture = bootstrap.bind(hostAddress);
        channelFuture.awaitUninterruptibly();
        channel = channelFuture.channel();
        allChannels.add(channel);
    }
}

From source file:org.apache.drill.exec.rpc.BasicClient.java

License:Apache License

public BasicClient(RpcConfig rpcMapping, ByteBufAllocator alloc, EventLoopGroup eventLoopGroup, T handshakeType,
        Class<HANDSHAKE_RESPONSE> responseClass, Parser<HANDSHAKE_RESPONSE> handshakeParser) {
    super(rpcMapping);
    this.responseClass = responseClass;
    this.handshakeType = handshakeType;
    this.handshakeParser = handshakeParser;
    final long timeoutInMillis = rpcMapping.hasTimeout()
            ? (long) (rpcMapping.getTimeout() * 1000.0 * PERCENT_TIMEOUT_BEFORE_SENDING_PING)
            : -1;//from   www.  ja  v a2 s .  c o m
    this.pingHandler = rpcMapping.hasTimeout() ? new IdlePingHandler(timeoutInMillis) : null;

    b = new Bootstrap() //
            .group(eventLoopGroup) //
            .channel(TransportCheck.getClientSocketChannel()) //
            .option(ChannelOption.ALLOCATOR, alloc) //
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 30 * 1000).option(ChannelOption.SO_REUSEADDR, true)
            .option(ChannelOption.SO_RCVBUF, 1 << 17) //
            .option(ChannelOption.SO_SNDBUF, 1 << 17) //
            .option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {

                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    // logger.debug("initializing client connection.");
                    connection = initRemoteConnection(ch);

                    ch.closeFuture().addListener(getCloseHandler(ch, connection));

                    final ChannelPipeline pipe = ch.pipeline();

                    pipe.addLast("protocol-decoder", getDecoder(connection.getAllocator()));
                    pipe.addLast("message-decoder", new RpcDecoder("c-" + rpcConfig.getName()));
                    pipe.addLast("protocol-encoder", new RpcEncoder("c-" + rpcConfig.getName()));
                    pipe.addLast("handshake-handler", new ClientHandshakeHandler(connection));

                    if (pingHandler != null) {
                        pipe.addLast("idle-state-handler", pingHandler);
                    }

                    pipe.addLast("message-handler", new InboundHandler(connection));
                    pipe.addLast("exception-handler", new RpcExceptionHandler<R>(connection));
                }
            }); //

    // if(TransportCheck.SUPPORTS_EPOLL){
    // b.option(EpollChannelOption.SO_REUSEPORT, true); //
    // }
}