io.grpc.Status Java Examples

The following examples show how to use io.grpc.Status. 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: CampaignLabelServiceClientTest.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
@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 #2
Source File: ConversionUploadServiceClientTest.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
@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 #3
Source File: AbstractServerInstance.java    From bazel-buildfarm with 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 #4
Source File: AccountBudgetProposalServiceClientTest.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
@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 #5
Source File: AccountBudgetProposalServiceClientTest.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
@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 #6
Source File: OkHttpClientTransportTest.java    From grpc-java with 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 #7
Source File: RlsLoadBalancer.java    From grpc-java with 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 #8
Source File: BiddingStrategyServiceClientTest.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
@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 #9
Source File: ClientCallImpl.java    From grpc-nebula-java with 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 #10
Source File: TopicViewServiceClientTest.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
@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 #11
Source File: CallCredentialsApplyingTest.java    From grpc-java with 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 #12
Source File: ByteStreamServiceWriter.java    From bazel-buildfarm with 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 #13
Source File: MutateJobServiceClientTest.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
@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 #14
Source File: GoogleAdsServiceClientTest.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
@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 #15
Source File: ClientCallsTest.java    From grpc-java with 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 #16
Source File: GrpcHelperImpl.java    From apm-agent-java with 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 #17
Source File: NettyClientTransportTest.java    From grpc-nebula-java with 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 #18
Source File: CustomInterestServiceClientTest.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
@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 #19
Source File: BookstoreData.java    From java-docs-samples with 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 #20
Source File: TransmitUnexpectedExceptionInterceptorTest.java    From grpc-java-contrib with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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 #21
Source File: CachingRlsLbClient.java    From grpc-java with 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 #22
Source File: CampaignDraftServiceClientTest.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
@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 #23
Source File: BiddingStrategyServiceClientTest.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
@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 #24
Source File: AdGroupLabelServiceClientTest.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
@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 #25
Source File: MessageDeframer.java    From grpc-nebula-java with 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 #26
Source File: NettyClientHandlerTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void receivedGoAwayShouldCancelBufferedStream() throws Exception {
  // Force the stream to be buffered.
  receiveMaxConcurrentStreams(0);
  ChannelFuture future = enqueue(newCreateStreamCommand(grpcHeaders, streamTransportState));
  channelRead(goAwayFrame(0));
  assertTrue(future.isDone());
  assertFalse(future.isSuccess());
  Status status = Status.fromThrowable(future.cause());
  assertEquals(Status.Code.UNAVAILABLE, status.getCode());
  assertEquals("HTTP/2 error code: NO_ERROR\nReceived Goaway", status.getDescription());
}
 
Example #27
Source File: ManagedChannelImplTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void immediateDeadlineExceeded() {
  createChannel();
  ClientCall<String, Integer> call =
      channel.newCall(method, CallOptions.DEFAULT.withDeadlineAfter(0, TimeUnit.NANOSECONDS));
  call.start(mockCallListener, new Metadata());
  assertEquals(1, executor.runDueTasks());

  verify(mockCallListener).onClose(statusCaptor.capture(), any(Metadata.class));
  Status status = statusCaptor.getValue();
  assertSame(Status.DEADLINE_EXCEEDED.getCode(), status.getCode());
}
 
Example #28
Source File: AbstractStream.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
/** Called by the idle timer when the stream should close due to inactivity. */
private void handleIdleCloseTimer() {
  if (this.isOpen()) {
    // When timing out an idle stream there's no reason to force the stream into backoff when
    // it restarts so set the stream state to Initial instead of Error.
    close(State.Initial, Status.OK);
  }
}
 
Example #29
Source File: EtcdLockClient.java    From etcd-java with Apache License 2.0 5 votes vote down vote up
@Override
public final ListenableFuture<LockResponse> async(Executor executor) {
    if (lease == null) {
        if (builder.getLease() != 0L) {
            return super.async(executor);
        } else {
            lease = etcdClient.getSessionLease();
        }
    }
    long plId = lease.getLeaseId();
    if (plId != 0L) {
        builder.setLease(plId);
        return super.async(executor);
    }
    ListenableFuture<Long> fut;
    if (deadline == null) {
        fut = lease;
    } else {
        long remainingNanos = deadline.timeRemaining(NANOSECONDS);
        fut = Futures.catching(Futures.withTimeout(lease,
                remainingNanos, NANOSECONDS, grpcClient.getInternalExecutor()),
                TimeoutException.class, te -> {
                    throw Status.DEADLINE_EXCEEDED.withCause(te)
                        .withDescription(String.format("deadline exceeded after %dns",
                            remainingNanos)).asRuntimeException();
                }, MoreExecutors.directExecutor());
    }
    return Futures.transformAsync(fut, id -> {
        builder.setLease(id);
        return super.async(executor);
    }, executor);
}
 
Example #30
Source File: ServerCallImplTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void sendMessage_closesOnFailure() {
  call.sendHeaders(new Metadata());
  doThrow(new RuntimeException("bad")).when(stream).writeMessage(isA(InputStream.class));

  call.sendMessage(1234L);

  verify(stream).close(isA(Status.class), isA(Metadata.class));
}