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

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

Introduction

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

Prototype

File certificate

To view the source code for io.netty.handler.ssl.util SelfSignedCertificate certificate.

Click Source Link

Usage

From source file:com.juaby.labs.rpc.server.Rpc2Server.java

License:Apache License

public void start() {
    RpcThreadFactory threadName = new RpcThreadFactory("RPC-SVR-WORKER", false);
    int threads = Runtime.getRuntime().availableProcessors() * 2 + 1;
    bossGroup = new NioEventLoopGroup(threads, threadName);

    workerGroup = new NioEventLoopGroup();
    try {// w  w  w .ja v  a  2 s  .c o m
        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) throws Exception {
                        ChannelPipeline p = ch.pipeline();

                        // Configure SSL.
                        final SslContext sslCtx;
                        if (SSL) {
                            SelfSignedCertificate ssc = new SelfSignedCertificate();
                            sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
                        } else {
                            sslCtx = null;
                        }

                        if (sslCtx != null) {
                            p.addLast(sslCtx.newHandler(ch.alloc()));
                        }
                        p.addLast(
                                //output
                                new Rpc2ServerEncoder(),
                                //input
                                new Rpc2ServerDecoder(ServiceConfig.MAX_OBJECT_SIZE), new Rpc2ServerHandler());
                    }
                });

        // Bind and start to accept incoming connections.
        //b.bind(HOST, PORT).sync().channel().closeFuture().sync();
        b.bind(host, port);
    } finally {
    }
}

From source file:com.linecorp.armeria.server.AbstractVirtualHostBuilder.java

License:Apache License

/**
 * Configures SSL or TLS of this {@link VirtualHost} with an auto-generated self-signed certificate.
 * <strong>Note:</strong> You should never use this in production but only for a testing purpose.
 *
 * @throws CertificateException if failed to generate a self-signed certificate
 *//*from w w  w  . java 2s .c  om*/
public B tlsSelfSigned() throws SSLException, CertificateException {
    final SelfSignedCertificate ssc = new SelfSignedCertificate(defaultHostname);
    return tls(ssc.certificate(), ssc.privateKey());
}

From source file:com.linecorp.armeria.server.http.HttpServerTest.java

License:Apache License

@Override
protected void configureServer(ServerBuilder sb) throws Exception {

    sb.numWorkers(1);/*from   w w  w .j ava 2  s  .  c  o m*/
    sb.port(0, SessionProtocol.HTTP);
    sb.port(0, SessionProtocol.HTTPS);

    SelfSignedCertificate ssc = new SelfSignedCertificate();
    sb.sslContext(SessionProtocol.HTTPS, ssc.certificate(), ssc.privateKey());

    sb.serviceUnder("/delay", new AbstractHttpService() {
        @Override
        protected void doGet(ServiceRequestContext ctx, HttpRequest req, HttpResponseWriter res) {
            final long delayMillis = Long.parseLong(ctx.mappedPath().substring(1));
            ctx.eventLoop().schedule(() -> res.respond(HttpStatus.OK), delayMillis, TimeUnit.MILLISECONDS);
        }
    });

    sb.serviceUnder("/informed_delay", new AbstractHttpService() {
        @Override
        protected void doGet(ServiceRequestContext ctx, HttpRequest req, HttpResponseWriter res) {
            final long delayMillis = Long.parseLong(ctx.mappedPath().substring(1));

            // Send 9 informational responses before sending the actual response.
            for (int i = 1; i <= 9; i++) {
                ctx.eventLoop().schedule(() -> res.respond(HttpStatus.PROCESSING), delayMillis * i / 10,
                        TimeUnit.MILLISECONDS);
            }

            // Send the actual response.
            ctx.eventLoop().schedule(() -> res.respond(HttpStatus.OK), delayMillis, TimeUnit.MILLISECONDS);
        }
    });

    sb.serviceUnder("/content_delay", new AbstractHttpService() {
        @Override
        protected void doGet(ServiceRequestContext ctx, HttpRequest req, HttpResponseWriter res) {
            final long delayMillis = Long.parseLong(ctx.mappedPath().substring(1));

            res.write(HttpHeaders.of(HttpStatus.OK));

            // Send 10 characters ('0' - '9') at fixed rate.
            for (int i = 0; i < 10; i++) {
                final int finalI = i;
                ctx.eventLoop().schedule(() -> {
                    res.write(HttpData.ofAscii(String.valueOf(finalI)));
                    if (finalI == 9) {
                        res.close();
                    }
                }, delayMillis * i / 10, TimeUnit.MILLISECONDS);
            }
        }
    });

    sb.serviceUnder("/path", new AbstractHttpService() {
        @Override
        protected void doHead(ServiceRequestContext ctx, HttpRequest req, HttpResponseWriter res) {
            res.write(HttpHeaders.of(HttpStatus.OK).setInt(HttpHeaderNames.CONTENT_LENGTH,
                    ctx.mappedPath().length()));
            res.close();
        }

        @Override
        protected void doGet(ServiceRequestContext ctx, HttpRequest req, HttpResponseWriter res) {
            res.write(HttpHeaders.of(HttpStatus.OK).setInt(HttpHeaderNames.CONTENT_LENGTH,
                    ctx.mappedPath().length()));
            res.write(HttpData.ofAscii(ctx.mappedPath()));
            res.close();
        }
    });

    sb.serviceAt("/echo", new AbstractHttpService() {
        @Override
        protected void doPost(ServiceRequestContext ctx, HttpRequest req, HttpResponseWriter res) {
            res.write(HttpHeaders.of(HttpStatus.OK));
            req.subscribe(new Subscriber<HttpObject>() {
                private Subscription s;

                @Override
                public void onSubscribe(Subscription s) {
                    this.s = s;
                    s.request(1);
                }

                @Override
                public void onNext(HttpObject http2Object) {
                    if (http2Object instanceof HttpData) {
                        res.write(http2Object);
                    }
                    s.request(1);
                }

                @Override
                public void onError(Throwable t) {
                    res.close(t);
                }

                @Override
                public void onComplete() {
                    res.close();
                }
            });
        }
    });

    sb.serviceAt("/count", new CountingService(false));
    sb.serviceAt("/slow_count", new CountingService(true));

    sb.serviceUnder("/zeroes", new AbstractHttpService() {
        @Override
        protected void doGet(ServiceRequestContext ctx, HttpRequest req, HttpResponseWriter res) {
            final long length = Long.parseLong(ctx.mappedPath().substring(1));
            res.write(HttpHeaders.of(HttpStatus.OK).setLong(HttpHeaderNames.CONTENT_LENGTH, length));

            stream(res, length, STREAMING_CONTENT_CHUNK_LENGTH);
        }
    });

    final Function<Service<HttpRequest, HttpResponse>, Service<HttpRequest, HttpResponse>> decorator = delegate -> new DecoratingService<HttpRequest, HttpResponse, HttpRequest, HttpResponse>(
            delegate) {
        @Override
        public HttpResponse serve(ServiceRequestContext ctx, HttpRequest req) throws Exception {
            ctx.setRequestTimeoutMillis(serverRequestTimeoutMillis);
            ctx.setMaxRequestLength(serverMaxRequestLength);
            return delegate().serve(ctx, req);
        }
    };
    sb.decorator(decorator);
}

From source file:com.linecorp.armeria.test.webapp.WebAppContainerTest.java

License:Apache License

@Override
protected void configureServer(ServerBuilder sb) throws Exception {
    sb.port(0, SessionProtocol.HTTP);/* w ww  .j  av a  2s . co m*/
    sb.port(0, SessionProtocol.HTTPS);
    SelfSignedCertificate certificate = new SelfSignedCertificate();
    sb.sslContext(SessionProtocol.HTTPS, certificate.certificate(), certificate.privateKey());
}

From source file:com.lm.WebSocketServer.java

License:Apache License

public static void main(String[] args) throws Exception {

    try (InputStream resourceAsStream = WebSocketServer.class.getResourceAsStream("/project.properties")) {
        PROPERTIES.load(resourceAsStream);
    } catch (IOException e) {
        e.printStackTrace();/*from w ww .  j  a v  a 2 s .  co  m*/
    }

    if (args.length > 0) {
        PROPERTIES.setProperty("port", args[0]);
    }

    if (args.length > 1) {
        PROPERTIES.setProperty("access_key", args[1]);
    }

    setLogConfig("file".equals(PROPERTIES.getProperty("log")));

    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
    } 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 WebSocketServerInitializer(sslCtx));

        int port = Integer.parseInt(PROPERTIES.getProperty("port", "8080"));
        Channel ch = b.bind(port).sync().channel();

        Console con = System.console();
        if (con != null) {
            while (ch.isOpen()) {
                String s = System.console().readLine().toLowerCase();
                switch (s) {
                case "logtofile":
                    setLogConfig(true);
                    break;
                case "logtoconsole":
                    setLogConfig(false);
                    break;
                case "exit":
                    for (Channel channel : CLIENT_NAMES.keySet()) {
                        channel.writeAndFlush(
                                new TextWebSocketFrame("03:  "));
                    }
                    ch.close();
                    break;
                }
            }
        }
        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.lxz.talk.websocketx.client.WebSocketClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    URI uri = new URI(URL);
    String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
    final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    final int port;
    if (uri.getPort() == -1) {
        if ("http".equalsIgnoreCase(scheme)) {
            port = 80;//w w w.  j  a  v  a2  s  .  co  m
        } else if ("https".equalsIgnoreCase(scheme)) {
            port = 443;
        } else {
            port = -1;
        }
    } else {
        port = uri.getPort();
    }

    if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme)) {
        System.err.println("Only WS(S) is supported.");
        return;
    }

    final boolean ssl = "wss".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
    } else {
        sslCtx = null;
    }

    EventLoopGroup group = new NioEventLoopGroup();
    try {
        // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00.
        // If you change it to V00, ping is not supported and remember to change
        // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline.
        final WebSocketClientHandler handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory
                .newHandshaker(uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders()));

        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) {
                ChannelPipeline p = ch.pipeline();
                if (sslCtx != null) {
                    p.addLast(sslCtx.newHandler(ch.alloc(), host, port));
                }
                p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), handler);
            }
        });

        Channel ch = b.connect(uri.getHost(), port).sync().channel();
        handler.handshakeFuture().sync();

        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            String msg = console.readLine();
            if (msg == null) {
                break;
            } else if ("bye".equals(msg.toLowerCase())) {
                ch.writeAndFlush(new CloseWebSocketFrame());
                ch.closeFuture().sync();
                break;
            } else if ("ping".equals(msg.toLowerCase())) {
                WebSocketFrame frame = new PingWebSocketFrame(
                        Unpooled.wrappedBuffer(new byte[] { 8, 1, 8, 1 }));
                ch.writeAndFlush(frame);
            } else {
                WebSocketFrame frame = new TextWebSocketFrame(msg);
                ch.writeAndFlush(frame);
            }
        }
    } finally {
        group.shutdownGracefully();
    }
}

From source file:com.lxz.talk.websocketx.server.WebSocketServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*  www .jav a2s . c  o m*/
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
    } 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 WebSocketServerInitializer(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:com.metasoft.empire.net.websocket.WebSocketServer.java

License:Apache License

public static void start() throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*from   w w w  . j  ava2  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 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:com.myseti.framework.monitor.net.MonitorServer.java

@Override
public void run() {
    try {//from   w  w  w  .  j av  a  2s  .c o m
        // Configure SSL.
        final SslContext sslCtx;
        if (SSL) {
            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 MonitorServerHandler()).childHandler(new MonitorServerInitializer(sslCtx));

            b.bind(PORT).sync().channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    } catch (Exception ex) {

    }
    super.run(); //To change body of generated methods, choose Tools | Templates.
}

From source file:com.netty.file.HttpUploadServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {//from www  . ja v a  2s.  c  om
        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 HttpUploadServerInitializer(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();
    }
}