Example usage for io.netty.channel ChannelOption SO_SNDBUF

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

Introduction

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

Prototype

ChannelOption SO_SNDBUF

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

Click Source Link

Usage

From source file:net.pms.network.HTTPServer.java

License:Open Source License

public boolean start() throws IOException {
    hostname = configuration.getServerHostname();
    InetSocketAddress address;/*from   ww w  .j a  v  a 2s  . co  m*/

    if (StringUtils.isNotBlank(hostname)) {
        LOGGER.info("Using forced address " + hostname);
        InetAddress tempIA = InetAddress.getByName(hostname);

        if (tempIA != null && networkInterface != null
                && networkInterface.equals(NetworkInterface.getByInetAddress(tempIA))) {
            address = new InetSocketAddress(tempIA, port);
        } else {
            address = new InetSocketAddress(hostname, port);
        }
    } else if (isAddressFromInterfaceFound(configuration.getNetworkInterface())) { // XXX sets iafinal and networkInterface
        LOGGER.info("Using address {} found on network interface: {}", iafinal,
                networkInterface.toString().trim().replace('\n', ' '));
        address = new InetSocketAddress(iafinal, port);
    } else {
        LOGGER.info("Using localhost address");
        address = new InetSocketAddress(port);
    }

    LOGGER.info("Created socket: " + address);

    if (configuration.isHTTPEngineV2()) { // HTTP Engine V2
        bossGroup = new NioEventLoopGroup(1);
        workerGroup = new NioEventLoopGroup();

        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.SO_REUSEADDR, true)
                .childOption(ChannelOption.SO_SNDBUF, 65536).childOption(ChannelOption.SO_RCVBUF, 65536);
        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).localAddress(address)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast("HttpHandler", new HttpServerCodec())
                                // eliminate the need to decode http chunks from the client
                                .addLast("aggregator", new HttpObjectAggregator(64 * 1024))
                                .addLast("chunkedWriter", new ChunkedWriteHandler())
                                .addLast("handler", new RequestHandlerV2());
                    }
                });

        try {
            channel = bootstrap.bind().channel();
        } catch (Exception e) {
            LOGGER.error("Another program is using port " + port + ", which UMS needs.");
            LOGGER.error("You can change the port UMS uses on the General Configuration tab.");
            LOGGER.trace("The error was: " + e);
            PMS.get().getFrame().setStatusCode(0, Messages.getString("PMS.141"), "icon-status-warning.png");
        }

        if (hostname == null && iafinal != null) {
            hostname = iafinal.getHostAddress();
        } else if (hostname == null) {
            hostname = InetAddress.getLocalHost().getHostAddress();
        }
    } else { // HTTP Engine V1
        serverSocketChannel = ServerSocketChannel.open();

        serverSocket = serverSocketChannel.socket();
        serverSocket.setReuseAddress(true);
        serverSocket.bind(address);

        if (hostname == null && iafinal != null) {
            hostname = iafinal.getHostAddress();
        } else if (hostname == null) {
            hostname = InetAddress.getLocalHost().getHostAddress();
        }

        runnable = new Thread(this, "HTTP Server");
        runnable.setDaemon(false);
        runnable.start();
    }

    return true;
}

From source file:net.qing.sms.simulator.NettySmsSimulatorServer.java

License:Apache License

protected void applyConnectionOptions(ServerBootstrap bootstrap) {
    SocketConfig config = configuration.getSocketConfig();
    bootstrap.childOption(ChannelOption.TCP_NODELAY, config.isTcpNoDelay());
    if (config.getTcpSendBufferSize() != -1) {
        bootstrap.childOption(ChannelOption.SO_SNDBUF, config.getTcpSendBufferSize());
    }/*from w w w . jav a2  s.c o m*/
    if (config.getTcpReceiveBufferSize() != -1) {
        bootstrap.childOption(ChannelOption.SO_RCVBUF, config.getTcpReceiveBufferSize());
    }
    // bootstrap.option(ChannelOption.ALLOCATOR,
    // PooledByteBufAllocator.DEFAULT);
    bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    // bootstrap.childOption(ChannelOption.ALLOCATOR,
    // PooledByteBufAllocator.DEFAULT);
    bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, config.isTcpKeepAlive());
    bootstrap.option(ChannelOption.SO_LINGER, config.getSoLinger());
    bootstrap.option(ChannelOption.SO_REUSEADDR, config.isReuseAddress());
    bootstrap.option(ChannelOption.SO_BACKLOG, config.getAcceptBackLog());
}

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

License:Apache License

public synchronized void start() throws Exception {
    if (channelClazz != null) {
        // Already started
        return;//from www  .ja  v a 2  s.c  om
    }

    if (useInvm) {
        channelClazz = LocalServerChannel.class;
        eventLoopGroup = new LocalEventLoopGroup();
    } else {
        int threadsToUse;

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

            threadsToUse = Runtime.getRuntime().availableProcessors() * 3;
        } else {
            threadsToUse = this.nioRemotingThreads;
        }
        channelClazz = NioServerSocketChannel.class;
        eventLoopGroup = new NioEventLoopGroup(threadsToUse,
                new ActiveMQThreadFactory("activemq-netty-threads", true, getThisClassLoader()));
    }

    bootstrap = new ServerBootstrap();
    bootstrap.group(eventLoopGroup);
    bootstrap.channel(channelClazz);
    final SSLContext context;
    if (sslEnabled) {
        try {
            if (keyStorePath == null && TransportConstants.DEFAULT_TRUSTSTORE_PROVIDER.equals(keyStoreProvider))
                throw new IllegalArgumentException("If \"" + TransportConstants.SSL_ENABLED_PROP_NAME
                        + "\" is true then \"" + TransportConstants.KEYSTORE_PATH_PROP_NAME
                        + "\" must be non-null " + "unless an alternative \""
                        + TransportConstants.KEYSTORE_PROVIDER_PROP_NAME + "\" has been specified.");
            context = SSLSupport.createContext(keyStoreProvider, keyStorePath, keyStorePassword,
                    trustStoreProvider, trustStorePath, trustStorePassword);
        } catch (Exception e) {
            IllegalStateException ise = new IllegalStateException(
                    "Unable to create NettyAcceptor for " + host + ":" + port);
            ise.initCause(e);
            throw ise;
        }
    } else {
        context = null; // Unused
    }

    final AtomicBoolean warningPrinted = new AtomicBoolean(false);

    ChannelInitializer<Channel> factory = new ChannelInitializer<Channel>() {
        @Override
        public void initChannel(Channel channel) throws Exception {
            ChannelPipeline pipeline = channel.pipeline();
            if (sslEnabled) {
                SSLEngine engine = context.createSSLEngine();

                engine.setUseClientMode(false);

                if (needClientAuth)
                    engine.setNeedClientAuth(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) {
                        ActiveMQServerLogger.LOGGER.invalidCipherSuite(SSLSupport
                                .parseArrayIntoCommandSeparatedList(engine.getSupportedCipherSuites()));
                        throw e;
                    }
                }

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

                // Strip "SSLv3" from the current enabled protocols to address the POODLE exploit.
                // This recommendation came from http://www.oracle.com/technetwork/java/javase/documentation/cve-2014-3566-2342133.html
                String[] protocols = engine.getEnabledProtocols();
                Set<String> set = new HashSet<>();
                for (String s : protocols) {
                    if (s.equals("SSLv3") || s.equals("SSLv2Hello")) {
                        if (!warningPrinted.get()) {
                            ActiveMQServerLogger.LOGGER.disallowedProtocol(s);
                        }
                        continue;
                    }
                    set.add(s);
                }
                warningPrinted.set(true);
                engine.setEnabledProtocols(set.toArray(new String[0]));

                SslHandler handler = new SslHandler(engine);

                pipeline.addLast("ssl", handler);
            }
            pipeline.addLast(protocolHandler.getProtocolDecoder());
        }
    };
    bootstrap.childHandler(factory);

    // Bind
    bootstrap.childOption(ChannelOption.TCP_NODELAY, tcpNoDelay);
    if (tcpReceiveBufferSize != -1) {
        bootstrap.childOption(ChannelOption.SO_RCVBUF, tcpReceiveBufferSize);
    }
    if (tcpSendBufferSize != -1) {
        bootstrap.childOption(ChannelOption.SO_SNDBUF, tcpSendBufferSize);
    }
    if (backlog != -1) {
        bootstrap.option(ChannelOption.SO_BACKLOG, backlog);
    }
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    bootstrap.childOption(ChannelOption.SO_REUSEADDR, true);
    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.childOption(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);
    channelGroup = new DefaultChannelGroup("activemq-accepted-channels", GlobalEventExecutor.INSTANCE);

    serverChannelGroup = new DefaultChannelGroup("activemq-acceptor-channels", GlobalEventExecutor.INSTANCE);

    if (httpUpgradeEnabled) {
        // the channel will be bound by the Web container and hand over after the HTTP Upgrade
        // handshake is successful
    } else {
        startServerChannels();

        paused = false;

        if (notificationService != null) {
            TypedProperties props = new TypedProperties();
            props.putSimpleStringProperty(new SimpleString("factory"),
                    new SimpleString(NettyAcceptorFactory.class.getName()));
            props.putSimpleStringProperty(new SimpleString("host"), new SimpleString(host));
            props.putIntProperty(new SimpleString("port"), port);
            Notification notification = new Notification(null, CoreNotificationType.ACCEPTOR_STARTED, props);
            notificationService.sendNotification(notification);
        }

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

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

        ActiveMQServerLogger.LOGGER.startedAcceptor(host, port, protocolsString);
    }
}

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

License:Apache License

public synchronized void start() {
    if (channelClazz != null) {
        return;/* w w w . j  av a2 s. com*/
    }

    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.NettyAcceptor.java

License:Apache License

public synchronized void start() throws Exception {
    if (channelClazz != null) {
        // Already started
        return;//from  w ww  .  ja  v a2 s  . com
    }

    if (useInvm) {
        channelClazz = LocalServerChannel.class;
        eventLoopGroup = new LocalEventLoopGroup();
    } else {
        int threadsToUse;

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

            threadsToUse = Runtime.getRuntime().availableProcessors() * 3;
        } else {
            threadsToUse = this.nioRemotingThreads;
        }
        channelClazz = NioServerSocketChannel.class;
        eventLoopGroup = new NioEventLoopGroup(threadsToUse,
                new ActiveMQThreadFactory("activemq-netty-threads", true, getThisClassLoader()));
    }

    bootstrap = new ServerBootstrap();
    bootstrap.group(eventLoopGroup);
    bootstrap.channel(channelClazz);
    final SSLContext context;
    if (sslEnabled) {
        try {
            if (keyStorePath == null && TransportConstants.DEFAULT_TRUSTSTORE_PROVIDER.equals(keyStoreProvider))
                throw new IllegalArgumentException("If \"" + TransportConstants.SSL_ENABLED_PROP_NAME
                        + "\" is true then \"" + TransportConstants.KEYSTORE_PATH_PROP_NAME
                        + "\" must be non-null " + "unless an alternative \""
                        + TransportConstants.KEYSTORE_PROVIDER_PROP_NAME + "\" has been specified.");
            context = SSLSupport.createContext(keyStoreProvider, keyStorePath, keyStorePassword,
                    trustStoreProvider, trustStorePath, trustStorePassword);
        } catch (Exception e) {
            IllegalStateException ise = new IllegalStateException(
                    "Unable to create NettyAcceptor for " + host + ":" + port);
            ise.initCause(e);
            throw ise;
        }
    } else {
        context = null; // Unused
    }

    ChannelInitializer<Channel> factory = new ChannelInitializer<Channel>() {
        @Override
        public void initChannel(Channel channel) throws Exception {
            ChannelPipeline pipeline = channel.pipeline();
            if (sslEnabled) {
                SSLEngine engine = context.createSSLEngine();

                engine.setUseClientMode(false);

                if (needClientAuth)
                    engine.setNeedClientAuth(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) {
                        ActiveMQServerLogger.LOGGER.invalidCipherSuite(SSLSupport
                                .parseArrayIntoCommandSeparatedList(engine.getSupportedCipherSuites()));
                        throw e;
                    }
                }

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

                // Strip "SSLv3" from the current enabled protocols to address the POODLE exploit.
                // This recommendation came from http://www.oracle.com/technetwork/java/javase/documentation/cve-2014-3566-2342133.html
                String[] protocols = engine.getEnabledProtocols();
                Set<String> set = new HashSet<>();
                for (String s : protocols) {
                    if (s.equals("SSLv3") || s.equals("SSLv2Hello")) {
                        ActiveMQServerLogger.LOGGER.disallowedProtocol(s);
                        continue;
                    }
                    set.add(s);
                }
                engine.setEnabledProtocols(set.toArray(new String[0]));

                SslHandler handler = new SslHandler(engine);

                pipeline.addLast("ssl", handler);
            }
            pipeline.addLast(protocolHandler.getProtocolDecoder());
        }
    };
    bootstrap.childHandler(factory);

    // Bind
    bootstrap.childOption(ChannelOption.TCP_NODELAY, tcpNoDelay);
    if (tcpReceiveBufferSize != -1) {
        bootstrap.childOption(ChannelOption.SO_RCVBUF, tcpReceiveBufferSize);
    }
    if (tcpSendBufferSize != -1) {
        bootstrap.childOption(ChannelOption.SO_SNDBUF, tcpSendBufferSize);
    }
    if (backlog != -1) {
        bootstrap.option(ChannelOption.SO_BACKLOG, backlog);
    }
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    bootstrap.childOption(ChannelOption.SO_REUSEADDR, true);
    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.childOption(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);
    channelGroup = new DefaultChannelGroup("activemq-accepted-channels", GlobalEventExecutor.INSTANCE);

    serverChannelGroup = new DefaultChannelGroup("activemq-acceptor-channels", GlobalEventExecutor.INSTANCE);

    if (httpUpgradeEnabled) {
        // the channel will be bound by the Web container and hand over after the HTTP Upgrade
        // handshake is successful
    } else {
        startServerChannels();

        paused = false;

        if (notificationService != null) {
            TypedProperties props = new TypedProperties();
            props.putSimpleStringProperty(new SimpleString("factory"),
                    new SimpleString(NettyAcceptorFactory.class.getName()));
            props.putSimpleStringProperty(new SimpleString("host"), new SimpleString(host));
            props.putIntProperty(new SimpleString("port"), port);
            Notification notification = new Notification(null, CoreNotificationType.ACCEPTOR_STARTED, props);
            notificationService.sendNotification(notification);
        }

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

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

        ActiveMQServerLogger.LOGGER.startedNettyAcceptor(TransportConstants.NETTY_VERSION, host, port);
    }
}

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  .  java  2  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());
    }/*from   w  ww . ja  v a  2s  . 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());
    }// www.  ja v a  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.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   w  ww  .  ja  va2s  .c om*/

    // 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.NettyProducer.java

License:Apache License

protected ChannelFuture openConnection() throws Exception {
    ChannelFuture answer;//  w w  w. java  2 s  . co  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;
    }
}