Search in sources :

Example 6 with StatusRuntimeException

use of io.grpc.StatusRuntimeException in project grpc-java by grpc.

the class ReconnectTestClient method runTest.

private void runTest() throws Exception {
    try {
        controlChannel = NettyChannelBuilder.forAddress("127.0.0.1", serverControlPort).negotiationType(NegotiationType.PLAINTEXT).build();
        controlStub = ReconnectServiceGrpc.newBlockingStub(controlChannel);
        if (useOkhttp) {
            retryChannel = OkHttpChannelBuilder.forAddress("127.0.0.1", serverRetryPort).negotiationType(io.grpc.okhttp.NegotiationType.TLS).build();
        } else {
            retryChannel = NettyChannelBuilder.forAddress("127.0.0.1", serverRetryPort).negotiationType(NegotiationType.TLS).build();
        }
        retryStub = ReconnectServiceGrpc.newBlockingStub(retryChannel);
        controlStub.start(Empty.getDefaultInstance());
        long startTimeStamp = System.currentTimeMillis();
        while ((System.currentTimeMillis() - startTimeStamp) < TEST_TIME_MS) {
            try {
                retryStub.start(Empty.getDefaultInstance());
            } catch (StatusRuntimeException expected) {
            // Make CheckStyle happy.
            }
            Thread.sleep(50);
        }
        ReconnectInfo info = controlStub.stop(Empty.getDefaultInstance());
        assertTrue(info.getPassed());
    } finally {
        controlChannel.shutdownNow();
        retryChannel.shutdownNow();
    }
}
Also used : StatusRuntimeException(io.grpc.StatusRuntimeException) ReconnectInfo(io.grpc.testing.integration.Messages.ReconnectInfo)

Example 7 with StatusRuntimeException

use of io.grpc.StatusRuntimeException in project grpc-java by grpc.

the class RouteGuideClientTest method getFeature_error.

/**
   * Example for testing blocking unary call.
   */
@Test
public void getFeature_error() {
    Point requestPoint = Point.newBuilder().setLatitude(-1).setLongitude(-1).build();
    final AtomicReference<Point> pointDelivered = new AtomicReference<Point>();
    final StatusRuntimeException fakeError = new StatusRuntimeException(Status.DATA_LOSS);
    // implement the fake service
    RouteGuideImplBase getFeatureImpl = new RouteGuideImplBase() {

        @Override
        public void getFeature(Point point, StreamObserver<Feature> responseObserver) {
            pointDelivered.set(point);
            responseObserver.onError(fakeError);
        }
    };
    serviceRegistry.addService(getFeatureImpl);
    client.getFeature(-1, -1);
    assertEquals(requestPoint, pointDelivered.get());
    ArgumentCaptor<Throwable> errorCaptor = ArgumentCaptor.forClass(Throwable.class);
    verify(testHelper).onRpcError(errorCaptor.capture());
    assertEquals(fakeError.getStatus(), Status.fromThrowable(errorCaptor.getValue()));
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) StatusRuntimeException(io.grpc.StatusRuntimeException) AtomicReference(java.util.concurrent.atomic.AtomicReference) RouteGuideImplBase(io.grpc.examples.routeguide.RouteGuideGrpc.RouteGuideImplBase) Test(org.junit.Test)

Example 8 with StatusRuntimeException

use of io.grpc.StatusRuntimeException in project grpc-java by grpc.

the class CascadingTest method startChainingServer.

/**
   * Create a chain of client to server calls which can be cancelled top down.
   *
   * @return a Future that completes when call chain is created
   */
private Future<?> startChainingServer(final int depthThreshold) throws IOException {
    final AtomicInteger serversReady = new AtomicInteger();
    final SettableFuture<Void> chainReady = SettableFuture.create();
    class ChainingService extends TestServiceGrpc.TestServiceImplBase {

        @Override
        public void unaryCall(final SimpleRequest request, final StreamObserver<SimpleResponse> responseObserver) {
            ((ServerCallStreamObserver) responseObserver).setOnCancelHandler(new Runnable() {

                @Override
                public void run() {
                    receivedCancellations.countDown();
                }
            });
            if (serversReady.incrementAndGet() == depthThreshold) {
                // Stop recursion
                chainReady.set(null);
                return;
            }
            Context.currentContextExecutor(otherWork).execute(new Runnable() {

                @Override
                public void run() {
                    try {
                        blockingStub.unaryCall(request);
                    } catch (StatusRuntimeException e) {
                        Status status = e.getStatus();
                        if (status.getCode() == Status.Code.CANCELLED) {
                            observedCancellations.countDown();
                        } else {
                            responseObserver.onError(e);
                        }
                    }
                }
            });
        }
    }
    server = InProcessServerBuilder.forName("channel").executor(otherWork).addService(new ChainingService()).build().start();
    return chainReady;
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) ServerCallStreamObserver(io.grpc.stub.ServerCallStreamObserver) Status(io.grpc.Status) ServerCallStreamObserver(io.grpc.stub.ServerCallStreamObserver) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) StatusRuntimeException(io.grpc.StatusRuntimeException) SimpleRequest(io.grpc.testing.integration.Messages.SimpleRequest)

Example 9 with StatusRuntimeException

use of io.grpc.StatusRuntimeException in project grpc-java by grpc.

the class MoreInProcessTest method asyncClientStreaming_serverErrorPriorToRequest.

@Test
public void asyncClientStreaming_serverErrorPriorToRequest() throws Exception {
    // implement a service
    final Status fakeError = Status.INVALID_ARGUMENT;
    TestServiceImplBase clientStreamingImpl = new TestServiceImplBase() {

        @Override
        public StreamObserver<StreamingInputCallRequest> streamingInputCall(StreamObserver<StreamingInputCallResponse> responseObserver) {
            // send error directly
            responseObserver.onError(new StatusRuntimeException(fakeError));
            responseObserver.onCompleted();
            return new StreamObserver<StreamingInputCallRequest>() {

                @Override
                public void onNext(StreamingInputCallRequest value) {
                }

                @Override
                public void onError(Throwable t) {
                }

                @Override
                public void onCompleted() {
                }
            };
        }
    };
    serviceRegistry.addService(clientStreamingImpl);
    // implement a client
    final CountDownLatch finishLatch = new CountDownLatch(1);
    final AtomicReference<StreamingInputCallResponse> responseRef = new AtomicReference<StreamingInputCallResponse>();
    final AtomicReference<Throwable> throwableRef = new AtomicReference<Throwable>();
    StreamObserver<StreamingInputCallResponse> responseObserver = new StreamObserver<StreamingInputCallResponse>() {

        @Override
        public void onNext(StreamingInputCallResponse response) {
            responseRef.set(response);
        }

        @Override
        public void onError(Throwable t) {
            throwableRef.set(t);
            finishLatch.countDown();
        }

        @Override
        public void onCompleted() {
            finishLatch.countDown();
        }
    };
    // make a gRPC call
    TestServiceGrpc.newStub(inProcessChannel).streamingInputCall(responseObserver);
    assertTrue(finishLatch.await(900, TimeUnit.MILLISECONDS));
    assertEquals(fakeError.getCode(), Status.fromThrowable(throwableRef.get()).getCode());
    assertNull(responseRef.get());
}
Also used : Status(io.grpc.Status) StreamObserver(io.grpc.stub.StreamObserver) StreamingInputCallRequest(io.grpc.testing.integration.Messages.StreamingInputCallRequest) StatusRuntimeException(io.grpc.StatusRuntimeException) TestServiceImplBase(io.grpc.testing.integration.TestServiceGrpc.TestServiceImplBase) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) StreamingInputCallResponse(io.grpc.testing.integration.Messages.StreamingInputCallResponse) Test(org.junit.Test)

Example 10 with StatusRuntimeException

use of io.grpc.StatusRuntimeException in project grpc-java by grpc.

the class TlsTest method clientRejectsUntrustedServerCert.

/**
   * Tests that a client configured using GrpcSslContexts refuses to talk to a server that has an
   * an untrusted certificate.
   */
@Test
public void clientRejectsUntrustedServerCert() throws Exception {
    // Create & start a server.
    File serverCertFile = TestUtils.loadCert("badserver.pem");
    File serverPrivateKeyFile = TestUtils.loadCert("badserver.key");
    X509Certificate[] serverTrustedCaCerts = { TestUtils.loadX509Cert("ca.pem") };
    server = serverBuilder(0, serverCertFile, serverPrivateKeyFile, serverTrustedCaCerts).addService(new TestServiceImpl(executor)).build().start();
    // Create a client.
    File clientCertChainFile = TestUtils.loadCert("client.pem");
    File clientPrivateKeyFile = TestUtils.loadCert("client.key");
    X509Certificate[] clientTrustedCaCerts = { TestUtils.loadX509Cert("ca.pem") };
    channel = clientChannel(server.getPort(), clientContextBuilder.keyManager(clientCertChainFile, clientPrivateKeyFile).trustManager(clientTrustedCaCerts).build());
    TestServiceGrpc.TestServiceBlockingStub client = TestServiceGrpc.newBlockingStub(channel);
    // Check that the TLS handshake fails.
    Empty request = Empty.getDefaultInstance();
    try {
        client.emptyCall(request);
        fail("TLS handshake should have failed, but didn't; received RPC response");
    } catch (StatusRuntimeException e) {
        // GRPC reports this situation by throwing a StatusRuntimeException that wraps either a
        // javax.net.ssl.SSLHandshakeException or a java.nio.channels.ClosedChannelException.
        // Thus, reliably detecting the underlying cause is not feasible.
        // TODO(carl-mastrangelo): eventually replace this with a hamcrest matcher.
        assertEquals(Throwables.getStackTraceAsString(e), Status.Code.UNAVAILABLE, e.getStatus().getCode());
    }
}
Also used : Empty(com.google.protobuf.EmptyProtos.Empty) StatusRuntimeException(io.grpc.StatusRuntimeException) File(java.io.File) X509Certificate(java.security.cert.X509Certificate) Test(org.junit.Test)

Aggregations

StatusRuntimeException (io.grpc.StatusRuntimeException)125 Test (org.junit.Test)108 ApiException (com.google.api.gax.grpc.ApiException)74 ByteString (com.google.protobuf.ByteString)12 Status (io.grpc.Status)12 ArrayList (java.util.ArrayList)11 SubscriptionName (com.google.pubsub.v1.SubscriptionName)9 Metadata (io.grpc.Metadata)7 ProjectName (com.google.monitoring.v3.ProjectName)6 TopicName (com.google.pubsub.v1.TopicName)6 StreamObserver (io.grpc.stub.StreamObserver)6 ByteArrayInputStream (java.io.ByteArrayInputStream)6 Document (com.google.cloud.language.v1beta2.Document)5 ParentNameOneof (com.google.logging.v2.ParentNameOneof)5 ExecutionException (java.util.concurrent.ExecutionException)5 Document (com.google.cloud.language.v1.Document)4 EncodingType (com.google.cloud.language.v1beta2.EncodingType)4 HelloReply (io.grpc.examples.helloworld.HelloReply)4 HelloRequest (io.grpc.examples.helloworld.HelloRequest)4 IOException (java.io.IOException)4