Java Code Examples for io.grpc.ClientCall#sendMessage()
The following examples show how to use
io.grpc.ClientCall#sendMessage() .
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: ErrorHandlingClient.java From grpc-nebula-java with Apache License 2.0 | 6 votes |
/** * 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 2
Source File: LoggingInterceptorTest.java From google-ads-java with Apache License 2.0 | 6 votes |
private static Listener simulateCall( RequestLogger requestLogger, Detail detail, Summary summary, MethodDescriptor methodDescriptor, Channel nextChannel, ClientCall nextCall) { LoggingInterceptor interceptor = new LoggingInterceptor(requestLogger, detail.getRawRequestHeaders(), summary.getEndpoint()); // Simulate a call (mocked channel doesn't actually make a call). ClientCall call = interceptor.interceptCall(methodDescriptor, null, nextChannel); Metadata upstreamHeaders = new Metadata(); call.start(new Listener() {}, upstreamHeaders); call.sendMessage(detail.getRequest()); // Capture the response listener and return this so we can test with different responses. ArgumentCaptor<Listener> listenerCaptor = ArgumentCaptor.forClass(Listener.class); verify(nextCall).start(listenerCaptor.capture(), eq(upstreamHeaders)); return listenerCaptor.getValue(); }
Example 3
Source File: ErrorHandlingClient.java From grpc-java with Apache License 2.0 | 6 votes |
/** * 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 4
Source File: DetailErrorSample.java From grpc-nebula-java with Apache License 2.0 | 5 votes |
/** * 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!"); } }
Example 5
Source File: LoadClient.java From grpc-nebula-java with Apache License 2.0 | 5 votes |
@Override public void run() { while (true) { maxOutstanding.acquireUninterruptibly(); if (shutdown) { maxOutstanding.release(); return; } final ClientCall<ByteBuf, ByteBuf> call = channel.newCall(LoadServer.GENERIC_STREAMING_PING_PONG_METHOD, CallOptions.DEFAULT); call.start(new ClientCall.Listener<ByteBuf>() { long now = System.nanoTime(); @Override public void onMessage(ByteBuf message) { delay(System.nanoTime() - now); if (shutdown) { call.cancel("Shutting down", null); return; } call.request(1); call.sendMessage(genericRequest.slice()); now = System.nanoTime(); } @Override public void onClose(Status status, Metadata trailers) { maxOutstanding.release(); Level level = shutdown ? Level.FINE : Level.INFO; if (!status.isOk() && status.getCode() != Status.Code.CANCELLED) { log.log(level, "Error in Generic Async Ping-Pong call", status.getCause()); } } }, new Metadata()); call.request(1); call.sendMessage(genericRequest.slice()); } }
Example 6
Source File: DetailErrorSample.java From grpc-java with Apache License 2.0 | 5 votes |
/** * 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!"); } }
Example 7
Source File: LoadClient.java From grpc-java with Apache License 2.0 | 5 votes |
@Override public void run() { while (true) { maxOutstanding.acquireUninterruptibly(); if (shutdown) { maxOutstanding.release(); return; } final ClientCall<ByteBuf, ByteBuf> call = channel.newCall(LoadServer.GENERIC_STREAMING_PING_PONG_METHOD, CallOptions.DEFAULT); call.start(new ClientCall.Listener<ByteBuf>() { long now = System.nanoTime(); @Override public void onMessage(ByteBuf message) { delay(System.nanoTime() - now); if (shutdown) { call.cancel("Shutting down", null); return; } call.request(1); call.sendMessage(genericRequest.slice()); now = System.nanoTime(); } @Override public void onClose(Status status, Metadata trailers) { maxOutstanding.release(); Level level = shutdown ? Level.FINE : Level.INFO; if (!status.isOk() && status.getCode() != Status.Code.CANCELLED) { log.log(level, "Error in Generic Async Ping-Pong call", status.getCause()); } } }, new Metadata()); call.request(1); call.sendMessage(genericRequest.slice()); } }
Example 8
Source File: AbstractInteropTest.java From grpc-nebula-java with Apache License 2.0 | 4 votes |
@Test public void serverStreamingShouldBeFlowControlled() throws Exception { final StreamingOutputCallRequest request = StreamingOutputCallRequest.newBuilder() .addResponseParameters(ResponseParameters.newBuilder().setSize(100000)) .addResponseParameters(ResponseParameters.newBuilder().setSize(100001)) .build(); final List<StreamingOutputCallResponse> goldenResponses = Arrays.asList( StreamingOutputCallResponse.newBuilder() .setPayload(Payload.newBuilder() .setBody(ByteString.copyFrom(new byte[100000]))).build(), StreamingOutputCallResponse.newBuilder() .setPayload(Payload.newBuilder() .setBody(ByteString.copyFrom(new byte[100001]))).build()); long start = System.nanoTime(); final ArrayBlockingQueue<Object> queue = new ArrayBlockingQueue<>(10); ClientCall<StreamingOutputCallRequest, StreamingOutputCallResponse> call = channel.newCall(TestServiceGrpc.getStreamingOutputCallMethod(), CallOptions.DEFAULT); call.start(new ClientCall.Listener<StreamingOutputCallResponse>() { @Override public void onHeaders(Metadata headers) {} @Override public void onMessage(final StreamingOutputCallResponse message) { queue.add(message); } @Override public void onClose(Status status, Metadata trailers) { queue.add(status); } }, new Metadata()); call.sendMessage(request); call.halfClose(); // Time how long it takes to get the first response. call.request(1); Object response = queue.poll(operationTimeoutMillis(), TimeUnit.MILLISECONDS); assertTrue(response instanceof StreamingOutputCallResponse); assertResponse(goldenResponses.get(0), (StreamingOutputCallResponse) response); long firstCallDuration = System.nanoTime() - start; // Without giving additional flow control, make sure that we don't get another response. We wait // until we are comfortable the next message isn't coming. We may have very low nanoTime // resolution (like on Windows) or be using a testing, in-process transport where message // handling is instantaneous. In both cases, firstCallDuration may be 0, so round up sleep time // to at least 1ms. assertNull(queue.poll(Math.max(firstCallDuration * 4, 1 * 1000 * 1000), TimeUnit.NANOSECONDS)); // Make sure that everything still completes. call.request(1); response = queue.poll(operationTimeoutMillis(), TimeUnit.MILLISECONDS); assertTrue(response instanceof StreamingOutputCallResponse); assertResponse(goldenResponses.get(1), (StreamingOutputCallResponse) response); assertEquals(Status.OK, queue.poll(operationTimeoutMillis(), TimeUnit.MILLISECONDS)); }
Example 9
Source File: ByteStreamServiceTest.java From bazel-buildfarm with Apache License 2.0 | 4 votes |
@Test public void writePutsIntoBlobStore() throws IOException, InterruptedException { ByteString helloWorld = ByteString.copyFromUtf8("Hello, World!"); Digest digest = DIGEST_UTIL.compute(helloWorld); String uuid = UUID.randomUUID().toString(); String resourceName = createBlobUploadResourceName(uuid, digest); Channel channel = InProcessChannelBuilder.forName(fakeServerName).directExecutor().build(); ClientCall<WriteRequest, WriteResponse> call = channel.newCall(ByteStreamGrpc.getWriteMethod(), CallOptions.DEFAULT); ClientCall.Listener<WriteResponse> callListener = new ClientCall.Listener<WriteResponse>() { boolean complete = false; boolean callHalfClosed = false; @Override public void onReady() { while (call.isReady()) { if (complete) { if (!callHalfClosed) { call.halfClose(); callHalfClosed = true; } return; } call.sendMessage( WriteRequest.newBuilder() .setResourceName(resourceName) .setData(helloWorld) .setFinishWrite(true) .build()); complete = true; } } }; call.start(callListener, new Metadata()); call.request(1); verify(simpleBlobStore, times(1)) .put(eq(digest.getHash()), eq(digest.getSizeBytes()), any(InputStream.class)); }
Example 10
Source File: ByteStreamServiceTest.java From bazel-buildfarm with Apache License 2.0 | 4 votes |
@Test public void writeCanBeResumed() throws IOException, InterruptedException { ByteString helloWorld = ByteString.copyFromUtf8("Hello, World!"); Digest digest = DIGEST_UTIL.compute(helloWorld); String uuid = UUID.randomUUID().toString(); String resourceName = createBlobUploadResourceName(uuid, digest); Channel channel = InProcessChannelBuilder.forName(fakeServerName).directExecutor().build(); ClientCall<WriteRequest, WriteResponse> initialCall = channel.newCall(ByteStreamGrpc.getWriteMethod(), CallOptions.DEFAULT); ByteString initialData = helloWorld.substring(0, 6); ClientCall.Listener<WriteResponse> initialCallListener = new ClientCall.Listener<WriteResponse>() { boolean complete = false; boolean callHalfClosed = false; @Override public void onReady() { while (initialCall.isReady()) { if (complete) { if (!callHalfClosed) { initialCall.halfClose(); callHalfClosed = true; } return; } initialCall.sendMessage( WriteRequest.newBuilder() .setResourceName(resourceName) .setData(initialData) .build()); complete = true; } } }; initialCall.start(initialCallListener, new Metadata()); initialCall.request(1); ByteStreamBlockingStub service = ByteStreamGrpc.newBlockingStub(channel); QueryWriteStatusResponse response = service.queryWriteStatus( QueryWriteStatusRequest.newBuilder().setResourceName(resourceName).build()); assertThat(response.getCommittedSize()).isEqualTo(initialData.size()); assertThat(response.getComplete()).isFalse(); ClientCall<WriteRequest, WriteResponse> finishCall = channel.newCall(ByteStreamGrpc.getWriteMethod(), CallOptions.DEFAULT); ClientCall.Listener<WriteResponse> finishCallListener = new ClientCall.Listener<WriteResponse>() { boolean complete = false; boolean callHalfClosed = false; @Override public void onReady() { while (finishCall.isReady()) { if (complete) { if (!callHalfClosed) { finishCall.halfClose(); callHalfClosed = true; } return; } finishCall.sendMessage( WriteRequest.newBuilder() .setResourceName(resourceName) .setWriteOffset(initialData.size()) .setData(helloWorld.substring(initialData.size())) .setFinishWrite(true) .build()); complete = true; } } }; finishCall.start(finishCallListener, new Metadata()); finishCall.request(1); ArgumentCaptor<InputStream> inputStreamCaptor = ArgumentCaptor.forClass(InputStream.class); verify(simpleBlobStore, times(1)) .put(eq(digest.getHash()), eq(digest.getSizeBytes()), inputStreamCaptor.capture()); InputStream inputStream = inputStreamCaptor.getValue(); assertThat(inputStream.available()).isEqualTo(helloWorld.size()); byte[] data = new byte[helloWorld.size()]; assertThat(inputStream.read(data)).isEqualTo(helloWorld.size()); assertThat(data).isEqualTo(helloWorld.toByteArray()); }
Example 11
Source File: AbstractInteropTest.java From grpc-java with Apache License 2.0 | 4 votes |
@Test public void serverStreamingShouldBeFlowControlled() throws Exception { final StreamingOutputCallRequest request = StreamingOutputCallRequest.newBuilder() .addResponseParameters(ResponseParameters.newBuilder().setSize(100000)) .addResponseParameters(ResponseParameters.newBuilder().setSize(100001)) .build(); final List<StreamingOutputCallResponse> goldenResponses = Arrays.asList( StreamingOutputCallResponse.newBuilder() .setPayload(Payload.newBuilder() .setBody(ByteString.copyFrom(new byte[100000]))).build(), StreamingOutputCallResponse.newBuilder() .setPayload(Payload.newBuilder() .setBody(ByteString.copyFrom(new byte[100001]))).build()); long start = System.nanoTime(); final ArrayBlockingQueue<Object> queue = new ArrayBlockingQueue<>(10); ClientCall<StreamingOutputCallRequest, StreamingOutputCallResponse> call = channel.newCall(TestServiceGrpc.getStreamingOutputCallMethod(), CallOptions.DEFAULT); call.start(new ClientCall.Listener<StreamingOutputCallResponse>() { @Override public void onHeaders(Metadata headers) {} @Override public void onMessage(final StreamingOutputCallResponse message) { queue.add(message); } @Override public void onClose(Status status, Metadata trailers) { queue.add(status); } }, new Metadata()); call.sendMessage(request); call.halfClose(); // Time how long it takes to get the first response. call.request(1); Object response = queue.poll(operationTimeoutMillis(), TimeUnit.MILLISECONDS); assertTrue(response instanceof StreamingOutputCallResponse); assertResponse(goldenResponses.get(0), (StreamingOutputCallResponse) response); long firstCallDuration = System.nanoTime() - start; // Without giving additional flow control, make sure that we don't get another response. We wait // until we are comfortable the next message isn't coming. We may have very low nanoTime // resolution (like on Windows) or be using a testing, in-process transport where message // handling is instantaneous. In both cases, firstCallDuration may be 0, so round up sleep time // to at least 1ms. assertNull(queue.poll(Math.max(firstCallDuration * 4, 1 * 1000 * 1000), TimeUnit.NANOSECONDS)); // Make sure that everything still completes. call.request(1); response = queue.poll(operationTimeoutMillis(), TimeUnit.MILLISECONDS); assertTrue(response instanceof StreamingOutputCallResponse); assertResponse(goldenResponses.get(1), (StreamingOutputCallResponse) response); assertEquals(Status.OK, queue.poll(operationTimeoutMillis(), TimeUnit.MILLISECONDS)); }
Example 12
Source File: XdsTestClient.java From grpc-java with Apache License 2.0 | 4 votes |
private void runQps() throws InterruptedException, ExecutionException { final SettableFuture<Void> failure = SettableFuture.create(); final class PeriodicRpc implements Runnable { @Override public void run() { final long requestId; final Set<XdsStatsWatcher> savedWatchers = new HashSet<>(); synchronized (lock) { currentRequestId += 1; requestId = currentRequestId; savedWatchers.addAll(watchers); } SimpleRequest request = SimpleRequest.newBuilder().setFillServerId(true).build(); ManagedChannel channel = channels.get((int) (requestId % channels.size())); final ClientCall<SimpleRequest, SimpleResponse> call = channel.newCall( TestServiceGrpc.getUnaryCallMethod(), CallOptions.DEFAULT.withDeadlineAfter(rpcTimeoutSec, TimeUnit.SECONDS)); call.start( new ClientCall.Listener<SimpleResponse>() { private String hostname; @Override public void onMessage(SimpleResponse response) { hostname = response.getHostname(); // TODO(ericgribkoff) Currently some test environments cannot access the stats RPC // service and rely on parsing stdout. if (printResponse) { System.out.println( "Greeting: Hello world, this is " + hostname + ", from " + call.getAttributes().get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR)); } } @Override public void onClose(Status status, Metadata trailers) { if (printResponse && !status.isOk()) { logger.log(Level.WARNING, "Greeting RPC failed with status {0}", status); } for (XdsStatsWatcher watcher : savedWatchers) { watcher.rpcCompleted(requestId, hostname); } } }, new Metadata()); call.sendMessage(request); call.request(1); call.halfClose(); } } long nanosPerQuery = TimeUnit.SECONDS.toNanos(1) / qps; ListenableScheduledFuture<?> future = exec.scheduleAtFixedRate(new PeriodicRpc(), 0, nanosPerQuery, TimeUnit.NANOSECONDS); Futures.addCallback( future, new FutureCallback<Object>() { @Override public void onFailure(Throwable t) { failure.setException(t); } @Override public void onSuccess(Object o) {} }, MoreExecutors.directExecutor()); failure.get(); }