类io.grpc.examples.helloworld.GreeterGrpc源码实例Demo

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

源代码1 项目: grpc-nebula-java   文件: HelloWorldAltsClient.java
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();
  }
}
 
源代码2 项目: grpc-nebula-java   文件: ErrorHandlingClient.java
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();
}
 
源代码3 项目: grpc-nebula-java   文件: ErrorHandlingClient.java
/**
 * 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!");
  }
}
 
源代码4 项目: grpc-nebula-java   文件: HelloworldActivity.java
@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);
  }
}
 
@Test
public void afterResponseMaxAge_cacheEntryInvalidated() 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);
  assertSame(reply1, reply2);

  // Wait for cache entry to expire
  sleepAtLeast(1001);

  assertNotEquals(
      reply1,
      ClientCalls.blockingUnaryCall(
          channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message));
  Truth.assertThat(cache.removedKeys).hasSize(1);
  assertEquals(
      new SafeMethodCachingInterceptor.Key(
          GreeterGrpc.getSayHelloMethod().getFullMethodName(), message),
      cache.removedKeys.get(0));
}
 
源代码6 项目: quarkus   文件: ScalingTestBase.java
Set<String> getThreadsUsedFor100Requests() throws InterruptedException, ExecutionException, TimeoutException {
    int requestNo = 100;
    List<Callable<String>> calls = new ArrayList<>();
    for (int i = 0; i < requestNo; i++) {
        calls.add(() -> {
            ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 9000)
                    .usePlaintext()
                    .build();
            HelloReply reply = GreeterGrpc.newBlockingStub(channel)
                    .sayHello(HelloRequest.newBuilder().setName("foo").build());
            channel.shutdownNow();
            return reply.getMessage();
        });
    }
    List<Future<String>> results = Executors.newFixedThreadPool(requestNo)
            .invokeAll(calls);

    Set<String> threads = new HashSet<>();
    for (Future<String> result : results) {
        threads.add(result.get(10, TimeUnit.SECONDS));
    }
    return threads;
}
 
源代码7 项目: grpc-java   文件: HelloWorldAltsClient.java
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();
  }
}
 
源代码8 项目: brave   文件: BaseITTracingClientInterceptor.java
@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);
}
 
源代码9 项目: grpc-java   文件: RetryingHelloWorldClient.java
/**
 * Construct client connecting to HelloWorld server at {@code host:port}.
 */
public RetryingHelloWorldClient(String host, int port, boolean enableRetries) {

  ManagedChannelBuilder<?> channelBuilder = ManagedChannelBuilder.forAddress(host, port)
      // Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid
      // needing certificates.
      .usePlaintext();
  if (enableRetries) {
    Map<String, ?> serviceConfig = getRetryingServiceConfig();
    logger.info("Client started with retrying configuration: " + serviceConfig);
    channelBuilder.defaultServiceConfig(serviceConfig).enableRetry();
  }
  channel = channelBuilder.build();
  blockingStub = GreeterGrpc.newBlockingStub(channel);
  this.enableRetries = enableRetries;
}
 
源代码10 项目: grpc-java   文件: ErrorHandlingClient.java
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();
}
 
源代码11 项目: grpc-java   文件: ErrorHandlingClient.java
/**
 * 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!");
  }
}
 
源代码12 项目: grpc-java   文件: DetailErrorSample.java
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();
}
 
源代码13 项目: brave   文件: BaseITTracingClientInterceptor.java
/**
 * This ensures that response callbacks run in the invocation context, not the client one. This
 * allows async chaining to appear caused by the parent, not by the most recent client. Otherwise,
 * we would see a client span child of a client span, which could be confused with duplicate
 * instrumentation and affect dependency link counts.
 */
@Test public void callbackContextIsFromInvocationTime() {
  AssertableCallback<HelloReply> callback = new AssertableCallback<>();

  // Capture the current trace context when onSuccess or onError occur
  AtomicReference<TraceContext> invocationContext = new AtomicReference<>();
  callback.setListener(() -> invocationContext.set(currentTraceContext.get()));

  TraceContext parent = newTraceContext(SamplingFlags.SAMPLED);
  try (Scope scope = currentTraceContext.newScope(parent)) {
    GreeterGrpc.newStub(client).sayHello(HELLO_REQUEST, new StreamObserverAdapter(callback));
  }

  callback.join(); // ensures listener ran
  assertThat(invocationContext.get()).isSameAs(parent);
  assertChildOf(testSpanHandler.takeRemoteSpan(CLIENT), parent);
}
 
源代码14 项目: grpc-java   文件: HedgingHelloWorldClient.java
/** Construct client connecting to HelloWorld server at {@code host:port}. */
public HedgingHelloWorldClient(String host, int port, boolean hedging) {
  Map<String, ?> hedgingServiceConfig =
    new Gson()
        .fromJson(
            new JsonReader(
                new InputStreamReader(
                    HedgingHelloWorldClient.class.getResourceAsStream(
                        "hedging_service_config.json"),
                    UTF_8)),
            Map.class);

  ManagedChannelBuilder<?> channelBuilder = ManagedChannelBuilder.forAddress(host, port)
      // Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid
      // needing certificates.
      .usePlaintext();
  if (hedging) {
    channelBuilder.defaultServiceConfig(hedgingServiceConfig).enableRetry();
  }
  channel = channelBuilder.build();
  blockingStub = GreeterGrpc.newBlockingStub(channel);
  this.hedging = hedging;
}
 
源代码15 项目: grpc-java   文件: HelloworldActivity.java
@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);
  }
}
 
@Test
public void afterResponseMaxAge_cacheEntryInvalidated() 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);
  assertSame(reply1, reply2);

  // Wait for cache entry to expire
  sleepAtLeast(1001);

  assertNotEquals(
      reply1,
      ClientCalls.blockingUnaryCall(
          channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message));
  Truth.assertThat(cache.removedKeys).hasSize(1);
  assertEquals(
      new SafeMethodCachingInterceptor.Key(
          GreeterGrpc.getSayHelloMethod().getFullMethodName(), message),
      cache.removedKeys.get(0));
}
 
源代码17 项目: brave   文件: BaseITTracingServerInterceptor.java
/**
 * NOTE: for this to work, the tracing interceptor must be last (so that it executes first)
 *
 * <p>Also notice that we are only making the current context available in the request side.
 */
@Test public void currentSpanVisibleToUserInterceptors() throws IOException {
  AtomicReference<TraceContext> fromUserInterceptor = new AtomicReference<>();
  init(new ServerInterceptor() {
    @Override
    public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call,
        Metadata headers, ServerCallHandler<ReqT, RespT> next) {
      fromUserInterceptor.set(tracing.currentTraceContext().get());
      return next.startCall(call, headers);
    }
  });

  GreeterGrpc.newBlockingStub(client).sayHello(HELLO_REQUEST);

  assertThat(fromUserInterceptor.get())
      .isNotNull();

  testSpanHandler.takeRemoteSpan(Span.Kind.SERVER);
}
 
源代码18 项目: brave   文件: BaseITTracingClientInterceptor.java
@Test public void userInterceptor_throwsOnHalfClose() {
  closeClient(client);
  client = newClient(new ClientInterceptor() {
    @Override public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
        MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions,
        Channel channel) {
      ClientCall<ReqT, RespT> call = channel.newCall(methodDescriptor, callOptions);
      return new SimpleForwardingClientCall<ReqT, RespT>(call) {
        @Override public void halfClose() {
          throw new IllegalStateException("I'm a bad interceptor.");
        }
      };
    }
  }, grpcTracing.newClientInterceptor());

  assertThatThrownBy(() -> GreeterGrpc.newBlockingStub(client).sayHello(HELLO_REQUEST))
      .isInstanceOf(IllegalStateException.class);
  testSpanHandler.takeRemoteSpanWithErrorMessage(CLIENT, "I'm a bad interceptor.");
}
 
源代码19 项目: brave   文件: BaseITTracingServerInterceptor.java
@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);
}
 
源代码20 项目: brave   文件: BaseITTracingServerInterceptor.java
@Test public void userInterceptor_throwsOnSendMessage() throws IOException {
  init(new ServerInterceptor() {
    @Override public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
        ServerCall<ReqT, RespT> call, Metadata metadata, ServerCallHandler<ReqT, RespT> next) {
      return next.startCall(new SimpleForwardingServerCall<ReqT, RespT>(call) {
        @Override public void sendMessage(RespT message) {
          throw new IllegalStateException("I'm a bad interceptor.");
        }
      }, metadata);
    }
  });

  assertThatThrownBy(() -> GreeterGrpc.newBlockingStub(client).sayHello(HELLO_REQUEST))
      .isInstanceOf(StatusRuntimeException.class);
  testSpanHandler.takeRemoteSpanWithErrorMessage(Span.Kind.SERVER, "I'm a bad interceptor.");
}
 
源代码21 项目: brave   文件: BaseITTracingServerInterceptor.java
@Test public void userInterceptor_throwsOnOnHalfClose() throws IOException {
  init(new ServerInterceptor() {
    @Override public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
        ServerCall<ReqT, RespT> call, Metadata metadata, ServerCallHandler<ReqT, RespT> next) {
      return new SimpleForwardingServerCallListener<ReqT>(next.startCall(call, metadata)) {
        @Override public void onHalfClose() {
          throw new IllegalStateException("I'm a bad interceptor.");
        }
      };
    }
  });

  assertThatThrownBy(() -> GreeterGrpc.newBlockingStub(client).sayHello(HELLO_REQUEST))
      .isInstanceOf(StatusRuntimeException.class);
  testSpanHandler.takeRemoteSpanWithErrorMessage(Span.Kind.SERVER, "I'm a bad interceptor.");
}
 
源代码22 项目: brave   文件: BaseITTracingServerInterceptor.java
@Test public void customSampler() throws IOException {
  RpcTracing rpcTracing = RpcTracing.newBuilder(tracing).serverSampler(RpcRuleSampler.newBuilder()
      .putRule(methodEquals("SayHelloWithManyReplies"), NEVER_SAMPLE)
      .putRule(serviceEquals("helloworld.greeter"), ALWAYS_SAMPLE)
      .build()).build();
  grpcTracing = GrpcTracing.create(rpcTracing);
  init();

  // unsampled
  // NOTE: An iterator request is lazy: invoking the iterator invokes the request
  GreeterGrpc.newBlockingStub(client).sayHelloWithManyReplies(HELLO_REQUEST).hasNext();

  // sampled
  GreeterGrpc.newBlockingStub(client).sayHello(HELLO_REQUEST);

  assertThat(testSpanHandler.takeRemoteSpan(Span.Kind.SERVER).name())
      .isEqualTo("helloworld.Greeter/SayHello");

  // @After will also check that sayHelloWithManyReplies was not sampled
}
 
源代码23 项目: brave   文件: BaseITTracingClientInterceptor.java
@Test public void userInterceptor_throwsOnStart() {
  closeClient(client);
  client = newClient(new ClientInterceptor() {
    @Override public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
        MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions,
        Channel channel) {
      ClientCall<ReqT, RespT> call = channel.newCall(methodDescriptor, callOptions);
      return new SimpleForwardingClientCall<ReqT, RespT>(call) {
        @Override public void start(Listener<RespT> responseListener, Metadata headers) {
          throw new IllegalStateException("I'm a bad interceptor.");
        }
      };
    }
  }, grpcTracing.newClientInterceptor());

  assertThatThrownBy(() -> GreeterGrpc.newBlockingStub(client).sayHello(HELLO_REQUEST))
      .isInstanceOf(IllegalStateException.class);
  testSpanHandler.takeRemoteSpanWithErrorMessage(CLIENT, "I'm a bad interceptor.");
}
 
/** Construct client connecting to HelloWorld server at {@code host:port}. */
public CompressingHelloWorldClient(String host, int port) {
  channel = ManagedChannelBuilder.forAddress(host, port)
      .usePlaintext()
      .build();
  blockingStub = GreeterGrpc.newBlockingStub(channel);
}
 
源代码25 项目: grpc-nebula-java   文件: CustomHeaderClient.java
/**
 * A custom client.
 */
private CustomHeaderClient(String host, int port) {
  originChannel = ManagedChannelBuilder.forAddress(host, port)
      .usePlaintext()
      .build();
  ClientInterceptor interceptor = new HeaderClientInterceptor();
  Channel channel = ClientInterceptors.intercept(originChannel, interceptor);
  blockingStub = GreeterGrpc.newBlockingStub(channel);
}
 
源代码26 项目: grpc-nebula-java   文件: HelloJsonServer.java
@Override
public ServerServiceDefinition bindService() {
  return io.grpc.ServerServiceDefinition
      .builder(GreeterGrpc.getServiceDescriptor().getName())
      .addMethod(HelloJsonClient.HelloJsonStub.METHOD_SAY_HELLO,
          asyncUnaryCall(
              new UnaryMethod<HelloRequest, HelloReply>() {
                @Override
                public void invoke(
                    HelloRequest request, StreamObserver<HelloReply> responseObserver) {
                  sayHello(request, responseObserver);
                }
              }))
      .build();
}
 
源代码27 项目: grpc-nebula-java   文件: ErrorHandlingClient.java
void blockingCall() {
  GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channel);
  try {
    stub.sayHello(HelloRequest.newBuilder().setName("Bart").build());
  } catch (Exception e) {
    Status status = Status.fromThrowable(e);
    Verify.verify(status.getCode() == Status.Code.INTERNAL);
    Verify.verify(status.getDescription().contains("Eggplant"));
    // Cause is not transmitted over the wire.
  }
}
 
源代码28 项目: grpc-nebula-java   文件: ErrorHandlingClient.java
void futureCallCallback() {
  GreeterFutureStub stub = GreeterGrpc.newFutureStub(channel);
  ListenableFuture<HelloReply> response =
      stub.sayHello(HelloRequest.newBuilder().setName("Maggie").build());

  final CountDownLatch latch = new CountDownLatch(1);

  Futures.addCallback(
      response,
      new FutureCallback<HelloReply>() {
        @Override
        public void onSuccess(@Nullable HelloReply result) {
          // Won't be called, since the server in this example always fails.
        }

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

  if (!Uninterruptibles.awaitUninterruptibly(latch, 1, TimeUnit.SECONDS)) {
    throw new RuntimeException("timeout!");
  }
}
 
源代码29 项目: grpc-nebula-java   文件: ErrorHandlingClient.java
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!");
  }
}
 
源代码30 项目: grpc-nebula-java   文件: DetailErrorSample.java
void blockingCall() {
  GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channel);
  try {
    stub.sayHello(HelloRequest.newBuilder().build());
  } catch (Exception e) {
    verifyErrorReply(e);
  }
}
 
 类所在包
 同包方法