Example usage for io.netty.handler.ssl SslContextBuilder forServer

List of usage examples for io.netty.handler.ssl SslContextBuilder forServer

Introduction

In this page you can find the example usage for io.netty.handler.ssl SslContextBuilder forServer.

Prototype

boolean forServer

To view the source code for io.netty.handler.ssl SslContextBuilder forServer.

Click Source Link

Usage

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  a va 2 s .  c  om
        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.common.http.netty.Netty2WaySslAuthTest.java

License:Open Source License

@Test
public void testCustomSslContext() throws Throwable {
    Path keyFile = getCanonicalFileForResource("/ssl/server.pem").toPath();
    Path certificateFile = getCanonicalFileForResource("/ssl/server.crt").toPath();
    SslContext customContext = SslContextBuilder.forServer(certificateFile.toFile(), keyFile.toFile(), null)
            .build();//  w ww .  ja v  a2s.c  om
    NettyHttpListener l = new NettyHttpListener(this.host);
    l.setSSLContext(customContext);

    // verify that we can not set context after host is started
    NettyHttpListener hostListener = (NettyHttpListener) this.host.getListener();
    try {
        hostListener.setSSLContext(customContext);
        throw new RuntimeException("call should have thrown an exception");
    } catch (IllegalStateException e) {

    }

    // now stop the host, replace the listener, and restart
    this.host.stop();
    this.host.setPort(0);
    this.host.setSecurePort(0);
    this.host.setListener(l);
    this.host.start();
    assertEquals(l, this.host.getListener());
    hostListener = (NettyHttpListener) this.host.getListener();
    assertEquals(hostListener.getSSLContext(), customContext);

    test2WaySsl();
}

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

License:Open Source License

@Override
public void setSSLContextFiles(URI certFile, URI keyFile, String keyPassphrase) throws Throwable {
    if (isListening()) {
        throw new IllegalStateException("listener already started");
    }//from w  ww  .ja  va 2  s.  co m
    this.sslContext = SslContextBuilder.forServer(new File(certFile), new File(keyFile), keyPassphrase).build();
}

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;
    }//from w w  w.j  a  va  2 s .c  o  m

    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;
}

From source file:com.yahoo.pulsar.broker.service.PulsarChannelInitializer.java

License:Apache License

@Override
protected void initChannel(SocketChannel ch) throws Exception {
    if (enableTLS) {
        File tlsCert = new File(serviceConfig.getTlsCertificateFilePath());
        File tlsKey = new File(serviceConfig.getTlsKeyFilePath());
        SslContextBuilder builder = SslContextBuilder.forServer(tlsCert, tlsKey);
        if (serviceConfig.isTlsAllowInsecureConnection()) {
            builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
        } else {/*w w w  .j  av  a2  s  .  com*/
            if (serviceConfig.getTlsTrustCertsFilePath().isEmpty()) {
                // Use system default
                builder.trustManager((File) null);
            } else {
                File trustCertCollection = new File(serviceConfig.getTlsTrustCertsFilePath());
                builder.trustManager(trustCertCollection);
            }
        }
        SslContext sslCtx = builder.clientAuth(ClientAuth.OPTIONAL).build();
        ch.pipeline().addLast(TLS_HANDLER, sslCtx.newHandler(ch.alloc()));
    }
    ch.pipeline().addLast("frameDecoder",
            new PulsarLengthFieldFrameDecoder(PulsarDecoder.MaxFrameSize, 0, 4, 0, 4));
    ch.pipeline().addLast("handler", new ServerCnx(brokerService));
}

From source file:com.yahoo.pulsar.discovery.service.ServiceChannelInitializer.java

License:Apache License

@Override
protected void initChannel(SocketChannel ch) throws Exception {
    if (enableTLS) {
        File tlsCert = new File(serviceConfig.getTlsCertificateFilePath());
        File tlsKey = new File(serviceConfig.getTlsKeyFilePath());
        SslContextBuilder builder = SslContextBuilder.forServer(tlsCert, tlsKey);
        // allows insecure connection
        builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
        SslContext sslCtx = builder.clientAuth(ClientAuth.OPTIONAL).build();
        ch.pipeline().addLast(TLS_HANDLER, sslCtx.newHandler(ch.alloc()));
    }// www  .ja  v  a2 s .c o m
    ch.pipeline().addLast("frameDecoder",
            new PulsarLengthFieldFrameDecoder(PulsarDecoder.MaxFrameSize, 0, 4, 0, 4));
    ch.pipeline().addLast("handler", new ServerConnection(discoveryService));
}

From source file:com.zy.learning.netty.websocket.WebSocketServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*from w  ww  . ja va 2s  .c  o m*/
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ProtocolDetectorInitializer());
        //.childHandler(new WebSocketServerInitializer(sslCtx));

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

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

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

From source file:demo.netty.discard.DiscardServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*from   w ww  . j  av  a  2 s  .  c o  m*/
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    public void initChannel(SocketChannel ch) {
                        ChannelPipeline p = ch.pipeline();
                        if (sslCtx != null) {
                            p.addLast(sslCtx.newHandler(ch.alloc()));
                        }
                        p.addLast(new DiscardServerHandler());
                    }
                });

        // Bind and start to accept incoming connections.
        ChannelFuture f = b.bind(PORT).sync();

        // Wait until the server socket is closed.
        // In this example, this does not happen, but you can do that to gracefully
        // shut down your server.
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}

From source file:dpfmanager.shell.modules.server.core.HttpServer.java

License:Open Source License

public void start() throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*from w  ww  . j a v  a 2  s .co m*/
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup);
        b.channel(NioServerSocketChannel.class);
        b.handler(new LoggingHandler(LogLevel.INFO));
        b.childHandler(new HttpServerInitializer(sslCtx, context));

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

        context.send(BasicConfig.MODULE_MESSAGE, new LogMessage(getClass(), Level.DEBUG,
                DPFManagerProperties.getBundle().getString("startedServer").replace("%1", getServerUri()),
                true));

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

From source file:edumsg.netty.EduMsgNettyServer.java

License:Open Source License

public static void main(String[] args) throws Exception {
    Logger log = Logger.getLogger(EduMsgNettyServer.class);
    // Configure SSL.
    EduMsgRedis.redisCache.flushDB();/*from  w  w w .  j a  v a2  s.co m*/
    //        EduMsgRedis.bgSave();
    final SslContext sslCtx;
    if (SSL) {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new EduMsgNettyServerInitializer(sslCtx));
        //            b.option(ChannelOption.SO_KEEPALIVE, true);
        Channel ch = b.bind(PORT).sync().channel();

        System.err.println("Server is listening on " + (SSL ? "https" : "http") + "://127.0.0.1:" + PORT + '/');

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