Example usage for io.netty.handler.ssl.util SelfSignedCertificate SelfSignedCertificate

List of usage examples for io.netty.handler.ssl.util SelfSignedCertificate SelfSignedCertificate

Introduction

In this page you can find the example usage for io.netty.handler.ssl.util SelfSignedCertificate SelfSignedCertificate.

Prototype

public SelfSignedCertificate() throws CertificateException 

Source Link

Document

Creates a new instance.

Usage

From source file:io.crate.protocols.postgres.SslReqHandlerTest.java

/**
 * Uses a simple (and insecure) self-signed certificate.
 *///from  w ww . j av a 2 s .  c om
private static SslContext getSelfSignedSslContext() {
    try {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        return SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey())
                .trustManager(InsecureTrustManagerFactory.INSTANCE).startTls(false).build();
    } catch (Exception e) {
        throw new RuntimeException("Couldn't setup self signed certificate", e);
    }
}

From source file:io.netty.example.echo.EchoServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/* w  ww . ja  v  a 2 s  .  co m*/
        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();
    final EchoServerHandler serverHandler = new EchoServerHandler();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        if (sslCtx != null) {
                            p.addLast(sslCtx.newHandler(ch.alloc()));
                        }
                        //p.addLast(new LoggingHandler(LogLevel.INFO));
                        p.addLast(serverHandler);
                    }
                });

        // Start the server.
        ChannelFuture f = b.bind(PORT).sync();

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:io.pravega.segmentstore.server.host.handler.PravegaConnectionListener.java

License:Open Source License

public void startListening() {
    // Configure SSL.
    final SslContext sslCtx;
    if (ssl) {/* w w w. j a  va 2  s. c  o m*/
        try {
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
        } catch (CertificateException | SSLException e) {
            throw new RuntimeException(e);
        }
    } else {
        sslCtx = null;
    }
    boolean nio = false;
    try {
        bossGroup = new EpollEventLoopGroup(1);
        workerGroup = new EpollEventLoopGroup();
    } catch (ExceptionInInitializerError | NoClassDefFoundError e) {
        nio = true;
        bossGroup = new NioEventLoopGroup(1);
        workerGroup = new NioEventLoopGroup();
    }

    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(nio ? NioServerSocketChannel.class : EpollServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    if (sslCtx != null) {
                        p.addLast(sslCtx.newHandler(ch.alloc()));
                    }
                    ServerConnectionInboundHandler lsh = new ServerConnectionInboundHandler();
                    // p.addLast(new LoggingHandler(LogLevel.INFO));
                    p.addLast(new ExceptionLoggingHandler(ch.remoteAddress().toString()),
                            new CommandEncoder(null),
                            new LengthFieldBasedFrameDecoder(MAX_WIRECOMMAND_SIZE, 4, 4), new CommandDecoder(),
                            new AppendDecoder(), lsh);
                    lsh.setRequestProcessor(new AppendProcessor(store, lsh,
                            new PravegaRequestProcessor(store, lsh, statsRecorder), statsRecorder));
                }
            });

    // Start the server.
    serverChannel = b.bind(host, port).awaitUninterruptibly().channel();
}

From source file:io.riox.springxd.sinks.websocket.NettyWebSocketServer.java

License:Apache License

public void run() throws SSLException, CertificateException, InterruptedException {
    // Configure SSL.
    final SslContext sslCtx;
    if (ssl) {//w  w  w  .  j  a va 2 s  . c om
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
    } else {
        sslCtx = null;
    }

    new ServerBootstrap().group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new NettyWebSocketServerInitializer(sslCtx)).bind(port).sync().channel();

    log.info("************************************************");
    log.info("Started netty websocket server on port {}", port);
    log.info("************************************************");
}

From source file:io.viewserver.network.netty.tcp.NettyTcpEndpoint.java

License:Apache License

@Override
public ServerBootstrap getServerBootstrap(EventLoopGroup parentGroup, EventLoopGroup childGroup,
        ChannelHandler handler) {//from   www. jav  a2 s  .c om
    SslContext sslContext;
    if (this.uri.getScheme().equals("tcps")) {
        if (keyCertChainFile == null) {
            log.warn("No certificate provided for WSS endpoint - will use self-signed");
            try {
                SelfSignedCertificate certificate = new SelfSignedCertificate();
                keyCertChainFile = certificate.certificate();
                keyFile = certificate.privateKey();
                usingSelfSignedCertificate = true;
            } catch (CertificateException e) {
                throw new RuntimeException(e);
            }
        }
        try {
            sslContext = SslContextBuilder.forServer(keyCertChainFile, keyFile, keyPassword).build();
        } catch (SSLException e) {
            throw new RuntimeException(e);
        }
    } else if (this.uri.getScheme().equals("tcp")) {
        sslContext = null;
    } else {
        throw new IllegalArgumentException("Invalid scheme '" + uri.getScheme() + "' for web socket endpoint");
    }

    ServerBootstrap server = new ServerBootstrap();
    server.group(parentGroup, childGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<Channel>() {
                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    if (sslContext != null) {
                        pipeline.addLast(sslContext.newHandler(ch.alloc()));
                    }
                    pipeline.addLast(handler);
                }
            }).option(ChannelOption.TCP_NODELAY, true);
    server.bind(uri.getHost(), uri.getPort());
    return server;
}

From source file:io.viewserver.network.netty.websocket.NettyWebSocketEndpoint.java

License:Apache License

@Override
public ServerBootstrap getServerBootstrap(EventLoopGroup parentGroup, EventLoopGroup childGroup,
        ChannelHandler handler) {/*  w  w  w  . j av a  2  s.  co  m*/
    if (this.uri.getScheme().equals("wss")) {
        if (keyCertChainFile == null) {
            log.warn("No certificate provided for WSS endpoint - will use self-signed");
            try {
                SelfSignedCertificate certificate = new SelfSignedCertificate();
                keyCertChainFile = certificate.certificate();
                keyFile = certificate.privateKey();
                usingSelfSignedCertificate = true;
            } catch (CertificateException e) {
                throw new RuntimeException(e);
            }
        }
        try {
            serverSslContext = SslContextBuilder.forServer(keyCertChainFile, keyFile, keyPassword).build();
        } catch (SSLException e) {
            throw new RuntimeException(e);
        }
    } else if (!this.uri.getScheme().equals("ws")) {
        throw new IllegalArgumentException("Invalid scheme '" + uri.getScheme() + "' for web socket endpoint");
    }

    ServerBootstrap server = new ServerBootstrap();
    server.group(parentGroup, childGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<Channel>() {
                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    if (serverSslContext != null) {
                        pipeline.addLast(serverSslContext.newHandler(ch.alloc()));
                    }
                    pipeline.addLast(new HttpServerCodec());
                    pipeline.addLast(new HttpObjectAggregator(65536));
                    //                        pipeline.addLast(new WebSocketServerCompressionHandler());
                    pipeline.addLast("websocket", new WebSocketServerProtocolHandler("/"));
                    pipeline.addLast(new ChannelInboundHandlerAdapter() {
                        @Override
                        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                            if (evt == WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE) {
                                ChannelPipeline pipeline = ctx.channel().pipeline();
                                pipeline.addAfter("websocket", "ws-decoder-xx",
                                        new MessageToMessageDecoder<BinaryWebSocketFrame>() {
                                            @Override
                                            protected void decode(ChannelHandlerContext ctx,
                                                    BinaryWebSocketFrame msg, List<Object> out)
                                                    throws Exception {
                                                out.add(msg.content().retain());
                                            }
                                        });

                                pipeline.addAfter("websocket", "ws-encoder-xx",
                                        new MessageToMessageEncoder<ByteBuf>() {
                                            @Override
                                            protected void encode(ChannelHandlerContext ctx, ByteBuf msg,
                                                    List<Object> out) throws Exception {
                                                out.add(new BinaryWebSocketFrame(msg).retain());
                                            }
                                        });
                            }

                            super.userEventTriggered(ctx, evt);
                        }
                    });

                    pipeline.addLast("frameDecoder", new ChannelInboundHandlerAdapter());
                    pipeline.addLast("frameEncoder", new ChannelOutboundHandlerAdapter());
                    pipeline.addLast(handler);
                }
            });

    server.bind(uri.getPort());
    return server;
}

From source file:itlab.teleport.HttpServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    File_config.Read_ini();/*from  w  w w .  j  a  v  a 2s.co  m*/
    // Configure SSL.
    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.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new HttpServerInitializer(sslCtx));

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

        System.err.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:jlibs.wamp4j.netty.NettyServerEndpoint.java

License:Apache License

@Override
public void bind(final URI uri, final String subProtocols[], final AcceptListener listener) {
    final SslContext sslContext;
    if ("wss".equals(uri.getScheme())) {
        try {// w ww.  jav  a2  s.c o  m
            if (sslSettings == null) {
                SelfSignedCertificate ssc = new SelfSignedCertificate();
                sslSettings = new SSLSettings().keyFile(ssc.privateKey()).certificateFile(ssc.certificate());
            }
            ClientAuth clientAuth = ClientAuth.values()[sslSettings.clientAuthentication.ordinal()];
            sslContext = SslContextBuilder
                    .forServer(sslSettings.certificateFile, sslSettings.keyFile, sslSettings.keyPassword)
                    .clientAuth(clientAuth).trustManager(sslSettings.trustCertChainFile).build();
        } catch (Throwable thr) {
            listener.onError(thr);
            return;
        }
    } else if ("ws".equals(uri.getScheme()))
        sslContext = null;
    else
        throw new IllegalArgumentException("invalid protocol: " + uri.getScheme());

    int port = uri.getPort();
    if (port == -1)
        port = sslContext == null ? 80 : 443;
    ServerBootstrap bootstrap = new ServerBootstrap().group(eventLoopGroup)
            .channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.MAX_MESSAGES_PER_READ, 50000)
            .childOption(ChannelOption.WRITE_SPIN_COUNT, 50000)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    if (sslContext != null)
                        ch.pipeline().addLast(sslContext.newHandler(ch.alloc()));
                    ch.pipeline().addLast(new HttpServerCodec(), new HttpObjectAggregator(65536),
                            new Handshaker(uri, listener, subProtocols));
                }
            });
    bootstrap.bind(uri.getHost(), port).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                channel = future.channel();
                channel.attr(ACCEPT_LISTENER).set(listener);
                listener.onBind(NettyServerEndpoint.this);
            } else
                listener.onError(future.cause());
        }
    });
}

From source file:lee.study.server.BoomOnlineServer.java

License:Apache License

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

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

        Channel ch = b.bind(PORT).sync().channel();
        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:main.java.ch.epfl.lpd.ServerThread.java

License:Apache License

public void run() {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*from w ww. java 2s .c om*/
        SelfSignedCertificate ssc;
        try {
            ssc = new SelfSignedCertificate();
            sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            logger.error("Got exception", e);
        }
    } 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)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        /*
                        if (sslCtx != null) {
                           p.addLast(sslCtx.newHandler(ch.alloc()));
                        }
                        */
                        p.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
                        p.addLast("decoder", new StringDecoder());
                        p.addLast("encoder", new StringEncoder());
                        //p.addLast(new LoggingHandler(LogLevel.INFO));
                        p.addLast(new ServerHandler());
                    }
                });

        // Start the server.
        ChannelFuture f;
        try {
            f = b.bind(PORT).sync();
            // Wait until the server socket is closed.
            f.channel().closeFuture().sync();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            logger.error("Got exception", e);
        }

    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}