io.grpc.examples.helloworld.GreeterGrpc Java Examples

The following examples show how to use io.grpc.examples.helloworld.GreeterGrpc. 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 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.");
}
 
Example #2
Source File: ErrorHandlingClient.java    From grpc-nebula-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 #3
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 #4
Source File: HelloworldActivity.java    From grpc-nebula-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 #5
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 #6
Source File: HeaderServerInterceptorTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void serverHeaderDeliveredToClient() {
  class SpyingClientInterceptor implements ClientInterceptor {
    ClientCall.Listener<?> spyListener;

    @Override
    public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
        MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
      return new SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {
        @Override
        public void start(Listener<RespT> responseListener, Metadata headers) {
          spyListener = responseListener =
              mock(ClientCall.Listener.class, delegatesTo(responseListener));
          super.start(responseListener, headers);
        }
      };
    }
  }

  SpyingClientInterceptor clientInterceptor = new SpyingClientInterceptor();
  GreeterBlockingStub blockingStub = GreeterGrpc.newBlockingStub(channel)
      .withInterceptors(clientInterceptor);
  ArgumentCaptor<Metadata> metadataCaptor = ArgumentCaptor.forClass(Metadata.class);

  blockingStub.sayHello(HelloRequest.getDefaultInstance());

  assertNotNull(clientInterceptor.spyListener);
  verify(clientInterceptor.spyListener).onHeaders(metadataCaptor.capture());
  assertEquals(
      "customRespondValue",
      metadataCaptor.getValue().get(HeaderServerInterceptor.CUSTOM_HEADER_KEY));
}
 
Example #7
Source File: SafeMethodCachingInterceptorTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #8
Source File: ScalingTestBase.java    From quarkus with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #9
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 #10
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 #11
Source File: ErrorHandlingClient.java    From grpc-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: 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 #13
Source File: BaseITTracingClientInterceptor.java    From brave with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #14
Source File: RetryingHelloWorldClient.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #15
Source File: BaseITTracingServerInterceptor.java    From brave with Apache License 2.0 6 votes vote down vote up
@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
}
 
Example #16
Source File: BaseITTracingServerInterceptor.java    From brave with Apache License 2.0 6 votes vote down vote up
@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.");
}
 
Example #17
Source File: BaseITTracingServerInterceptor.java    From brave with Apache License 2.0 6 votes vote down vote up
@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.");
}
 
Example #18
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 #19
Source File: BaseITTracingClientInterceptor.java    From brave with Apache License 2.0 6 votes vote down vote up
@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.");
}
 
Example #20
Source File: BaseITTracingServerInterceptor.java    From brave with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #21
Source File: SafeMethodCachingInterceptorTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #22
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 #23
Source File: HedgingHelloWorldClient.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
/** 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;
}
 
Example #24
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 #25
Source File: SafeMethodCachingInterceptorTest.java    From grpc-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 #26
Source File: BaseITTracingServerInterceptor.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void reusesPropagatedSpanId() {
  TraceContext parent = newTraceContext(SamplingFlags.SAMPLED);
  Channel channel = clientWithB3SingleHeader(parent);
  GreeterGrpc.newBlockingStub(channel).sayHello(HELLO_REQUEST);

  assertSameIds(testSpanHandler.takeRemoteSpan(Span.Kind.SERVER), parent);
}
 
Example #27
Source File: SafeMethodCachingInterceptorTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void afterDefaultMaxAge_cacheEntryInvalidated() throws Exception {
  SafeMethodCachingInterceptor interceptorWithCustomMaxAge =
      SafeMethodCachingInterceptor.newSafeMethodCachingInterceptor(cache, 1);
  channelToUse = ClientInterceptors.intercept(baseChannel, interceptorWithCustomMaxAge);

  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));
}
 
Example #28
Source File: SafeMethodCachingInterceptorTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void invalidResponseMaxAge_usesDefault() throws Exception {
  SafeMethodCachingInterceptor interceptorWithCustomMaxAge =
      SafeMethodCachingInterceptor.newSafeMethodCachingInterceptor(cache, 1);
  channelToUse = ClientInterceptors.intercept(baseChannel, interceptorWithCustomMaxAge);
  cacheControlDirectives.add("max-age=-10");

  HelloReply reply1 =
      ClientCalls.blockingUnaryCall(
          channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
  HelloReply reply2 =
      ClientCalls.blockingUnaryCall(
          channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
  assertEquals(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));
}
 
Example #29
Source File: ErrorHandlingClient.java    From grpc-nebula-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!");
  }
}
 
Example #30
Source File: DetailErrorSample.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
void blockingCall() {
  GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channel);
  try {
    stub.sayHello(HelloRequest.newBuilder().build());
  } catch (Exception e) {
    verifyErrorReply(e);
  }
}