io.grpc.ServerCall Java Examples

The following examples show how to use io.grpc.ServerCall. 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: ServerImpl.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
private <WReqT, WRespT> ServerStreamListener startWrappedCall(
    String fullMethodName,
    ServerMethodDefinition<WReqT, WRespT> methodDef,
    ServerStream stream,
    Metadata headers,
    Context.CancellableContext context,
    Tag tag) {

  ServerCallImpl<WReqT, WRespT> call = new ServerCallImpl<>(
      stream,
      methodDef.getMethodDescriptor(),
      headers,
      context,
      decompressorRegistry,
      compressorRegistry,
      serverCallTracer,
      tag);

  ServerCall.Listener<WReqT> listener =
      methodDef.getServerCallHandler().startCall(call, headers);
  if (listener == null) {
    throw new NullPointerException(
        "startCall() returned a null listener for method " + fullMethodName);
  }
  return call.newServerStreamListener(listener);
}
 
Example #2
Source File: ServerCallsTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void clientSendsOne_errorMissingRequest_serverStreaming() {
  ServerCallRecorder serverCall = new ServerCallRecorder(SERVER_STREAMING_METHOD);
  ServerCallHandler<Integer, Integer> callHandler =
      ServerCalls.asyncServerStreamingCall(
          new ServerCalls.ServerStreamingMethod<Integer, Integer>() {
            @Override
            public void invoke(Integer req, StreamObserver<Integer> responseObserver) {
              fail("should not be reached");
            }
          });
  ServerCall.Listener<Integer> listener = callHandler.startCall(serverCall, new Metadata());
  listener.onHalfClose();
  assertThat(serverCall.responses).isEmpty();
  assertEquals(Status.Code.INTERNAL, serverCall.status.getCode());
  assertEquals(ServerCalls.MISSING_REQUEST, serverCall.status.getDescription());

}
 
Example #3
Source File: ServerCallsTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void disablingInboundAutoFlowControlSuppressesRequestsForMoreMessages() throws Exception {
  ServerCallHandler<Integer, Integer> callHandler =
      ServerCalls.asyncBidiStreamingCall(
          new ServerCalls.BidiStreamingMethod<Integer, Integer>() {
            @Override
            public StreamObserver<Integer> invoke(StreamObserver<Integer> responseObserver) {
              ServerCallStreamObserver<Integer> serverCallObserver =
                  (ServerCallStreamObserver<Integer>) responseObserver;
              serverCallObserver.disableAutoInboundFlowControl();
              return new ServerCalls.NoopStreamObserver<>();
            }
          });
  ServerCall.Listener<Integer> callListener =
      callHandler.startCall(serverCall, new Metadata());
  callListener.onReady();
  // Transport should not call this if nothing has been requested but forcing it here
  // to verify that message delivery does not trigger a call to request(1).
  callListener.onMessage(1);
  // Should never be called
  assertThat(serverCall.requestCalls).isEmpty();
}
 
Example #4
Source File: BinaryLogProviderTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
private static <ReqT, RespT> ServerCall.Listener<ReqT> startServerCallHelper(
    final ServerMethodDefinition<ReqT, RespT> methodDef,
    final List<Object> serializedResp) {
  ServerCall<ReqT, RespT> serverCall = new NoopServerCall<ReqT, RespT>() {
    @Override
    public void sendMessage(RespT message) {
      serializedResp.add(message);
    }

    @Override
    public MethodDescriptor<ReqT, RespT> getMethodDescriptor() {
      return methodDef.getMethodDescriptor();
    }
  };
  return methodDef.getServerCallHandler().startCall(serverCall, new Metadata());
}
 
Example #5
Source File: RPCTracingHelpers.java    From pravega with Apache License 2.0 6 votes vote down vote up
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, final Metadata headers,
                                                             ServerCallHandler<ReqT, RespT> next) {
    // Check if this RPC has tags to track request (e.g., older clients).
    if (headers != null && headers.containsKey(DESCRIPTOR_HEADER) && headers.containsKey(ID_HEADER)) {
        RequestTag requestTag = new RequestTag(headers.get(DESCRIPTOR_HEADER), Long.parseLong(headers.get(ID_HEADER)));
        requestTracker.trackRequest(requestTag);
        log.debug(requestTag.getRequestId(), "Received tag from RPC request {}.",
                requestTag.getRequestDescriptor());
    } else {
        log.debug("No tags provided for call {} in headers: {}.", call.getMethodDescriptor().getFullMethodName(),
                headers);
    }

    return next.startCall(new ForwardingServerCall.SimpleForwardingServerCall<ReqT, RespT>(call) {
        @Override
        public void sendHeaders(Metadata responseHeaders) {
            super.sendHeaders(responseHeaders);
        }
    }, headers);
}
 
Example #6
Source File: ServerCallsTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void cannotDisableAutoRequestAfterServiceInvocation() throws Exception {
  final AtomicReference<ServerCallStreamObserver<Integer>> callObserver =
      new AtomicReference<>();
  ServerCallHandler<Integer, Integer> callHandler =
      ServerCalls.asyncBidiStreamingCall(
          new ServerCalls.BidiStreamingMethod<Integer, Integer>() {
            @Override
            public StreamObserver<Integer> invoke(StreamObserver<Integer> responseObserver) {
              callObserver.set((ServerCallStreamObserver<Integer>) responseObserver);
              return new ServerCalls.NoopStreamObserver<>();
            }
          });
  ServerCall.Listener<Integer> callListener =
      callHandler.startCall(serverCall, new Metadata());
  callListener.onMessage(1);
  try {
    callObserver.get().disableAutoRequest();
    fail("Cannot set onCancel handler after service invocation");
  } catch (IllegalStateException expected) {
    // Expected
  }
}
 
Example #7
Source File: ServerImplTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testStreamClose_clientOkTriggersDelayedCancellation() throws Exception {
  AtomicBoolean contextCancelled = new AtomicBoolean(false);
  AtomicReference<Context> context = new AtomicReference<>();
  AtomicReference<ServerCall<String, Integer>> callReference = new AtomicReference<>();

  ServerStreamListener streamListener = testStreamClose_setup(callReference,
      context, contextCancelled, null);

  // For close status OK:
  // isCancelled is expected to be true after all pending work is done
  assertFalse(callReference.get().isCancelled());
  assertFalse(context.get().isCancelled());
  streamListener.closed(Status.OK);
  assertFalse(callReference.get().isCancelled());
  assertFalse(context.get().isCancelled());

  assertEquals(1, executor.runDueTasks());
  assertTrue(callReference.get().isCancelled());
  assertTrue(context.get().isCancelled());
  assertTrue(contextCancelled.get());
}
 
Example #8
Source File: ServerCallListenerInstrumentation.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
@Advice.OnMethodExit(suppress = Throwable.class, onThrowable = Throwable.class)
private static void onExit(@Advice.Thrown @Nullable Throwable thrown,
                           @Advice.This ServerCall.Listener<?> listener,
                           @Advice.Local("transaction") @Nullable Transaction transaction) {

    if (null == tracer || grpcHelperManager == null || transaction == null) {
        return;
    }

    GrpcHelper helper = grpcHelperManager.getForClassLoaderOfClass(ServerCall.Listener.class);
    if (helper == null) {
        return;
    }

    helper.exitServerListenerMethod(thrown, listener, transaction, false);
}
 
Example #9
Source File: ServerCallListenerInstrumentation.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
@Advice.OnMethodExit(suppress = Throwable.class, onThrowable = Throwable.class)
private static void onExit(@Advice.Thrown @Nullable Throwable thrown,
                           @Advice.This ServerCall.Listener<?> listener,
                           @Advice.Local("transaction") @Nullable Transaction transaction) {

    if (null == tracer || grpcHelperManager == null) {
        return;
    }

    GrpcHelper helper = grpcHelperManager.getForClassLoaderOfClass(ServerCall.Listener.class);
    if (helper == null) {
        return;
    }

    helper.exitServerListenerMethod(thrown, listener, transaction, true);
}
 
Example #10
Source File: TransportCompressionTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Override
protected AbstractServerImplBuilder<?> getServerBuilder() {
  return NettyServerBuilder.forPort(0)
      .maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE)
      .compressorRegistry(compressors)
      .decompressorRegistry(decompressors)
      .intercept(new ServerInterceptor() {
          @Override
          public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call,
              Metadata headers, ServerCallHandler<ReqT, RespT> next) {
            Listener<ReqT> listener = next.startCall(call, headers);
            // TODO(carl-mastrangelo): check that encoding was set.
            call.setMessageCompression(true);
            return listener;
          }
        });
}
 
Example #11
Source File: ServerCallHandlerInstrumentation.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
@Advice.OnMethodExit(suppress = Throwable.class, onThrowable = Throwable.class)
private static void onExit(@Advice.Thrown @Nullable Throwable thrown,
                           @Advice.Argument(0) ServerCall<?, ?> serverCall,
                           @Advice.Return ServerCall.Listener<?> listener,
                           @Advice.Local("transaction") @Nullable Transaction transaction) {

    if (transaction == null) {
        return;
    }
    if (thrown != null) {
        // terminate transaction in case of exception as it won't be stored
        transaction.deactivate().end();
        return;
    }

    GrpcHelper helper = grpcHelperManager.getForClassLoaderOfClass(ServerCall.class);
    if (helper != null) {
        helper.registerTransaction(serverCall, listener, transaction);
    }

}
 
Example #12
Source File: DebugServerInterceptor.java    From grpc-java-contrib with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers,
        ServerCallHandler<ReqT, RespT> next) {
    logMethod(REQUEST, call.getMethodDescriptor());
    logHeaders(REQUEST, headers);
    return new ForwardingServerCallListener.SimpleForwardingServerCallListener<ReqT>(
            next.startCall(new SimpleForwardingServerCall<ReqT, RespT>(call) {

                @Override
                public void sendHeaders(Metadata responseHeaders) {
                    logMethod(RESPONSE, call.getMethodDescriptor());
                    logHeaders(RESPONSE, responseHeaders);
                    super.sendHeaders(responseHeaders);
                }

                @Override
                public void sendMessage(RespT message) {
                    logMessage(RESPONSE, message);
                    super.sendMessage(message);
                }
            }, headers)) {
 
Example #13
Source File: ConnectionInterceptor.java    From rpc-bench with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("checkstyle:MethodTypeParameterName")
@Override
public <ReqT, RespT> Listener<ReqT> interceptCall(
    final ServerCall<ReqT, RespT> call, final Metadata headers,
    final ServerCallHandler<ReqT, RespT> next) {
  TL.set(call);

  return next.startCall(new SimpleForwardingServerCall<ReqT, RespT>(call) {
    @Override
    public void close(final Status status, final Metadata trailers) {
      super.close(status, trailers);
      TL.remove();
    }

  }, headers);
}
 
Example #14
Source File: AuthorizationCheckingServerInterceptor.java    From grpc-spring-boot-starter with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <ReqT, RespT> Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> call, final Metadata headers,
        final ServerCallHandler<ReqT, RespT> next) {
    final MethodDescriptor<ReqT, RespT> methodDescriptor = call.getMethodDescriptor();
    final InterceptorStatusToken token;
    try {
        token = beforeInvocation(methodDescriptor);
    } catch (final AuthenticationException | AccessDeniedException e) {
        log.debug("Access denied");
        throw e;
    }
    log.debug("Access granted");
    final Listener<ReqT> result;
    try {
        result = next.startCall(call, headers);
    } finally {
        finallyInvocation(token);
    }
    // TODO: Call that here or in onHalfClose?
    return (Listener<ReqT>) afterInvocation(token, result);
}
 
Example #15
Source File: TracingServerInterceptor.java    From brave with Apache License 2.0 6 votes vote down vote up
@Override
public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call,
  Metadata headers, ServerCallHandler<ReqT, RespT> next) {
  GrpcServerRequest request = new GrpcServerRequest(nameToKey, call, headers);

  Span span = handler.handleReceive(request);
  AtomicReference<Span> spanRef = new AtomicReference<>(span);

  // startCall invokes user interceptors, so we place the span in scope here
  Listener<ReqT> result;
  try (Scope scope = currentTraceContext.maybeScope(span.context())) {
    result = next.startCall(new TracingServerCall<>(call, span, spanRef, request), headers);
  } catch (Throwable e) {
    // Another interceptor may throw an exception during startCall, in which case no other
    // callbacks are called, so go ahead and close the span here.
    //
    // See instrumentation/grpc/RATIONALE.md for why we don't use the handler here
    spanRef.set(null);
    if (span != null) span.error(e).finish();
    throw e;
  }

  return new TracingServerCallListener<>(result, span, spanRef, request);
}
 
Example #16
Source File: HeaderServerInterceptor.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
    ServerCall<ReqT, RespT> call,
    final Metadata requestHeaders,
    ServerCallHandler<ReqT, RespT> next) {
  logger.info("header received from client:" + requestHeaders);
  return next.startCall(new SimpleForwardingServerCall<ReqT, RespT>(call) {
    @Override
    public void sendHeaders(Metadata responseHeaders) {
      responseHeaders.put(CUSTOM_HEADER_KEY, "customRespondValue");
      super.sendHeaders(responseHeaders);
    }
  }, requestHeaders);
}
 
Example #17
Source File: AltsServerBuilder.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public <ReqT, RespT> Listener<ReqT> interceptCall(
    ServerCall<ReqT, RespT> serverCall,
    Metadata metadata,
    ServerCallHandler<ReqT, RespT> nextHandler) {
  serverCall.close(status, new Metadata());
  return new Listener<ReqT>() {};
}
 
Example #18
Source File: ServerAuthInterceptor.java    From startup-os with Apache License 2.0 5 votes vote down vote up
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
    ServerCall<ReqT, RespT> serverCall,
    Metadata metadata,
    ServerCallHandler<ReqT, RespT> serverCallHandler) {
  String token = metadata.get(Metadata.Key.of("token", ASCII_STRING_MARSHALLER));
  System.out.println("Token: " + token);

  boolean tokenIsValid = false;

  try {
    FirebaseToken firebaseToken = FirebaseAuth.getInstance().verifyIdToken(token);
    System.err.println("Email for token: " + firebaseToken.getEmail());

    // TODO: properly validate whether user has rights
    //noinspection ConstantConditions
    if (true) {
      tokenIsValid = true;
    }

  } catch (Exception e) {
    e.printStackTrace();
    System.err.println("Was unable to parse token");
  }

  if (!tokenIsValid) {
    serverCall.close(Status.UNAUTHENTICATED, metadata);
    return new ServerCall.Listener<ReqT>() {};
  } else {
    return serverCallHandler.startCall(serverCall, metadata);
  }
}
 
Example #19
Source File: ServerCallListenerInstrumentation.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Advice.OnMethodEnter(suppress = Throwable.class)
private static void onEnter(@Advice.This ServerCall.Listener<?> listener,
                            @Advice.Local("transaction") Transaction transaction) {

    if (null == tracer || grpcHelperManager == null) {
        return;
    }

    GrpcHelper helper = grpcHelperManager.getForClassLoaderOfClass(ServerCall.Listener.class);
    if (helper == null) {
        return;
    }

    transaction = helper.enterServerListenerMethod(listener);
}
 
Example #20
Source File: ServerCallListenerInstrumentation.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Advice.OnMethodEnter(suppress = Throwable.class)
private static void onEnter(@Advice.This ServerCall.Listener<?> listener,
                            @Advice.Local("transaction") Transaction transaction) {

    if (null == tracer || grpcHelperManager == null) {
        return;
    }

    GrpcHelper helper = grpcHelperManager.getForClassLoaderOfClass(ServerCall.Listener.class);
    if (helper == null) {
        return;
    }

    transaction = helper.enterServerListenerMethod(listener);
}
 
Example #21
Source File: GrpcHelperImpl.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Override
public void setTransactionStatus(Status status, @Nullable Throwable thrown, ServerCall<?, ?> serverCall) {
    Transaction transaction = serverCallTransactions.remove(serverCall);

    if (transaction != null) {
        setTransactionStatus(status, thrown, transaction);
        if (thrown != null) {
            // transaction ended due to an exception, we have to end it
            transaction.end();
        }
    }
}
 
Example #22
Source File: PasswordAuthInterceptor.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> serverCall, Metadata headers,
                                                             ServerCallHandler<ReqT, RespT> serverCallHandler) {
    var actualPasswordValue = headers.get(Key.of(PASSWORD_KEY, ASCII_STRING_MARSHALLER));

    if (actualPasswordValue == null)
        throw new StatusRuntimeException(UNAUTHENTICATED.withDescription(
                format("missing '%s' rpc header value", PASSWORD_KEY)));

    if (!actualPasswordValue.equals(expectedPasswordValue))
        throw new StatusRuntimeException(UNAUTHENTICATED.withDescription(
                format("incorrect '%s' rpc header value", PASSWORD_KEY)));

    return serverCallHandler.startCall(serverCall, headers);
}
 
Example #23
Source File: AbstractInteropTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
/**
 * Captures the request attributes. Useful for testing ServerCalls.
 * {@link ServerCall#getAttributes()}
 */
private static ServerInterceptor recordServerCallInterceptor(
    final AtomicReference<ServerCall<?, ?>> serverCallCapture) {
  return new ServerInterceptor() {
    @Override
    public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
        ServerCall<ReqT, RespT> call,
        Metadata requestHeaders,
        ServerCallHandler<ReqT, RespT> next) {
      serverCallCapture.set(call);
      return next.startCall(call, requestHeaders);
    }
  };
}
 
Example #24
Source File: BaseITTracingServerInterceptor.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void userInterceptor_throwsOnStartCall() throws IOException {
  init(new ServerInterceptor() {
    @Override public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
        ServerCall<ReqT, RespT> call, Metadata metadata, ServerCallHandler<ReqT, RespT> next) {
      throw new IllegalStateException("I'm a bad interceptor.");
    }
  });

  assertThatThrownBy(() -> GreeterGrpc.newBlockingStub(client).sayHello(HELLO_REQUEST))
      .isInstanceOf(StatusRuntimeException.class);
  testSpanHandler.takeRemoteSpanWithErrorMessage(Span.Kind.SERVER, "I'm a bad interceptor.");
}
 
Example #25
Source File: GrpcOpenCensusInterceptor.java    From heroic with Apache License 2.0 5 votes vote down vote up
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
    final ServerCall<ReqT, RespT> call, final Metadata headers,
    final ServerCallHandler<ReqT, RespT> next) {

    final Span span = tracer.getCurrentSpan();
    span.putAttributes(environmentMetadata.toAttributes());
    span.putAttribute("protocol", stringAttributeValue("grpc"));
    span.putAttribute("span.kind", stringAttributeValue("server"));

    tracingConfig.getTags().forEach(
        (key, value) -> span.putAttribute(key, stringAttributeValue(value)));

    return next.startCall(call, headers);
}
 
Example #26
Source File: MetricCollectingServerInterceptor.java    From grpc-spring-boot-starter with MIT License 5 votes vote down vote up
@Override
public <Q, A> ServerCall.Listener<Q> interceptCall(
        final ServerCall<Q, A> call,
        final Metadata requestHeaders,
        final ServerCallHandler<Q, A> next) {
    final MetricSet metrics = metricsFor(call.getMethodDescriptor());
    final ServerCall<Q, A> monitoringCall = new MetricCollectingServerCall<>(call, this.registry,
            metrics.getResponseCounter(), metrics.getTimerFunction());
    return new MetricCollectingServerCallListener<>(
            next.startCall(monitoringCall, requestHeaders), metrics.getRequestCounter());
}
 
Example #27
Source File: CommonErrorCatchingServerInterceptor.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
private <ReqT, RespT> void handlingException(ServerCall<ReqT, RespT> call, Exception e, boolean debug) {
    logger.info("Returning exception to the client: {}", e.getMessage(), e);
    Pair<Status, Metadata> statusAndMeta = exceptionMapper.of(e, debug);
    Status status = statusAndMeta.getLeft();
    safeClose(() -> call.close(status, statusAndMeta.getRight()));
    throw status.asRuntimeException();
}
 
Example #28
Source File: ServerImplTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void exceptionInStartCallPropagatesToStream() throws Exception {
  createAndStartServer();
  final Status status = Status.ABORTED.withDescription("Oh, no!");
  mutableFallbackRegistry.addService(ServerServiceDefinition.builder(
      new ServiceDescriptor("Waiter", METHOD))
      .addMethod(METHOD,
          new ServerCallHandler<String, Integer>() {
            @Override
            public ServerCall.Listener<String> startCall(
                ServerCall<String, Integer> call,
                Metadata headers) {
              throw status.asRuntimeException();
            }
          }).build());
  ServerTransportListener transportListener
      = transportServer.registerNewServerTransport(new SimpleServerTransport());
  transportListener.transportReady(Attributes.EMPTY);

  Metadata requestHeaders = new Metadata();
  StatsTraceContext statsTraceCtx =
      StatsTraceContext.newServerContext(streamTracerFactories, "Waiter/serve", requestHeaders);
  when(stream.statsTraceContext()).thenReturn(statsTraceCtx);

  transportListener.streamCreated(stream, "Waiter/serve", requestHeaders);
  verify(stream).streamId();
  verify(stream).setListener(streamListenerCaptor.capture());
  ServerStreamListener streamListener = streamListenerCaptor.getValue();
  assertNotNull(streamListener);
  verify(stream, atLeast(1)).statsTraceContext();
  verifyNoMoreInteractions(stream);
  verify(fallbackRegistry, never()).lookupMethod(any(String.class), any(String.class));

  assertEquals(1, executor.runDueTasks());
  verify(fallbackRegistry).lookupMethod("Waiter/serve", AUTHORITY);
  verify(stream).close(same(status), ArgumentMatchers.<Metadata>notNull());
  verify(stream, atLeast(1)).statsTraceContext();
}
 
Example #29
Source File: ServerCallsTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void cannotSetOnCancelHandlerAfterServiceInvocation() throws Exception {
  final AtomicReference<ServerCallStreamObserver<Integer>> callObserver =
      new AtomicReference<ServerCallStreamObserver<Integer>>();
  ServerCallHandler<Integer, Integer> callHandler =
      ServerCalls.asyncBidiStreamingCall(
          new ServerCalls.BidiStreamingMethod<Integer, Integer>() {
            @Override
            public StreamObserver<Integer> invoke(StreamObserver<Integer> responseObserver) {
              callObserver.set((ServerCallStreamObserver<Integer>) responseObserver);
              return new ServerCalls.NoopStreamObserver<Integer>();
            }
          });
  ServerCall.Listener<Integer> callListener =
      callHandler.startCall(serverCall, new Metadata());
  callListener.onMessage(1);
  try {
    callObserver.get().setOnCancelHandler(new Runnable() {
      @Override
      public void run() {
      }
    });
    fail("Cannot set onCancel handler after service invocation");
  } catch (IllegalStateException expected) {
    // Expected
  }
}
 
Example #30
Source File: ServerCalls.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Override
public ServerCall.Listener<ReqT> startCall(ServerCall<ReqT, RespT> call, Metadata headers) {
  Preconditions.checkArgument(
      call.getMethodDescriptor().getType().clientSendsOneMessage(),
      "asyncUnaryRequestCall is only for clientSendsOneMessage methods");
  ServerCallStreamObserverImpl<ReqT, RespT> responseObserver =
      new ServerCallStreamObserverImpl<ReqT, RespT>(call);
  // We expect only 1 request, but we ask for 2 requests here so that if a misbehaving client
  // sends more than 1 requests, ServerCall will catch it. Note that disabling auto
  // inbound flow control has no effect on unary calls.
  call.request(2);
  return new UnaryServerCallListener(responseObserver, call);
}