类io.grpc.netty.GrpcSslContexts源码实例Demo

下面列出了怎么用io.grpc.netty.GrpcSslContexts的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: grpc-nebula-java   文件: ConcurrencyTest.java
/**
 * Creates and starts a new {@link TestServiceImpl} server.
 */
private Server newServer() throws CertificateException, IOException {
  File serverCertChainFile = TestUtils.loadCert("server1.pem");
  File serverPrivateKeyFile = TestUtils.loadCert("server1.key");
  X509Certificate[] serverTrustedCaCerts = {
    TestUtils.loadX509Cert("ca.pem")
  };

  SslContext sslContext =
      GrpcSslContexts.forServer(serverCertChainFile, serverPrivateKeyFile)
                     .trustManager(serverTrustedCaCerts)
                     .clientAuth(ClientAuth.REQUIRE)
                     .build();

  return NettyServerBuilder.forPort(0)
      .sslContext(sslContext)
      .addService(new TestServiceImpl(serverExecutor))
      .build()
      .start();
}
 
源代码2 项目: grpc-nebula-java   文件: ConcurrencyTest.java
private ManagedChannel newClientChannel() throws CertificateException, IOException {
  File clientCertChainFile = TestUtils.loadCert("client.pem");
  File clientPrivateKeyFile = TestUtils.loadCert("client.key");
  X509Certificate[] clientTrustedCaCerts = {
    TestUtils.loadX509Cert("ca.pem")
  };

  SslContext sslContext =
      GrpcSslContexts.forClient()
                     .keyManager(clientCertChainFile, clientPrivateKeyFile)
                     .trustManager(clientTrustedCaCerts)
                     .build();

  return NettyChannelBuilder.forAddress("localhost", server.getPort())
      .overrideAuthority(TestUtils.TEST_SERVER_HOST)
      .negotiationType(NegotiationType.TLS)
      .sslContext(sslContext)
      .build();
}
 
源代码3 项目: grpc-nebula-java   文件: Http2OkHttpTest.java
@Override
protected AbstractServerImplBuilder<?> getServerBuilder() {
  // Starts the server with HTTPS.
  try {
    SslProvider sslProvider = SslContext.defaultServerProvider();
    if (sslProvider == SslProvider.OPENSSL && !OpenSsl.isAlpnSupported()) {
      // OkHttp only supports Jetty ALPN on OpenJDK. So if OpenSSL doesn't support ALPN, then we
      // are forced to use Jetty ALPN for Netty instead of OpenSSL.
      sslProvider = SslProvider.JDK;
    }
    SslContextBuilder contextBuilder = SslContextBuilder
        .forServer(TestUtils.loadCert("server1.pem"), TestUtils.loadCert("server1.key"));
    GrpcSslContexts.configure(contextBuilder, sslProvider);
    contextBuilder.ciphers(TestUtils.preferredTestCiphers(), SupportedCipherSuiteFilter.INSTANCE);
    return NettyServerBuilder.forPort(0)
        .flowControlWindow(65 * 1024)
        .maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE)
        .sslContext(contextBuilder.build());
  } catch (IOException ex) {
    throw new RuntimeException(ex);
  }
}
 
源代码4 项目: grpc-nebula-java   文件: Http2NettyTest.java
@Override
protected ManagedChannel createChannel() {
  try {
    NettyChannelBuilder builder = NettyChannelBuilder
        .forAddress(TestUtils.testServerAddress(getPort()))
        .flowControlWindow(65 * 1024)
        .maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE)
        .sslContext(GrpcSslContexts
            .forClient()
            .keyManager(TestUtils.loadCert("client.pem"), TestUtils.loadCert("client.key"))
            .trustManager(TestUtils.loadX509Cert("ca.pem"))
            .ciphers(TestUtils.preferredTestCiphers(), SupportedCipherSuiteFilter.INSTANCE)
            .build());
    io.grpc.internal.TestingAccessor.setStatsImplementation(
        builder, createClientCensusStatsModule());
    return builder.build();
  } catch (Exception ex) {
    throw new RuntimeException(ex);
  }
}
 
源代码5 项目: txle   文件: LoadBalancedClusterMessageSender.java
private static SslContext buildSslContext(AlphaClusterConfig clusterConfig) throws SSLException {
  SslContextBuilder builder = GrpcSslContexts.forClient();
  // openssl must be used because some older JDk does not support cipher suites required by http2,
  // and the performance of JDK ssl is pretty low compared to openssl.
  builder.sslProvider(SslProvider.OPENSSL);

  Properties prop = new Properties();
  try {
    prop.load(LoadBalancedClusterMessageSender.class.getClassLoader().getResourceAsStream("ssl.properties"));
  } catch (IOException e) {
    throw new IllegalArgumentException("Unable to read ssl.properties.", e);
  }

  builder.protocols(prop.getProperty("protocols").split(","));
  builder.ciphers(Arrays.asList(prop.getProperty("ciphers").split(",")));
  builder.trustManager(new File(clusterConfig.getCertChain()));

  if (clusterConfig.isEnableMutualAuth()) {
    builder.keyManager(new File(clusterConfig.getCert()), new File(clusterConfig.getKey()));
  }

  return builder.build();
}
 
private static SslContextBuilder getSslContextBuilder() {
  ClassLoader classLoader = LoadBalanceClusterMessageSenderWithTLSTest.class.getClassLoader();
  SslContextBuilder sslClientContextBuilder = SslContextBuilder.forServer(
      new File(classLoader.getResource("server.crt").getFile()),
      new File(classLoader.getResource("server.pem").getFile()))
      .protocols("TLSv1.2","TLSv1.1")
      .ciphers(Arrays.asList("ECDHE-RSA-AES128-GCM-SHA256",
          "ECDHE-RSA-AES256-GCM-SHA384",
          "ECDHE-ECDSA-AES128-SHA256"));

    sslClientContextBuilder.trustManager(new File(classLoader.getResource("client.crt").getFile()));
    sslClientContextBuilder.clientAuth(ClientAuth.REQUIRE);

  return GrpcSslContexts.configure(sslClientContextBuilder,
      SslProvider.OPENSSL);
}
 
源代码7 项目: txle   文件: GrpcStartable.java
private SslContextBuilder getSslContextBuilder(GrpcServerConfig config) {

    Properties prop = new Properties();
    ClassLoader classLoader = getClass().getClassLoader();
    try {
      prop.load(classLoader.getResourceAsStream("ssl.properties"));
    } catch (IOException e) {
      throw new IllegalStateException("Unable to read ssl.properties.", e);
    }

    InputStream cert = getInputStream(classLoader, config.getCert(), "Server Cert");
    InputStream key = getInputStream(classLoader, config.getKey(), "Server Key");

    SslContextBuilder sslClientContextBuilder = SslContextBuilder.forServer(cert, key)
        .protocols(prop.getProperty("protocols"))
        .ciphers(Arrays.asList(prop.getProperty("ciphers").split(",")));
    if (config.isMutualAuth()) {
      InputStream clientCert = getInputStream(classLoader, config.getClientCert(), "Client Cert");
      sslClientContextBuilder.trustManager(clientCert);
      sslClientContextBuilder.clientAuth(ClientAuth.REQUIRE);
    }
    return GrpcSslContexts.configure(sslClientContextBuilder,
        SslProvider.OPENSSL);
  }
 
源代码8 项目: txle   文件: AlphaIntegrationWithSSLTest.java
private static SslContext getSslContext(){
  ClassLoader classLoader = AlphaIntegrationWithSSLTest.class.getClassLoader();
  SslContext sslContext = null;
  try {
    sslContext = GrpcSslContexts.forClient().sslProvider(SslProvider.OPENSSL)
        .protocols("TLSv1.2","TLSv1.1")
        .ciphers(Arrays.asList("ECDHE-RSA-AES128-GCM-SHA256",
            "ECDHE-RSA-AES256-GCM-SHA384",
            "ECDHE-ECDSA-AES128-SHA256"))
        .trustManager(new File(classLoader.getResource("ca.crt").getFile()))
        .keyManager(new File(classLoader.getResource("client.crt").getFile()),
            new File(classLoader.getResource("client.pem").getFile())).build();
  } catch (SSLException e) {
    e.printStackTrace();
  }
  return sslContext;
}
 
源代码9 项目: julongchain   文件: SmartContractBase.java
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();
}
 
源代码10 项目: kafka-pubsub-emulator   文件: BaseIT.java
public static TransportChannelProvider getChannelProvider() {
  ManagedChannel channel = null;
  if (USE_SSL) {
    try {
      channel =
          NettyChannelBuilder.forAddress(LOCALHOST, PORT)
              .maxInboundMessageSize(100000)
              .sslContext(
                  GrpcSslContexts.forClient()
                      .trustManager(InsecureTrustManagerFactory.INSTANCE)
                      .build())
              .overrideAuthority(LOCALHOST + ":" + PORT)
              .build();
    } catch (SSLException e) {
      fail("Unable to create SSL channel " + e.getMessage());
    }
  } else {
    channel = ManagedChannelBuilder.forAddress(LOCALHOST, PORT).usePlaintext(true).build();
  }
  return FixedTransportChannelProvider.create(GrpcTransportChannel.create(channel));
}
 
源代码11 项目: kafka-pubsub-emulator   文件: BaseIT.java
public static AdminGrpc.AdminBlockingStub getAdminStub() {
  ManagedChannel channel = null;
  if (USE_SSL) {
    File certificate =
        new File(configurationRepository.getServer().getSecurity().getCertificateChainFile());
    try {
      channel =
          NettyChannelBuilder.forAddress(LOCALHOST, PORT)
              .maxInboundMessageSize(100000)
              .sslContext(GrpcSslContexts.forClient().trustManager(certificate).build())
              .build();
    } catch (SSLException e) {
      fail("Unable to create SSL channel " + e.getMessage());
    }
  } else {
    channel = ManagedChannelBuilder.forAddress(LOCALHOST, PORT).usePlaintext(true).build();
  }
  return AdminGrpc.newBlockingStub(channel);
}
 
源代码12 项目: startup-os   文件: Client.java
public static void main(String[] args) throws Exception {
  Flags.parseCurrentPackage(args);

  SslContext sslContext =
      GrpcSslContexts.forClient().trustManager(new File(certificateFile.get())).build();
  ManagedChannel channel =
      NettyChannelBuilder.forAddress("localhost", GRPC_PORT).sslContext(sslContext).build();

  GrpcAuthTestGrpc.GrpcAuthTestBlockingStub stub =
      GrpcAuthTestGrpc.newBlockingStub(channel)
          .withInterceptors(new ClientAuthInterceptor(token.get()));

  logger.at(Level.INFO).log("Calling server to increment %d", n.get());
  Protos.Response resp =
      stub.getNextNumber(Protos.Request.newBuilder().setNumber(n.get()).build());
  logger.at(Level.INFO).log("Got %d in response", resp.getNumber());
}
 
源代码13 项目: snowblossom   文件: CertGen.java
public static SslContext getServerSSLContext(WalletDatabase db)
  throws Exception
{
  if (db.getKeysCount() != 1) throw new RuntimeException("Unexpected number of keys in wallet db");
  if (db.getAddressesCount() != 1) throw new RuntimeException("Unexpected number of addresses in wallet db");
  WalletKeyPair wkp = db.getKeys(0);
  AddressSpec address_spec = db.getAddresses(0);
  
  WalletKeyPair tls_wkp = KeyUtil.generateWalletRSAKey(2048);
  KeyPair tls_pair = KeyUtil.decodeKeypair(tls_wkp);

  X509Certificate cert = generateSelfSignedCert(wkp, tls_wkp, address_spec);
  //System.out.println(cert);

  ByteString pem_cert = pemCodeCert(cert);
  ByteString pem_prv = pemCodeECPrivateKey(tls_pair.getPrivate());

  return GrpcSslContexts.forServer(pem_cert.newInput(), pem_prv.newInput()).build();
}
 
源代码14 项目: servicecomb-pack   文件: GrpcStartable.java
private SslContextBuilder getSslContextBuilder(GrpcServerConfig config) {

    Properties prop = new Properties();
    ClassLoader classLoader = getClass().getClassLoader();
    try {
      prop.load(classLoader.getResourceAsStream("ssl.properties"));
    } catch (IOException e) {
      throw new IllegalStateException("Unable to read ssl.properties.", e);
    }

    InputStream cert = getInputStream(classLoader, config.getCert(), "Server Cert");
    InputStream key = getInputStream(classLoader, config.getKey(), "Server Key");

    SslContextBuilder sslClientContextBuilder = SslContextBuilder.forServer(cert, key)
        .protocols(prop.getProperty("protocols"))
        .ciphers(Arrays.asList(prop.getProperty("ciphers").split(",")));
    if (config.isMutualAuth()) {
      InputStream clientCert = getInputStream(classLoader, config.getClientCert(), "Client Cert");
      sslClientContextBuilder.trustManager(clientCert);
      sslClientContextBuilder.clientAuth(ClientAuth.REQUIRE);
    }
    return GrpcSslContexts.configure(sslClientContextBuilder,
        SslProvider.OPENSSL);
  }
 
源代码15 项目: dremio-oss   文件: ConduitServer.java
@Override
public void start() throws Exception {
  final ConduitServiceRegistryImpl registry = (ConduitServiceRegistryImpl) registryProvider.get();

  for (BindableService service : registry.getServiceList()) {
    serverBuilder.addService(service);
  }

  for (CloseableBindableService closeableService : registry.getCloseableServiceList()) {
    serverBuilder.addService(closeableService);
    closeableServices.add(closeableService);
  }

  serverBuilder.maxInboundMetadataSize(Integer.MAX_VALUE).maxInboundMessageSize(Integer.MAX_VALUE)
    .intercept(TransmitStatusRuntimeExceptionInterceptor.instance());

  if (sslEngineFactory.isPresent()) {
    final SslContextBuilder contextBuilder = sslEngineFactory.get().newServerContextBuilder();
    // add gRPC overrides using #configure
    serverBuilder.sslContext(GrpcSslContexts.configure(contextBuilder).build());
  }
  server = serverBuilder.build();
  server.start();

  logger.info("ConduitServer is up. Listening on port '{}'", server.getPort());
}
 
@Before
public final void setupChannels() throws IOException {
    if(gRpcServerProperties.isEnabled()) {
        ManagedChannelBuilder<?> channelBuilder = ManagedChannelBuilder.forAddress("localhost", getPort());
        Resource certChain = Optional.ofNullable(gRpcServerProperties.getSecurity())
                .map(GRpcServerProperties.SecurityProperties::getCertChain)
                .orElse(null);
        if(null!= certChain){
            ((NettyChannelBuilder)channelBuilder)
                    .useTransportSecurity()
                    .sslContext(GrpcSslContexts.forClient().trustManager(certChain.getInputStream()).build());
        }else{
            channelBuilder.usePlaintext();
        }


        channel = onChannelBuild(channelBuilder).build();
    }
    if(StringUtils.hasText(gRpcServerProperties.getInProcessServerName())){
        inProcChannel = onChannelBuild(
                            InProcessChannelBuilder.forName(gRpcServerProperties.getInProcessServerName())
                            .usePlaintext()
                        ).build();

    }
}
 
源代码17 项目: credhub   文件: KMSEncryptionProvider.java
public KMSEncryptionProvider(final EncryptionConfiguration configuration) {
  super();

  setChannelInfo();

  SslContext sslContext;
  try {
    sslContext = GrpcSslContexts.forClient()
      .trustManager(new ByteArrayInputStream(configuration.getCa().getBytes(UTF_8)))
      .build();
  } catch (SSLException e) {
    throw new RuntimeException(e);
  }

  blockingStub = KeyManagementServiceGrpc.newBlockingStub(
    NettyChannelBuilder.forAddress(new DomainSocketAddress(configuration.getEndpoint()))
      .eventLoopGroup(group)
      .channelType(channelType)
      .keepAliveTime(DEFAULT_KEEPALIVE_TIMEOUT_NANOS, TimeUnit.NANOSECONDS)
      .useTransportSecurity()
      .sslContext(sslContext)
      .overrideAuthority(configuration.getHost())
      .build());
}
 
源代码18 项目: grpc-java   文件: ConcurrencyTest.java
/**
 * Creates and starts a new {@link TestServiceImpl} server.
 */
private Server newServer() throws CertificateException, IOException {
  File serverCertChainFile = TestUtils.loadCert("server1.pem");
  File serverPrivateKeyFile = TestUtils.loadCert("server1.key");
  X509Certificate[] serverTrustedCaCerts = {
    TestUtils.loadX509Cert("ca.pem")
  };

  SslContext sslContext =
      GrpcSslContexts.forServer(serverCertChainFile, serverPrivateKeyFile)
                     .trustManager(serverTrustedCaCerts)
                     .clientAuth(ClientAuth.REQUIRE)
                     .build();

  return NettyServerBuilder.forPort(0)
      .sslContext(sslContext)
      .addService(new TestServiceImpl(serverExecutor))
      .build()
      .start();
}
 
源代码19 项目: grpc-java   文件: ConcurrencyTest.java
private ManagedChannel newClientChannel() throws CertificateException, IOException {
  File clientCertChainFile = TestUtils.loadCert("client.pem");
  File clientPrivateKeyFile = TestUtils.loadCert("client.key");
  X509Certificate[] clientTrustedCaCerts = {
    TestUtils.loadX509Cert("ca.pem")
  };

  SslContext sslContext =
      GrpcSslContexts.forClient()
                     .keyManager(clientCertChainFile, clientPrivateKeyFile)
                     .trustManager(clientTrustedCaCerts)
                     .build();

  return NettyChannelBuilder.forAddress("localhost", server.getPort())
      .overrideAuthority(TestUtils.TEST_SERVER_HOST)
      .negotiationType(NegotiationType.TLS)
      .sslContext(sslContext)
      .build();
}
 
源代码20 项目: grpc-java   文件: Http2OkHttpTest.java
@Override
protected AbstractServerImplBuilder<?> getServerBuilder() {
  // Starts the server with HTTPS.
  try {
    SslProvider sslProvider = SslContext.defaultServerProvider();
    if (sslProvider == SslProvider.OPENSSL && !SslProvider.isAlpnSupported(SslProvider.OPENSSL)) {
      // OkHttp only supports Jetty ALPN on OpenJDK. So if OpenSSL doesn't support ALPN, then we
      // are forced to use Jetty ALPN for Netty instead of OpenSSL.
      sslProvider = SslProvider.JDK;
    }
    SslContextBuilder contextBuilder = SslContextBuilder
        .forServer(TestUtils.loadCert("server1.pem"), TestUtils.loadCert("server1.key"));
    GrpcSslContexts.configure(contextBuilder, sslProvider);
    contextBuilder.ciphers(TestUtils.preferredTestCiphers(), SupportedCipherSuiteFilter.INSTANCE);
    return NettyServerBuilder.forPort(0)
        .flowControlWindow(65 * 1024)
        .maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE)
        .sslContext(contextBuilder.build());
  } catch (IOException ex) {
    throw new RuntimeException(ex);
  }
}
 
源代码21 项目: grpc-java   文件: Http2NettyTest.java
@Override
protected AbstractServerImplBuilder<?> getServerBuilder() {
  // Starts the server with HTTPS.
  try {
    return NettyServerBuilder.forPort(0)
        .flowControlWindow(65 * 1024)
        .maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE)
        .sslContext(GrpcSslContexts
            .forServer(TestUtils.loadCert("server1.pem"), TestUtils.loadCert("server1.key"))
            .clientAuth(ClientAuth.REQUIRE)
            .trustManager(TestUtils.loadCert("ca.pem"))
            .ciphers(TestUtils.preferredTestCiphers(), SupportedCipherSuiteFilter.INSTANCE)
            .build());
  } catch (IOException ex) {
    throw new RuntimeException(ex);
  }
}
 
源代码22 项目: grpc-java   文件: Http2NettyTest.java
@Override
protected ManagedChannel createChannel() {
  try {
    NettyChannelBuilder builder = NettyChannelBuilder
        .forAddress(TestUtils.testServerAddress((InetSocketAddress) getListenAddress()))
        .flowControlWindow(65 * 1024)
        .maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE)
        .sslContext(GrpcSslContexts
            .forClient()
            .keyManager(TestUtils.loadCert("client.pem"), TestUtils.loadCert("client.key"))
            .trustManager(TestUtils.loadX509Cert("ca.pem"))
            .ciphers(TestUtils.preferredTestCiphers(), SupportedCipherSuiteFilter.INSTANCE)
            .build());
    // Disable the default census stats interceptor, use testing interceptor instead.
    io.grpc.internal.TestingAccessor.setStatsEnabled(builder, false);
    return builder.intercept(createCensusStatsClientInterceptor()).build();
  } catch (Exception ex) {
    throw new RuntimeException(ex);
  }
}
 
源代码23 项目: grpc-java   文件: ComputeEngineChannelBuilder.java
private ComputeEngineChannelBuilder(String target) {
  delegate = NettyChannelBuilder.forTarget(target);
  SslContext sslContext;
  try {
    sslContext = GrpcSslContexts.forClient().build();
  } catch (SSLException e) {
    throw new RuntimeException(e);
  }
  InternalNettyChannelBuilder.setProtocolNegotiatorFactory(
      delegate(),
      new GoogleDefaultProtocolNegotiatorFactory(
          /* targetServiceAccounts= */ ImmutableList.<String>of(),
          SharedResourcePool.forResource(HandshakerServiceChannel.SHARED_HANDSHAKER_CHANNEL),
          sslContext));
  CallCredentials credentials = MoreCallCredentials.from(ComputeEngineCredentials.create());
  Status status = Status.OK;
  if (!CheckGcpEnvironment.isOnGcp()) {
    status =
        Status.INTERNAL.withDescription(
            "Compute Engine Credentials can only be used on Google Cloud Platform");
  }
  delegate().intercept(new CallCredentialsInterceptor(credentials, status));
}
 
源代码24 项目: grpc-nebula-java   文件: HelloWorldClientTls.java
private static SslContext buildSslContext(String trustCertCollectionFilePath,
                                          String clientCertChainFilePath,
                                          String clientPrivateKeyFilePath) throws SSLException {
    SslContextBuilder builder = GrpcSslContexts.forClient();
    if (trustCertCollectionFilePath != null) {
        builder.trustManager(new File(trustCertCollectionFilePath));
    }
    if (clientCertChainFilePath != null && clientPrivateKeyFilePath != null) {
        builder.keyManager(new File(clientCertChainFilePath), new File(clientPrivateKeyFilePath));
    }
    return builder.build();
}
 
源代码25 项目: grpc-nebula-java   文件: HelloWorldServerTls.java
private SslContextBuilder getSslContextBuilder() {
    SslContextBuilder sslClientContextBuilder = SslContextBuilder.forServer(new File(certChainFilePath),
            new File(privateKeyFilePath));
    if (trustCertCollectionFilePath != null) {
        sslClientContextBuilder.trustManager(new File(trustCertCollectionFilePath));
        sslClientContextBuilder.clientAuth(ClientAuth.REQUIRE);
    }
    return GrpcSslContexts.configure(sslClientContextBuilder,
            SslProvider.OPENSSL);
}
 
源代码26 项目: grpc-nebula-java   文件: TestServiceServer.java
@VisibleForTesting
void start() throws Exception {
  executor = Executors.newSingleThreadScheduledExecutor();
  SslContext sslContext = null;
  if (useAlts) {
    server =
        AltsServerBuilder.forPort(port)
            .addService(
                ServerInterceptors.intercept(
                    new TestServiceImpl(executor), TestServiceImpl.interceptors()))
            .build()
            .start();
  } else {
    if (useTls) {
      sslContext =
          GrpcSslContexts.forServer(
                  TestUtils.loadCert("server1.pem"), TestUtils.loadCert("server1.key"))
              .build();
    }
    server =
        NettyServerBuilder.forPort(port)
            .sslContext(sslContext)
            .maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE)
            .addService(
                ServerInterceptors.intercept(
                    new TestServiceImpl(executor), TestServiceImpl.interceptors()))
            .build()
            .start();
  }
}
 
源代码27 项目: grpc-nebula-java   文件: StressTestClient.java
private ManagedChannel createChannel(InetSocketAddress address) {
  SslContext sslContext = null;
  if (useTestCa) {
    try {
      sslContext = GrpcSslContexts.forClient().trustManager(
          TestUtils.loadCert("ca.pem")).build();
    } catch (Exception ex) {
      throw new RuntimeException(ex);
    }
  }
  return NettyChannelBuilder.forAddress(address)
      .negotiationType(useTls ? NegotiationType.TLS : NegotiationType.PLAINTEXT)
      .sslContext(sslContext)
      .build();
}
 
源代码28 项目: grpc-nebula-java   文件: Utils.java
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;
}
 
@Override
public GoogleDefaultProtocolNegotiator buildProtocolNegotiator() {
  TsiHandshakerFactory altsHandshakerFactory =
      new TsiHandshakerFactory() {
        @Override
        public TsiHandshaker newHandshaker(String authority) {
          // Used the shared grpc channel to connecting to the ALTS handshaker service.
          // TODO: Release the channel if it is not used.
          // https://github.com/grpc/grpc-java/issues/4755.
          ManagedChannel channel =
              SharedResourceHolder.get(HandshakerServiceChannel.SHARED_HANDSHAKER_CHANNEL);
          AltsClientOptions handshakerOptions =
              new AltsClientOptions.Builder()
                  .setRpcProtocolVersions(RpcProtocolVersionsUtil.getRpcProtocolVersions())
                  .setTargetName(authority)
                  .build();
          return AltsTsiHandshaker.newClient(
              HandshakerServiceGrpc.newStub(channel), handshakerOptions);
        }
      };
  SslContext sslContext;
  try {
    sslContext = GrpcSslContexts.forClient().build();
  } catch (SSLException ex) {
    throw new RuntimeException(ex);
  }
  return negotiatorForTest =
      new GoogleDefaultProtocolNegotiator(altsHandshakerFactory, sslContext);
}
 
源代码30 项目: compass   文件: RemoteSignatureSource.java
private static SslContext buildSslContext(
    String trustCertCollectionFilePath,
    String clientCertChainFilePath,
    String clientPrivateKeyFilePath) throws SSLException {
  SslContextBuilder builder = GrpcSslContexts.forClient();
  if (trustCertCollectionFilePath != null) {
    builder.trustManager(new File(trustCertCollectionFilePath));
  }
  if (clientCertChainFilePath != null && !clientCertChainFilePath.isEmpty()
      && clientPrivateKeyFilePath != null && !clientPrivateKeyFilePath.isEmpty()) {
    builder.keyManager(new File(clientCertChainFilePath), new File(clientPrivateKeyFilePath));
  }
  return builder.build();
}
 
 类所在包
 同包方法