io.grpc.examples.helloworld.HelloRequest Java Examples

The following examples show how to use io.grpc.examples.helloworld.HelloRequest. 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 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 #2
Source File: GreeterImpl.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
    HelloRequest.DateTime reqDateTime = req.getDateTime();
    int i = 0;
    try {
        i = Integer.parseInt(reqDateTime.getTime());
    } catch (Exception e) {
        //TODO: handle exception
    }
    LocalDateTime dt = LocalDateTime.now();
    String dtStr = dt.format(datetimeFormatter[i % datetimeFormatter.length]);
    HelloRequest.DateTime rplyDateTime = HelloRequest.DateTime.newBuilder(reqDateTime)
        .setDate(dtStr).build();
    HelloReply reply = HelloReply.newBuilder()
        .setMessage("Hello " + req.getName())
        .setDateTime(rplyDateTime)
        .build();
    responseObserver.onNext(reply);
    responseObserver.onCompleted();
}
 
Example #3
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 #4
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 #5
Source File: BasicConsumer.java    From dubbo-samples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    ClassPathXmlApplicationContext context =
            new ClassPathXmlApplicationContext("spring/dubbo-demo-consumer.xml");
    context.start();

    /**
     * greeter sample
     */
    System.out.println("-------- Start simple unary call test -------- ");
    ReactorDubboGreeterGrpc.IReactorGreeter greeter = (ReactorDubboGreeterGrpc.IReactorGreeter) context.getBean("greeter");

    greeter
        .sayHello(HelloRequest.newBuilder().setName("world!").build())
        .subscribe(reply -> System.out.println("Result: " + reply));

    System.out.println("-------- End simple unary call test -------- \n\n\n");

    System.in.read();
}
 
Example #6
Source File: DetailErrorSample.java    From grpc-nebula-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 #7
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 #8
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 #9
Source File: BasicConsumer.java    From dubbo-samples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    ClassPathXmlApplicationContext context =
            new ClassPathXmlApplicationContext("spring/dubbo-demo-consumer.xml");
    context.start();

    /**
     * greeter sample
     */
    System.out.println("-------- Start simple unary call test -------- ");
    RxDubboGreeterGrpc.IRxGreeter greeter = (RxDubboGreeterGrpc.IRxGreeter) context.getBean("greeter");

    greeter
        .sayHello(HelloRequest.newBuilder().setName("world!").build())
        .subscribe(reply -> System.out.println("Result: " + reply));

    System.out.println("-------- End simple unary call test -------- \n\n\n");

    System.in.read();
}
 
Example #10
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 #11
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 #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: 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 #14
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 #15
Source File: AuthClient.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
/**
 * Say hello to server.
 *
 * @param name name to set in HelloRequest
 * @return the message in the HelloReply from the server
 */
public String greet(String name) {
  logger.info("Will try to greet " + name + " ...");
  HelloRequest request = HelloRequest.newBuilder().setName(name).build();

  // Use a stub with the given call credentials applied to invoke the RPC.
  HelloReply response =
      blockingStub
          .withCallCredentials(callCredentials)
          .sayHello(request);

  logger.info("Greeting: " + response.getMessage());
  return response.getMessage();
}
 
Example #16
Source File: HelloWorldClientTls.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
/**
 * Say hello to server.
 */
public void greet(String name) {
    logger.info("Will try to greet " + name + " ...");
    HelloRequest request = HelloRequest.newBuilder().setName(name).build();
    HelloReply response;
    try {
        response = blockingStub.sayHello(request);
    } catch (StatusRuntimeException e) {
        logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
        return;
    }
    logger.info("Greeting: " + response.getMessage());
}
 
Example #17
Source File: SafeMethodCachingInterceptorTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public void sayAnotherHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
  HelloReply reply =
      HelloReply.newBuilder()
          .setMessage("Hello again " + req.getName() + " " + count++)
          .build();
  responseObserver.onNext(reply);
  responseObserver.onCompleted();
}
 
Example #18
Source File: BaseITTracingServerInterceptor.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void setsErrorOnRuntimeException() {
  assertThatThrownBy(() -> GreeterGrpc.newBlockingStub(client)
      .sayHello(HelloRequest.newBuilder().setName("testerror").build()))
      .isInstanceOf(StatusRuntimeException.class);

  MutableSpan span = testSpanHandler.takeRemoteSpanWithErrorMessage(Span.Kind.SERVER, "testerror");
  assertThat(span.tags().get("grpc.status_code")).isNull();
}
 
Example #19
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 #20
Source File: AuthClientTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void greet() {
  ArgumentCaptor<Metadata> metadataCaptor = ArgumentCaptor.forClass(Metadata.class);
  String retVal = client.greet("John");

  verify(mockServerInterceptor).interceptCall(
      ArgumentMatchers.<ServerCall<HelloRequest, HelloReply>>any(),
      metadataCaptor.capture(),
      ArgumentMatchers.<ServerCallHandler<HelloRequest, HelloReply>>any());

  String token = metadataCaptor.getValue().get(Constant.AUTHORIZATION_METADATA_KEY);
  assertNotNull(token);
  assertTrue(token.startsWith("Bearer"));
  assertEquals("AuthClientTest user=John", retVal);
}
 
Example #21
Source File: ServerInterceptorPriorityReversedTest.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 #22
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 #23
Source File: ClientInterceptorPriorityTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void testInterceptors() {
    HelloReply reply = client
            .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 #24
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 #25
Source File: DetailErrorSample.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
void futureCallCallback() {
  GreeterFutureStub stub = GreeterGrpc.newFutureStub(channel);
  ListenableFuture<HelloReply> response =
      stub.sayHello(HelloRequest.newBuilder().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) {
          verifyErrorReply(t);
          latch.countDown();
        }
      },
      directExecutor());

  if (!Uninterruptibles.awaitUninterruptibly(latch, 1, TimeUnit.SECONDS)) {
    throw new RuntimeException("timeout!");
  }
}
 
Example #26
Source File: ClientInterceptorPriorityReversedTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void testInterceptors() {
    HelloReply reply = client
            .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 #27
Source File: ServerInterceptorRegistrationTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void testInterceptorRegistration() {
    HelloReply reply = GreeterGrpc.newBlockingStub(channel)
            .sayHello(HelloRequest.newBuilder().setName("neo").build());
    assertThat(reply.getMessage()).isEqualTo("Hello neo");

    assertThat(interceptor.getLastCall()).isNotZero();
}
 
Example #28
Source File: CompressingHelloWorldClient.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
/** Say hello to server. */
public void greet(String name) {
  logger.info("Will try to greet " + name + " ...");
  HelloRequest request = HelloRequest.newBuilder().setName(name).build();
  HelloReply response;
  try {
    // This enables compression for requests. Independent of this setting, servers choose whether
    // to compress responses.
    response = blockingStub.withCompression("gzip").sayHello(request);
  } catch (StatusRuntimeException e) {
    logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
    return;
  }
  logger.info("Greeting: " + response.getMessage());
}
 
Example #29
Source File: HelloWorldClientTls.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
/**
 * Say hello to server.
 */
public void greet(String name) {
    logger.info("Will try to greet " + name + " ...");
    HelloRequest request = HelloRequest.newBuilder().setName(name).build();
    HelloReply response;
    try {
        response = blockingStub.sayHello(request);
    } catch (StatusRuntimeException e) {
        logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
        return;
    }
    logger.info("Greeting: " + response.getMessage());
}
 
Example #30
Source File: HostnameGreeter.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() + ", from " + serverName)
      .build();
  responseObserver.onNext(reply);
  responseObserver.onCompleted();
}