Java Code Examples for io.grpc.netty.NettyChannelBuilder#sslContext()

The following examples show how to use io.grpc.netty.NettyChannelBuilder#sslContext() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ChaincodeBase.java    From fabric-chaincode-java with Apache License 2.0 7 votes vote down vote up
@SuppressWarnings("deprecation")
final ManagedChannelBuilder<?> newChannelBuilder() throws IOException {

    // Consider moving this to be pure GRPC
    // This is being reworked in master so leaving this 'as-is'
    final NettyChannelBuilder builder = NettyChannelBuilder.forAddress(host, port);
    LOGGER.info("Configuring channel connection to peer.");

    if (tlsEnabled) {
        builder.negotiationType(NegotiationType.TLS);
        builder.sslContext(createSSLContext());
    } else {
        builder.usePlaintext();
    }

    // there is a optional in GRPC to use 'directExecutor' rather than the inbuilt
    // gRPC thread management
    // not seen to make a marked difference in performance.
    // However if it ever does, then this is where it should be enabled
    return builder;
}
 
Example 2
Source File: EtcdClient.java    From etcd-java with Apache License 2.0 6 votes vote down vote up
/**
 * @return the built {@link EtcdClient} instance
 */
public EtcdClient build() {
    NettyChannelBuilder ncb;
    if (endpoints.size() == 1) {
        ncb = NettyChannelBuilder.forTarget(endpointToUriString(endpoints.get(0)));
        if (overrideAuthority != null) {
            ncb.overrideAuthority(overrideAuthority);
        }
    } else {
        ncb = NettyChannelBuilder
                .forTarget(StaticEtcdNameResolverFactory.ETCD)
                .nameResolverFactory(new StaticEtcdNameResolverFactory(
                        endpoints, overrideAuthority));
    }
    if (plainText) {
        ncb.usePlaintext();
    }
    if (sslContext != null) {
        ncb.sslContext(sslContext);
    }
    if (maxInboundMessageSize != 0) {
        ncb.maxInboundMessageSize(maxInboundMessageSize);
    }
    return new EtcdClient(ncb, defaultTimeoutMs, name, password,
            preemptAuth, threads, executor, sendViaEventLoop, sessTimeoutSecs);
}
 
Example 3
Source File: SmartContractBase.java    From julongchain with Apache License 2.0 6 votes vote down vote up
public ManagedChannel newPeerClientConnection() {
	final NettyChannelBuilder builder =
			NettyChannelBuilder.forAddress(host, port).maxInboundMessageSize(CommConstant.MAX_GRPC_MESSAGE_SIZE);
	logger.info("Configuring channel connection to peer.");

	if (tlsEnabled) {
		logger.info("TLS is enabled");
		try {
			final SslContext sslContext =
					GrpcSslContexts.forClient().trustManager(new File(this.rootCertFile)).build();
			builder.negotiationType(NegotiationType.TLS);
			if (!hostOverrideAuthority.equals("")) {
				logger.info("Host override " + hostOverrideAuthority);
				builder.overrideAuthority(hostOverrideAuthority);
			}
			builder.sslContext(sslContext);
			logger.info("TLS context built: " + sslContext);
		} catch (SSLException e) {
			logger.error("failed connect to peer with SSLException", e);
		}
	} else {
		builder.usePlaintext();
	}
	return builder.build();
}
 
Example 4
Source File: Utils.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
private static NettyChannelBuilder newNettyClientChannel(Transport transport,
    SocketAddress address, boolean tls, boolean testca, int flowControlWindow)
    throws IOException {
  NettyChannelBuilder builder =
      NettyChannelBuilder.forAddress(address).flowControlWindow(flowControlWindow);
  if (!tls) {
    builder.usePlaintext();
  } else if (testca) {
    File cert = TestUtils.loadCert("ca.pem");
    builder.sslContext(GrpcSslContexts.forClient().trustManager(cert).build());
  }

  DefaultThreadFactory tf = new DefaultThreadFactory("client-elg-", true /*daemon */);
  switch (transport) {
    case NETTY_NIO:
      builder
          .eventLoopGroup(new NioEventLoopGroup(0, tf))
          .channelType(NioSocketChannel.class);
      break;

    case NETTY_EPOLL:
      // These classes only work on Linux.
      builder
          .eventLoopGroup(new EpollEventLoopGroup(0, tf))
          .channelType(EpollSocketChannel.class);
      break;

    case NETTY_UNIX_DOMAIN_SOCKET:
      // These classes only work on Linux.
      builder
          .eventLoopGroup(new EpollEventLoopGroup(0, tf))
          .channelType(EpollDomainSocketChannel.class);
      break;

    default:
      // Should never get here.
      throw new IllegalArgumentException("Unsupported transport: " + transport);
  }
  return builder;
}
 
Example 5
Source File: BotSystem.java    From java-bot-sdk with Apache License 2.0 5 votes vote down vote up
private static ManagedChannel createChannel(BotSystemConfig config) throws Exception {
    Security.addProvider(new BouncyCastleProvider());

    NettyChannelBuilder nettyChannelBuilder = (NettyChannelBuilder) ManagedChannelBuilder
            .forAddress(config.getHost(), config.getPort())
            .idleTimeout(15, SECONDS)
            .keepAliveTime(30, SECONDS);

    if (config.getCertPath() != null && config.getCertPassword() != null) {
        File certFile = new File(config.getCertPath());

        SslContext sslContext = GrpcSslContexts.forClient()
                .keyManager(NetUtils.createKeyFactory(certFile, config.getCertPassword()))
                .build();

        nettyChannelBuilder.sslContext(sslContext);
    }

    if (!config.isSecure()) {
        nettyChannelBuilder.usePlaintext();
    }

    if (!config.isCompression()) {
        nettyChannelBuilder.decompressorRegistry(DecompressorRegistry.emptyInstance());
    }

    return nettyChannelBuilder.build();
}
 
Example 6
Source File: GoogleAuthUtils.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new gRPC {@link ManagedChannel}.
 *
 * @throws IOException in case the channel can't be constructed.
 */
public static ManagedChannel newChannel(
    String target, AuthAndTLSOptions options, ClientInterceptor... interceptors)
    throws IOException {
  Preconditions.checkNotNull(target);
  Preconditions.checkNotNull(options);
  Preconditions.checkNotNull(interceptors);

  final SslContext sslContext =
      options.tlsEnabled ? createSSlContext(options.tlsCertificate) : null;

  try {
    NettyChannelBuilder builder =
        NettyChannelBuilder.forTarget(target)
            .negotiationType(options.tlsEnabled ? NegotiationType.TLS : NegotiationType.PLAINTEXT)
            .defaultLoadBalancingPolicy("round_robin")
            .intercept(interceptors);
    if (sslContext != null) {
      builder.sslContext(sslContext);
      if (options.tlsAuthorityOverride != null) {
        builder.overrideAuthority(options.tlsAuthorityOverride);
      }
    }
    return builder.build();
  } catch (RuntimeException e) {
    // gRPC might throw all kinds of RuntimeExceptions: StatusRuntimeException,
    // IllegalStateException, NullPointerException, ...
    String message = "Failed to connect to '%s': %s";
    throw new IOException(String.format(message, target, e.getMessage()));
  }
}
 
Example 7
Source File: ControllerImplTest.java    From pravega with Apache License 2.0 5 votes vote down vote up
@Test
public void testCredPluginException() throws Exception {
    NettyChannelBuilder builder = spy(NettyChannelBuilder.forAddress("localhost", serverPort)
            .keepAliveTime(10, TimeUnit.SECONDS));

    final NettyChannelBuilder channelBuilder;
    if (testSecure) {
        channelBuilder = builder.sslContext(GrpcSslContexts.forClient().trustManager(
                new File(SecurityConfigDefaults.TLS_CA_CERT_PATH)).build());
    } else {
        channelBuilder = builder.usePlaintext();
    }
    // Setup mocks.
    ClientConfig cfg = spy(ClientConfig.builder()
            .credentials(new DefaultCredentials("pass", "user"))
            .trustStore(SecurityConfigDefaults.TLS_CA_CERT_PATH)
            .controllerURI(URI.create((testSecure ? "tls://" : "tcp://") + "localhost:" + serverPort))
            .build());
    doThrow(new IllegalStateException("Exception thrown by cred plugin")).when(cfg).getCredentials();
    ManagedChannel channel = mock(ManagedChannel.class);
    doReturn(channel).when(builder).build();
    ControllerImplConfig controllerCfg = new ControllerImplConfig(1, 1, 1, 1, 1000, cfg);
    //Verify exception scenario.
    assertThrows(IllegalStateException.class, () -> new ControllerImpl(channelBuilder, controllerCfg, this.executor));
    verify(channel, times(1)).shutdownNow();
    verify(channel, times(1)).awaitTermination(anyLong(), any(TimeUnit.class));
}
 
Example 8
Source File: GoogleAuthUtils.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new gRPC {@link ManagedChannel}.
 *
 * @throws IOException in case the channel can't be constructed.
 */
public static ManagedChannel newChannel(
    String target,
    String proxy,
    AuthAndTLSOptions options,
    @Nullable List<ClientInterceptor> interceptors)
    throws IOException {
  Preconditions.checkNotNull(target);
  Preconditions.checkNotNull(options);

  SslContext sslContext =
      isTlsEnabled(target)
          ? createSSlContext(
              options.tlsCertificate, options.tlsClientCertificate, options.tlsClientKey)
          : null;

  String targetUrl = convertTargetScheme(target);
  try {
    NettyChannelBuilder builder =
        newNettyChannelBuilder(targetUrl, proxy)
            .negotiationType(
                isTlsEnabled(target) ? NegotiationType.TLS : NegotiationType.PLAINTEXT);
    if (interceptors != null) {
      builder.intercept(interceptors);
    }
    if (sslContext != null) {
      builder.sslContext(sslContext);
      if (options.tlsAuthorityOverride != null) {
        builder.overrideAuthority(options.tlsAuthorityOverride);
      }
    }
    return builder.build();
  } catch (RuntimeException e) {
    // gRPC might throw all kinds of RuntimeExceptions: StatusRuntimeException,
    // IllegalStateException, NullPointerException, ...
    String message = "Failed to connect to '%s': %s";
    throw new IOException(String.format(message, targetUrl, e.getMessage()));
  }
}
 
Example 9
Source File: Utils.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
private static NettyChannelBuilder newNettyClientChannel(Transport transport,
    SocketAddress address, boolean tls, boolean testca, int flowControlWindow)
    throws IOException {
  NettyChannelBuilder builder =
      NettyChannelBuilder.forAddress(address).flowControlWindow(flowControlWindow);
  if (!tls) {
    builder.usePlaintext();
  } else if (testca) {
    File cert = TestUtils.loadCert("ca.pem");
    builder.sslContext(GrpcSslContexts.forClient().trustManager(cert).build());
  }

  DefaultThreadFactory tf = new DefaultThreadFactory("client-elg-", true /*daemon */);
  switch (transport) {
    case NETTY_NIO:
      builder
          .eventLoopGroup(new NioEventLoopGroup(0, tf))
          .channelType(NioSocketChannel.class);
      break;

    case NETTY_EPOLL:
      // These classes only work on Linux.
      builder
          .eventLoopGroup(new EpollEventLoopGroup(0, tf))
          .channelType(EpollSocketChannel.class);
      break;

    case NETTY_UNIX_DOMAIN_SOCKET:
      // These classes only work on Linux.
      builder
          .eventLoopGroup(new EpollEventLoopGroup(0, tf))
          .channelType(EpollDomainSocketChannel.class);
      break;

    default:
      // Should never get here.
      throw new IllegalArgumentException("Unsupported transport: " + transport);
  }
  return builder;
}
 
Example 10
Source File: Channels.java    From quarkus with Apache License 2.0 4 votes vote down vote up
public static Channel createChannel(String name) throws SSLException {
    InstanceHandle<GrpcClientConfigProvider> instance = Arc.container().instance(GrpcClientConfigProvider.class);

    if (!instance.isAvailable()) {
        throw new IllegalStateException("Unable to find the GrpcClientConfigProvider");
    }

    GrpcClientConfiguration config = instance.get().getConfiguration(name);
    String host = config.host;
    int port = config.port;
    boolean plainText = !config.ssl.trustStore.isPresent();
    Optional<Boolean> usePlainText = config.plainText;
    if (usePlainText.isPresent()) {
        plainText = usePlainText.get();
    }

    SslContext context = null;
    if (!plainText) {
        Path trustStorePath = config.ssl.trustStore.orElse(null);
        Path certificatePath = config.ssl.certificate.orElse(null);
        Path keyPath = config.ssl.key.orElse(null);
        SslContextBuilder sslContextBuilder = GrpcSslContexts.forClient();
        if (trustStorePath != null) {
            sslContextBuilder.trustManager(trustStorePath.toFile());
        }

        if (certificatePath != null && keyPath != null) {
            sslContextBuilder.keyManager(certificatePath.toFile(), keyPath.toFile());
        }

        context = sslContextBuilder.build();
    }

    NettyChannelBuilder builder = NettyChannelBuilder.forAddress(host, port)
            .flowControlWindow(config.flowControlWindow.orElse(DEFAULT_FLOW_CONTROL_WINDOW))
            .keepAliveWithoutCalls(config.keepAliveWithoutCalls)
            .maxHedgedAttempts(config.maxHedgedAttempts)
            .maxRetryAttempts(config.maxRetryAttempts)
            .maxInboundMetadataSize(config.maxInboundMessageSize.orElse(DEFAULT_MAX_HEADER_LIST_SIZE))
            .maxInboundMetadataSize(config.maxInboundMessageSize.orElse(DEFAULT_MAX_MESSAGE_SIZE))
            .negotiationType(NegotiationType.valueOf(config.negotiationType.toUpperCase()));

    if (config.retry) {
        builder.enableRetry();
    } else {
        builder.disableRetry();
    }

    if (config.maxTraceEvents.isPresent()) {
        builder.maxTraceEvents(config.maxTraceEvents.getAsInt());
    }
    Optional<String> userAgent = config.userAgent;
    if (userAgent.isPresent()) {
        builder.userAgent(userAgent.get());
    }
    if (config.retryBufferSize.isPresent()) {
        builder.retryBufferSize(config.retryBufferSize.getAsLong());
    }
    if (config.perRpcBufferLimit.isPresent()) {
        builder.perRpcBufferLimit(config.perRpcBufferLimit.getAsLong());
    }
    Optional<String> overrideAuthority = config.overrideAuthority;
    if (overrideAuthority.isPresent()) {
        builder.overrideAuthority(overrideAuthority.get());
    }
    Optional<Duration> keepAliveTime = config.keepAliveTime;
    if (keepAliveTime.isPresent()) {
        builder.keepAliveTime(keepAliveTime.get().toMillis(), TimeUnit.MILLISECONDS);
    }
    Optional<Duration> keepAliveTimeout = config.keepAliveTimeout;
    if (keepAliveTimeout.isPresent()) {
        builder.keepAliveTimeout(keepAliveTimeout.get().toMillis(), TimeUnit.MILLISECONDS);
    }
    Optional<Duration> idleTimeout = config.idleTimeout;
    if (idleTimeout.isPresent()) {
        builder.keepAliveTimeout(idleTimeout.get().toMillis(), TimeUnit.MILLISECONDS);
    }

    if (plainText) {
        builder.usePlaintext();
    }
    if (context != null) {
        builder.sslContext(context);
    }

    // Client-side interceptors
    Instance<ClientInterceptor> interceptors = Arc.container().beanManager().createInstance()
            .select(ClientInterceptor.class);
    for (ClientInterceptor clientInterceptor : getSortedInterceptors(interceptors)) {
        builder.intercept(clientInterceptor);
    }

    return builder.build();
}
 
Example 11
Source File: ControllerImplTest.java    From pravega with Apache License 2.0 4 votes vote down vote up
@Test
public void testKeepAlive() throws IOException, ExecutionException, InterruptedException {

    // Verify that keep-alive timeout less than permissible by the server results in a failure.
    NettyChannelBuilder builder = NettyChannelBuilder.forAddress("localhost", serverPort)
                                                     .keepAliveTime(10, TimeUnit.SECONDS);
    if (testSecure) {
        builder = builder.sslContext(GrpcSslContexts.forClient().trustManager(
                new File(SecurityConfigDefaults.TLS_CA_CERT_PATH)).build());
    } else {
        builder = builder.usePlaintext();
    }
    @Cleanup
    final ControllerImpl controller = new ControllerImpl(builder,
            ControllerImplConfig.builder().clientConfig(ClientConfig.builder()
                                                                    .trustStore(SecurityConfigDefaults.TLS_CA_CERT_PATH)
                                                                    .controllerURI(URI.create((testSecure ? "tls://" : "tcp://") + "localhost:" + serverPort))
                                                                    .build())
                                .retryAttempts(1).build(),
            this.executor);
    CompletableFuture<Boolean> createStreamStatus = controller.createStream("scope1", "streamdelayed", StreamConfiguration.builder()
            .scalingPolicy(ScalingPolicy.fixed(1))
            .build());
    AssertExtensions.assertFutureThrows("Should throw RetriesExhaustedException", createStreamStatus,
            throwable -> throwable instanceof RetriesExhaustedException);

    // Verify that the same RPC with permissible keepalive time succeeds.
    int serverPort2 = TestUtils.getAvailableListenPort();
    NettyServerBuilder testServerBuilder = NettyServerBuilder.forPort(serverPort2)
                                                             .addService(testServerImpl)
                                                             .permitKeepAliveTime(5, TimeUnit.SECONDS);

    if (testSecure) {
       testServerBuilder = testServerBuilder.useTransportSecurity(
               new File(SecurityConfigDefaults.TLS_SERVER_CERT_PATH),
               new File(SecurityConfigDefaults.TLS_SERVER_PRIVATE_KEY_PATH));
    }

    Server testServer = testServerBuilder.build()
            .start();

    builder = NettyChannelBuilder.forAddress("localhost", serverPort2)
                       .keepAliveTime(10, TimeUnit.SECONDS);
    if (testSecure) {
        builder = builder.sslContext(GrpcSslContexts.forClient().trustManager(
                new File(SecurityConfigDefaults.TLS_CA_CERT_PATH)).build());
    } else {
        builder = builder.usePlaintext();
    }
    @Cleanup
    final ControllerImpl controller1 = new ControllerImpl(builder,
            ControllerImplConfig.builder().clientConfig(ClientConfig.builder()
                                                                    .trustStore(SecurityConfigDefaults.TLS_CA_CERT_PATH)
                                                                    .controllerURI(URI.create((testSecure ? "tls://" : "tcp://") + "localhost:" + serverPort))
                                                                    .build())
                                .retryAttempts(1).build(), this.executor);
    createStreamStatus = controller1.createStream("scope1", "streamdelayed", StreamConfiguration.builder()
            .scalingPolicy(ScalingPolicy.fixed(1))
            .build());
    assertTrue(createStreamStatus.get());
    testServer.shutdownNow();
}
 
Example 12
Source File: InvokeGRPC.java    From nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Whenever this processor is triggered, we need to construct a client in order to communicate
 * with the configured gRPC service.
 *
 * @param context the processor context
 */
@OnScheduled
public void initializeClient(final ProcessContext context) throws Exception {

    channelReference.set(null);
    blockingStubReference.set(null);
    final ComponentLog logger = getLogger();

    final String host = context.getProperty(PROP_SERVICE_HOST).getValue();
    final int port = context.getProperty(PROP_SERVICE_PORT).asInteger();
    final Integer maxMessageSize = context.getProperty(PROP_MAX_MESSAGE_SIZE).asDataSize(DataUnit.B).intValue();
    String userAgent = USER_AGENT_PREFIX;
    try {
        userAgent += "_" + InetAddress.getLocalHost().getHostName();
    } catch (final UnknownHostException e) {
        logger.warn("Unable to determine local hostname. Defaulting gRPC user agent to {}.", new Object[]{USER_AGENT_PREFIX}, e);
    }

    final NettyChannelBuilder nettyChannelBuilder = NettyChannelBuilder.forAddress(host, port)
            // supports both gzip and plaintext, but will compress by default.
            .compressorRegistry(CompressorRegistry.getDefaultInstance())
            .decompressorRegistry(DecompressorRegistry.getDefaultInstance())
            .maxInboundMessageSize(maxMessageSize)
            .userAgent(userAgent);

    // configure whether or not we're using secure comms
    final boolean useSecure = context.getProperty(PROP_USE_SECURE).asBoolean();
    final SSLContextService sslContextService = context.getProperty(PROP_SSL_CONTEXT_SERVICE).asControllerService(SSLContextService.class);
    final SSLContext sslContext = sslContextService == null ? null : sslContextService.createSSLContext(SslContextFactory.ClientAuth.NONE);

    if (useSecure && sslContext != null) {
        SslContextBuilder sslContextBuilder = GrpcSslContexts.forClient();
        if(StringUtils.isNotBlank(sslContextService.getKeyStoreFile())) {
            final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm(),
                    sslContext.getProvider());
            final KeyStore keyStore = KeyStore.getInstance(sslContextService.getKeyStoreType());
            try (final InputStream is = new FileInputStream(sslContextService.getKeyStoreFile())) {
                keyStore.load(is, sslContextService.getKeyStorePassword().toCharArray());
            }
            keyManagerFactory.init(keyStore, sslContextService.getKeyStorePassword().toCharArray());
            sslContextBuilder.keyManager(keyManagerFactory);
        }

        if(StringUtils.isNotBlank(sslContextService.getTrustStoreFile())) {
            final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm(),
                    sslContext.getProvider());
            final KeyStore trustStore = KeyStore.getInstance(sslContextService.getTrustStoreType());
            try (final InputStream is = new FileInputStream(sslContextService.getTrustStoreFile())) {
                trustStore.load(is, sslContextService.getTrustStorePassword().toCharArray());
            }
            trustManagerFactory.init(trustStore);
            sslContextBuilder.trustManager(trustManagerFactory);
        }
        nettyChannelBuilder.sslContext(sslContextBuilder.build());

    } else {
        nettyChannelBuilder.usePlaintext(true);
    }

    final ManagedChannel channel = nettyChannelBuilder.build();
    final FlowFileServiceGrpc.FlowFileServiceBlockingStub blockingStub = FlowFileServiceGrpc.newBlockingStub(channel);
    channelReference.set(channel);
    blockingStubReference.set(blockingStub);
}
 
Example 13
Source File: TestGRPCClient.java    From nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Build a channel with the given host and port and optional ssl properties.
 *
 * @param host          the host to establish a connection with
 * @param port          the port on which to communicate with the host
 * @param sslProperties the properties by which to establish an ssl connection
 * @return a constructed channel
 */
public static ManagedChannel buildChannel(final String host, final int port, final Map<String, String> sslProperties)
        throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException {
    NettyChannelBuilder channelBuilder = NettyChannelBuilder.forAddress(host, port)
            .directExecutor()
            .compressorRegistry(CompressorRegistry.getDefaultInstance())
            .decompressorRegistry(DecompressorRegistry.getDefaultInstance())
            .userAgent("testAgent");

    if (sslProperties != null) {
        SslContextBuilder sslContextBuilder = SslContextBuilder.forClient();

        if(sslProperties.get(StandardSSLContextService.KEYSTORE.getName()) != null) {
            final KeyManagerFactory keyManager = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            final KeyStore keyStore = KeyStore.getInstance(sslProperties.get(StandardSSLContextService.KEYSTORE_TYPE.getName()));
            final String keyStoreFile = sslProperties.get(StandardSSLContextService.KEYSTORE.getName());
            final String keyStorePassword = sslProperties.get(StandardSSLContextService.KEYSTORE_PASSWORD.getName());
            try (final InputStream is = new FileInputStream(keyStoreFile)) {
                keyStore.load(is, keyStorePassword.toCharArray());
            }
            keyManager.init(keyStore, keyStorePassword.toCharArray());
            sslContextBuilder = sslContextBuilder.keyManager(keyManager);
        }

        if (sslProperties.get(StandardSSLContextService.TRUSTSTORE.getName()) != null) {
            final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            final KeyStore trustStore = KeyStore.getInstance(sslProperties.get(StandardSSLContextService.TRUSTSTORE_TYPE.getName()));
            final String trustStoreFile = sslProperties.get(StandardSSLContextService.TRUSTSTORE.getName());
            final String trustStorePassword = sslProperties.get(StandardSSLContextService.TRUSTSTORE_PASSWORD.getName());
            try (final InputStream is = new FileInputStream(trustStoreFile)) {
                trustStore.load(is, trustStorePassword.toCharArray());
            }
            trustManagerFactory.init(trustStore);
            sslContextBuilder = sslContextBuilder.trustManager(trustManagerFactory);
        }

        final String clientAuth = sslProperties.get(NEED_CLIENT_AUTH);
        if (clientAuth == null) {
            sslContextBuilder = sslContextBuilder.clientAuth(ClientAuth.REQUIRE);
        } else {
            sslContextBuilder = sslContextBuilder.clientAuth(ClientAuth.valueOf(clientAuth));
        }
        sslContextBuilder = GrpcSslContexts.configure(sslContextBuilder);
        channelBuilder = channelBuilder.sslContext(sslContextBuilder.build());
    } else {
        channelBuilder.usePlaintext(true);
    }
    return channelBuilder.build();
}