io.grpc.StatusException Java Examples

The following examples show how to use io.grpc.StatusException. 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: MetaStoreService.java    From metastore with Apache License 2.0 7 votes vote down vote up
@Override
public void getJsonSchema(
    MetaStoreP.GetJsonSchemaRequest request,
    StreamObserver<MetaStoreP.GetJsonSchemaResponse> responseObserver) {

  try {
    AbstractRegistry registry = metaStore.registries.get(request.getRegistryName());
    ProtoDomain pContainer = registry.get();
    String jsonSchema = ProtoToJsonSchema.convert(pContainer, request.getMessageName());

    responseObserver.onNext(
        MetaStoreP.GetJsonSchemaResponse.newBuilder().setSchema(jsonSchema).build());
    responseObserver.onCompleted();
  } catch (StatusException | StatusRuntimeException e) {
    responseObserver.onError(e);
  }
}
 
Example #2
Source File: NettyClientTransportTest.java    From grpc-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 #3
Source File: SpeechService.java    From android-docs-samples with Apache License 2.0 6 votes vote down vote up
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
        final MethodDescriptor<ReqT, RespT> method, CallOptions callOptions,
        final Channel next) {
    return new ClientInterceptors.CheckedForwardingClientCall<ReqT, RespT>(
            next.newCall(method, callOptions)) {
        @Override
        protected void checkedStart(Listener<RespT> responseListener, Metadata headers)
                throws StatusException {
            Metadata cachedSaved;
            URI uri = serviceUri(next, method);
            synchronized (this) {
                Map<String, List<String>> latestMetadata = getRequestMetadata(uri);
                if (mLastMetadata == null || mLastMetadata != latestMetadata) {
                    mLastMetadata = latestMetadata;
                    mCached = toHeaders(mLastMetadata);
                }
                cachedSaved = mCached;
            }
            headers.merge(cachedSaved);
            delegate().start(responseListener, headers);
        }
    };
}
 
Example #4
Source File: ServerCalls.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private static Throwable toStatusFailure(Throwable throwable) {
    if (throwable instanceof StatusException || throwable instanceof StatusRuntimeException) {
        return throwable;
    } else {
        String desc = throwable.getClass().getName();
        if (throwable.getMessage() != null) {
            desc += " - " + throwable.getMessage();
        }
        if (throwable instanceof IllegalArgumentException) {
            return Status.INVALID_ARGUMENT.withDescription(desc).asException();
        }
        return Status.fromThrowable(throwable)
                .withDescription(desc)
                .asException();
    }
}
 
Example #5
Source File: OkHttpClientTransportTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void ping_failsWhenTransportShutdown() throws Exception {
  initTransport();
  PingCallbackImpl callback = new PingCallbackImpl();
  clientTransport.ping(callback, MoreExecutors.directExecutor());
  assertEquals(1, getTransportStats(clientTransport).keepAlivesSent);
  assertEquals(0, callback.invocationCount);

  clientTransport.shutdown(SHUTDOWN_REASON);
  // ping failed on channel shutdown
  assertEquals(1, callback.invocationCount);
  assertTrue(callback.failureCause instanceof StatusException);
  assertSame(SHUTDOWN_REASON, ((StatusException) callback.failureCause).getStatus());

  // now that handler is in terminal state, all future pings fail immediately
  callback = new PingCallbackImpl();
  clientTransport.ping(callback, MoreExecutors.directExecutor());
  assertEquals(1, getTransportStats(clientTransport).keepAlivesSent);
  assertEquals(1, callback.invocationCount);
  assertTrue(callback.failureCause instanceof StatusException);
  assertSame(SHUTDOWN_REASON, ((StatusException) callback.failureCause).getStatus());
  shutdownAndVerify();
}
 
Example #6
Source File: GrpcClientTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
private void checkRequestLog(RequestLogChecker checker) throws Exception {
    final RequestLog log = requestLogQueue.take();
    assertThat(log.isComplete()).isTrue();

    final RpcRequest rpcReq = (RpcRequest) log.requestContent();
    final RpcResponse rpcRes = (RpcResponse) log.responseContent();
    assertThat(rpcReq).isNotNull();
    assertThat((Object) rpcRes).isNotNull();
    assertThat(rpcReq.serviceType()).isEqualTo(GrpcLogUtil.class);

    final Status grpcStatus;
    if (rpcRes.cause() != null) {
        grpcStatus = ((StatusException) rpcRes.cause()).getStatus();
    } else {
        grpcStatus = null;
    }

    checker.check(rpcReq, rpcRes, grpcStatus);
}
 
Example #7
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 #8
Source File: GrpcCommandService.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
@Override
public StreamObserver<PCmdActiveThreadCountRes> commandStreamActiveThreadCount(StreamObserver<Empty> streamConnectionManagerObserver) {
    final Long transportId = getTransportId();
    PinpointGrpcServer pinpointGrpcServer = grpcServerRepository.get(transportId);
    if (pinpointGrpcServer == null) {
        logger.info("{} => local. Can't find PinpointGrpcServer(transportId={})", getAgentInfo().getAgentKey(), transportId);
        streamConnectionManagerObserver.onError(new StatusException(Status.NOT_FOUND));
        return DisabledStreamObserver.DISABLED_INSTANCE;
    }

    try {
        return activeThreadCountService.handle(pinpointGrpcServer, streamConnectionManagerObserver);
    } catch (IllegalArgumentException e) {
        logger.warn("Failed to handle activeThreadCountService. agentKey={}, transportId={}", getAgentInfo().getAgentKey(), transportId, e);
        streamConnectionManagerObserver.onError(Status.INTERNAL.withDescription("Internal Server Error").asException());
        return DisabledStreamObserver.DISABLED_INSTANCE;
    }
}
 
Example #9
Source File: BookstoreData.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
public Book getBook(long shelfId, long bookId) throws StatusException {
  synchronized (lock) {
    @Nullable ShelfInfo shelfInfo = shelves.get(shelfId);
    if (shelfInfo == null) {
      throw Status.NOT_FOUND
          .withDescription("Unknown shelf ID")
          .asException();
    }
    @Nullable Book book = shelfInfo.books.get(bookId);
    if (book == null) {
      throw Status.NOT_FOUND
          .withDescription("Unknown book ID")
          .asException();
    }
    return book;
  }
}
 
Example #10
Source File: ActiveThreadCountService.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
@Override
public void onNext(PCmdActiveThreadCountRes response) {
    if (streamChannelId == -1) {
        streamChannelId = response.getCommonStreamResponse().getResponseId();
    }

    PCmdStreamResponse headerResponse = response.getCommonStreamResponse();
    int sequenceId = headerResponse.getSequenceId();
    if (sequenceId == 1) {
        boolean success = pinpointGrpcServer.handleStreamCreateMessage(streamChannelId, connectionObserver);
        if (!success) {
            connectionObserver.onError(new StatusException(Status.NOT_FOUND));
            return;
        }
    }

    try {
        pinpointGrpcServer.handleStreamMessage(streamChannelId, response);
    } catch (StreamException e) {
        logger.warn("Failed to handle streamMessage. message:{}", e.getMessage(), e);
        connectionObserver.onError(new StatusException(Status.INTERNAL.withDescription(e.getMessage())));
    }
}
 
Example #11
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 #12
Source File: MemoryInstance.java    From bazel-buildfarm with Apache License 2.0 6 votes vote down vote up
@Override
protected void validateAction(
    String operationName,
    Action action,
    PreconditionFailure.Builder preconditionFailure,
    RequestMetadata requestMetadata)
    throws InterruptedException, StatusException {
  if (action.hasTimeout() && config.hasMaximumActionTimeout()) {
    Duration timeout = action.getTimeout();
    Duration maximum = config.getMaximumActionTimeout();
    if (timeout.getSeconds() > maximum.getSeconds()
        || (timeout.getSeconds() == maximum.getSeconds()
            && timeout.getNanos() > maximum.getNanos())) {
      preconditionFailure
          .addViolationsBuilder()
          .setType(VIOLATION_TYPE_INVALID)
          .setSubject(Durations.toString(timeout) + " > " + Durations.toString(maximum))
          .setDescription(TIMEOUT_OUT_OF_BOUNDS);
    }
  }

  super.validateAction(operationName, action, preconditionFailure, requestMetadata);
}
 
Example #13
Source File: GrpcRequestHandler.java    From xio with Apache License 2.0 6 votes vote down vote up
private ByteBuf makeResponseBuffer(ByteBuffer requestBuffer)
    throws InvalidProtocolBufferException, StatusException {
  GrpcRequest grpcRequest = requestParser.parse(requestBuffer);
  GrpcResponse grpcResponse = appLogic.apply(grpcRequest);

  byte[] dataBytes = grpcResponse.toByteArray();
  int length = dataBytes.length;
  byte[] lengthByteBuffer = ByteBuffer.allocate(4).putInt(length).array();
  byte[] compressedByteBuffer = ByteBuffer.allocate(1).put((byte) 0).array();

  ByteBuf responseBuffer =
      UnpooledByteBufAllocator.DEFAULT.buffer(length + METADATA_SIZE, length + METADATA_SIZE);

  responseBuffer.writeBytes(compressedByteBuffer);
  responseBuffer.writeBytes(lengthByteBuffer);
  responseBuffer.writeBytes(dataBytes);

  return responseBuffer;
}
 
Example #14
Source File: AbstractServerInstance.java    From bazel-buildfarm with Apache License 2.0 6 votes vote down vote up
protected void validateAction(
    String operationName,
    Action action,
    PreconditionFailure.Builder preconditionFailure,
    RequestMetadata requestMetadata)
    throws InterruptedException, StatusException {
  ExecutorService service = newDirectExecutorService();
  ImmutableSet.Builder<Digest> inputDigestsBuilder = ImmutableSet.builder();
  Tree tree =
      getUnchecked(
          getTreeFuture(operationName, action.getInputRootDigest(), service, requestMetadata));
  validateAction(
      action,
      getUnchecked(expect(action.getCommandDigest(), Command.parser(), service, requestMetadata)),
      DigestUtil.proxyDirectoriesIndex(tree.getDirectories()),
      inputDigestsBuilder::add,
      preconditionFailure);
  validateInputs(inputDigestsBuilder.build(), preconditionFailure, service, requestMetadata);
}
 
Example #15
Source File: DefaultServerRequestFactory.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
@Override
public <T> ServerRequest<T> newServerRequest(Message<T> message) throws StatusException {
    final Context current = Context.current();
    final Header header = ServerContext.getAgentInfo(current);
    if (header == null) {
        throw Status.INTERNAL.withDescription("Not found request header").asException();
    }

    final TransportMetadata transportMetadata = ServerContext.getTransportMetadata(current);
    if (transportMetadata == null) {
        throw Status.INTERNAL.withDescription("Not found transportMetadata").asException();
    }

    InetSocketAddress inetSocketAddress = transportMetadata.getRemoteAddress();
    ServerRequest<T> request = new DefaultServerRequest<>(message, inetSocketAddress.getHostString(), inetSocketAddress.getPort());
    return request;
}
 
Example #16
Source File: UploadOutputsTest.java    From bazel-buildfarm with Apache License 2.0 6 votes vote down vote up
@Test
public void uploadOutputsUploadsEmptyOutputDirectories()
    throws IOException, StatusException, InterruptedException {
  Files.createDirectory(root.resolve("foo"));
  // maybe make some files...
  uploadOutputs(ImmutableList.<String>of(), ImmutableList.<String>of("foo"));
  Tree emptyTree = Tree.newBuilder().setRoot(Directory.getDefaultInstance()).build();
  ByteString emptyTreeBlob = emptyTree.toByteString();
  ArgumentCaptor<Map<HashCode, Chunker>> uploadCaptor = ArgumentCaptor.forClass(Map.class);
  verify(mockUploader).uploadBlobs(uploadCaptor.capture());
  Map<HashCode, Chunker> upload = uploadCaptor.getValue();
  Chunker chunker = upload.get(DIGEST_UTIL.computeHash(emptyTreeBlob));
  assertThat(chunker.next().getData()).isEqualTo(emptyTreeBlob);
  assertThat(resultBuilder.getOutputDirectoriesList())
      .containsExactly(
          OutputDirectory.newBuilder()
              .setPath("foo")
              .setTreeDigest(DIGEST_UTIL.compute(emptyTree))
              .build());
}
 
Example #17
Source File: RegistryService.java    From metastore with Apache License 2.0 5 votes vote down vote up
@Override
public void updateResourceBinding(
    RegistryP.UpdateResourceBindingRequest request,
    StreamObserver<RegistryP.UpdateResourceBindingResponse> responseObserver) {
  try {
    AbstractRegistry registry = metaStore.registries.get(request.getRegistryName());
    RegistryP.ResourceBinding resourceBinding = request.getBinding();
    registry.updateResourceBinding(resourceBinding, false);
    responseObserver.onNext(RegistryP.UpdateResourceBindingResponse.newBuilder().build());
    responseObserver.onCompleted();
  } catch (StatusException e) {
    responseObserver.onError(e);
  }
}
 
Example #18
Source File: Statuses.java    From grpc-java-contrib with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Executes a function on a {@code StatusException} or a {@code StatusRuntimeException}, passing in the exception's
 * metadata and trailers.
 *
 * @param t a {@code StatusException} or a {@code StatusRuntimeException}
 * @param function the function to execute, given the exception's status and trailers
 * @param <T> the function's return type
 *
 * @throws IllegalArgumentException if {@code t} is not a {@code StatusException} or a {@code StatusRuntimeException}
 */
public static <T> T doWithStatus(Throwable t, BiFunction<Status, Metadata, T> function) {
    if (t instanceof StatusException) {
        return function.apply(((StatusException) t).getStatus(), ((StatusException) t).getTrailers());
    }
    if (t instanceof StatusRuntimeException) {
        return function.apply(((StatusRuntimeException) t).getStatus(), ((StatusRuntimeException) t).getTrailers());
    }

    throw new IllegalArgumentException("Throwable " + t.getClass().getSimpleName() + " is neither a " +
            "StatusException nor a StatusRuntimeException");
}
 
Example #19
Source File: Actions.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
public static void checkPreconditionFailure(
    Digest actionDigest, PreconditionFailure preconditionFailure) throws StatusException {
  if (preconditionFailure.getViolationsCount() != 0) {
    throw StatusProto.toStatusException(
        Status.newBuilder()
            .setCode(Code.FAILED_PRECONDITION.getNumber())
            .setMessage(invalidActionVerboseMessage(actionDigest, preconditionFailure))
            .addDetails(Any.pack(preconditionFailure))
            .build());
  }
}
 
Example #20
Source File: ListenableFutureAssert.java    From curiostack with MIT License 5 votes vote down vote up
private Status getFailureGrpcStatus() {
  Throwable t = catchThrowable(() -> getUnchecked(actual));
  Throwable cause = t.getCause();
  if (cause instanceof StatusRuntimeException) {
    return ((StatusRuntimeException) cause).getStatus();
  } else if (cause instanceof StatusException) {
    return ((StatusException) cause).getStatus();
  } else {
    // Could throw AssertionError, but use assertj for consistent error messages. The following
    // is guaranteed to throw.
    assertThat(cause).isInstanceOfAny(StatusException.class, StatusRuntimeException.class);
    throw new IllegalStateException("Can't reach here.");
  }
}
 
Example #21
Source File: ServerCalls.java    From reactive-grpc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static Throwable prepareError(Throwable throwable) {
    if (throwable instanceof StatusException || throwable instanceof StatusRuntimeException) {
        return throwable;
    } else {
        return Status.fromThrowable(throwable).asException();
    }
}
 
Example #22
Source File: CancellableStreamObserverTest.java    From reactive-grpc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void statusExceptionTriggersHandlerFuseable() {
    CallStreamObserver delegate = mock(CallStreamObserver.class);
    final AtomicBoolean called = new AtomicBoolean(false);

    AbstractStreamObserverAndPublisher observer = new TestStreamObserverAndPublisherWithFusion(new ArrayBlockingQueue(1), null, new Runnable() {
        @Override
        public void run() {
            called.set(true);
        }
    });

    observer.onSubscribe(delegate);

    TestSubscriber test = Flowable.fromPublisher(observer)
                                  .observeOn(Schedulers.trampoline())
                                  .test();

    StatusException exception = Status.CANCELLED.asException();
    observer.onError(exception);

    test.awaitTerminalEvent();
    test.assertError(exception);

    assertThat(called.get()).isTrue();
    assertThat(observer.outputFused).isTrue();
}
 
Example #23
Source File: GrpcCommandService.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Override
public void commandActiveThreadLightDump(PCmdActiveThreadLightDumpRes activeThreadLightDumpResponse, StreamObserver<Empty> responseObserver) {
    final Long transportId = getTransportId();
    PinpointGrpcServer pinpointGrpcServer = grpcServerRepository.get(transportId);
    if (pinpointGrpcServer != null) {
        activeThreadLightDumpService.handle(pinpointGrpcServer, activeThreadLightDumpResponse, responseObserver);
        responseObserver.onNext(Empty.getDefaultInstance());
        responseObserver.onCompleted();
    } else {
        logger.info("{} => local. Can't find PinpointGrpcServer(transportId={})", getAgentInfo().getAgentKey(), transportId);
        responseObserver.onError(new StatusException(Status.NOT_FOUND));
    }
}
 
Example #24
Source File: GoogleCredentialsInterceptor.java    From Saiy-PS with GNU Affero General Public License v3.0 5 votes vote down vote up
private Map<String, List<String>> getRequestMetadata(URI uri) throws StatusException {
    try {
        return mCredentials.getRequestMetadata(uri);
    } catch (IOException e) {
        throw Status.UNAUTHENTICATED.withCause(e).asException();
    }
}
 
Example #25
Source File: AbstractSubscriberAndProducerTest.java    From reactive-grpc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Tag("unstable")
@RepeatedTest(2)
public void asyncModeWithRacingAndOnErrorOverOnNextTest()
    throws InterruptedException {
    final CountDownLatch cancellationLatch = new CountDownLatch(1);
    List<Integer> integers = Flowable.range(0, 10000000)
                                     .toList()
                                     .blockingGet();

    TestSubscriberProducer<Integer> producer = Flowable.fromIterable(integers)
                                                       .doOnCancel(new Action() {
                                                           @Override
                                                           public void run() {
                                                               cancellationLatch.countDown();
                                                           }
                                                       })
                                                       .hide()
                                                       .subscribeOn(Schedulers.io())
                                                       .observeOn(Schedulers.io(), true)
                                                       .subscribeWith(new TestSubscriberProducer<Integer>());

    TestCallStreamObserver<Integer> downstream = new TestCallStreamObserver<Integer>(
        executorService);
    producer.subscribe(downstream);

    racePauseResuming(downstream, 100);

    downstream.throwOnNext();

    Assertions.assertThat(downstream.awaitTerminal(1, TimeUnit.MINUTES)).isTrue();
    Assertions.assertThat(cancellationLatch.await(1, TimeUnit.MINUTES)).isTrue();
    Assertions.assertThat(downstream.e)
              .isExactlyInstanceOf(StatusException.class)
              .hasCauseInstanceOf(OnNextTestException.class);
    Assertions.assertThat(producer).hasFieldOrPropertyWithValue("sourceMode", 2);
    Assertions.assertThat(downstream.collected)
              .isSubsetOf(integers);
    Assertions.assertThat(unhandledThrowable).isEmpty();
}
 
Example #26
Source File: GrpcServiceServerTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static void checkRequestLogStatus(RequestLogStatusChecker checker) throws Exception {
    final RequestLog log = requestLogQueue.take();
    assertThat(log.isComplete()).isTrue();

    final RpcRequest rpcReq = (RpcRequest) log.requestContent();
    final RpcResponse rpcRes = (RpcResponse) log.responseContent();
    assertThat(rpcReq).isNull();
    assertThat((Object) rpcRes).isNotNull();

    assertThat(rpcRes.cause()).isNotNull();
    checker.check(((StatusException) rpcRes.cause()).getStatus());
}
 
Example #27
Source File: ShadowRegistry.java    From metastore with Apache License 2.0 5 votes vote down vote up
private void updateShadowCache() {
  ProtoDomain original = null;
  try {
    original = registries.get(shadowOf).get();
  } catch (StatusException e) {
    throw new RuntimeException("Unable to find registry with name " + shadowOf);
  }
  protoContainer = new ShadowApply().applyDelta(original, this.delta);
  protoContainer.registerOptions();
}
 
Example #28
Source File: AbstractSubscriberAndProducer.java    From reactive-grpc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static Throwable prepareError(Throwable throwable) {
    if (throwable instanceof StatusException || throwable instanceof StatusRuntimeException) {
        return throwable;
    } else {
        return Status.fromThrowable(throwable).asException();
    }
}
 
Example #29
Source File: GrpcClientTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static void assertResponseTimeoutExceptionOrDeadlineExceeded(@Nullable Throwable cause) {
    assertThat(cause).isNotNull();

    // Both exceptions can be raised when a timeout occurs due to timing issues,
    // and the first triggered one wins.
    if (cause instanceof ResponseTimeoutException) {
        return;
    }
    if (cause instanceof StatusException) {
        assertThat(((StatusException) cause).getStatus().getCode()).isEqualTo(Code.DEADLINE_EXCEEDED);
        return;
    }
    fail("cause must be a ResponseTimeoutException or a StatusException: ", cause);
}
 
Example #30
Source File: BookstoreData.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public void deleteShelf(long shelfId) throws StatusException {
  synchronized (lock) {
    if (shelves.remove(shelfId) == null) {
      throw Status.NOT_FOUND
          .withDescription("Unknown shelf ID")
          .asException();
    }
  }
}