io.grpc.ManagedChannel Java Examples
The following examples show how to use
io.grpc.ManagedChannel.
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: HelloWorldAltsClient.java From grpc-java with Apache License 2.0 | 6 votes |
private void run(String[] args) throws InterruptedException { parseArgs(args); ExecutorService executor = Executors.newFixedThreadPool(1); ManagedChannel channel = AltsChannelBuilder.forTarget(serverAddress).executor(executor).build(); try { GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channel); HelloReply resp = stub.sayHello(HelloRequest.newBuilder().setName("Waldo").build()); logger.log(Level.INFO, "Got {0}", resp); } finally { channel.shutdown(); channel.awaitTermination(1, TimeUnit.SECONDS); // Wait until the channel has terminated, since tasks can be queued after the channel is // shutdown. executor.shutdown(); } }
Example #2
Source File: ManagedChannelImplIdlenessTest.java From grpc-java with Apache License 2.0 | 6 votes |
@Test public void updateOobChannelAddresses_existingAddressDoesNotConnect() { ClientCall<String, Integer> call = channel.newCall(method, CallOptions.DEFAULT); call.start(mockCallListener, new Metadata()); // Create LB ArgumentCaptor<Helper> helperCaptor = ArgumentCaptor.forClass(null); verify(mockLoadBalancerProvider).newLoadBalancer(helperCaptor.capture()); Helper helper = helperCaptor.getValue(); ManagedChannel oobChannel = helper.createOobChannel(servers.get(0), "localhost"); oobChannel.newCall(method, CallOptions.DEFAULT).start(mockCallListener, new Metadata()); MockClientTransportInfo t0 = newTransports.poll(); t0.listener.transportReady(); List<SocketAddress> changedList = new ArrayList<>(servers.get(0).getAddresses()); changedList.add(new FakeSocketAddress("aDifferentServer")); helper.updateOobChannelAddresses(oobChannel, new EquivalentAddressGroup(changedList)); oobChannel.newCall(method, CallOptions.DEFAULT).start(mockCallListener, new Metadata()); assertNull(newTransports.poll()); }
Example #3
Source File: Http2NettyTest.java From grpc-nebula-java with Apache License 2.0 | 6 votes |
@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); } }
Example #4
Source File: HealthCheckingLoadBalancerFactoryTest.java From grpc-nebula-java with Apache License 2.0 | 6 votes |
@After public void teardown() throws Exception { // All scheduled tasks have been accounted for assertThat(clock.getPendingTasks()).isEmpty(); // Health-check streams are usually not closed in the tests because handleSubchannelState() is // faked. Force closing for clean up. for (Server server : servers) { server.shutdownNow(); assertThat(server.awaitTermination(1, TimeUnit.SECONDS)).isTrue(); } for (ManagedChannel channel : channels) { channel.shutdownNow(); assertThat(channel.awaitTermination(1, TimeUnit.SECONDS)).isTrue(); } for (HealthImpl impl : healthImpls) { assertThat(impl.checkCalled).isFalse(); } }
Example #5
Source File: GrpcChannelControllerImpl.java From onos with Apache License 2.0 | 6 votes |
@Override public void destroy(URI channelUri) { checkNotNull(channelUri); channelLocks.get(channelUri).lock(); try { final ManagedChannel channel = channels.remove(channelUri); if (channel != null) { shutdownNowAndWait(channel, channelUri); } final GrpcLoggingInterceptor interceptor = interceptors.remove(channelUri); if (interceptor != null) { interceptor.close(); } } finally { channelLocks.get(channelUri).unlock(); } }
Example #6
Source File: BaseIT.java From kafka-pubsub-emulator with Apache License 2.0 | 6 votes |
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)); }
Example #7
Source File: StubInstance.java From bazel-buildfarm with Apache License 2.0 | 6 votes |
public StubInstance( String name, String identifier, DigestUtil digestUtil, ManagedChannel channel, long deadlineAfter, TimeUnit deadlineAfterUnits, Retrier retrier, @Nullable ListeningScheduledExecutorService retryService) { this.name = name; this.identifier = identifier; this.digestUtil = digestUtil; this.channel = channel; this.deadlineAfter = deadlineAfter; this.deadlineAfterUnits = deadlineAfterUnits; this.retrier = retrier; this.retryService = retryService; }
Example #8
Source File: ManagedChannelImplIdlenessTest.java From grpc-nebula-java with Apache License 2.0 | 6 votes |
@Test public void updateOobChannelAddresses_newAddressConnects() { ClientCall<String, Integer> call = channel.newCall(method, CallOptions.DEFAULT); call.start(mockCallListener, new Metadata()); // Create LB ArgumentCaptor<Helper> helperCaptor = ArgumentCaptor.forClass(null); verify(mockLoadBalancerFactory).newLoadBalancer(helperCaptor.capture()); Helper helper = helperCaptor.getValue(); ManagedChannel oobChannel = helper.createOobChannel(servers.get(0), "localhost"); oobChannel.newCall(method, CallOptions.DEFAULT).start(mockCallListener, new Metadata()); MockClientTransportInfo t0 = newTransports.poll(); t0.listener.transportReady(); helper.updateOobChannelAddresses(oobChannel, servers.get(1)); oobChannel.newCall(method, CallOptions.DEFAULT).start(mockCallListener, new Metadata()); MockClientTransportInfo t1 = newTransports.poll(); t1.listener.transportReady(); }
Example #9
Source File: Example1Client.java From blog-sample with Apache License 2.0 | 6 votes |
public static void main(String[] args) throws Exception { // STEP1 构造 Channel 和 BlockingStub ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", Constant.RUNNING_PORT) // Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid needing certificates. .usePlaintext() .build(); UserRpcServiceGrpc.UserRpcServiceBlockingStub blockingStub = UserRpcServiceGrpc.newBlockingStub(channel); int requestAge = 20; logger.info("Will try to query age = " + requestAge + " ..."); // STEP2 发起 gRPC 请求 UserRpcProto.AgeRequest request = UserRpcProto.AgeRequest.newBuilder().setAge(20).build(); try { UserRpcProto.UserResponse response = blockingStub.listByAge(request); logger.info("Response: " + ProtoUtils.toStr(response)); } catch (StatusRuntimeException e) { logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus()); } finally { // STEP3 关闭 Channel channel.shutdown().awaitTermination(5, TimeUnit.SECONDS); } }
Example #10
Source File: HelloWorldClientTest.java From grpc-java with Apache License 2.0 | 6 votes |
@Before public void setUp() throws Exception { // Generate a unique in-process server name. String serverName = InProcessServerBuilder.generateName(); // Create a server, add service, start, and register for automatic graceful shutdown. grpcCleanup.register(InProcessServerBuilder .forName(serverName).directExecutor().addService(serviceImpl).build().start()); // Create a client channel and register for automatic graceful shutdown. ManagedChannel channel = grpcCleanup.register( InProcessChannelBuilder.forName(serverName).directExecutor().build()); // Create a HelloWorldClient using the in-process channel; client = new HelloWorldClient(channel); }
Example #11
Source File: UcoreSender.java From dble with GNU General Public License v2.0 | 6 votes |
public UcoreInterface.SubscribeNodesOutput subscribeNodes(UcoreInterface.SubscribeNodesInput subscribeNodesInput) throws IOException { try { return stub.withDeadlineAfter(GRPC_SUBTIMEOUT, TimeUnit.SECONDS).subscribeNodes(subscribeNodesInput); } catch (Exception e) { //the first try failure ,try for all the other ucore ip for (String ip : getIpList()) { ManagedChannel channel = null; try { channel = ManagedChannelBuilder.forAddress(ip, Integer.parseInt(getValue(ClusterParamCfg.CLUSTER_PLUGINS_PORT))).usePlaintext(true).build(); stub = UcoreGrpc.newBlockingStub(channel).withDeadlineAfter(GRPC_SUBTIMEOUT, TimeUnit.SECONDS); return stub.withDeadlineAfter(GRPC_SUBTIMEOUT, TimeUnit.SECONDS).subscribeNodes(subscribeNodesInput); } catch (Exception e2) { LOGGER.info("try connection IP " + ip + " failure ", e2); if (channel != null) { channel.shutdownNow(); } } } } throw new IOException("ALL the ucore connect failure"); }
Example #12
Source File: DemoFmService.java From capillary with Apache License 2.0 | 6 votes |
private void handleDataMessage(Map<String, String> dataMap) { try { Utils.initialize(this); // Get the encryption algorithm and the ciphertext bytes. KeyAlgorithm keyAlgorithm = KeyAlgorithm.valueOf(dataMap.get(Constants.CAPILLARY_KEY_ALGORITHM_KEY)); byte[] ciphertext = Base64.decode(dataMap.get(Constants.CAPILLARY_CIPHERTEXT_KEY)); // Create the gRPC channel. ManagedChannel channel = Utils.createGrpcChannel(this); // Create the DemoCapillaryHandler. DemoCapillaryHandler handler = new DemoCapillaryHandler(this, channel); // Handle ciphertext. Utils.getKeyManager(this, keyAlgorithm) .getDecrypterManager().decrypt(ciphertext, handler, keyAlgorithm); // Close the gRPC channel. channel.shutdown(); } catch (GeneralSecurityException | IOException e) { e.printStackTrace(); } }
Example #13
Source File: XdsClient.java From grpc-java with Apache License 2.0 | 5 votes |
/** * Creates a channel to the first server in the given list. */ @Override ManagedChannel createChannel(List<ServerInfo> servers) { checkArgument(!servers.isEmpty(), "No management server provided."); XdsLogger logger = XdsLogger.withPrefix("xds-client-channel-factory"); ServerInfo serverInfo = servers.get(0); String serverUri = serverInfo.getServerUri(); logger.log(XdsLogLevel.INFO, "Creating channel to {0}", serverUri); List<ChannelCreds> channelCredsList = serverInfo.getChannelCredentials(); ManagedChannelBuilder<?> channelBuilder = null; // Use the first supported channel credentials configuration. // Currently, only "google_default" is supported. for (ChannelCreds creds : channelCredsList) { if (creds.getType().equals("google_default")) { logger.log(XdsLogLevel.INFO, "Using channel credentials: google_default"); channelBuilder = GoogleDefaultChannelBuilder.forTarget(serverUri); break; } } if (channelBuilder == null) { logger.log(XdsLogLevel.INFO, "Using default channel credentials"); channelBuilder = ManagedChannelBuilder.forTarget(serverUri); } return channelBuilder .keepAliveTime(5, TimeUnit.MINUTES) .build(); }
Example #14
Source File: PeerEventServiceClient.java From fabric-sdk-java with Apache License 2.0 | 5 votes |
String getStatus() { ManagedChannel lmanagedChannel = managedChannel; if (lmanagedChannel == null) { return "No grpc managed channel active. peer eventing client service is shutdown: " + shutdown; } else { StringBuilder sb = new StringBuilder(1000); sb.append("peer eventing client service is shutdown: ").append(shutdown) .append(", grpc isShutdown: ").append(lmanagedChannel.isShutdown()) .append(", grpc isTerminated: ").append(lmanagedChannel.isTerminated()) .append(", grpc state: ").append("" + lmanagedChannel.getState(false)); return sb.toString(); } }
Example #15
Source File: GrpcITest.java From java-specialagent with Apache License 2.0 | 5 votes |
public static void main(final String[] args) throws InterruptedException, IOException { final CountDownLatch latch = TestUtil.initExpectedSpanLatch(2); final Server server = ServerBuilder.forPort(8086).addService(new GreeterImpl()).build().start(); final ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 8086).usePlaintext(true).build(); final GreeterBlockingStub greeterBlockingStub = GreeterGrpc.newBlockingStub(channel); greeterBlockingStub.sayHello(HelloRequest.newBuilder().setName("world").build()).getMessage(); server.shutdownNow(); TestUtil.checkSpan(latch, new ComponentSpanCount("java-grpc", 2) ); }
Example #16
Source File: GoogleDefaultChannelBuilder.java From grpc-nebula-java with Apache License 2.0 | 5 votes |
@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); }
Example #17
Source File: AndroidChannelBuilderTest.java From grpc-nebula-java with Apache License 2.0 | 5 votes |
@Test @Config(sdk = 24) public void resetConnectBackoffAndEnterIdle_api24() { shadowOf(connectivityManager).setActiveNetworkInfo(MOBILE_DISCONNECTED); TestChannel delegateChannel = new TestChannel(); ManagedChannel androidChannel = new AndroidChannelBuilder.AndroidChannel( delegateChannel, RuntimeEnvironment.application.getApplicationContext()); assertThat(delegateChannel.resetCount).isEqualTo(0); assertThat(delegateChannel.enterIdleCount).isEqualTo(0); // Establish an initial network connection shadowOf(connectivityManager).setActiveNetworkInfo(MOBILE_CONNECTED); assertThat(delegateChannel.resetCount).isEqualTo(1); assertThat(delegateChannel.enterIdleCount).isEqualTo(0); // Switch to another network to trigger enterIdle() shadowOf(connectivityManager).setActiveNetworkInfo(WIFI_CONNECTED); assertThat(delegateChannel.resetCount).isEqualTo(1); assertThat(delegateChannel.enterIdleCount).isEqualTo(1); // Switch to an offline network and then to null shadowOf(connectivityManager).setActiveNetworkInfo(WIFI_DISCONNECTED); shadowOf(connectivityManager).setActiveNetworkInfo(null); assertThat(delegateChannel.resetCount).isEqualTo(1); assertThat(delegateChannel.enterIdleCount).isEqualTo(1); // Establish a connection shadowOf(connectivityManager).setActiveNetworkInfo(MOBILE_CONNECTED); assertThat(delegateChannel.resetCount).isEqualTo(2); assertThat(delegateChannel.enterIdleCount).isEqualTo(1); // Disconnect, then shutdown the channel and verify that the callback has been unregistered shadowOf(connectivityManager).setActiveNetworkInfo(null); androidChannel.shutdown(); shadowOf(connectivityManager).setActiveNetworkInfo(MOBILE_CONNECTED); assertThat(delegateChannel.resetCount).isEqualTo(2); assertThat(delegateChannel.enterIdleCount).isEqualTo(1); }
Example #18
Source File: ReferenceCountManagedChannel.java From sofa-rpc with Apache License 2.0 | 5 votes |
@Override public ManagedChannel shutdown() { if (referenceCount.decrementAndGet() <= 0) { return grpcChannel.shutdown(); } return grpcChannel; }
Example #19
Source File: CloudSpeechSession.java From live-transcribe-speech-engine with Apache License 2.0 | 5 votes |
public CloudSpeechSession( CloudSpeechSessionParams params, SpeechSessionListener speechSessionListener, int sampleRateHz, ManagedChannel channel) { this.params = params; this.channel = channel; this.speechSessionListener = speechSessionListener; this.sampleRateHz = sampleRateHz; this.encoder = new StreamingAudioEncoder(); }
Example #20
Source File: GRpcAutoConfigurationIntegrationTest.java From genie with Apache License 2.0 | 5 votes |
/** * Check that channel is a singleton. */ @Test public void channelBean() { final ManagedChannel channel1 = applicationContext.getBean(ManagedChannel.class); final ManagedChannel channel2 = applicationContext.getBean(ManagedChannel.class); Assert.assertNotNull(channel1); Assert.assertNotNull(channel2); Assert.assertSame(channel1, channel2); }
Example #21
Source File: Worker.java From bazel-buildfarm with Apache License 2.0 | 5 votes |
private static Instance newStubInstance( String name, ManagedChannel channel, DigestUtil digestUtil, long deadlineAfterSeconds) { return new StubInstance( name, /* identifier=*/ "", digestUtil, channel, deadlineAfterSeconds, SECONDS, retrier, retryScheduler); }
Example #22
Source File: LoadBalancedClusterMessageSender.java From txle with Apache License 2.0 | 5 votes |
@Override public void close() { scheduler.shutdown(); for (ManagedChannel channel : channels) { channel.shutdownNow(); } }
Example #23
Source File: GrpcController.java From grpc-swagger with MIT License | 5 votes |
@SneakyThrows @RequestMapping("/{rawFullMethodName}") public Result<Object> invokeMethod(@PathVariable String rawFullMethodName, @RequestBody String payload, @RequestParam(defaultValue = "{}") String headers) { GrpcMethodDefinition methodDefinition = parseToMethodDefinition(rawFullMethodName); JSONObject jsonObject = JSON.parseObject(payload); HostAndPort endPoint; if (jsonObject.containsKey(ENDPOINT_PARAM)) { endPoint = HostAndPort.fromString(jsonObject.getString(ENDPOINT_PARAM)); jsonObject.remove(ENDPOINT_PARAM); payload = JSON.toJSONString(jsonObject); } else { String fullServiceName = methodDefinition.getFullServiceName(); endPoint = ServiceConfigManager.getEndPoint(fullServiceName); } if (endPoint == null) { return Result.success("can't find target endpoint"); } Map<String, Object> metaHeaderMap = JSON.parseObject(headers); ManagedChannel channel = null; try { channel = ChannelFactory.create(endPoint, metaHeaderMap); CallResults results = grpcProxyService.invokeMethod(methodDefinition, channel, DEFAULT, singletonList(payload)); return Result.success(results.asJSON()).setEndpoint(endPoint.toString()); } finally { if (channel != null) { channel.shutdown(); } } }
Example #24
Source File: RqdClientGrpc.java From OpenCue with Apache License 2.0 | 5 votes |
private RqdInterfaceGrpc.RqdInterfaceBlockingStub getStub(String host) throws ExecutionException { if (channelCache == null) { buildChannelCache(); } ManagedChannel channel = channelCache.get(host); return RqdInterfaceGrpc.newBlockingStub(channel); }
Example #25
Source File: GrpcChannelScope.java From micronaut-grpc with Apache License 2.0 | 5 votes |
@Override public <T> T get( BeanResolutionContext resolutionContext, BeanDefinition<T> beanDefinition, BeanIdentifier identifier, Provider<T> provider) { BeanResolutionContext.Segment segment = resolutionContext.getPath().currentSegment().orElseThrow(() -> new IllegalStateException("@GrpcChannel used in invalid location") ); Argument argument = segment.getArgument(); String value = argument.getAnnotationMetadata().getValue(GrpcChannel.class, String.class).orElse(null); if (StringUtils.isEmpty(value)) { throw new DependencyInjectionException(resolutionContext, argument, "No value specified to @GrpcChannel annotation"); } if (!Channel.class.isAssignableFrom(argument.getType())) { throw new DependencyInjectionException(resolutionContext, argument, "@GrpcChannel used on type that is not a Channel"); } if ("grpc-server".equalsIgnoreCase(value)) { return (T) applicationContext.getBean(ManagedChannel.class, Qualifiers.byName("grpc-server")); } if (!(provider instanceof ParametrizedProvider)) { throw new DependencyInjectionException(resolutionContext, argument, "GrpcChannelScope called with invalid bean provider"); } value = applicationContext.resolveRequiredPlaceholders(value); String finalValue = value; return (T) channels.computeIfAbsent(new ChannelKey(identifier, value), channelKey -> (ManagedChannel) ((ParametrizedProvider<T>) provider).get(finalValue) ); }
Example #26
Source File: Http2NettyLocalChannelTest.java From grpc-java with Apache License 2.0 | 5 votes |
@Override protected ManagedChannel createChannel() { NettyChannelBuilder builder = NettyChannelBuilder .forAddress(new LocalAddress("in-process-1")) .negotiationType(NegotiationType.PLAINTEXT) .channelType(LocalChannel.class) .eventLoopGroup(eventLoopGroup) .flowControlWindow(65 * 1024) .maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE); // Disable the default census stats interceptor, use testing interceptor instead. io.grpc.internal.TestingAccessor.setStatsEnabled(builder, false); return builder.intercept(createCensusStatsClientInterceptor()).build(); }
Example #27
Source File: JaegerIntegrationTest.java From opentelemetry-java with Apache License 2.0 | 5 votes |
private static void setupJaegerExporter() { ManagedChannel jaegerChannel = ManagedChannelBuilder.forAddress("127.0.0.1", jaegerContainer.getMappedPort(COLLECTOR_PORT)) .usePlaintext() .build(); SpanExporter jaegerExporter = JaegerGrpcSpanExporter.newBuilder() .setServiceName(SERVICE_NAME) .setChannel(jaegerChannel) .setDeadlineMs(30000) .build(); OpenTelemetrySdk.getTracerProvider() .addSpanProcessor(SimpleSpanProcessor.newBuilder(jaegerExporter).build()); }
Example #28
Source File: GrpcServiceServerTest.java From armeria with Apache License 2.0 | 5 votes |
@Test void longMaxRequestLimit() throws Exception { final ManagedChannel channel = ManagedChannelBuilder.forAddress("127.0.0.1", serverWithLongMaxRequestLimit.httpPort()) .usePlaintext() .build(); try { final UnitTestServiceBlockingStub stub = UnitTestServiceGrpc.newBlockingStub(channel); assertThat(stub.staticUnaryCall(REQUEST_MESSAGE)).isEqualTo(RESPONSE_MESSAGE); } finally { channel.shutdownNow(); requestLogQueue.take(); } }
Example #29
Source File: TripleClientTransport.java From sofa-rpc with Apache License 2.0 | 5 votes |
/** * Create new connection * * @param url */ private ManagedChannel initChannel(ProviderInfo url) { ClientInterceptor clientHeaderClientInterceptor = buildClientHeaderClientInterceptor(); NettyChannelBuilder builder = NettyChannelBuilder.forAddress(url.getHost(), url.getPort()); builder.usePlaintext(); builder.disableRetry(); builder.intercept(clientHeaderClientInterceptor); return builder.build(); }
Example #30
Source File: Http2OkHttpTest.java From grpc-nebula-java with Apache License 2.0 | 5 votes |
@Test public void hostnameVerifierWithCorrectHostname() throws Exception { ManagedChannel channel = createChannelBuilder() .overrideAuthority(GrpcUtil.authorityFromHostAndPort( TestUtils.TEST_SERVER_HOST, getPort())) .hostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return false; } }) .build(); TestServiceGrpc.TestServiceBlockingStub blockingStub = TestServiceGrpc.newBlockingStub(channel); Throwable actualThrown = null; try { blockingStub.emptyCall(Empty.getDefaultInstance()); } catch (Throwable t) { actualThrown = t; } assertNotNull("The rpc should have been failed due to hostname verification", actualThrown); Throwable cause = Throwables.getRootCause(actualThrown); assertTrue( "Failed by unexpected exception: " + cause, cause instanceof SSLPeerUnverifiedException); channel.shutdown(); }