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(true).build(); blockingCall(); futureCallDirect(); futureCallCallback(); asyncCall(); advancedAsyncCall(); channel.shutdown(); server.shutdown(); channel.awaitTermination(1, TimeUnit.SECONDS); server.awaitTermination(); }
/** * 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!"); } }
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(true).build(); blockingCall(); futureCallDirect(); futureCallCallback(); asyncCall(); advancedAsyncCall(); channel.shutdown(); server.shutdown(); channel.awaitTermination(1, TimeUnit.SECONDS); server.awaitTermination(); }
@Test public void clientHeaderDeliveredToServer() { grpcServerRule.getServiceRegistry() .addService(ServerInterceptors.intercept(new GreeterImplBase() {}, mockServerInterceptor)); GreeterBlockingStub blockingStub = GreeterGrpc.newBlockingStub( ClientInterceptors.intercept(grpcServerRule.getChannel(), 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( Matchers.<ServerCall<HelloRequest, HelloReply>>any(), metadataCaptor.capture(), Matchers.<ServerCallHandler<HelloRequest, HelloReply>>any()); assertEquals( "customRequestValue", metadataCaptor.getValue().get(HeaderClientInterceptor.CUSTOM_HEADER_KEY)); }
@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(true).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); } }
/** Say hello to server. */ public void greet(final String name) { final ClientCall<HelloRequest, HelloReply> call = channel.newCall(GreeterGrpc.METHOD_SAY_HELLO, CallOptions.DEFAULT); final CountDownLatch latch = new CountDownLatch(1); call.start(new Listener<HelloReply>() { @Override public void onHeaders(Metadata headers) { super.onHeaders(headers); String encoding = headers.get(GrpcUtil.MESSAGE_ENCODING_KEY); if (encoding == null) { throw new RuntimeException("No compression selected!"); } } @Override public void onMessage(HelloReply message) { super.onMessage(message); logger.info("Greeting: " + message.getMessage()); latch.countDown(); } @Override public void onClose(Status status, Metadata trailers) { latch.countDown(); if (!status.isOk()) { throw status.asRuntimeException(); } } }, new Metadata()); call.setMessageCompression(true); call.sendMessage(HelloRequest.newBuilder().setName(name).build()); call.request(1); call.halfClose(); Uninterruptibles.awaitUninterruptibly(latch, 100, TimeUnit.SECONDS); }
/** * A simple client method that like {@link io.grpc.examples.helloworld.HelloWorldClient}. */ private 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()); }
/** 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()); }
/** 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()); }
@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(); }
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. } }
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!"); } }
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!"); } }
void blockingCall() { GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channel); try { stub.sayHello(HelloRequest.newBuilder().build()); } catch (Exception e) { verifyErrorReply(e); } }
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!"); } }
void asyncCall() { GreeterStub stub = GreeterGrpc.newStub(channel); HelloRequest request = HelloRequest.newBuilder().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) { verifyErrorReply(t); 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!"); } }
/** * 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(trailers.containsKey(DEBUG_INFO_TRAILER_KEY)); try { Verify.verify(trailers.get(DEBUG_INFO_TRAILER_KEY).equals(DEBUG_INFO)); } catch (IllegalArgumentException e) { throw new VerifyException(e); } latch.countDown(); } }, new Metadata()); call.sendMessage(HelloRequest.newBuilder().build()); call.halfClose(); if (!Uninterruptibles.awaitUninterruptibly(latch, 1, TimeUnit.SECONDS)) { throw new RuntimeException("timeout!"); } }
@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(); } }; grpcServerRule.getServiceRegistry() .addService(ServerInterceptors.intercept(greeterImplBase, new HeaderServerInterceptor())); }
@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(grpcServerRule.getChannel()) .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)); }
@Override public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) { HelloReply reply = HelloReply.newBuilder().setMessage("Hello " + req.getName() + " " + count++).build(); responseObserver.onNext(reply); responseObserver.onCompleted(); }
@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(); }
@Override public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) { HelloReply reply = HelloReply.newBuilder().setMessage("Hey " + req.getName() + " " + count++).build(); responseObserver.onNext(reply); responseObserver.onCompleted(); }
@Test public void differentMethodCallsAreNotConflated() { MethodDescriptor<HelloRequest, HelloReply> anotherSafeMethod = GreeterGrpc.getSayAnotherHelloMethod().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); }
@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); }
@Override public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) { HelloReply reply = HelloReply.newBuilder().setMessage("Hello =============> " + req.getName()).build(); responseObserver.onNext(reply); responseObserver.onCompleted(); }
public String sendMessage(String name) { GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(serverChannel); HelloReply response = stub.sayHello(HelloRequest.newBuilder().setName(name).build()); return response.getMessage(); }
@Query("sayHello") HelloReply sayHello(HelloRequest request, GreeterGrpc.GreeterBlockingStub client) { return client.sayHello(request); }
@Override public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) { HelloReply reply = HelloReply.newBuilder().setMessage("Hello " + req.getName()).build(); responseObserver.onNext(reply); responseObserver.onCompleted(); }
public HelloReply sayHello(HelloRequest request) { return blockingUnaryCall( getChannel(), METHOD_SAY_HELLO, getCallOptions(), request); }
private void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) { HelloReply reply = HelloReply.newBuilder().setMessage("Hello " + req.getName()).build(); responseObserver.onNext(reply); responseObserver.onCompleted(); }
@Override protected String doInBackground(Object... params) { String host = (String) params[0]; String message = (String) params[1]; String portStr = (String) params[2]; boolean useGet = (boolean) params[3]; boolean noCache = (boolean) params[4]; boolean onlyIfCached = (boolean) params[5]; int port = TextUtils.isEmpty(portStr) ? 0 : Integer.valueOf(portStr); try { channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext(true).build(); Channel channelToUse = ClientInterceptors.intercept( channel, SafeMethodCachingInterceptor.newSafeMethodCachingInterceptor(cache)); HelloRequest request = HelloRequest.newBuilder().setName(message).build(); HelloReply reply; if (useGet) { MethodDescriptor<HelloRequest, HelloReply> safeCacheableUnaryCallMethod = GreeterGrpc.getSayHelloMethod().toBuilder().setSafe(true).build(); CallOptions callOptions = CallOptions.DEFAULT; if (noCache) { callOptions = callOptions.withOption(SafeMethodCachingInterceptor.NO_CACHE_CALL_OPTION, true); } if (onlyIfCached) { callOptions = callOptions.withOption( SafeMethodCachingInterceptor.ONLY_IF_CACHED_CALL_OPTION, true); } reply = ClientCalls.blockingUnaryCall( channelToUse, safeCacheableUnaryCallMethod, callOptions, request); } else { GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channelToUse); reply = stub.sayHello(request); } return reply.getMessage(); } catch (Exception e) { Log.e(TAG, "RPC failed", e); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); pw.flush(); return String.format("Failed... : %n%s", sw); } }