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:com.gdut.Netty_testing.dongjun.server.ElectricControlServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*from  ww  w. j  av a2  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 ElectricControlServerInitializer(sslCtx));

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

}

From source file:com.gdut.Netty_testing.time_server.server.TimeServer.java

License:Apache License

/**
 * /*from w ww.j av  a2  s  .  c  o  m*/
 * @Title: main
 * @Description: TODO
 * @param @param args
 * @param @throws Exception
 * @return void
 * @throws
 */
public static void main(String[] args) throws Exception {
    // 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.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), new TimeEncoder(),
                                new TimeServerHandler());
                        // new TimeEncoder(),
                    }
                });

        // Start the server.
        ChannelFuture f = b.bind(PORT).sync();
        f.addListener(new GenericFutureListener<Future<? super Void>>() {

            public void operationComplete(Future<? super Void> future) throws Exception {
                // TODO Auto-generated method stub
                System.out.println("success " + future.isSuccess());
            }
        });

        // 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:com.hazelcast.openshift.TunnelServer.java

License:Open Source License

@Override
protected ServerBootstrap createBootstrap(int localPort) throws Exception {
    SslContext sslContext;/*from  w w  w.j a va  2 s  . c om*/
    if (!ssl) {
        sslContext = null;

    } else {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslContext = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    }

    System.out.println("Creating serverside http-socket: (" + localPort + ") => (" + forwardHost + ":"
            + forwardPort + ")");
    return new ServerBootstrap().option(ChannelOption.SO_BACKLOG, 20).group(getBossGroup(), getWorkerGroup())
            .channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {

                @Override
                protected void initChannel(SocketChannel channel) throws Exception {
                    ChannelPipeline pipeline = channel.pipeline();
                    if (sslContext != null) {
                        pipeline.addLast("ssl", sslContext.newHandler(channel.alloc()));
                    }
                    pipeline.addLast("http-codec", new HttpServerCodec());
                    pipeline.addLast(new TunnelClientAcceptor(getWorkerGroup(), forwardHost, forwardPort));
                }
            });

}

From source file:com.hipishare.chat.test.EchoServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*  ww  w  .j  av a2s.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();
    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(new IdleStateHandler(30, 10, 0, TimeUnit.SECONDS));
                        p.addLast(new HeartBeatHandler());
                        p.addLast(new EchoServerHandler());
                    }
                });

        // 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:com.hzmsc.scada.Jmtis.server.PortUnificationServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL context
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    final SslContext sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*  w w  w  . j ava  2  s  .co 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 {
                        System.out.println("initChannel..........................");
                        ch.pipeline().addLast(new PortUnificationServerHandler(sslCtx));
                    }
                });

        // Bind and start to accept incoming connections.
        b.bind(PORT).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.intuit.karate.netty.FeatureServer.java

License:Open Source License

private static SslContext getSslContext() { // self signed
    try {/* ww w  .j  a  va  2  s.  co m*/
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        return SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.intuit.karate.netty.NettyUtils.java

License:Open Source License

public static void createSelfSignedCertificate(File cert, File key) {
    try {/* www. ja  v a 2  s  .  co  m*/
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        FileUtils.copy(ssc.certificate(), cert);
        FileUtils.copy(ssc.privateKey(), key);
    } catch (Exception e) {
        throw new RuntimeException();
    }
}

From source file:com.jt.flash.proxy.server.ProxyServer.java

License:Apache License

public void start() {
    try {//from w w w  .ja v a 2  s.  co m
        log.info("Proxying server start at port {}", upstreamPort);
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        SslContext sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
        ConfigService.reload(configDao.loadLastest());
        ServerBootstrap b = new ServerBootstrap();
        channel = b.group(proxyServerBossGroup, proxyServerWorkerGroup).channel(NioServerSocketChannel.class)
                .childOption(ChannelOption.AUTO_READ, false).handler(new LoggingHandler(LogLevel.DEBUG))
                .childHandler(new ProxyInitializer(sslCtx)).bind(upstreamPort).channel();
    } catch (Exception e) {
        log.warn("start proxy server fail", e);
    }
}

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 {//  ww  w  .j a  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.http.HttpServerTest.java

License:Apache License

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

    sb.numWorkers(1);//from   w  w w  .  ja  v  a2  s  .co  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);
}