io.grpc.examples.helloworld.HelloReply Java Examples

The following examples show how to use io.grpc.examples.helloworld.HelloReply. 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: BaseITTracingClientInterceptor.java    From brave with Apache License 2.0 6 votes vote down vote up
@Test public void deprecated_clientParserTestStreamingResponse() {
  closeClient(client);
  grpcTracing = grpcTracing.toBuilder().clientParser(new GrpcClientParser() {
    int receiveCount = 0;

    @Override protected <M> void onMessageReceived(M message, SpanCustomizer span) {
      span.tag("grpc.message_received." + receiveCount++, message.toString());
    }
  }).build();
  client = newClient();

  Iterator<HelloReply> replies = GreeterGrpc.newBlockingStub(client)
      .sayHelloWithManyReplies(HelloRequest.newBuilder().setName("this is dog").build());
  assertThat(replies).toIterable().hasSize(10);

  // all response messages are tagged to the same span
  assertThat(testSpanHandler.takeRemoteSpan(CLIENT).tags()).hasSize(10);
}
 
Example #2
Source File: RetryingHelloWorldClient.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
/**
 * Say hello to server in a blocking unary call.
 */
public void greet(String name) {
  HelloRequest request = HelloRequest.newBuilder().setName(name).build();
  HelloReply response = null;
  StatusRuntimeException statusRuntimeException = null;
  try {
    response = blockingStub.sayHello(request);
  } catch (StatusRuntimeException e) {
    failedRpcs.incrementAndGet();
    statusRuntimeException = e;
  }

  totalRpcs.incrementAndGet();

  if (statusRuntimeException == null) {
    logger.log(Level.INFO,"Greeting: {0}", new Object[]{response.getMessage()});
  } else {
    logger.log(Level.INFO,"RPC failed: {0}", new Object[]{statusRuntimeException.getStatus()});
  }
}
 
Example #3
Source File: HeaderServerInterceptorTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  GreeterImplBase greeterImplBase =
      new GreeterImplBase() {
        @Override
        public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) {
          responseObserver.onNext(HelloReply.getDefaultInstance());
          responseObserver.onCompleted();
        }
      };
  // 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(ServerInterceptors.intercept(greeterImplBase, new HeaderServerInterceptor()))
      .build().start());
  // Create a client channel and register for automatic graceful shutdown.
  channel =
      grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build());
}
 
Example #4
Source File: SafeMethodCachingInterceptorTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void requestWithNoCacheOptionSkipsCache() {
  HelloReply reply1 =
      ClientCalls.blockingUnaryCall(
          channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
  HelloReply reply2 =
      ClientCalls.blockingUnaryCall(
          channelToUse,
          safeGreeterSayHelloMethod,
          CallOptions.DEFAULT.withOption(SafeMethodCachingInterceptor.NO_CACHE_CALL_OPTION, true),
          message);
  HelloReply reply3 =
      ClientCalls.blockingUnaryCall(
          channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);

  assertNotEquals(reply1, reply2);
  assertSame(reply1, reply3);
}
 
Example #5
Source File: BaseITTracingServerInterceptor.java    From brave with Apache License 2.0 6 votes vote down vote up
@Test public void serverParserTestWithStreamingResponse() throws IOException {
  grpcTracing = grpcTracing.toBuilder().serverParser(new GrpcServerParser() {
    int responsesSent = 0;

    @Override protected <M> void onMessageSent(M message, SpanCustomizer span) {
      span.tag("grpc.message_sent." + responsesSent++, message.toString());
    }
  }).build();
  init();

  Iterator<HelloReply> replies = GreeterGrpc.newBlockingStub(client)
      .sayHelloWithManyReplies(HELLO_REQUEST);
  assertThat(replies).toIterable().hasSize(10);
  // all response messages are tagged to the same span
  assertThat(testSpanHandler.takeRemoteSpan(Span.Kind.SERVER).tags()).hasSize(10);
}
 
Example #6
Source File: HelloworldActivity.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Override
protected String doInBackground(String... params) {
  String host = params[0];
  String message = params[1];
  String portStr = params[2];
  int port = TextUtils.isEmpty(portStr) ? 0 : Integer.valueOf(portStr);
  try {
    channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext().build();
    GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channel);
    HelloRequest request = HelloRequest.newBuilder().setName(message).build();
    HelloReply reply = stub.sayHello(request);
    return reply.getMessage();
  } catch (Exception e) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    e.printStackTrace(pw);
    pw.flush();
    return String.format("Failed... : %n%s", sw);
  }
}
 
Example #7
Source File: HelloWorldAltsClient.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
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 #8
Source File: DetailErrorSample.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
void run() throws Exception {
  Server server = ServerBuilder.forPort(0).addService(new GreeterGrpc.GreeterImplBase() {
    @Override
    public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) {
      Metadata trailers = new Metadata();
      trailers.put(DEBUG_INFO_TRAILER_KEY, DEBUG_INFO);
      responseObserver.onError(Status.INTERNAL.withDescription(DEBUG_DESC)
          .asRuntimeException(trailers));
    }
  }).build().start();
  channel =
      ManagedChannelBuilder.forAddress("localhost", server.getPort()).usePlaintext().build();

  blockingCall();
  futureCallDirect();
  futureCallCallback();
  asyncCall();
  advancedAsyncCall();

  channel.shutdown();
  server.shutdown();
  channel.awaitTermination(1, TimeUnit.SECONDS);
  server.awaitTermination();
}
 
Example #9
Source File: HeaderServerInterceptorTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  GreeterImplBase greeterImplBase =
      new GreeterImplBase() {
        @Override
        public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) {
          responseObserver.onNext(HelloReply.getDefaultInstance());
          responseObserver.onCompleted();
        }
      };
  // 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(ServerInterceptors.intercept(greeterImplBase, new HeaderServerInterceptor()))
      .build().start());
  // Create a client channel and register for automatic graceful shutdown.
  channel =
      grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build());
}
 
Example #10
Source File: SafeMethodCachingInterceptorTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void responseNoCacheDirective_notCached() throws Exception {
  cacheControlDirectives.add("no-cache");

  HelloReply reply1 =
      ClientCalls.blockingUnaryCall(
          channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
  HelloReply reply2 =
      ClientCalls.blockingUnaryCall(
          channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);

  assertNotEquals(reply1, reply2);
  assertNotEquals(reply1, reply2);
  Truth.assertThat(cache.internalCache).isEmpty();
  Truth.assertThat(cache.removedKeys).isEmpty();
}
 
Example #11
Source File: ErrorHandlingClient.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
void run() throws Exception {
  // Port 0 means that the operating system will pick an available port to use.
  Server server = ServerBuilder.forPort(0).addService(new GreeterGrpc.GreeterImplBase() {
    @Override
    public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) {
      responseObserver.onError(Status.INTERNAL
          .withDescription("Eggplant Xerxes Crybaby Overbite Narwhal").asRuntimeException());
    }
  }).build().start();
  channel =
      ManagedChannelBuilder.forAddress("localhost", server.getPort()).usePlaintext().build();

  blockingCall();
  futureCallDirect();
  futureCallCallback();
  asyncCall();
  advancedAsyncCall();

  channel.shutdown();
  server.shutdown();
  channel.awaitTermination(1, TimeUnit.SECONDS);
  server.awaitTermination();
}
 
Example #12
Source File: SafeMethodCachingInterceptorTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void cacheHit_doesNotResetExpiration() throws Exception {
  cacheControlDirectives.add("max-age=1");

  HelloReply reply1 =
      ClientCalls.blockingUnaryCall(
          channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
  HelloReply reply2 =
      ClientCalls.blockingUnaryCall(
          channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);

  sleepAtLeast(1001);

  HelloReply reply3 =
      ClientCalls.blockingUnaryCall(
          channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);

  assertSame(reply1, reply2);
  assertNotEquals(reply1, reply3);
  Truth.assertThat(cache.internalCache).hasSize(1);
  Truth.assertThat(cache.removedKeys).hasSize(1);
}
 
Example #13
Source File: ErrorHandlingClient.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
/**
 * This is more advanced and does not make use of the stub.  You should not normally need to do
 * this, but here is how you would.
 */
void advancedAsyncCall() {
  ClientCall<HelloRequest, HelloReply> call =
      channel.newCall(GreeterGrpc.getSayHelloMethod(), CallOptions.DEFAULT);

  final CountDownLatch latch = new CountDownLatch(1);

  call.start(new ClientCall.Listener<HelloReply>() {

    @Override
    public void onClose(Status status, Metadata trailers) {
      Verify.verify(status.getCode() == Status.Code.INTERNAL);
      Verify.verify(status.getDescription().contains("Narwhal"));
      // Cause is not transmitted over the wire.
      latch.countDown();
    }
  }, new Metadata());

  call.sendMessage(HelloRequest.newBuilder().setName("Marge").build());
  call.halfClose();

  if (!Uninterruptibles.awaitUninterruptibly(latch, 1, TimeUnit.SECONDS)) {
    throw new RuntimeException("timeout!");
  }
}
 
Example #14
Source File: StrictModeHelloworldActivity.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Override
protected String doInBackground(String... params) {
  String host = params[0];
  String message = params[1];
  String portStr = params[2];
  int port = TextUtils.isEmpty(portStr) ? 0 : Integer.valueOf(portStr);
  try {
    channel =
        OkHttpChannelBuilder.forAddress(host, port)
            .transportExecutor(new NetworkTaggingExecutor(0xFDD))
            .usePlaintext()
            .build();
    GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channel);
    HelloRequest request = HelloRequest.newBuilder().setName(message).build();
    HelloReply reply = stub.sayHello(request);
    return reply.getMessage();
  } catch (Exception e) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    e.printStackTrace(pw);
    pw.flush();
    return String.format("Failed... : %n%s", sw);
  }
}
 
Example #15
Source File: HelloWorldAltsClient.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
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 #16
Source File: SafeMethodCachingInterceptorTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void cacheHit_doesNotResetExpiration() throws Exception {
  cacheControlDirectives.add("max-age=1");

  HelloReply reply1 =
      ClientCalls.blockingUnaryCall(
          channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
  HelloReply reply2 =
      ClientCalls.blockingUnaryCall(
          channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);

  sleepAtLeast(1001);

  HelloReply reply3 =
      ClientCalls.blockingUnaryCall(
          channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);

  assertSame(reply1, reply2);
  assertNotEquals(reply1, reply3);
  Truth.assertThat(cache.internalCache).hasSize(1);
  Truth.assertThat(cache.removedKeys).hasSize(1);
}
 
Example #17
Source File: SafeMethodCachingInterceptorTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void responseNoCacheDirective_notCached() throws Exception {
  cacheControlDirectives.add("no-cache");

  HelloReply reply1 =
      ClientCalls.blockingUnaryCall(
          channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
  HelloReply reply2 =
      ClientCalls.blockingUnaryCall(
          channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);

  assertNotEquals(reply1, reply2);
  assertNotEquals(reply1, reply2);
  Truth.assertThat(cache.internalCache).isEmpty();
  Truth.assertThat(cache.removedKeys).isEmpty();
}
 
Example #18
Source File: SafeMethodCachingInterceptorTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
  HelloReply reply =
      HelloReply.newBuilder().setMessage("Hey " + req.getName() + " " + count++).build();
  responseObserver.onNext(reply);
  responseObserver.onCompleted();
}
 
Example #19
Source File: GrpcGreeterImpl.java    From dubbo-samples with Apache License 2.0 5 votes vote down vote up
@Override
public Single<HelloReply> sayHello(Single<HelloRequest> request) {
    System.out.println("Executing thread is " + Thread.currentThread().getName());
    return request
            .map(HelloRequest::getName)
            .map(name -> {
                String greeting = "Hello " + name;
                System.out.println("Returning " + greeting);
                return greeting;
            })
            .map(greeting -> HelloReply.newBuilder().setMessage(greeting).build());
}
 
Example #20
Source File: ServerInterceptorPriorityTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void testInterceptors() {
    HelloReply reply = GreeterGrpc.newBlockingStub(channel)
            .sayHello(HelloRequest.newBuilder().setName("neo").build());
    assertThat(reply.getMessage()).isEqualTo("Hello neo");

    assertThat(interceptor1.getLastCall()).isNotZero();
    assertThat(interceptor2.getLastCall()).isNotZero();

    assertThat(interceptor2.getLastCall()).isGreaterThan(interceptor1.getLastCall());
}
 
Example #21
Source File: SslBasicConsumer.java    From dubbo-samples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    SslConfig sslConfig = new SslConfig();
    if (args.length > 0) {
        if (args.length != 1 && args.length != 3) {
            System.out.println(
                    "USAGE: BasicConsumer [trustCertCollectionFilePath [certChainFilePath privateKeyFilePath]]\n " +
                            "Specify 'certChainFilePath' and 'privateKeyFilePath' only if you need Mutual TLS.");
            System.exit(0);
        }

        switch (args.length) {
            case 1:
                sslConfig.setClientTrustCertCollectionPath(args[0]);
                break;
            case 3:
                sslConfig.setClientTrustCertCollectionPath(args[0]);
                sslConfig.setClientKeyCertChainPath(args[1]);
                sslConfig.setClientPrivateKeyPath(args[2]);
        }
    }

    DubboBootstrap bootstrap = DubboBootstrap.getInstance()
            .application(new ApplicationConfig("first-dubbo-consumer"))
            .registry(new RegistryConfig("zookeeper://127.0.0.1:2181"))
            .ssl(sslConfig);

    ReferenceConfig<IGreeter> reference = new ReferenceConfig<>();
    reference.setInterface(IGreeter.class);

    bootstrap.reference(reference);

    bootstrap.start();

    IGreeter service = bootstrap.getCache().get(reference);
    HelloReply helloReply = service.sayHello(HelloRequest.newBuilder().setName("dubbo").build());
    System.out.println(helloReply.getMessage());
}
 
Example #22
Source File: AuthServer.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
  // get client id added to context by interceptor
  String clientId = Constant.CLIENT_ID_CONTEXT_KEY.get();
  logger.info("Processing request from " + clientId);
  HelloReply reply = HelloReply.newBuilder().setMessage("Hello, " + req.getName()).build();
  responseObserver.onNext(reply);
  responseObserver.onCompleted();
}
 
Example #23
Source File: GrpcGreeterImpl.java    From dubbo-samples with Apache License 2.0 5 votes vote down vote up
@Override
public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) {
    System.out.println("Executing thread is " + Thread.currentThread().getName());
    HelloReply reply = HelloReply.newBuilder().setMessage("Hello " + request.getName()).build();
    responseObserver.onNext(reply);
    responseObserver.onCompleted();
}
 
Example #24
Source File: SafeMethodCachingInterceptorTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void differentServiceCallsAreNotConflated() {
  MethodDescriptor<HelloRequest, HelloReply> anotherSafeMethod =
      AnotherGreeterGrpc.getSayHelloMethod().toBuilder().setSafe(true).build();

  HelloReply reply1 =
      ClientCalls.blockingUnaryCall(
          channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
  HelloReply reply2 =
      ClientCalls.blockingUnaryCall(
          channelToUse, anotherSafeMethod, CallOptions.DEFAULT, message);

  assertNotEquals(reply1, reply2);
}
 
Example #25
Source File: HeaderClientInterceptorTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void clientHeaderDeliveredToServer() 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(ServerInterceptors.intercept(new GreeterImplBase() {}, mockServerInterceptor))
      .build().start());
  // Create a client channel and register for automatic graceful shutdown.
  ManagedChannel channel = grpcCleanup.register(
      InProcessChannelBuilder.forName(serverName).directExecutor().build());
  GreeterBlockingStub blockingStub = GreeterGrpc.newBlockingStub(
      ClientInterceptors.intercept(channel, new HeaderClientInterceptor()));
  ArgumentCaptor<Metadata> metadataCaptor = ArgumentCaptor.forClass(Metadata.class);

  try {
    blockingStub.sayHello(HelloRequest.getDefaultInstance());
    fail();
  } catch (StatusRuntimeException expected) {
    // expected because the method is not implemented at server side
  }

  verify(mockServerInterceptor).interceptCall(
      ArgumentMatchers.<ServerCall<HelloRequest, HelloReply>>any(),
      metadataCaptor.capture(),
      ArgumentMatchers.<ServerCallHandler<HelloRequest, HelloReply>>any());
  assertEquals(
      "customRequestValue",
      metadataCaptor.getValue().get(HeaderClientInterceptor.CUSTOM_HEADER_KEY));
}
 
Example #26
Source File: ClientInterceptorRegistrationTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void testInterceptorRegistration() {
    HelloReply reply = client
            .sayHello(HelloRequest.newBuilder().setName("neo").build());
    assertThat(reply.getMessage()).isEqualTo("Hello neo");
    assertThat(interceptor.getLastCall()).isNotZero();
}
 
Example #27
Source File: SafeMethodCachingInterceptorTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void unsafeCallsAreNotCached() {
  GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channelToUse);

  HelloReply reply1 = stub.sayHello(message);
  HelloReply reply2 = stub.sayHello(message);

  assertNotEquals(reply1, reply2);
}
 
Example #28
Source File: SafeMethodCachingInterceptorTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
  HelloReply reply =
      HelloReply.newBuilder().setMessage("Hello " + req.getName() + " " + count++).build();
  responseObserver.onNext(reply);
  responseObserver.onCompleted();
}
 
Example #29
Source File: SafeMethodCachingInterceptorTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void responseMaxAgeZero_notAddedToCache() throws Exception {
  cacheControlDirectives.add("max-age=0");

  HelloReply reply1 =
      ClientCalls.blockingUnaryCall(
          channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
  HelloReply reply2 =
      ClientCalls.blockingUnaryCall(
          channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);

  assertNotEquals(reply1, reply2);
  Truth.assertThat(cache.internalCache).isEmpty();
  Truth.assertThat(cache.removedKeys).isEmpty();
}
 
Example #30
Source File: ErrorHandlingClient.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
void asyncCall() {
  GreeterStub stub = GreeterGrpc.newStub(channel);
  HelloRequest request = HelloRequest.newBuilder().setName("Homer").build();
  final CountDownLatch latch = new CountDownLatch(1);
  StreamObserver<HelloReply> responseObserver = new StreamObserver<HelloReply>() {

    @Override
    public void onNext(HelloReply value) {
      // Won't be called.
    }

    @Override
    public void onError(Throwable t) {
      Status status = Status.fromThrowable(t);
      Verify.verify(status.getCode() == Status.Code.INTERNAL);
      Verify.verify(status.getDescription().contains("Overbite"));
      // Cause is not transmitted over the wire..
      latch.countDown();
    }

    @Override
    public void onCompleted() {
      // Won't be called, since the server in this example always fails.
    }
  };
  stub.sayHello(request, responseObserver);

  if (!Uninterruptibles.awaitUninterruptibly(latch, 1, TimeUnit.SECONDS)) {
    throw new RuntimeException("timeout!");
  }
}