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.intuit.karate.netty.WebSocketClientInitializer.java

License:Open Source License

public WebSocketClientInitializer(WebSocketOptions options, WebSocketListener listener) {
    this.uri = options.getUri();
    this.port = options.getPort();
    if (options.isSsl()) {
        try {/* w w w .  j  a v  a 2 s  . c  om*/
            sslContext = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE)
                    .build();
        } catch (SSLException e) {
            throw new RuntimeException(e);
        }
    } else {
        sslContext = null;
    }
    HttpHeaders nettyHeaders = new DefaultHttpHeaders();
    Map<String, Object> headers = options.getHeaders();
    if (headers != null) {
        headers.forEach((k, v) -> nettyHeaders.add(k, v));
    }
    WebSocketClientHandshaker handShaker = WebSocketClientHandshakerFactory.newHandshaker(uri,
            WebSocketVersion.V13, options.getSubProtocol(), true, nettyHeaders, options.getMaxPayloadSize());
    handler = new WebSocketClientHandler(handShaker, listener);
}

From source file:com.kumuluz.ee.config.etcd.Etcd2ConfigurationSource.java

License:MIT License

@Override
public void init(ConfigurationDispatcher configurationDispatcher) {

    this.configurationDispatcher = configurationDispatcher;

    ConfigurationUtil configurationUtil = ConfigurationUtil.getInstance();
    // get namespace
    this.namespace = InitializationUtils.getNamespace(eeConfig, configurationUtil, "etcd");
    log.info("Using namespace: " + this.namespace);

    // get user credentials
    String etcdUsername = configurationUtil.get("kumuluzee.config.etcd.username").orElse(null);
    String etcdPassword = configurationUtil.get("kumuluzee.config.etcd.password").orElse(null);

    // get CA certificate
    String cert = configurationUtil.get("kumuluzee.config.etcd.ca").orElse(null);
    SslContext sslContext = null;//from   w w  w. jav  a 2s . c  o m
    if (cert != null) {

        cert = cert.replaceAll("\\s+", "").replace("-----BEGINCERTIFICATE-----", "")
                .replace("-----ENDCERTIFICATE-----", "");

        byte[] decoded = Base64.getDecoder().decode(cert);

        try {
            X509Certificate certificate = (X509Certificate) CertificateFactory.getInstance("X.509")
                    .generateCertificate(new ByteArrayInputStream(decoded));

            sslContext = SslContextBuilder.forClient().trustManager(certificate).build();

        } catch (CertificateException e) {
            log.severe("Certificate exception: " + e.toString());
        } catch (SSLException e) {
            log.severe("SSL exception: " + e.toString());
        }

    }

    // initialize security context
    EtcdSecurityContext etcdSecurityContext = null;
    if (etcdUsername != null && !etcdUsername.isEmpty() && etcdPassword != null && !etcdPassword.isEmpty()) {
        if (sslContext != null) {
            etcdSecurityContext = new EtcdSecurityContext(sslContext, etcdUsername, etcdPassword);
        } else {
            etcdSecurityContext = new EtcdSecurityContext(etcdUsername, etcdPassword);
        }
    } else if (sslContext != null) {
        etcdSecurityContext = new EtcdSecurityContext(sslContext);
    }

    // get etcd host names
    String etcdUrls = configurationUtil.get("kumuluzee.config.etcd.hosts").orElse(null);
    if (etcdUrls != null && !etcdUrls.isEmpty()) {

        String[] splittedEtcdUrls = etcdUrls.split(",");
        URI[] etcdHosts = new URI[splittedEtcdUrls.length];
        for (int i = 0; i < etcdHosts.length; i++) {
            etcdHosts[i] = URI.create(splittedEtcdUrls[i]);
        }

        if (etcdHosts.length % 2 == 0) {
            log.warning("Using an odd number of etcd hosts is recommended. See etcd documentation.");
        }

        if (etcdSecurityContext != null) {

            etcd = new EtcdClient(etcdSecurityContext, etcdHosts);

        } else {

            etcd = new EtcdClient(etcdHosts);

        }

        etcd.setRetryHandler(new RetryOnce(0));

        // get retry dellays
        startRetryDelay = InitializationUtils.getStartRetryDelayMs(configurationUtil, "etcd");
        maxRetryDelay = InitializationUtils.getMaxRetryDelayMs(configurationUtil, "etcd");

        log.info("etcd2 configuration source successfully initialised.");

    } else {
        log.severe("No etcd server hosts provided. Specify hosts with configuration key"
                + "kumuluzee.config.etcd.hosts in format "
                + "http://192.168.99.100:2379,http://192.168.99.101:2379,http://192.168.99.102:2379");
    }

}

From source file:com.linecorp.armeria.client.http.HttpClientPipelineConfigurator.java

License:Apache License

HttpClientPipelineConfigurator(SessionProtocol sessionProtocol, SessionOptions options) {
    switch (sessionProtocol) {
    case HTTP://from   ww w  . ja v  a2  s .c o  m
    case HTTPS:
        httpPreference = HttpPreference.HTTP2_PREFERRED;
        break;
    case H1:
    case H1C:
        httpPreference = HttpPreference.HTTP1_REQUIRED;
        break;
    case H2:
    case H2C:
        httpPreference = HttpPreference.HTTP2_REQUIRED;
        break;
    default:
        // Should never reach here.
        throw new Error();
    }

    this.options = requireNonNull(options, "options");

    if (sessionProtocol.isTls()) {
        try {
            final SslContextBuilder builder = SslContextBuilder.forClient();

            builder.sslProvider(NativeLibraries.isOpenSslAvailable() ? SslProvider.OPENSSL : SslProvider.JDK);
            options.trustManagerFactory().ifPresent(builder::trustManager);

            if (httpPreference == HttpPreference.HTTP2_REQUIRED
                    || httpPreference == HttpPreference.HTTP2_PREFERRED) {

                builder.ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                        .applicationProtocolConfig(
                                new ApplicationProtocolConfig(ApplicationProtocolConfig.Protocol.ALPN,
                                        // NO_ADVERTISE is currently the only mode supported by both OpenSsl and
                                        // JDK providers.
                                        ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
                                        // ACCEPT is currently the only mode supported by both OpenSsl and JDK
                                        // providers.
                                        ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
                                        ApplicationProtocolNames.HTTP_2));
            }
            sslCtx = builder.build();
        } catch (SSLException e) {
            throw new IllegalStateException("failed to create an SslContext", e);
        }
    } else {
        sslCtx = null;
    }
}

From source file:com.linecorp.armeria.client.HttpClientPipelineConfigurator.java

License:Apache License

HttpClientPipelineConfigurator(HttpClientFactory clientFactory, SessionProtocol sessionProtocol) {
    this.clientFactory = clientFactory;

    if (sessionProtocol == HTTP || sessionProtocol == HTTPS) {
        httpPreference = HttpPreference.HTTP2_PREFERRED;
    } else if (sessionProtocol == H1 || sessionProtocol == H1C) {
        httpPreference = HttpPreference.HTTP1_REQUIRED;
    } else if (sessionProtocol == H2 || sessionProtocol == H2C) {
        httpPreference = HttpPreference.HTTP2_REQUIRED;
    } else {/*from   w  ww. j ava2 s  . c  o  m*/
        // Should never reach here.
        throw new Error();
    }

    if (sessionProtocol.isTls()) {
        try {
            final SslContextBuilder builder = SslContextBuilder.forClient();

            builder.sslProvider(Flags.useOpenSsl() ? SslProvider.OPENSSL : SslProvider.JDK);
            clientFactory.sslContextCustomizer().accept(builder);

            if (httpPreference == HttpPreference.HTTP2_REQUIRED
                    || httpPreference == HttpPreference.HTTP2_PREFERRED) {

                builder.ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                        .applicationProtocolConfig(
                                new ApplicationProtocolConfig(ApplicationProtocolConfig.Protocol.ALPN,
                                        // NO_ADVERTISE is currently the only mode supported by both OpenSsl and
                                        // JDK providers.
                                        ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
                                        // ACCEPT is currently the only mode supported by both OpenSsl and JDK
                                        // providers.
                                        ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
                                        ApplicationProtocolNames.HTTP_2));
            }
            sslCtx = builder.build();
        } catch (SSLException e) {
            throw new IllegalStateException("failed to create an SslContext", e);
        }
    } else {
        sslCtx = null;
    }
}

From source file:com.linecorp.armeria.client.HttpConfigurator.java

License:Apache License

HttpConfigurator(SessionProtocol sessionProtocol, RemoteInvokerOptions options) {
    switch (sessionProtocol) {
    case HTTP:/*from   w w w. j  a  v  a 2 s  . c  o  m*/
    case HTTPS:
        httpPreference = HttpPreference.HTTP2_PREFERRED;
        break;
    case H1:
    case H1C:
        httpPreference = HttpPreference.HTTP1_REQUIRED;
        break;
    case H2:
    case H2C:
        httpPreference = HttpPreference.HTTP2_REQUIRED;
        break;
    default:
        // Should never reach here.
        throw new Error();
    }

    this.options = requireNonNull(options, "options");

    if (sessionProtocol.isTls()) {
        try {
            final SslContextBuilder builder = SslContextBuilder.forClient();

            builder.sslProvider(NativeLibraries.isOpenSslAvailable() ? SslProvider.OPENSSL : SslProvider.JDK);
            options.trustManagerFactory().ifPresent(builder::trustManager);

            if (httpPreference == HttpPreference.HTTP2_REQUIRED
                    || httpPreference == HttpPreference.HTTP2_PREFERRED) {

                builder.ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                        .applicationProtocolConfig(
                                new ApplicationProtocolConfig(ApplicationProtocolConfig.Protocol.ALPN,
                                        // NO_ADVERTISE is currently the only mode supported by both OpenSsl and
                                        // JDK providers.
                                        ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
                                        // ACCEPT is currently the only mode supported by both OpenSsl and JDK
                                        // providers.
                                        ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
                                        ApplicationProtocolNames.HTTP_2));
            }
            sslCtx = builder.build();
        } catch (SSLException e) {
            throw new IllegalStateException("failed to create a SslContext", e);
        }
    } else {
        sslCtx = null;
    }
}

From source file:com.linecorp.armeria.server.thrift.THttp2Client.java

License:Apache License

THttp2Client(String uriStr) throws TTransportException {
    uri = URI.create(uriStr);/*from   ww w  .j ava 2s .  co  m*/

    int port;
    switch (uri.getScheme()) {
    case "http":
        port = uri.getPort();
        if (port < 0) {
            port = 80;
        }
        sslCtx = null;
        break;
    case "https":
        port = uri.getPort();
        if (port < 0) {
            port = 443;
        }

        try {
            sslCtx = SslContextBuilder.forClient()
                    .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                    .trustManager(InsecureTrustManagerFactory.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))
                    .build();
        } catch (SSLException e) {
            throw new TTransportException(TTransportException.UNKNOWN, e);
        }
        break;
    default:
        throw new IllegalArgumentException("unknown scheme: " + uri.getScheme());
    }

    String host = uri.getHost();
    if (host == null) {
        throw new IllegalArgumentException("host not specified: " + uriStr);
    }

    String path = uri.getPath();
    if (path == null) {
        throw new IllegalArgumentException("path not specified: " + uriStr);
    }

    this.host = host;
    this.port = port;
    this.path = path;
}

From source file:com.look.netty.demo.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.ltln.modules.ni.omc.system.simulator.AlmClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    Constants.init();//from  www . j ava  2  s .  co m
    final SslContext sslCtx;
    if (SSL) {
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    final EventExecutorGroup handlerGroup = new DefaultEventExecutorGroup(1);
    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 AlarmMsgDecoder(8192, 7, 2, 0, 0, false));
                        p.addLast(new AlarmMsgEncoder());
                        p.addLast(handlerGroup, new AlarmClientHandler());
                    }
                });

        // 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.mastfrog.netty.http.client.Initializer.java

License:Open Source License

@Override
protected void initChannel(Channel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();
    if (ssl) {/*from   www .jav  a2s  .c om*/
        SslContext clientContext = context == null
                ? SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build()
                : context;
        pipeline.addLast("ssl", new ExceptionForwardingSslHandler(
                clientContext.newEngine(ByteBufAllocator.DEFAULT, hostPort.host(), hostPort.port())));
    }
    pipeline.addLast("http-codec", new HttpClientCodec(maxInitialLineLength, maxChunkSize, maxChunkSize));
    if (compress) {
        pipeline.addLast("decompressor", new HttpContentDecompressor());
    }
    pipeline.addLast("handler", handler);
}

From source file:com.mobicage.rogerthat.plugins.news.NewsChannel.java

License:Apache License

public void connect() {
    if (TestUtils.isRunningTest()) {
        return;//from w w  w.  j  a v  a2  s . co m
    }
    T.NEWS();
    if (mIsConnected) {
        L.d("Already connected to news channel");
        return;
    } else if (!mService.getNetworkConnectivityManager().isConnected()) {
        L.d("Cannot connect to news channel: no internet connection.");
        return;
    } else if (mHost == null) {
        L.d("Not connecting to news channel because no host was found");
        return;
    } else if (mPort == -1) {
        L.d("Not connecting to news channel because no port was found");
        return;
    }
    mIsRetryingToConnect = true;
    L.d("Attemping to connect to news channel...");
    final SslContext sslCtx;
    if (CloudConstants.NEWS_CHANNEL_SSL) {
        try {
            if (CloudConstants.NEWS_CHANNEL_MUST_VALIDATE_SSL_CERTIFICATE) {
                TrustManagerFactory factory = TrustManagerFactory
                        .getInstance(TrustManagerFactory.getDefaultAlgorithm());
                KeyStore keyStore = KeyStore.getInstance("AndroidCAStore"); // Gets the default system keystore
                keyStore.load(null, null);
                factory.init(keyStore);
                sslCtx = SslContextBuilder.forClient().trustManager(factory).build();
            } else {
                sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE)
                        .build();
            }
        } catch (NoSuchAlgorithmException | KeyStoreException | CertificateException | IOException e) {
            L.bug(e);
            return;
        }
    } else {
        sslCtx = null;
    }
    if (mEventLoopGroup == null) {
        mEventLoopGroup = new NioEventLoopGroup();
    }
    Bootstrap b = new Bootstrap();
    b.group(mEventLoopGroup).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) {
                        SslHandler sslHandler = sslCtx.newHandler(ch.alloc(), mHost, mPort);
                        Future<Channel> handshakeDone = sslHandler.handshakeFuture();
                        handshakeDone.addListener(new GenericFutureListener<Future<? super Channel>>() {
                            @Override
                            public void operationComplete(Future<? super Channel> future) throws Exception {
                                authenticate();
                            }
                        });
                        p.addLast(sslHandler);
                    }
                    // decoder
                    p.addLast(new DelimiterBasedFrameDecoder(102400, Delimiters.lineDelimiter()));
                    p.addLast(new StringDecoder(Charset.forName("UTF-8")));

                    //encoder
                    p.addLast(new StringEncoder(Charset.forName("UTF-8")));
                    p.addLast(NewsChannel.this);
                }
            });
    // Bind and start to accept incoming connections.
    mChannel = b.connect(mHost, mPort).channel();
}