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:org.springframework.cloud.gateway.test.ssl.ClientCertAuthSSLTests.java

License:Apache License

@Before
public void setup() throws Exception {
    KeyStore store = KeyStore.getInstance("JKS");

    try {// w w  w. j  a va2s  .  com
        URL url = ResourceUtils.getURL(keyStore);
        store.load(url.openStream(), keyStorePassword != null ? keyStorePassword.toCharArray() : null);
    } catch (Exception e) {
        throw new WebServerException("Could not load key store ' " + keyStore + "'", e);
    }

    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    char[] keyPasswordCharArray = keyPassword != null ? keyPassword.toCharArray() : null;

    if (keyPasswordCharArray == null && keyStorePassword != null) {
        keyPasswordCharArray = keyStorePassword.toCharArray();
    }

    keyManagerFactory.init(store, keyPasswordCharArray);

    try {
        SslContext sslContext = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE)
                .keyManager(keyManagerFactory).build();
        HttpClient httpClient = HttpClient.create().secure(ssl -> ssl.sslContext(sslContext));
        setup(new ReactorClientHttpConnector(httpClient), "https://localhost:" + port);
    } catch (SSLException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.springframework.cloud.gateway.test.ssl.SingleCertSSLTests.java

License:Apache License

@Before
public void setup() {
    try {//from   ww  w  .j  a v a2s  .  co m
        SslContext sslContext = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE)
                .build();
        HttpClient httpClient = HttpClient.create().secure(ssl -> ssl.sslContext(sslContext));
        setup(new ReactorClientHttpConnector(httpClient), "https://localhost:" + port);
    } catch (SSLException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.springframework.credhub.configuration.ClientHttpConnectorFactory.java

License:Apache License

/**
 * Create a {@link ClientHttpConnector} for the given {@link ClientOptions}.
 *
 * @param options must not be {@literal null}
 * @return a new {@link ClientHttpConnector}.
 *//*from  ww w .  ja  va 2s  .com*/
public static ClientHttpConnector create(ClientOptions options) {
    HttpClient httpClient = HttpClient.create();

    if (usingCustomCerts(options)) {
        TrustManagerFactory trustManagerFactory = sslCertificateUtils
                .createTrustManagerFactory(options.getCaCertFiles());

        httpClient = httpClient.secure(sslContextSpec -> sslContextSpec.sslContext(
                SslContextBuilder.forClient().sslProvider(SslProvider.JDK).trustManager(trustManagerFactory)));
    } else {
        httpClient = httpClient.secure(sslContextSpec -> sslContextSpec
                .sslContext(SslContextBuilder.forClient().sslProvider(SslProvider.JDK)));
    }

    if (options.getConnectionTimeout() != null) {
        httpClient = httpClient
                .tcpConfiguration(tcpClient -> tcpClient.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
                        Math.toIntExact(options.getConnectionTimeout().toMillis())));
    }

    return new ReactorClientHttpConnector(httpClient);
}

From source file:org.thingsboard.rule.engine.mqtt.credentials.CertPemClientCredentials.java

License:Apache License

@Override
public Optional<SslContext> initSslContext() {
    try {/* w w  w .j  a v  a 2  s .c  o m*/
        Security.addProvider(new BouncyCastleProvider());
        return Optional.of(SslContextBuilder.forClient().keyManager(createAndInitKeyManagerFactory())
                .trustManager(createAndInitTrustManagerFactory()).clientAuth(ClientAuth.REQUIRE).build());
    } catch (Exception e) {
        log.error("[{}:{}] Creating TLS factory failed!", caCert, cert, e);
        throw new RuntimeException("Creating TLS factory failed!", e);
    }
}

From source file:org.thingsboard.rule.engine.mqtt.TbMqttNode.java

License:Apache License

private Optional<SslContext> initSslContext() throws SSLException {
    Optional<SslContext> result = this.config.getCredentials().initSslContext();
    if (this.config.isSsl() && !result.isPresent()) {
        result = Optional.of(SslContextBuilder.forClient().build());
    }//from w w  w .j  a v a  2  s. co  m
    return result;
}

From source file:org.thingsboard.rule.engine.rest.TbRestApiCallNode.java

License:Apache License

@Override
public void init(TbContext ctx, TbNodeConfiguration configuration) throws TbNodeException {
    try {//from  w  w w.  jav  a2 s  .com
        this.config = TbNodeUtils.convert(configuration, TbRestApiCallNodeConfiguration.class);
        this.eventLoopGroup = new NioEventLoopGroup();
        Netty4ClientHttpRequestFactory nettyFactory = new Netty4ClientHttpRequestFactory(this.eventLoopGroup);
        nettyFactory.setSslContext(SslContextBuilder.forClient().build());
        httpClient = new AsyncRestTemplate(nettyFactory);
    } catch (SSLException e) {
        throw new TbNodeException(e);
    }
}

From source file:org.thingsplode.synapse.proxy.EndpointProxy.java

License:Apache License

public Dispatcher acquireDispatcher() throws SSLException, InterruptedException {
    if (this.lifecycle == ComponentLifecycle.UNITIALIZED) {
        throw new IllegalStateException(
                "Please set this value before starting the " + EndpointProxy.class.getSimpleName());
    }//from  w w  w  .ja  v  a2s  . com

    int port = this.connectionUri.getPort() == -1 ? this.transport.getSchemaDefaultPort()
            : this.connectionUri.getPort();

    if (transport.ssl) {
        //todo: extends beyond prototype quality
        sslContext = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    }
    //final int dirtyTrickPort = port; //needed because for some reason the compiler does not accept port and unitialized final int, even if there's an else in the if statement above.
    if (this.msgIdGeneratorStrategy == null) {
        this.msgIdGeneratorStrategy = () -> UUID.randomUUID().toString();
    }
    Dispatcher dispatcher = new Dispatcher(retryConnection, dfh, msgIdGeneratorStrategy, b,
            this.connectionUri.getHost(), port);
    dispatcher.connect();
    dispatchers.add(dispatcher);
    return dispatcher;
}

From source file:org.wso2.carbon.data.provider.utils.WebSocketClient.java

License:Open Source License

/**
 * @return true if the handshake is done properly.
 * @throws URISyntaxException throws if there is an error in the URI syntax.
 * @throws InterruptedException throws if the connecting the server is interrupted.
 *//* w  w w. j  a  va2s. c  o  m*/
public boolean handhshake() throws InterruptedException, URISyntaxException, SSLException {
    boolean isDone;
    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;
        } else if ("wss".equalsIgnoreCase(scheme)) {
            port = 443;
        } else {
            port = -1;
        }
    } else {
        port = uri.getPort();
    }

    if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme)) {
        logger.error("Only WS(S) is supported.");
        return false;
    }

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

    group = new NioEventLoopGroup();

    HttpHeaders headers = new DefaultHttpHeaders();
    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.
        handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory.newHandshaker(uri,
                WebSocketVersion.V13, subProtocol, true, headers));

        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),
                        WebSocketClientCompressionHandler.INSTANCE, handler);
            }
        });

        channel = b.connect(uri.getHost(), port).sync().channel();
        isDone = handler.handshakeFuture().sync().isSuccess();
        logger.debug("WebSocket Handshake successful : " + isDone);
        return isDone;
    } catch (Exception e) {
        logger.error("Handshake unsuccessful : " + e.getMessage(), e);
        return false;
    }
}

From source file:org.wso2.carbon.esb.websocket.client.WebSocketTestClient.java

License:Open Source License

/**
 * @return true if the handshake is done properly.
 * @throws URISyntaxException   throws if there is an error in the URI syntax.
 * @throws InterruptedException throws if the connecting the server is interrupted.
 *///  www. jav  a2  s  .co  m
public boolean handhshake() throws InterruptedException, URISyntaxException, SSLException, ProtocolException {
    boolean isSuccess;
    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;
        } else if ("wss".equalsIgnoreCase(scheme)) {
            port = 443;
        } else {
            port = -1;
        }
    } else {
        port = uri.getPort();
    }

    if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme)) {
        logger.error("Only WS(S) is supported.");
        return false;
    }

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

    group = new NioEventLoopGroup();

    HttpHeaders headers = new DefaultHttpHeaders();
    for (Map.Entry<String, String> entry : customHeaders.entrySet()) {
        headers.add(entry.getKey(), entry.getValue());
    }
    // 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.
    handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory.newHandshaker(uri,
            WebSocketVersion.V13, subProtocol, true, headers), latch);

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.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),
                    WebSocketClientCompressionHandler.INSTANCE, handler);
        }
    });

    channel = bootstrap.connect(uri.getHost(), port).sync().channel();
    isSuccess = handler.handshakeFuture().sync().isSuccess();
    logger.info("WebSocket Handshake successful : " + isSuccess);
    return isSuccess;
}

From source file:org.wso2.carbon.http2.transport.util.Http2ConnectionFactory.java

License:Open Source License

/**
 * Create new connection and return client handler
 *
 * @param uri/*from www. j  a  v a2  s .  co  m*/
 * @return Http2ClientHandler
 * @throws AxisFault
 */
private Http2ClientHandler cacheNewConnection(HttpHost uri) throws AxisFault {

    final SslContext sslCtx;
    final boolean SSL;
    if (uri.getSchemeName().equalsIgnoreCase("https")) {
        SSL = true;
    } else
        SSL = false;
    try {
        // Handling SSL
        if (SSL) {
            Parameter trustParam = trasportOut.getParameter(Http2Constants.TRUST_STORE_CONFIG_ELEMENT);
            OMElement tsEle = null;
            if (trustParam != null) {
                tsEle = trustParam.getParameterElement();
            }
            final String location = tsEle.getFirstChildWithName(new QName(Http2Constants.TRUST_STORE_LOCATION))
                    .getText();
            final String storePassword = tsEle
                    .getFirstChildWithName(new QName(Http2Constants.TRUST_STORE_PASSWORD)).getText();

            SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
            sslCtx = SslContextBuilder.forClient()
                    .trustManager(SSLUtil.createTrustmanager(location, storePassword)).sslProvider(provider)
                    .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                    .trustManager(InsecureTrustManagerFactory.INSTANCE)
                    .applicationProtocolConfig(
                            new ApplicationProtocolConfig(ApplicationProtocolConfig.Protocol.ALPN,
                                    ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
                                    ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
                                    ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1))
                    .build();
        } else {
            sslCtx = null;
        }
        Http2ClientInitializer initializer = new Http2ClientInitializer(sslCtx, Integer.MAX_VALUE);

        String HOST = uri.getHostName();
        Integer PORT = uri.getPort();
        // Configure the client.
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.remoteAddress(HOST, PORT);
        b.handler(initializer);
        // Start the client.
        Channel channel = b.connect().syncUninterruptibly().channel();

        log.debug("Connected to [" + HOST + ':' + PORT + ']');

        Http2SettingsHandler http2SettingsHandler = initializer.settingsHandler();
        http2SettingsHandler.awaitSettings(5, TimeUnit.SECONDS);

        final String key = generateKey(URI.create(uri.toURI()));
        Http2ClientHandler handler = initializer.responseHandler();

        clientConnections.put(key, handler);

        channel.closeFuture().addListener(new GenericFutureListener<Future<? super Void>>() {
            @Override
            public void operationComplete(Future<? super Void> future) throws Exception {
                clientConnections.remove(key);
            }
        });
        return initializer.responseHandler();
    } catch (SSLException e) {
        throw new AxisFault("Error while connection establishment:", e);
    } catch (Exception e) {
        throw new AxisFault("Error while connection establishment:" + e);
    }
}