Example usage for io.netty.handler.ssl OpenSsl isAlpnSupported

List of usage examples for io.netty.handler.ssl OpenSsl isAlpnSupported

Introduction

In this page you can find the example usage for io.netty.handler.ssl OpenSsl isAlpnSupported.

Prototype

@Deprecated
public static boolean isAlpnSupported() 

Source Link

Document

Returns true if the used version of openssl supports <a href="https://tools.ietf.org/html/rfc7301">ALPN</a>.

Usage

From source file:com.flysoloing.learning.network.netty.http2.helloworld.client.Http2Client.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/* w  w  w  .ja  v a2 s .c  om*/
        SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
        sslCtx = SslContextBuilder.forClient().sslProvider(provider)
                /* NOTE: the cipher filter may not include all ciphers required by the HTTP/2 specification.
                 * Please refer to the HTTP/2 specification for cipher requirements. */
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .trustManager(InsecureTrustManagerFactory.INSTANCE)
                .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN,
                        // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
                        SelectorFailureBehavior.NO_ADVERTISE,
                        // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
                        SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2,
                        ApplicationProtocolNames.HTTP_1_1))
                .build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup workerGroup = new NioEventLoopGroup();
    Http2ClientInitializer initializer = new Http2ClientInitializer(sslCtx, Integer.MAX_VALUE);

    try {
        // Configure the client.
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.remoteAddress(HOST, PORT);
        b.handler(initializer);

        // Start the client.
        Channel channel = b.connect().syncUninterruptibly().channel();
        System.out.println("Connected to [" + HOST + ':' + PORT + ']');

        // Wait for the HTTP/2 upgrade to occur.
        Http2SettingsHandler http2SettingsHandler = initializer.settingsHandler();
        http2SettingsHandler.awaitSettings(5, TimeUnit.SECONDS);

        HttpResponseHandler responseHandler = initializer.responseHandler();
        int streamId = 3;
        HttpScheme scheme = SSL ? HttpScheme.HTTPS : HttpScheme.HTTP;
        AsciiString hostName = new AsciiString(HOST + ':' + PORT);
        System.err.println("Sending request(s)...");
        if (URL != null) {
            // Create a simple GET request.
            FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, URL);
            request.headers().add(HttpHeaderNames.HOST, hostName);
            request.headers().add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), scheme.name());
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
            responseHandler.put(streamId, channel.write(request), channel.newPromise());
            streamId += 2;
        }
        if (URL2 != null) {
            // Create a simple POST request with a body.
            FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, POST, URL2,
                    wrappedBuffer(URL2DATA.getBytes(CharsetUtil.UTF_8)));
            request.headers().add(HttpHeaderNames.HOST, hostName);
            request.headers().add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), scheme.name());
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
            responseHandler.put(streamId, channel.write(request), channel.newPromise());
        }
        channel.flush();
        responseHandler.awaitResponses(5, TimeUnit.SECONDS);
        System.out.println("Finished HTTP/2 request(s)");

        // Wait until the connection is closed.
        channel.close().syncUninterruptibly();
    } finally {
        workerGroup.shutdownGracefully();
    }
}

From source file:com.flysoloing.learning.network.netty.http2.helloworld.multiplex.server.Http2Server.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {//from w  ww. j a  v  a  2s  . c  o  m
        SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).sslProvider(provider)
                /* NOTE: the cipher filter may not include all ciphers required by the HTTP/2 specification.
                 * Please refer to the HTTP/2 specification for cipher requirements. */
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN,
                        // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
                        SelectorFailureBehavior.NO_ADVERTISE,
                        // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
                        SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2,
                        ApplicationProtocolNames.HTTP_1_1))
                .build();
    } else {
        sslCtx = null;
    }
    // Configure the server.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(group).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new Http2ServerInitializer(sslCtx));

        Channel ch = b.bind(PORT).sync().channel();

        System.err.println("Open your HTTP/2-enabled web browser and navigate to " + (SSL ? "https" : "http")
                + "://127.0.0.1:" + PORT + '/');

        ch.closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}

From source file:com.google.cloud.compatchecker.GoogleCloudCompatChecker.java

License:Apache License

public static boolean check() {
    Properties osProperties = new Properties();
    new OsDetector().detect(osProperties, Lists.<String>newArrayList());

    String bitMode = System.getProperty("sun.arch.data.model");

    boolean openSslIsAvailable = OpenSsl.isAvailable();
    boolean openSslAlpnIsSupported = OpenSsl.isAlpnSupported();
    String javaVersion = Runtime.class.getPackage().getImplementationVersion();
    String javaSpecificationVersion = System.getProperty("java.specification.version");

    System.out.println("OS details:");
    System.out.println("  " + Detector.DETECTED_NAME + ": " + osProperties.get(Detector.DETECTED_NAME));
    System.out.println("  " + Detector.DETECTED_ARCH + ": " + osProperties.get(Detector.DETECTED_ARCH));
    System.out.println(/*www .j  a  va2s  .c o  m*/
            "  " + Detector.DETECTED_CLASSIFIER + ": " + osProperties.get(Detector.DETECTED_CLASSIFIER));
    System.out.println("  " + Detector.DETECTED_RELEASE + ": " + osProperties.get(Detector.DETECTED_RELEASE));
    System.out.println("  " + Detector.DETECTED_RELEASE_VERSION + ": "
            + osProperties.get(Detector.DETECTED_RELEASE_VERSION));
    System.out.println("JVM details:");
    System.out.println("  Java version: " + javaVersion);
    System.out.println("  Java specification version: " + javaSpecificationVersion);
    System.out.println("  JVM bit mode: " + bitMode);
    System.out.println("OpenSSL details:");
    System.out.println("  open ssl is available: " + openSslIsAvailable);
    System.out.println("  ALPN is supported: " + openSslAlpnIsSupported);

    String osClassifier = (String) osProperties.get(Detector.DETECTED_CLASSIFIER);

    boolean compatible = true;
    boolean warnings = false;
    System.out.println("Checking compatibility...");
    if (supportedClassifiers.contains(osClassifier)) {
        System.out.println("  [PASS] This OS + architecture is supported.");
    } else {
        System.out.println("  [FAIL] This OS + architecture is NOT supported.");
        compatible = false;
    }
    if (bitMode.equals("64")) {
        System.out.println("  [PASS] 64-bit JVM is supported.");
    } else {
        System.out.println("  [FAIL] " + bitMode + "-bit JVM is NOT supported.");
        compatible = false;
    }
    if (openSslIsAvailable) {
        System.out.println("  [PASS] Open SSL is available");
    } else {
        System.out.println("  [FAIL] Open SSL is NOT available");
        if (OpenSsl.unavailabilityCause() != null) {
            System.out.println("         Open SSL Unavailability cause:");
            OpenSsl.unavailabilityCause().printStackTrace(System.out);
        }
        compatible = false;
    }
    if (openSslAlpnIsSupported) {
        System.out.println("  [PASS] Open SSL ALPN is supported");
    } else {
        System.out.println("  [FAIL] Open SSL ALPN is NOT supported");
        compatible = false;
    }
    if (javaSpecificationVersion == null) {
        System.out.println("  [WARN] Couldn't detect java specification version.");
        warnings = true;
    } else if (javaSpecificationVersion.equals("1.7")) {
        System.out.println("  [WARN] gRPC doesn't work on Google App Engine Standard under Java 1.7");
        warnings = true;
    }
    if (!compatible) {
        System.out.println("Result: FAIL");
        System.out.println("  Your environment is not supported by Forked Tomcat Native.");
        System.out.println("  See http://netty.io/wiki/forked-tomcat-native.html for details.");
        System.out.println("  This means that you won't be able to use grpc-based APIs, but");
        System.out.println("  http1-based APIs should still work.");
    } else {
        System.out.println("Result: UNKNOWN (checker implementation not complete)");
        System.out.println("  Based on what was checked, nothing was identified that would");
        System.out.println("  prevent you from using grpc-based APIs.");
        if (warnings) {
            System.out.println("  However, there were some warnings to watch out for.");
        }
    }

    return compatible;
}

From source file:com.hop.hhxx.example.http2.helloworld.client.Http2Client.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*  w  w w  .j a  va  2 s  .  c o  m*/
        SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
        sslCtx = SslContextBuilder.forClient().sslProvider(provider)
                /* NOTE: the cipher filter may not include all ciphers required by the HTTP/2 specification.
                 * Please refer to the HTTP/2 specification for cipher requirements. */
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .trustManager(InsecureTrustManagerFactory.INSTANCE)
                .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN,
                        // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
                        SelectorFailureBehavior.NO_ADVERTISE,
                        // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
                        SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2,
                        ApplicationProtocolNames.HTTP_1_1))
                .build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup workerGroup = new NioEventLoopGroup();
    Http2ClientInitializer initializer = new Http2ClientInitializer(sslCtx, Integer.MAX_VALUE);

    try {
        // Configure the client.
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.remoteAddress(HOST, PORT);
        b.handler(initializer);

        // Start the client.
        Channel channel = b.connect().syncUninterruptibly().channel();
        System.out.println("Connected to [" + HOST + ':' + PORT + ']');

        // Wait for the HTTP/2 upgrade to occur.
        Http2SettingsHandler http2SettingsHandler = initializer.settingsHandler();
        http2SettingsHandler.awaitSettings(5, TimeUnit.SECONDS);

        HttpResponseHandler responseHandler = initializer.responseHandler();
        int streamId = 3;
        HttpScheme scheme = SSL ? HttpScheme.HTTPS : HttpScheme.HTTP;
        AsciiString hostName = new AsciiString(HOST + ':' + PORT);
        System.err.println("Sending request(s)...");
        if (URL != null) {
            // Create a simple GET request.
            FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, URL);
            request.headers().add(HttpHeaderNames.HOST, hostName);
            request.headers().add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), scheme.name());
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
            responseHandler.put(streamId, channel.writeAndFlush(request), channel.newPromise());
            streamId += 2;
        }
        if (URL2 != null) {
            // Create a simple POST request with a body.
            FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, POST, URL2,
                    Unpooled.copiedBuffer(URL2DATA.getBytes(CharsetUtil.UTF_8)));
            request.headers().add(HttpHeaderNames.HOST, hostName);
            request.headers().add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), scheme.name());
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
            responseHandler.put(streamId, channel.writeAndFlush(request), channel.newPromise());
            streamId += 2;
        }
        responseHandler.awaitResponses(5, TimeUnit.SECONDS);
        System.out.println("Finished HTTP/2 request(s)");

        // Wait until the connection is closed.
        channel.close().syncUninterruptibly();
    } finally {
        workerGroup.shutdownGracefully();
    }
}

From source file:com.relayrides.pushy.apns.ApnsClientBuilder.java

License:Open Source License

/**
 * Constructs a new {@link ApnsClient} with the previously-set configuration.
 *
 * @return a new ApnsClient instance with the previously-set configuration
 *
 * @throws SSLException if an SSL context could not be created for the new client for any reason
 *
 * @since 0.8//from   w w w. ja  va2  s .  co m
 */
public ApnsClient build() throws SSLException {
    final SslContext sslContext;
    {
        final SslProvider sslProvider;

        if (this.preferredSslProvider != null) {
            sslProvider = this.preferredSslProvider;
        } else {
            if (OpenSsl.isAvailable()) {
                if (OpenSsl.isAlpnSupported()) {
                    log.info("Native SSL provider is available and supports ALPN; will use native provider.");
                    sslProvider = SslProvider.OPENSSL;
                } else {
                    log.info(
                            "Native SSL provider is available, but does not support ALPN; will use JDK SSL provider.");
                    sslProvider = SslProvider.JDK;
                }
            } else {
                log.info("Native SSL provider not available; will use JDK SSL provider.");
                sslProvider = SslProvider.JDK;
            }
        }

        final SslContextBuilder sslContextBuilder = SslContextBuilder.forClient().sslProvider(sslProvider)
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .applicationProtocolConfig(
                        new ApplicationProtocolConfig(Protocol.ALPN, SelectorFailureBehavior.NO_ADVERTISE,
                                SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2));

        if (this.trustedServerCertificatePemFile != null) {
            sslContextBuilder.trustManager(this.trustedServerCertificatePemFile);
        } else if (this.trustedServerCertificateInputStream != null) {
            sslContextBuilder.trustManager(this.trustedServerCertificateInputStream);
        } else if (this.trustedServerCertificates != null) {
            sslContextBuilder.trustManager(this.trustedServerCertificates);
        }

        sslContext = sslContextBuilder.build();
    }

    final ApnsClient apnsClient = new ApnsClient(sslContext, this.eventLoopGroup);

    apnsClient.setMetricsListener(this.metricsListener);
    apnsClient.setProxyHandlerFactory(this.proxyHandlerFactory);

    if (this.connectionTimeout != null) {
        apnsClient.setConnectionTimeout((int) this.connectionTimeoutUnit.toMillis(this.connectionTimeout));
    }

    if (this.writeTimeout != null) {
        apnsClient.setWriteTimeout(this.writeTimeoutUnit.toMillis(this.writeTimeout));
    }

    if (this.gracefulShutdownTimeout != null) {
        apnsClient.setGracefulShutdownTimeout(
                this.gracefulShutdownTimeoutUnit.toMillis(this.gracefulShutdownTimeout));
    }

    return apnsClient;
}

From source file:com.relayrides.pushy.apns.MockApnsServerBuilder.java

License:Open Source License

/**
 * Constructs a new {@link MockApnsServer} with the previously-set configuration.
 *
 * @return a new MockApnsServer instance with the previously-set configuration
 *
 * @throws SSLException if an SSL context could not be created for the new server for any reason
 *
 * @since 0.8/*  www.  ja va2  s.c o m*/
 */
public MockApnsServer build() throws SSLException {
    final SslContext sslContext;
    {
        final SslProvider sslProvider;

        if (this.preferredSslProvider != null) {
            sslProvider = this.preferredSslProvider;
        } else {
            if (OpenSsl.isAvailable()) {
                if (OpenSsl.isAlpnSupported()) {
                    log.info("Native SSL provider is available and supports ALPN; will use native provider.");
                    sslProvider = SslProvider.OPENSSL;
                } else {
                    log.info(
                            "Native SSL provider is available, but does not support ALPN; will use JDK SSL provider.");
                    sslProvider = SslProvider.JDK;
                }
            } else {
                log.info("Native SSL provider not available; will use JDK SSL provider.");
                sslProvider = SslProvider.JDK;
            }
        }

        final SslContextBuilder sslContextBuilder;

        if (this.certificateChain != null && this.privateKey != null) {
            sslContextBuilder = SslContextBuilder.forServer(this.privateKey, this.privateKeyPassword,
                    this.certificateChain);
        } else if (this.certificateChainPemFile != null && this.privateKeyPkcs8File != null) {
            sslContextBuilder = SslContextBuilder.forServer(this.certificateChainPemFile,
                    this.privateKeyPkcs8File, this.privateKeyPassword);
        } else if (this.certificateChainInputStream != null && this.privateKeyPkcs8InputStream != null) {
            sslContextBuilder = SslContextBuilder.forServer(this.certificateChainInputStream,
                    this.privateKeyPkcs8InputStream, this.privateKeyPassword);
        } else {
            throw new IllegalStateException("Must specify server credentials before building a mock server.");
        }

        sslContextBuilder.sslProvider(sslProvider)
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .clientAuth(ClientAuth.OPTIONAL).applicationProtocolConfig(
                        new ApplicationProtocolConfig(Protocol.ALPN, SelectorFailureBehavior.NO_ADVERTISE,
                                SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2));

        sslContext = sslContextBuilder.build();
    }

    final MockApnsServer server = new MockApnsServer(sslContext, this.eventLoopGroup);
    server.setEmulateInternalErrors(this.emulateInternalErrors);

    return server;
}

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

License:Open Source License

public BenchmarkApnsServer(final InputStream certificateChainInputStream,
        final InputStream privateKeyPkcs8InputStream, final NioEventLoopGroup eventLoopGroup)
        throws SSLException {
    final SslContext sslContext;
    {//w  w  w .j a  v  a  2  s  . co m
        final SslProvider sslProvider;

        if (OpenSsl.isAvailable()) {
            if (OpenSsl.isAlpnSupported()) {
                sslProvider = SslProvider.OPENSSL;
            } else {
                sslProvider = SslProvider.JDK;
            }
        } else {
            sslProvider = SslProvider.JDK;
        }

        sslContext = SslContextBuilder.forServer(certificateChainInputStream, privateKeyPkcs8InputStream, null)
                .sslProvider(sslProvider)
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .clientAuth(ClientAuth.OPTIONAL)
                .applicationProtocolConfig(
                        new ApplicationProtocolConfig(ApplicationProtocolConfig.Protocol.ALPN,
                                ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
                                ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
                                ApplicationProtocolNames.HTTP_2))
                .build();
    }

    this.bootstrap = new ServerBootstrap();
    this.bootstrap.group(eventLoopGroup);

    this.bootstrap.channel(NioServerSocketChannel.class);
    this.bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(final SocketChannel channel) throws Exception {
            final SslHandler sslHandler = sslContext.newHandler(channel.alloc());
            channel.pipeline().addLast(sslHandler);
            channel.pipeline()
                    .addLast(new ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_1_1) {

                        @Override
                        protected void configurePipeline(final ChannelHandlerContext context,
                                final String protocol) throws Exception {
                            if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
                                context.pipeline().addLast(
                                        new BenchmarkApnsServerHandler.BenchmarkApnsServerHandlerBuilder()
                                                .initialSettings(new Http2Settings()
                                                        .maxConcurrentStreams(MAX_CONCURRENT_STREAMS))
                                                .build());

                                BenchmarkApnsServer.this.allChannels.add(context.channel());
                            } else {
                                throw new IllegalStateException("Unexpected protocol: " + protocol);
                            }
                        }
                    });
        }
    });
}

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

License:Open Source License

/**
 * Selects an SSL provider based on the availability of of an ALPN-capable native provider.
 *
 * @return an ALPN-capable native SSL provider if available, or else the JDK SSL provider
 *//*w  w w  .  j a v  a  2  s  .  c o m*/
public static SslProvider getSslProvider() {
    final SslProvider sslProvider;

    if (OpenSsl.isAvailable()) {
        if (OpenSsl.isAlpnSupported()) {
            log.info("Native SSL provider is available and supports ALPN; will use native provider.");
            sslProvider = SslProvider.OPENSSL;
        } else {
            log.info("Native SSL provider is available, but does not support ALPN; will use JDK SSL provider.");
            sslProvider = SslProvider.JDK;
        }
    } else {
        log.info("Native SSL provider not available; will use JDK SSL provider.");
        sslProvider = SslProvider.JDK;
    }

    return sslProvider;
}

From source file:com.vela.iot.active.netty.http2.server.Http2Server.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {// w w  w .  j  ava  2  s.  co  m
        SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).sslProvider(provider)
                /*
                * NOTE: the cipher filter may not include all ciphers
                * required by the HTTP/2 specification. Please refer to the
                * HTTP/2 specification for cipher requirements.
                */
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN,
                        // NO_ADVERTISE is currently the only mode
                        // supported by both OpenSsl and JDK
                        // providers.
                        SelectorFailureBehavior.NO_ADVERTISE,
                        // ACCEPT is currently the only mode
                        // supported by both OpenSsl and JDK
                        // providers.
                        SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2,
                        ApplicationProtocolNames.HTTP_1_1))
                .build();
    } else {
        sslCtx = null;
    }
    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup(7);
    try {
        LastInboundHandler serverLastInboundHandler = new SharableLastInboundHandler();
        ServerBootstrap b = new ServerBootstrap();
        // BACKLOG?ServerSocket?????1Java50
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new Http2Codec(true, serverLastInboundHandler));
                        //p.addLast(new HttpContentCompressor(1));
                        p.addLast(new HelloWorldHttp2HandlerBuilder().build());
                    }
                });

        Channel ch = b.bind(HOST, PORT).sync().channel();

        System.err.println("Open your HTTP/2-enabled web browser and navigate to " + (SSL ? "https" : "http")
                + "://127.0.0.1:" + PORT + '/');

        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.vmware.xenon.host.XenonHostWithPeerListener.java

License:Open Source License

private int startPeerListener() throws Throwable {
    if (this.hostArgs.nodeGroupPublicUri == null) {
        return ServiceHost.PORT_VALUE_LISTENER_DISABLED;
    }/*www  .j a  va  2s .  c om*/

    URI uri = URI.create(this.hostArgs.nodeGroupPublicUri);
    NettyHttpListener peerListener = new NettyHttpListener(this);

    boolean isHttps = uri.getScheme().equals("https");
    if (isHttps) {
        SslContextBuilder builder;
        if (this.hostArgs.peerCertificateFile != null && this.hostArgs.peerKeyFile != null) {
            builder = SslContextBuilder.forServer(this.hostArgs.peerCertificateFile.toFile(),
                    this.hostArgs.peerKeyFile.toFile(), this.hostArgs.peerKeyPassphrase);
        } else {
            builder = SslContextBuilder.forServer(this.hostArgs.certificateFile.toFile(),
                    this.hostArgs.keyFile.toFile(), this.hostArgs.keyPassphrase);
        }

        if (OpenSsl.isAlpnSupported()) {
            builder.ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                    .applicationProtocolConfig(
                            new ApplicationProtocolConfig(ApplicationProtocolConfig.Protocol.ALPN,
                                    ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
                                    ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
                                    ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1));
        }

        peerListener.setSSLContext(builder.build());
    }

    peerListener.start(uri.getPort(), uri.getHost());
    int assignedPort = peerListener.getPort();
    log(Level.INFO, "Started peer listener on %s",
            UriUtils.buildUri(uri.getScheme(), uri.getHost(), assignedPort, null, null));
    return assignedPort;
}