Example usage for io.netty.channel ChannelOption SO_REUSEADDR

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

Introduction

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

Prototype

ChannelOption SO_REUSEADDR

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

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 w  ww.j  a  v  a  2s .  com*/

    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 ww  . j  a  va2 s . co  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:net.sourceforge.entrainer.socket.EntrainerSocketManager.java

License:Open Source License

private void initAcceptor() {
    bootstrap = new ServerBootstrap();
    bootstrap.option(ChannelOption.SO_REUSEADDR, Boolean.TRUE);
    EventLoopGroup parent = new NioEventLoopGroup();
    EventLoopGroup worker = new NioEventLoopGroup();

    bootstrap.group(parent, worker);//from w  ww.  j  a v  a  2  s.  com
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.childHandler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast(new PortUnificationHandler(nettyConnectionHandler, webSocketHandler));
        }
    });
}

From source file:net.tomp2p.connection.ChannelCreator.java

License:Apache License

/**
 * Creates a channel to the given address. This will setup the TCP
 * connection/*from  w  w w  . ja  v a2 s.  c om*/
 * 
 * @param socketAddress
 *            The address to send future messages
 * @param connectionTimeoutMillis
 *            The timeout for establishing a TCP connection
 * @param channelHandlers
 *            The handlers to set
 * @param futureResponse
 *            the futureResponse
 * @return The channel future object or null if we are shut down.
 */
public ChannelFuture createTCP(final SocketAddress socketAddress, final int connectionTimeoutMillis,
        final Map<String, Pair<EventExecutorGroup, ChannelHandler>> channelHandlers,
        final FutureResponse futureResponse) {
    readTCP.lock();
    try {
        if (shutdownTCP) {
            return null;
        }
        if (!semaphoreTCP.tryAcquire()) {
            LOG.error("Tried to acquire more resources (TCP) than announced!");
            throw new RuntimeException("Tried to acquire more resources (TCP) than announced!");
        }
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectionTimeoutMillis);
        b.option(ChannelOption.TCP_NODELAY, true);
        b.option(ChannelOption.SO_LINGER, 0);
        b.option(ChannelOption.SO_REUSEADDR, true);
        Map<String, Pair<EventExecutorGroup, ChannelHandler>> channelHandlers2 = channelClientConfiguration
                .pipelineFilter().filter(channelHandlers, true, true);
        addHandlers(b, channelHandlers2);

        ChannelFuture channelFuture = b.connect(socketAddress,
                new InetSocketAddress(channelClientConfiguration.senderTCP(), 0));

        recipients.add(channelFuture.channel());
        setupCloseListener(channelFuture, semaphoreTCP, futureResponse);
        return channelFuture;
    } finally {
        readTCP.unlock();
    }
}

From source file:net.tomp2p.connection2.ChannelCreator.java

License:Apache License

/**
 * Creates a channel to the given address. This will setup the TCP connection
 * //from   w  w  w  .jav a  2s .c  om
 * @param socketAddress
 *            The address to send future messages
 * @param connectionTimeoutMillis
 *            The timeout for establishing a TCP connection
 * @param channelHandlers
 *            The handlers to set
 * @return The channel future object or null if we are shut down.
 */
public ChannelFuture createTCP(final SocketAddress socketAddress, final int connectionTimeoutMillis,
        final Map<String, ChannelHandler> channelHandlers) {
    readTCP.lock();
    try {
        if (shutdownTCP) {
            return null;
        }
        if (!semaphoreTCP.tryAcquire()) {
            LOG.error("Tried to acquire more resources (TCP) than announced!");
            throw new RuntimeException("Tried to acquire more resources (TCP) than announced!");
        }
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectionTimeoutMillis);
        b.option(ChannelOption.TCP_NODELAY, true);
        b.option(ChannelOption.SO_LINGER, 0);
        b.option(ChannelOption.SO_REUSEADDR, true);
        // b.option(ChannelOption.SO_KEEPALIVE, Boolean.TRUE);
        channelClientConfiguration.pipelineFilter().filter(channelHandlers, true, true);
        addHandlers(b, channelHandlers);

        ChannelFuture channelFuture = b.connect(socketAddress);

        setupCloseListener(channelFuture, semaphoreTCP);
        CREATED_TCP_CONNECTIONS.incrementAndGet();
        return channelFuture;
    } finally {
        readTCP.unlock();
    }
}

From source file:org.aaron.sms.broker.SMSBrokerTCPServer.java

License:Open Source License

@Override
protected ChannelFuture doBootstrap(ChannelInitializer<Channel> childHandler) {
    final ServerBootstrap b = new ServerBootstrap();
    b.group(getEventLoopGroup()).channel(TCPEventLoopGroupContainer.getServerChannelClass())
            .childHandler(childHandler).option(ChannelOption.SO_REUSEADDR, true);
    return b.bind(listenAddress, listenPort);
}

From source file:org.aaron.sms.broker.SMSBrokerUnixServer.java

License:Open Source License

@Override
protected ChannelFuture doBootstrap(ChannelInitializer<Channel> childHandler) {
    final ServerBootstrap b = new ServerBootstrap();
    b.group(getEventLoopGroup()).channel(UnixEventLoopGroupContainer.getServerChannelClass())
            .childHandler(childHandler).option(ChannelOption.SO_REUSEADDR, true);
    return b.bind(new DomainSocketAddress(socketPath));
}

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;/* www  . ja  v a 2s .  c  o  m*/
    }

    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;/*from  ww w  . j  ava  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, 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;//w  ww. j  a  v a  2  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);
    }
}