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:io.opencensus.exporter.metrics.ocagent.OcAgentMetricsExporterConfigurationTest.java

License:Apache License

@Test
public void setAndGet() throws SSLException {
    Duration oneMinute = Duration.create(60, 0);
    Duration fiveMinutes = Duration.create(300, 0);
    SslContext sslContext = SslContextBuilder.forClient().build();
    OcAgentMetricsExporterConfiguration configuration = OcAgentMetricsExporterConfiguration.builder()
            .setEndPoint("192.168.0.1:50051").setServiceName("service").setUseInsecure(false)
            .setSslContext(sslContext).setRetryInterval(fiveMinutes).setExportInterval(oneMinute).build();
    assertThat(configuration.getEndPoint()).isEqualTo("192.168.0.1:50051");
    assertThat(configuration.getServiceName()).isEqualTo("service");
    assertThat(configuration.getUseInsecure()).isFalse();
    assertThat(configuration.getSslContext()).isEqualTo(sslContext);
    assertThat(configuration.getRetryInterval()).isEqualTo(fiveMinutes);
    assertThat(configuration.getExportInterval()).isEqualTo(oneMinute);
}

From source file:io.opencensus.exporter.trace.ocagent.OcAgentTraceExporterConfigurationTest.java

License:Apache License

@Test
public void setAndGet() throws SSLException {
    Duration oneMinute = Duration.create(60, 0);
    SslContext sslContext = SslContextBuilder.forClient().build();
    OcAgentTraceExporterConfiguration configuration = OcAgentTraceExporterConfiguration.builder()
            .setEndPoint("192.168.0.1:50051").setServiceName("service").setUseInsecure(false)
            .setSslContext(sslContext).setRetryInterval(oneMinute).setEnableConfig(false).build();
    assertThat(configuration.getEndPoint()).isEqualTo("192.168.0.1:50051");
    assertThat(configuration.getServiceName()).isEqualTo("service");
    assertThat(configuration.getUseInsecure()).isFalse();
    assertThat(configuration.getSslContext()).isEqualTo(sslContext);
    assertThat(configuration.getRetryInterval()).isEqualTo(oneMinute);
    assertThat(configuration.getEnableConfig()).isFalse();
}

From source file:io.pravega.client.netty.impl.ConnectionFactoryImpl.java

License:Open Source License

@Override
public CompletableFuture<ClientConnection> establishConnection(PravegaNodeUri location, ReplyProcessor rp) {
    Preconditions.checkNotNull(location);
    Exceptions.checkNotClosed(closed.get(), this);
    final SslContext sslCtx;
    if (ssl) {//from  w  w  w .j av a  2 s  .  c om
        try {
            sslCtx = SslContextBuilder.forClient().trustManager(FingerprintTrustManagerFactory
                    .getInstance(FingerprintTrustManagerFactory.getDefaultAlgorithm())).build();
        } catch (SSLException | NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    } else {
        sslCtx = null;
    }
    AppendBatchSizeTracker batchSizeTracker = new AppendBatchSizeTrackerImpl();
    ClientConnectionInboundHandler handler = new ClientConnectionInboundHandler(location.getEndpoint(), rp,
            batchSizeTracker);
    Bootstrap b = new Bootstrap();
    b.group(group).channel(nio ? NioSocketChannel.class : EpollSocketChannel.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(), location.getEndpoint(), location.getPort()));
                    }
                    // p.addLast(new LoggingHandler(LogLevel.INFO));
                    p.addLast(new ExceptionLoggingHandler(location.getEndpoint()),
                            new CommandEncoder(batchSizeTracker),
                            new LengthFieldBasedFrameDecoder(WireCommands.MAX_WIRECOMMAND_SIZE, 4, 4),
                            new CommandDecoder(), handler);
                }
            });

    // Start the client.
    CompletableFuture<ClientConnection> result = new CompletableFuture<>();
    try {
        b.connect(location.getEndpoint(), location.getPort()).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) {
                if (future.isSuccess()) {
                    result.complete(handler);
                } else {
                    result.completeExceptionally(future.cause());
                }
            }
        });
    } catch (Exception e) {
        result.completeExceptionally(e);
    }
    return result;
}

From source file:io.spikex.core.util.connection.KeyStoreHelper.java

License:Apache License

public SslContext buildJdkClientContext(final boolean clientAuth) throws KeyStoreException {

    SslContext ctx = null;//from   w  w w . ja  v a  2  s  .co  m

    try {
        TrustManagerFactory trustMgrFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        {
            String password = geTrustStorePassword();
            KeyStore trustStore = loadKeyStore(getTrustStorePath(), password);
            trustMgrFactory.init(trustStore);
        }

        if (clientAuth) {

            KeyManagerFactory keyMgrFactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            String password = geKeyStorePassword();
            KeyStore keyStore = loadKeyStore(getKeyStorePath(), password);
            keyMgrFactory.init(keyStore, password != null ? password.toCharArray() : null);

            ctx = SslContextBuilder.forClient().sslProvider(SslProvider.JDK).trustManager(trustMgrFactory)
                    .keyManager(keyMgrFactory).build();
        } else {
            ctx = SslContextBuilder.forClient().sslProvider(SslProvider.JDK).trustManager(trustMgrFactory)
                    .build();
        }
    } catch (IOException | NoSuchAlgorithmException | UnrecoverableKeyException e) {
        throw new KeyStoreException("Failed to build SSL context", e);
    }

    return ctx;
}

From source file:io.spikex.core.util.connection.KeyStoreHelper.java

License:Apache License

public SslContext buildOpenSslClientContext(final boolean clientAuth) throws IOException {

    SslContext ctx;//from  w ww.  j a v a 2  s  .  c om

    if (clientAuth) {
        ctx = SslContextBuilder.forClient().sslProvider(SslProvider.OPENSSL)
                .trustManager(getTrustCertChainPath().toAbsolutePath().normalize().toFile())
                .keyManager(getClientCertPath().toAbsolutePath().normalize().toFile(),
                        getClientKeyPath().toAbsolutePath().normalize().toFile())
                .build();
    } else {
        ctx = SslContextBuilder.forClient().sslProvider(SslProvider.OPENSSL)
                .trustManager(getTrustCertChainPath().toAbsolutePath().normalize().toFile()).build();
    }

    return ctx;
}

From source file:io.vertx.core.net.impl.SSLHelper.java

License:Open Source License

private SslContext createContext(VertxInternal vertx) {
    try {//  w w w  .j  a  va2  s  . co m
        KeyManagerFactory keyMgrFactory = getKeyMgrFactory(vertx);
        TrustManagerFactory trustMgrFactory = getTrustMgrFactory(vertx);
        SslContextBuilder builder;
        if (client) {
            builder = SslContextBuilder.forClient();
            if (keyMgrFactory != null) {
                builder.keyManager(keyMgrFactory);
            }
        } else {
            if (keyMgrFactory == null) {
                throw new VertxException("Key/certificate is mandatory for SSL");
            }
            builder = SslContextBuilder.forServer(keyMgrFactory);
        }
        Collection<String> cipherSuites = enabledCipherSuites;
        if (openSsl) {
            builder.sslProvider(SslProvider.OPENSSL);
            if (cipherSuites == null || cipherSuites.isEmpty()) {
                cipherSuites = OpenSsl.availableOpenSslCipherSuites();
            }
        } else {
            builder.sslProvider(SslProvider.JDK);
            if (cipherSuites == null || cipherSuites.isEmpty()) {
                cipherSuites = DEFAULT_JDK_CIPHER_SUITE;
            }
        }
        if (trustMgrFactory != null) {
            builder.trustManager(trustMgrFactory);
        }
        if (cipherSuites != null && cipherSuites.size() > 0) {
            builder.ciphers(cipherSuites);
        }
        if (useAlpn && applicationProtocols != null && applicationProtocols.size() > 0) {
            builder.applicationProtocolConfig(new ApplicationProtocolConfig(
                    ApplicationProtocolConfig.Protocol.ALPN,
                    ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
                    ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT, applicationProtocols
                            .stream().map(PROTOCOL_NAME_MAPPING::get).collect(Collectors.toList())));
        }
        return builder.build();
    } catch (Exception e) {
        throw new VertxException(e);
    }
}

From source file:io.viewserver.network.netty.tcp.NettyTcpEndpoint.java

License:Apache License

@Override
public IClient getClient(EventLoopGroup eventLoopGroup, ChannelHandler handler) {
    SslContext sslContext;/*w  w  w .  j a v  a  2  s .co  m*/
    if (this.uri.getScheme().equals("tcps")) {
        try {
            SslContextBuilder builder = SslContextBuilder.forClient();
            if (bypassCertificateChecks || usingSelfSignedCertificate) {
                builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
            }
            sslContext = builder.build();
        } catch (SSLException e) {
            throw new RuntimeException(e);
        }
    } else {
        sslContext = null;
    }

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            if (sslContext != null) {
                pipeline.addLast(sslContext.newHandler(ch.alloc(), uri.getHost(), uri.getPort()));
            }
            pipeline.addLast(handler);
        }
    });
    return () -> bootstrap.connect(uri.getHost(), uri.getPort());
}

From source file:io.viewserver.network.netty.websocket.NettyWebSocketEndpoint.java

License:Apache License

@Override
public IClient getClient(EventLoopGroup eventLoopGroup, ChannelHandler handler) {
    SslContext sslContext;//  w  ww  .  ja  va 2 s .  c  o m
    if (this.uri.getScheme().equals("wss")) {
        try {
            SslContextBuilder builder = SslContextBuilder.forClient();
            if (bypassCertificateChecks || usingSelfSignedCertificate) {
                builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
            }
            sslContext = builder.build();
        } catch (SSLException e) {
            throw new RuntimeException(e);
        }
    } else {
        sslContext = null;
    }

    Bootstrap bootstrap = new Bootstrap();
    WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(uri,
            WebSocketVersion.V13, null, false, new DefaultHttpHeaders());
    bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            if (sslContext != null) {
                pipeline.addLast(sslContext.newHandler(ch.alloc(), uri.getHost(), uri.getPort()));
            }
            pipeline.addLast(new HttpClientCodec());
            pipeline.addLast(new HttpObjectAggregator(1 << 30));
            pipeline.addLast("websocket", new WebSocketClientProtocolHandler(handshaker));
            pipeline.addLast(new ChannelInboundHandlerAdapter() {
                @Override
                public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                    if (evt == WebSocketClientProtocolHandler.ClientHandshakeStateEvent.HANDSHAKE_COMPLETE) {
                        ChannelPipeline pipeline = ctx.channel().pipeline();
                        pipeline.addAfter("websocket", "ws-decoder-xx",
                                new MessageToMessageDecoder<BinaryWebSocketFrame>() {
                                    @Override
                                    protected void decode(ChannelHandlerContext ctx, BinaryWebSocketFrame msg,
                                            List<Object> out) throws Exception {
                                        out.add(msg.content().retain());
                                    }
                                });

                        pipeline.addAfter("websocket", "ws-encoder-xx", new MessageToMessageEncoder<ByteBuf>() {
                            @Override
                            protected void encode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out)
                                    throws Exception {
                                out.add(new BinaryWebSocketFrame(msg).retain());
                            }
                        });
                    }

                    super.userEventTriggered(ctx, evt);
                }
            });

            pipeline.addLast("frameDecoder", new ChannelInboundHandlerAdapter());
            pipeline.addLast("frameEncoder", new ChannelOutboundHandlerAdapter());
            pipeline.addLast(handler);
        }
    });
    return () -> bootstrap.connect(uri.getHost(), uri.getPort());
}

From source file:jlibs.wamp4j.netty.NettyClientEndpoint.java

License:Apache License

@Override
public void connect(final URI uri, final ConnectListener listener, final String... subProtocols) {
    final SslContext sslContext;
    if ("wss".equals(uri.getScheme())) {
        try {/*from w ww  .  j  a  v  a2s  .c  o m*/
            if (sslSettings == null) {
                sslContext = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE)
                        .build();
            } else {
                sslContext = SslContextBuilder.forClient().trustManager(sslSettings.trustCertChainFile)
                        .keyManager(sslSettings.certificateFile, sslSettings.keyFile, sslSettings.keyPassword)
                        .build();
            }
        } catch (Throwable thr) {
            listener.onError(thr);
            return;
        }
    } else if ("ws".equals(uri.getScheme()))
        sslContext = null;
    else
        throw new IllegalArgumentException("invalid protocol: " + uri.getScheme());

    final int port = uri.getPort() == -1 ? (sslContext == null ? 80 : 443) : uri.getPort();

    Bootstrap bootstrap = new Bootstrap().group(eventLoopGroup).channel(NioSocketChannel.class)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.MAX_MESSAGES_PER_READ, 50000).option(ChannelOption.WRITE_SPIN_COUNT, 50000)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    if (sslContext != null)
                        ch.pipeline().addLast(sslContext.newHandler(ch.alloc(), uri.getHost(), port));
                    WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(uri,
                            WebSocketVersion.V13, Util.toString(subProtocols), false, new DefaultHttpHeaders());
                    ch.pipeline().addLast(new HttpClientCodec(), new HttpObjectAggregator(8192),
                            new WebSocketClientProtocolHandler(handshaker) {
                                @Override
                                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
                                        throws Exception {
                                    super.exceptionCaught(ctx, cause);
                                    listener.onError(cause);
                                }
                            }, new HandshakeListener(handshaker, listener));
                }
            });
    bootstrap.connect(uri.getHost(), port).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                assert !future.channel().isOpen();
                listener.onError(future.cause());
            }
        }
    });
}

From source file:jmeter.plugins.http2.sampler.NettyHttp2Client.java

License:Apache License

private SslContext getSslContext() {
    SslContext sslCtx = null;//from ww  w  . j  a va 2 s.  c  o m

    final SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;

    try {
        sslCtx = SslContextBuilder.forClient().sslProvider(provider)
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .trustManager(InsecureTrustManagerFactory.INSTANCE)
                .applicationProtocolConfig(
                        new ApplicationProtocolConfig(Protocol.ALPN, SelectorFailureBehavior.NO_ADVERTISE,
                                SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2))
                .build();
    } catch (SSLException exception) {
        return null;
    }

    return sslCtx;
}