Java Code Examples for io.grpc.Status

The following examples show how to use io.grpc.Status. These examples are extracted from open source projects. 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 Project: grpc-nebula-java   Source File: ClientCallImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onReady() {
  class StreamOnReady extends ContextRunnable {
    StreamOnReady() {
      super(context);
    }

    @Override
    public final void runInContext() {
      try {
        observer.onReady();
      } catch (Throwable t) {
        Status status =
            Status.CANCELLED.withCause(t).withDescription("Failed to call onReady.");
        stream.cancel(status);
        close(status, new Metadata());
      }
    }
  }

  callExecutor.execute(new StreamOnReady());
}
 
Example 2
@Test
@SuppressWarnings("all")
public void mutateBiddingStrategiesExceptionTest() throws Exception {
  StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
  mockBiddingStrategyService.addException(exception);

  try {
    String customerId = "customerId-1772061412";
    List<BiddingStrategyOperation> operations = new ArrayList<>();
    boolean partialFailure = true;
    boolean validateOnly = false;

    client.mutateBiddingStrategies(customerId, operations, partialFailure, validateOnly);
    Assert.fail("No exception raised");
  } catch (InvalidArgumentException e) {
    // Expected exception
  }
}
 
Example 3
@Test
@SuppressWarnings("all")
public void mutateAccountBudgetProposalExceptionTest() throws Exception {
  StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
  mockAccountBudgetProposalService.addException(exception);

  try {
    String customerId = "customerId-1772061412";
    AccountBudgetProposalOperation operation =
        AccountBudgetProposalOperation.newBuilder().build();
    boolean validateOnly = false;

    client.mutateAccountBudgetProposal(customerId, operation, validateOnly);
    Assert.fail("No exception raised");
  } catch (InvalidArgumentException e) {
    // Expected exception
  }
}
 
Example 4
Source Project: bazel-buildfarm   Source File: ByteStreamServiceWriter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onNext(WriteRequest request) {
  checkState(
      (hasSeenResourceName && request.getResourceName().isEmpty())
          || request.getResourceName().equals(resourceName));
  hasSeenResourceName = true;
  checkState(!finished);
  ByteString data = request.getData();
  if (data.isEmpty() || request.getWriteOffset() == out.size()) {
    try {
      request.getData().writeTo(out);
      finished = request.getFinishWrite();
      if (finished) {
        long committedSize = out.size();
        content.set(out.toByteString());
        responseObserver.onNext(
            WriteResponse.newBuilder().setCommittedSize(committedSize).build());
      }
    } catch (IOException e) {
      responseObserver.onError(Status.fromThrowable(e).asException());
    }
  } else {
    responseObserver.onError(Status.INVALID_ARGUMENT.asException());
  }
}
 
Example 5
@Test
@SuppressWarnings("all")
public void getMutateJobExceptionTest() throws Exception {
  StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
  mockMutateJobService.addException(exception);

  try {
    String formattedResourceName =
        MutateJobServiceClient.formatMutateJobName("[CUSTOMER]", "[MUTATE_JOB]");

    client.getMutateJob(formattedResourceName);
    Assert.fail("No exception raised");
  } catch (InvalidArgumentException e) {
    // Expected exception
  }
}
 
Example 6
Source Project: grpc-nebula-java   Source File: MessageDeframer.java    License: Apache License 2.0 6 votes vote down vote up
private InputStream getCompressedBody() {
  if (decompressor == Codec.Identity.NONE) {
    throw Status.INTERNAL.withDescription(
        "Can't decode compressed gRPC message as compression not configured")
        .asRuntimeException();
  }

  try {
    // Enforce the maxMessageSize limit on the returned stream.
    InputStream unlimitedStream =
        decompressor.decompress(ReadableBuffers.openStream(nextFrame, true));
    return new SizeEnforcingInputStream(
        unlimitedStream, maxInboundMessageSize, statsTraceCtx);
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example 7
@Test
@SuppressWarnings("all")
public void mutateExceptionTest() throws Exception {
  StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
  mockGoogleAdsService.addException(exception);

  try {
    String customerId = "customerId-1772061412";
    List<MutateOperation> mutateOperations = new ArrayList<>();
    boolean partialFailure = true;
    boolean validateOnly = false;

    client.mutate(customerId, mutateOperations, partialFailure, validateOnly);
    Assert.fail("No exception raised");
  } catch (InvalidArgumentException e) {
    // Expected exception
  }
}
 
Example 8
@Test
@SuppressWarnings("all")
public void mutateAdGroupLabelsExceptionTest2() throws Exception {
  StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
  mockAdGroupLabelService.addException(exception);

  try {
    String customerId = "customerId-1772061412";
    List<AdGroupLabelOperation> operations = new ArrayList<>();

    client.mutateAdGroupLabels(customerId, operations);
    Assert.fail("No exception raised");
  } catch (InvalidArgumentException e) {
    // Expected exception
  }
}
 
Example 9
@Test
@SuppressWarnings("all")
public void mutateBiddingStrategiesExceptionTest() throws Exception {
  StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
  mockBiddingStrategyService.addException(exception);

  try {
    String customerId = "customerId-1772061412";
    List<BiddingStrategyOperation> operations = new ArrayList<>();
    boolean partialFailure = true;
    boolean validateOnly = false;

    client.mutateBiddingStrategies(customerId, operations, partialFailure, validateOnly);
    Assert.fail("No exception raised");
  } catch (InvalidArgumentException e) {
    // Expected exception
  }
}
 
Example 10
@Test
public void exactTypeMatches() {
    GreeterGrpc.GreeterImplBase svc = new GreeterGrpc.GreeterImplBase() {
        @Override
        public void sayHello(HelloRequest request, StreamObserver<HelloResponse> responseObserver) {
            responseObserver.onError(new ArithmeticException("Divide by zero"));
        }
    };

    ServerInterceptor interceptor = new TransmitUnexpectedExceptionInterceptor().forExactType(ArithmeticException.class);

    serverRule.getServiceRegistry().addService(ServerInterceptors.intercept(svc, interceptor));
    GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(serverRule.getChannel());

    assertThatThrownBy(() -> stub.sayHello(HelloRequest.newBuilder().setName("World").build()))
            .isInstanceOf(StatusRuntimeException.class)
            .matches(sre -> ((StatusRuntimeException) sre).getStatus().getCode().equals(Status.INTERNAL.getCode()), "is Status.INTERNAL")
            .hasMessageContaining("Divide by zero");
}
 
Example 11
@Test
@SuppressWarnings("all")
public void mutateCustomInterestsExceptionTest2() throws Exception {
  StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
  mockCustomInterestService.addException(exception);

  try {
    String customerId = "customerId-1772061412";
    List<CustomInterestOperation> operations = new ArrayList<>();

    client.mutateCustomInterests(customerId, operations);
    Assert.fail("No exception raised");
  } catch (InvalidArgumentException e) {
    // Expected exception
  }
}
 
Example 12
@Test
@SuppressWarnings("all")
public void mutateCampaignLabelsExceptionTest2() throws Exception {
  StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
  mockCampaignLabelService.addException(exception);

  try {
    String customerId = "customerId-1772061412";
    List<CampaignLabelOperation> operations = new ArrayList<>();

    client.mutateCampaignLabels(customerId, operations);
    Assert.fail("No exception raised");
  } catch (InvalidArgumentException e) {
    // Expected exception
  }
}
 
Example 13
Source Project: apm-agent-java   Source File: GrpcHelperImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void exitServerListenerMethod(@Nullable Throwable thrown,
                                     ServerCall.Listener<?> listener,
                                     @Nullable Transaction transaction,
                                     boolean isLastMethod) {
    if (transaction == null) {
        return;
    }

    transaction.deactivate();

    if (isLastMethod || null != thrown) {
        // when there is a runtime exception thrown in one of the listener methods the calling code will catch it
        // and set 'unknown' status, we just replicate this behavior as we don't instrument the part that does this
        if (thrown != null) {
            setTransactionStatus(Status.UNKNOWN, thrown, transaction);
        }
        transaction.end();
        serverListenerTransactions.remove(listener);
    }

}
 
Example 14
Source Project: grpc-nebula-java   Source File: NettyClientTransportTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void maxHeaderListSizeShouldBeEnforcedOnClient() throws Exception {
  startServer();

  NettyClientTransport transport =
      newTransport(newNegotiator(), DEFAULT_MAX_MESSAGE_SIZE, 1, null, true);
  callMeMaybe(transport.start(clientTransportListener));

  try {
    // Send a single RPC and wait for the response.
    new Rpc(transport, new Metadata()).halfClose().waitForResponse();
    fail("The stream should have been failed due to client received header exceeds header list"
        + " size limit!");
  } catch (Exception e) {
    Throwable rootCause = getRootCause(e);
    Status status = ((StatusException) rootCause).getStatus();
    assertEquals(Status.Code.INTERNAL, status.getCode());
    assertEquals("HTTP/2 error code: PROTOCOL_ERROR\nReceived Rst Stream",
        status.getDescription());
  }
}
 
Example 15
Source Project: java-docs-samples   Source File: BookstoreData.java    License: Apache License 2.0 6 votes vote down vote up
public Book createBook(long shelfId, Book book) throws StatusException {
  synchronized (lock) {
    @Nullable ShelfInfo shelfInfo = shelves.get(shelfId);
    if (shelfInfo == null) {
      throw Status.NOT_FOUND
          .withDescription("Unknown shelf ID")
          .asException();
    }
    shelfInfo.lastBookId++;
    book = book.toBuilder()
        .setId(shelfInfo.lastBookId)
        .build();
    shelfInfo.books.put(shelfInfo.lastBookId, book);
  }
  return book;
}
 
Example 16
Source Project: grpc-java   Source File: CachingRlsLbClient.java    License: Apache License 2.0 6 votes vote down vote up
BackoffCacheEntry(RouteLookupRequest request, Status status, BackoffPolicy backoffPolicy) {
  super(request);
  this.status = checkNotNull(status, "status");
  this.backoffPolicy = checkNotNull(backoffPolicy, "backoffPolicy");
  long delayNanos = backoffPolicy.nextBackoffNanos();
  this.expireNanos = timeProvider.currentTimeNanos() + delayNanos;
  this.scheduledHandle =
      synchronizationContext.schedule(
          new Runnable() {
            @Override
            public void run() {
              transitionToPending();
            }
          },
          delayNanos,
          TimeUnit.NANOSECONDS,
          scheduledExecutorService);
}
 
Example 17
@Test
@SuppressWarnings("all")
public void mutateCampaignDraftsExceptionTest2() throws Exception {
  StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
  mockCampaignDraftService.addException(exception);

  try {
    String customerId = "customerId-1772061412";
    List<CampaignDraftOperation> operations = new ArrayList<>();

    client.mutateCampaignDrafts(customerId, operations);
    Assert.fail("No exception raised");
  } catch (InvalidArgumentException e) {
    // Expected exception
  }
}
 
Example 18
Source Project: grpc-java   Source File: ClientCallsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void blockingServerStreamingCall_HasBlockingStubType() {
  NoopClientCall<Integer, Integer> call = new NoopClientCall<Integer, Integer>() {
    @Override
    public void start(io.grpc.ClientCall.Listener<Integer> listener, Metadata headers) {
      listener.onMessage(1);
      listener.onClose(Status.OK, new Metadata());
    }
  };
  when(mockChannel.newCall(
      ArgumentMatchers.<MethodDescriptor<Integer, Integer>>any(), any(CallOptions.class)))
      .thenReturn(call);

  Iterator<Integer> unused =
      ClientCalls.blockingServerStreamingCall(mockChannel, UNARY_METHOD, CallOptions.DEFAULT, 1);

  verify(mockChannel).newCall(methodDescriptorCaptor.capture(), callOptionsCaptor.capture());
  CallOptions capturedCallOption = callOptionsCaptor.getValue();
  assertThat(capturedCallOption.getOption(ClientCalls.STUB_TYPE_OPTION))
      .isEquivalentAccordingToCompareTo(StubType.BLOCKING);
}
 
Example 19
Source Project: grpc-java   Source File: CallCredentialsApplyingTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void fail_inline() {
  final Status error = Status.FAILED_PRECONDITION.withDescription("channel not secure for creds");
  when(mockTransport.getAttributes()).thenReturn(Attributes.EMPTY);
  doAnswer(new Answer<Void>() {
      @Override
      public Void answer(InvocationOnMock invocation) throws Throwable {
        CallCredentials.MetadataApplier applier =
            (CallCredentials.MetadataApplier) invocation.getArguments()[2];
        applier.fail(error);
        return null;
      }
    }).when(mockCreds).applyRequestMetadata(any(RequestInfo.class),
        same(mockExecutor), any(CallCredentials.MetadataApplier.class));

  FailingClientStream stream =
      (FailingClientStream) transport.newStream(method, origHeaders, callOptions);

  verify(mockTransport, never()).newStream(method, origHeaders, callOptions);
  assertSame(error, stream.getError());
}
 
Example 20
@Test
@SuppressWarnings("all")
public void uploadClickConversionsExceptionTest2() throws Exception {
  StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
  mockConversionUploadService.addException(exception);

  try {
    String customerId = "customerId-1772061412";
    List<ClickConversion> conversions = new ArrayList<>();

    client.uploadClickConversions(customerId, conversions);
    Assert.fail("No exception raised");
  } catch (InvalidArgumentException e) {
    // Expected exception
  }
}
 
Example 21
Source Project: bazel-buildfarm   Source File: AbstractServerInstance.java    License: Apache License 2.0 6 votes vote down vote up
protected void errorOperation(
    Operation operation, RequestMetadata requestMetadata, com.google.rpc.Status status)
    throws InterruptedException {
  if (operation.getDone()) {
    throw new IllegalStateException("Trying to error already completed operation [" + name + "]");
  }
  ExecuteOperationMetadata metadata = expectExecuteOperationMetadata(operation);
  if (metadata == null) {
    metadata = ExecuteOperationMetadata.getDefaultInstance();
  }
  CompletedOperationMetadata completedMetadata =
      CompletedOperationMetadata.newBuilder()
          .setExecuteOperationMetadata(
              metadata.toBuilder().setStage(ExecutionStage.Value.COMPLETED).build())
          .setRequestMetadata(requestMetadata)
          .build();
  putOperation(
      operation
          .toBuilder()
          .setDone(true)
          .setMetadata(Any.pack(completedMetadata))
          .setResponse(Any.pack(ExecuteResponse.newBuilder().setStatus(status).build()))
          .build());
}
 
Example 22
@Test
@SuppressWarnings("all")
public void mutateAccountBudgetProposalExceptionTest2() throws Exception {
  StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
  mockAccountBudgetProposalService.addException(exception);

  try {
    String customerId = "customerId-1772061412";
    AccountBudgetProposalOperation operation =
        AccountBudgetProposalOperation.newBuilder().build();

    client.mutateAccountBudgetProposal(customerId, operation);
    Assert.fail("No exception raised");
  } catch (InvalidArgumentException e) {
    // Expected exception
  }
}
 
Example 23
Source Project: grpc-java   Source File: OkHttpClientTransportTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void receiveDataWithoutHeader() throws Exception {
  initTransport();
  MockStreamListener listener = new MockStreamListener();
  OkHttpClientStream stream =
      clientTransport.newStream(method, new Metadata(), CallOptions.DEFAULT);
  stream.start(listener);
  stream.request(1);
  Buffer buffer = createMessageFrame(new byte[1]);
  frameHandler().data(false, 3, buffer, (int) buffer.size());

  // Trigger the failure by a trailer.
  frameHandler().headers(
      true, true, 3, 0, grpcResponseHeaders(), HeadersMode.HTTP_20_HEADERS);

  listener.waitUntilStreamClosed();
  assertEquals(Status.INTERNAL.getCode(), listener.status.getCode());
  assertTrue(listener.status.getDescription().startsWith("headers not received before payload"));
  assertEquals(0, listener.messages.size());
  shutdownAndVerify();
}
 
Example 24
@Test
@SuppressWarnings("all")
public void getTopicViewExceptionTest() throws Exception {
  StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
  mockTopicViewService.addException(exception);

  try {
    String formattedResourceName =
        TopicViewServiceClient.formatTopicViewName("[CUSTOMER]", "[TOPIC_VIEW]");

    client.getTopicView(formattedResourceName);
    Assert.fail("No exception raised");
  } catch (InvalidArgumentException e) {
    // Expected exception
  }
}
 
Example 25
Source Project: grpc-java   Source File: RlsLoadBalancer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void handleNameResolutionError(final Status error) {
  class ErrorPicker extends SubchannelPicker {
    @Override
    public PickResult pickSubchannel(PickSubchannelArgs args) {
      return PickResult.withError(error);
    }

    @Override
    public String toString() {
      return MoreObjects.toStringHelper(this)
          .add("error", error)
          .toString();
    }
  }

  if (routeLookupClient != null) {
    routeLookupClient.close();
    routeLookupClient = null;
    lbPolicyConfiguration = null;
  }
  helper.updateBalancingState(ConnectivityState.TRANSIENT_FAILURE, new ErrorPicker());
}
 
Example 26
Source Project: google-ads-java   Source File: LabelServiceClientTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("all")
public void getLabelExceptionTest() throws Exception {
  StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
  mockLabelService.addException(exception);

  try {
    String formattedResourceName = LabelServiceClient.formatLabelName("[CUSTOMER]", "[LABEL]");

    client.getLabel(formattedResourceName);
    Assert.fail("No exception raised");
  } catch (InvalidArgumentException e) {
    // Expected exception
  }
}
 
Example 27
Source Project: grpc-java   Source File: OkHttpClientTransportTest.java    License: Apache License 2.0 5 votes vote down vote up
private void shouldHeadersBeFlushed(boolean shouldBeFlushed) throws Exception {
  initTransport();
  MockStreamListener listener = new MockStreamListener();
  OkHttpClientStream stream =
      clientTransport.newStream(method, new Metadata(), CallOptions.DEFAULT);
  stream.start(listener);
  verify(frameWriter, timeout(TIME_OUT_MS)).synStream(
      eq(false), eq(false), eq(3), eq(0), ArgumentMatchers.<Header>anyList());
  if (shouldBeFlushed) {
    verify(frameWriter, timeout(TIME_OUT_MS)).flush();
  } else {
    verify(frameWriter, timeout(TIME_OUT_MS).times(0)).flush();
  }
  stream.cancel(Status.CANCELLED);
}
 
Example 28
Source Project: grpc-nebula-java   Source File: NettyClientHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void cancelWhileBufferedShouldSucceed() throws Exception {
  // Force the stream to be buffered.
  receiveMaxConcurrentStreams(0);

  ChannelFuture createFuture = createStream();
  assertFalse(createFuture.isDone());

  ChannelFuture cancelFuture = cancelStream(Status.CANCELLED);
  assertTrue(cancelFuture.isSuccess());
  assertTrue(createFuture.isDone());
  assertTrue(createFuture.isSuccess());
}
 
Example 29
Source Project: grpc-java   Source File: RetriableStreamTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void hedging_perRpcBufferLimitExceeded() {
  ClientStream mockStream1 = mock(ClientStream.class);
  ClientStream mockStream2 = mock(ClientStream.class);
  doReturn(mockStream1).when(retriableStreamRecorder).newSubstream(0);
  doReturn(mockStream2).when(retriableStreamRecorder).newSubstream(1);

  hedgingStream.start(masterListener);
  ArgumentCaptor<ClientStreamListener> sublistenerCaptor1 =
      ArgumentCaptor.forClass(ClientStreamListener.class);
  verify(mockStream1).start(sublistenerCaptor1.capture());

  ClientStreamTracer bufferSizeTracer1 = bufferSizeTracer;
  bufferSizeTracer1.outboundWireSize(PER_RPC_BUFFER_LIMIT - 1);

  fakeClock.forwardTime(HEDGING_DELAY_IN_SECONDS, TimeUnit.SECONDS);
  ArgumentCaptor<ClientStreamListener> sublistenerCaptor2 =
      ArgumentCaptor.forClass(ClientStreamListener.class);
  verify(mockStream2).start(sublistenerCaptor2.capture());

  ClientStreamTracer bufferSizeTracer2 = bufferSizeTracer;
  bufferSizeTracer2.outboundWireSize(PER_RPC_BUFFER_LIMIT - 1);

  verify(retriableStreamRecorder, never()).postCommit();

  // bufferLimitExceeded
  bufferSizeTracer2.outboundWireSize(2);

  ArgumentCaptor<Status> statusCaptor = ArgumentCaptor.forClass(Status.class);
  verify(mockStream1).cancel(statusCaptor.capture());
  assertEquals(Status.CANCELLED.getCode(), statusCaptor.getValue().getCode());
  assertEquals(CANCELLED_BECAUSE_COMMITTED, statusCaptor.getValue().getDescription());
  verify(retriableStreamRecorder).postCommit();

  verifyNoMoreInteractions(mockStream1);
  verifyNoMoreInteractions(mockStream2);
}
 
Example 30
Source Project: grpc-java   Source File: ManagedChannelImplTest.java    License: Apache License 2.0 5 votes vote down vote up
FakeNameResolverFactory(
    List<URI> expectedUris,
    List<EquivalentAddressGroup> servers,
    boolean resolvedAtStart,
    Status error) {
  this.expectedUris = expectedUris;
  this.servers = servers;
  this.resolvedAtStart = resolvedAtStart;
  this.error = error;
}