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

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

Introduction

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

Prototype

public static SslContextBuilder forClient() 

Source Link

Document

Creates a builder for new client-side SslContext .

Usage

From source file:com.thomas.netty4.websocket.client.GxWebSocketProducer.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;//from w w w . j a  v a  2 s .c o 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) {
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } 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 GxWebSocketClientHandler handler = new GxWebSocketClientHandler(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();

        new Thread(new HelloWS(ch)).start();

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

From source file:com.topsec.bdc.platform.api.test.discard.DiscardClient.java

License:Apache License

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

    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*from ww  w .  java2 s. c o m*/
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {

                ChannelPipeline p = ch.pipeline();
                if (sslCtx != null) {
                    p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
                }
                p.addLast(new DiscardClientHandler());
            }
        });

        // Make the connection attempt.
        ChannelFuture f = b.connect(HOST, PORT).sync();

        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}

From source file:com.topsec.bdc.platform.api.test.echo.EchoClient.java

License:Apache License

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

    // Configure SSL.git
    final SslContext sslCtx;
    if (SSL) {//from  www  . j av  a 2s  .  c  o  m
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {

                        ChannelPipeline p = ch.pipeline();
                        if (sslCtx != null) {
                            p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
                        }
                        //p.addLast(new LoggingHandler(LogLevel.INFO));
                        p.addLast(new EchoClientHandler());
                    }
                });

        // Start the client.
        ChannelFuture f = b.connect(HOST, PORT).sync();

        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down the event loop to terminate all threads.
        group.shutdownGracefully();
    }
}

From source file:com.topsec.bdc.platform.api.test.http.snoop.HttpSnoopClient.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();
    String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    int port = uri.getPort();
    if (port == -1) {
        if ("http".equalsIgnoreCase(scheme)) {
            port = 80;/*  ww  w  .  j  a v  a 2 s  .  c o  m*/
        } else if ("https".equalsIgnoreCase(scheme)) {
            port = 443;
        }
    }

    if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
        System.err.println("Only HTTP(S) is supported.");
        return;
    }

    // Configure SSL context if necessary.
    final boolean ssl = "https".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new HttpSnoopClientInitializer(sslCtx));

        // Make the connection attempt.
        Channel ch = b.connect(host, port).sync().channel();

        // Prepare the HTTP request.
        HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
                uri.getRawPath());
        request.headers().set(HttpHeaders.Names.HOST, host);
        request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
        request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);

        // Set some example cookies.
        request.headers().set(HttpHeaders.Names.COOKIE, ClientCookieEncoder
                .encode(new DefaultCookie("my-cookie", "foo"), new DefaultCookie("another-cookie", "bar")));

        // Send the HTTP request.
        ch.writeAndFlush(request);

        // Wait for the server to close the connection.
        ch.closeFuture().sync();
    } finally {
        // Shut down executor threads to exit.
        group.shutdownGracefully();
    }
}

From source file:com.topsec.bdc.platform.api.test.http.upload.HttpUploadClient.java

License:Apache License

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

    String postSimple, postFile, get;
    if (BASE_URL.endsWith("/")) {
        postSimple = BASE_URL + "formpost";
        postFile = BASE_URL + "formpostmultipart";
        get = BASE_URL + "formget";
    } else {// w  w w  .  j  a va  2  s  .  co m
        postSimple = BASE_URL + "/formpost";
        postFile = BASE_URL + "/formpostmultipart";
        get = BASE_URL + "/formget";
    }

    URI uriSimple = new URI(postSimple);
    String scheme = uriSimple.getScheme() == null ? "http" : uriSimple.getScheme();
    String host = uriSimple.getHost() == null ? "127.0.0.1" : uriSimple.getHost();
    int port = uriSimple.getPort();
    if (port == -1) {
        if ("http".equalsIgnoreCase(scheme)) {
            port = 80;
        } else if ("https".equalsIgnoreCase(scheme)) {
            port = 443;
        }
    }

    if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
        System.err.println("Only HTTP(S) is supported.");
        return;
    }

    final boolean ssl = "https".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    URI uriFile = new URI(postFile);
    File file = new File(FILE);
    if (!file.canRead()) {
        throw new FileNotFoundException(FILE);
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();

    // setup the factory: here using a mixed memory/disk based on size threshold
    HttpDataFactory factory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE); // Disk if MINSIZE exceed

    DiskFileUpload.deleteOnExitTemporaryFile = true; // should delete file on exit (in normal exit)
    DiskFileUpload.baseDirectory = null; // system temp directory
    DiskAttribute.deleteOnExitTemporaryFile = true; // should delete file on exit (in normal exit)
    DiskAttribute.baseDirectory = null; // system temp directory

    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new HttpUploadClientIntializer(sslCtx));

        // Simple Get form: no factory used (not usable)
        List<Entry<String, String>> headers = formget(b, host, port, get, uriSimple);
        if (headers == null) {
            factory.cleanAllHttpDatas();
            return;
        }

        // Simple Post form: factory used for big attributes
        List<InterfaceHttpData> bodylist = formpost(b, host, port, uriSimple, file, factory, headers);
        if (bodylist == null) {
            factory.cleanAllHttpDatas();
            return;
        }

        // Multipart Post form: factory used
        formpostmultipart(b, host, port, uriFile, factory, headers, bodylist);
    } finally {
        // Shut down executor threads to exit.
        group.shutdownGracefully();

        // Really clean all temporary files if they still exist
        factory.cleanAllHttpDatas();
    }
}

From source file:com.topsec.bdc.platform.api.test.http.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 ? "ws" : uri.getScheme();
    final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    final int port;
    if (uri.getPort() == -1) {
        if ("ws".equalsIgnoreCase(scheme)) {
            port = 80;//from   w w  w.  j a v a 2 s .  co  m
        } else if ("wss".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) {
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } 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.turo.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
 * @throws IllegalStateException if this method is called without specifying an APNs server address, if this method
 * is called without providing TLS credentials or a signing key, or if this method is called with both TLS
 * credentials and a signing key//from  w w  w  . j av a 2 s .c  o  m
 *
 * @since 0.8
 */
public ApnsClient build() throws SSLException {
    if (this.apnsServerAddress == null) {
        throw new IllegalStateException("No APNs server address specified.");
    }

    if (this.clientCertificate == null && this.privateKey == null && this.signingKey == null) {
        throw new IllegalStateException("No client credentials specified; either TLS credentials (a "
                + "certificate/private key) or an APNs signing key must be provided before building a client.");
    } else if ((this.clientCertificate != null || this.privateKey != null) && this.signingKey != null) {
        throw new IllegalStateException("Clients may not have both a signing key and TLS credentials.");
    }

    final SslContext sslContext;
    {
        final SslProvider sslProvider;

        if (OpenSsl.isAvailable()) {
            log.info("Native SSL provider is available; will use native provider.");
            sslProvider = SslProvider.OPENSSL_REFCNT;
        } 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);

        if (this.clientCertificate != null && this.privateKey != null) {
            sslContextBuilder.keyManager(this.privateKey, this.privateKeyPassword, this.clientCertificate);
        }

        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 client = new ApnsClient(this.apnsServerAddress, sslContext, this.signingKey,
            this.proxyHandlerFactory, this.connectionTimeoutMillis, this.idlePingIntervalMillis,
            this.gracefulShutdownTimeoutMillis, this.concurrentConnections, this.metricsListener,
            this.frameLogger, this.eventLoopGroup);

    if (sslContext instanceof ReferenceCounted) {
        ((ReferenceCounted) sslContext).release();
    }

    return client;
}

From source file:com.vmware.xenon.common.test.websockets.JsWebSocket.java

License:Open Source License

/**
 * Standard constructor WebSocket(uri) available in JavaScript API
 *
 * @param endpointUri Websocket endpoint URI
 */// w  ww.j a v a2 s .c o  m
public JsWebSocket(String endpointUri) throws Exception {
    URI uri = new URI(endpointUri);
    String scheme = uri.getScheme() == null ? WS_SCHEME : uri.getScheme();
    final String host = uri.getHost() == null ? ServiceHost.LOCAL_HOST : uri.getHost();
    final int port;
    if (uri.getPort() == -1) {
        if (WS_SCHEME.equalsIgnoreCase(scheme)) {
            port = 80;
        } else if (WSS_SCHEME.equalsIgnoreCase(scheme)) {
            port = 443;
        } else {
            port = -1;
        }
    } else {
        port = uri.getPort();
    }

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

    final boolean ssl = WSS_SCHEME.equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    this.group = new NioEventLoopGroup();

    // 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.
    DefaultHttpHeaders headers = new DefaultHttpHeaders();
    if (OperationContext.getAuthorizationContext() != null
            && OperationContext.getAuthorizationContext().getToken() != null) {
        headers.add(HttpHeaderNames.COOKIE,
                CookieJar.encodeCookies(
                        Collections.singletonMap(AuthenticationConstants.REQUEST_AUTH_TOKEN_COOKIE,
                                OperationContext.getAuthorizationContext().getToken())));
    }
    final WebSocketClientHandler handler = new WebSocketClientHandler(
            WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, false, headers));
    Bootstrap b = new Bootstrap();
    b.group(this.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);
        }
    });

    this.channel = b.connect(uri.getHost(), port).sync().channel();
    handler.handshakeFuture.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            try {
                JsExecutor.executeSynchronously(() -> {
                    if (future.isSuccess()) {
                        if (JsWebSocket.this.onopen != null) {
                            JsWebSocket.this.onopen.call(Context.getCurrentContext(), getParentScope(),
                                    JsWebSocket.this, new Object[] { null });
                        }
                    } else {
                        throw new RuntimeException(future.cause());
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

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

License:Open Source License

private ServiceClient createAllTrustingHttp2ServiceClient() throws Throwable {
    ServiceClient client = newAllTrustingServiceClient();

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    try (InputStream stream = new FileInputStream("../xenon-common/src/test/resources/ssl/client.p12")) {
        keyStore.load(stream, "changeit".toCharArray());
    }/*from  ww w. j  a  v a  2 s.  c o  m*/
    kmf.init(keyStore, "changeit".toCharArray());

    SslContext http2ClientContext = SslContextBuilder.forClient().keyManager(kmf)
            .trustManager(InsecureTrustManagerFactory.INSTANCE)
            .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
            .applicationProtocolConfig(new ApplicationProtocolConfig(ApplicationProtocolConfig.Protocol.ALPN,
                    ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
                    ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
                    ApplicationProtocolNames.HTTP_2))
            .build();

    ((NettyHttpServiceClient) client).setHttp2SslContext(http2ClientContext);
    client.start();
    return client;
}

From source file:com.vsct.dt.strowgr.admin.gui.configuration.NSQConfigFactory.java

License:Apache License

public SslContext getSslContext() throws SSLException {
    if (useSSL && sslContext == null) {
        sslContext = SslContextBuilder.forClient().build();
    }/*from   w w  w.j a  va  2 s  . c  o  m*/
    return sslContext;
}