io.grpc.ServerCall.Listener Java Examples

The following examples show how to use io.grpc.ServerCall.Listener. 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: 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 #2
Source File: ServerInterceptorsTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void callNextTwice() {
  ServerInterceptor interceptor = new ServerInterceptor() {
    @Override
    public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
        ServerCall<ReqT, RespT> call,
        Metadata headers,
        ServerCallHandler<ReqT, RespT> next) {
      // Calling next twice is permitted, although should only rarely be useful.
      assertSame(listener, next.startCall(call, headers));
      return next.startCall(call, headers);
    }
  };
  ServerServiceDefinition intercepted = ServerInterceptors.intercept(serviceDefinition,
      interceptor);
  assertSame(listener,
      getSoleMethod(intercepted).getServerCallHandler().startCall(call, headers));
  verify(handler, times(2)).startCall(same(call), same(headers));
  verifyNoMoreInteractions(handler);
}
 
Example #3
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 #4
Source File: ServerInterceptorsTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void argumentsPassed() {
  @SuppressWarnings("unchecked")
  final ServerCall<String, Integer> call2 = new NoopServerCall<String, Integer>();
  @SuppressWarnings("unchecked")
  final ServerCall.Listener<String> listener2 = mock(ServerCall.Listener.class);

  ServerInterceptor interceptor = new ServerInterceptor() {
      @SuppressWarnings("unchecked") // Lot's of casting for no benefit.  Not intended use.
      @Override
      public <R1, R2> ServerCall.Listener<R1> interceptCall(
          ServerCall<R1, R2> call,
          Metadata headers,
          ServerCallHandler<R1, R2> next) {
        assertSame(call, ServerInterceptorsTest.this.call);
        assertSame(listener,
            next.startCall((ServerCall<R1, R2>)call2, headers));
        return (ServerCall.Listener<R1>) listener2;
      }
    };
  ServerServiceDefinition intercepted = ServerInterceptors.intercept(
      serviceDefinition, Arrays.asList(interceptor));
  assertSame(listener2,
      getSoleMethod(intercepted).getServerCallHandler().startCall(call, headers));
  verify(handler).startCall(call2, headers);
}
 
Example #5
Source File: TransportCompressionTest.java    From grpc-nebula-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 #6
Source File: GrpcMonitoringInterceptor.java    From feast 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) {

  long startCallMillis = System.currentTimeMillis();
  String fullMethodName = call.getMethodDescriptor().getFullMethodName();
  String methodName = fullMethodName.substring(fullMethodName.indexOf("/") + 1);

  return next.startCall(
      new SimpleForwardingServerCall<ReqT, RespT>(call) {
        @Override
        public void close(Status status, Metadata trailers) {
          Metrics.requestLatency
              .labels(methodName)
              .observe((System.currentTimeMillis() - startCallMillis) / 1000f);
          Metrics.grpcRequestCount.labels(methodName, status.getCode().name()).inc();
          super.close(status, trailers);
        }
      },
      headers);
}
 
Example #7
Source File: MonitoringInterceptor.java    From feast 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) {

  long startCallMillis = System.currentTimeMillis();
  String fullMethodName = call.getMethodDescriptor().getFullMethodName();
  String serviceName = MethodDescriptor.extractFullServiceName(fullMethodName);
  String methodName = fullMethodName.substring(fullMethodName.indexOf("/") + 1);

  return next.startCall(
      new SimpleForwardingServerCall<ReqT, RespT>(call) {
        @Override
        public void close(Status status, Metadata trailers) {
          GrpcMetrics.requestLatency
              .labels(serviceName, methodName, status.getCode().name())
              .observe((System.currentTimeMillis() - startCallMillis) / 1000f);
          super.close(status, trailers);
        }
      },
      headers);
}
 
Example #8
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 #9
Source File: LeaderServerInterceptor.java    From titus-control-plane 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) {

    if (SupervisorServiceGrpc.getServiceDescriptor().getMethods().contains(call.getMethodDescriptor())) {
        // Supervisor API calls are not restricted to the active leader.
        return next.startCall(call, headers);
    }

    if (leaderActivator.isLeader()) {
        if (leaderActivator.isActivated()) {
            return next.startCall(call, headers);
        } else {
            call.close(Status.UNAVAILABLE.withDescription("Titus Master is initializing and not yet available."), new Metadata());
            return new ServerCall.Listener<ReqT>() {
            };
        }
    } else {
        call.close(Status.UNAVAILABLE.withDescription("Titus Master is not leader."), new Metadata());
        return new ServerCall.Listener<ReqT>() {
        };
    }
}
 
Example #10
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 #11
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 #12
Source File: ExternalRpcServer.java    From seldon-server 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) {
	logger.info("Call intercepted "+headers.toString());
	String token = headers.get(authKey);
	if (StringUtils.notEmpty(token))
	{
		try
		{
			logger.info("Token "+token);
			ConsumerBean consumer = resourceServer.validateResourceFromToken(token);
			logger.info("Setting call to client "+consumer.getShort_name());
			return new SeldonServerCallListener<ReqT>(next.startCall(call, headers),consumer.getShort_name(),this);
		}
		catch (APIException e)
		{
			logger.warn("API exception on getting token ",e);
			return next.startCall(call, headers);
		}
	}
	else
	{
		logger.warn("Empty token ignoring call");
		return next.startCall(call, headers);
	}
}
 
Example #13
Source File: GrpcServiceServerTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
public <REQ, RESP> Listener<REQ> interceptCall(ServerCall<REQ, RESP> call, Metadata headers,
                                               ServerCallHandler<REQ, RESP> next) {
    if (!call.getMethodDescriptor().equals(UnitTestServiceGrpc.getErrorReplaceExceptionMethod())) {
        return next.startCall(call, headers);
    }
    return next.startCall(new SimpleForwardingServerCall<REQ, RESP>(call) {
        @Override
        public void close(Status status, Metadata trailers) {
            if (status.getCause() instanceof IllegalStateException &&
                status.getCause().getMessage().equals("This error should be replaced")) {
                status = status.withDescription("Error was replaced");
            }
            delegate().close(status, trailers);
        }
    }, headers);
}
 
Example #14
Source File: HedgingHelloWorldServer.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Override
public <HelloRequestT, HelloReplyT> Listener<HelloRequestT> interceptCall(
    ServerCall<HelloRequestT, HelloReplyT> call,
    Metadata headers, ServerCallHandler<HelloRequestT, HelloReplyT> next) {
  int random = new Random().nextInt(100);
  long delay = 0;
  if (random < 1) {
    delay = 10_000;
  } else if (random < 5) {
    delay = 5_000;
  } else if (random < 10) {
    delay = 2_000;
  }

  if (delay > 0) {
    try {
      Thread.sleep(delay);
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    }
  }
  return next.startCall(call, headers);
}
 
Example #15
Source File: ServerInterceptorsTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void callNextTwice() {
  ServerInterceptor interceptor = new ServerInterceptor() {
    @Override
    public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
        ServerCall<ReqT, RespT> call,
        Metadata headers,
        ServerCallHandler<ReqT, RespT> next) {
      // Calling next twice is permitted, although should only rarely be useful.
      assertSame(listener, next.startCall(call, headers));
      return next.startCall(call, headers);
    }
  };
  ServerServiceDefinition intercepted = ServerInterceptors.intercept(serviceDefinition,
      interceptor);
  assertSame(listener,
      getSoleMethod(intercepted).getServerCallHandler().startCall(call, headers));
  verify(handler, times(2)).startCall(same(call), same(headers));
  verifyNoMoreInteractions(handler);
}
 
Example #16
Source File: ServerInterceptorsTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void argumentsPassed() {
  @SuppressWarnings("unchecked")
  final ServerCall<String, Integer> call2 = new NoopServerCall<>();
  @SuppressWarnings("unchecked")
  final ServerCall.Listener<String> listener2 = mock(ServerCall.Listener.class);

  ServerInterceptor interceptor = new ServerInterceptor() {
      @SuppressWarnings("unchecked") // Lot's of casting for no benefit.  Not intended use.
      @Override
      public <R1, R2> ServerCall.Listener<R1> interceptCall(
          ServerCall<R1, R2> call,
          Metadata headers,
          ServerCallHandler<R1, R2> next) {
        assertSame(call, ServerInterceptorsTest.this.call);
        assertSame(listener,
            next.startCall((ServerCall<R1, R2>)call2, headers));
        return (ServerCall.Listener<R1>) listener2;
      }
    };
  ServerServiceDefinition intercepted = ServerInterceptors.intercept(
      serviceDefinition, Arrays.asList(interceptor));
  assertSame(listener2,
      getSoleMethod(intercepted).getServerCallHandler().startCall(call, headers));
  verify(handler).startCall(call2, headers);
}
 
Example #17
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 #18
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 #19
Source File: GrpcRequestScope.java    From grpc-spring-boot-starter with MIT License 5 votes vote down vote up
@Override
public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers,
        ServerCallHandler<ReqT, RespT> next) {
    ScopedBeansContainer container = new ScopedBeansContainer();
    Context context = Context.current().withValue(GRPC_REQUEST_KEY, container);
    context.addListener(this, MoreExecutors.directExecutor());
    return Contexts.interceptCall(context, call, headers, next);
}
 
Example #20
Source File: ProtoReflectionServiceInterceptor.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public <I, O> Listener<I> interceptCall(ServerCall<I, O> call, Metadata headers,
                                        ServerCallHandler<I, O> next) {
    // Should set server before calling this
    assert server != null;

    final Context context = Context.current().withValue(InternalServer.SERVER_CONTEXT_KEY, server);
    return Contexts.interceptCall(context, call, headers, next);
}
 
Example #21
Source File: OrcaMetricReportingServerInterceptor.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> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
  Context ctx = Context.current();
  CallMetricRecorder callMetricRecorder = InternalCallMetricRecorder.CONTEXT_KEY.get(ctx);
  if (callMetricRecorder == null) {
    callMetricRecorder = InternalCallMetricRecorder.newCallMetricRecorder();
    ctx = ctx.withValue(InternalCallMetricRecorder.CONTEXT_KEY, callMetricRecorder);
  }
  final CallMetricRecorder finalCallMetricRecorder = callMetricRecorder;
  ServerCall<ReqT, RespT> trailerAttachingCall =
      new SimpleForwardingServerCall<ReqT, RespT>(call) {
        @Override
        public void close(Status status, Metadata trailers) {
          Map<String, Double> metricValues =
              InternalCallMetricRecorder.finalizeAndDump(finalCallMetricRecorder);
          // Only attach a metric report if there are some metric values to be reported.
          if (!metricValues.isEmpty()) {
            OrcaLoadReport report =
                OrcaLoadReport.newBuilder().putAllRequestCost(metricValues).build();
            trailers.put(ORCA_ENDPOINT_LOAD_METRICS_KEY, report);
          }
          super.close(status, trailers);
        }
      };
  return Contexts.interceptCall(
      ctx,
      trailerAttachingCall,
      headers,
      next);
}
 
Example #22
Source File: ModelDBAuthInterceptor.java    From modeldb with Apache License 2.0 5 votes vote down vote up
/**
 * @param call: ServerCall
 * @param requestHeaders : Metadata request headers
 * @param next: ServerCallHandler
 * @param <R>: Request
 * @param <S>: Response
 * @return {@link Contexts}
 */
@Override
public <R, S> Listener<R> interceptCall(
    ServerCall<R, S> call, Metadata requestHeaders, ServerCallHandler<R, S> next) {
  LOGGER.trace("Headers : {}", requestHeaders);
  String methodName = call.getMethodDescriptor().getFullMethodName();
  if (!ModelDBConstants.GRPC_HEALTH_CHECK_METHOD_NAME.equalsIgnoreCase(methodName)) {
    LOGGER.info("methodName: {}", methodName);
  }
  Context context =
      Context.current()
          .withValue(METADATA_INFO, requestHeaders)
          .withValue(METHOD_NAME, methodName);
  ServerCall.Listener<R> delegate = Contexts.interceptCall(context, call, requestHeaders, next);
  ACTIVE_REQUEST_COUNT.incrementAndGet();
  LOGGER.trace("Active Request count {}", ACTIVE_REQUEST_COUNT.get());
  return new ForwardingServerCallListener.SimpleForwardingServerCallListener<R>(delegate) {

    @Override
    public void onCancel() {
      ACTIVE_REQUEST_COUNT.decrementAndGet();
      LOGGER.trace("Decrease Request count oon onCancel()");
      LOGGER.trace("Active Request count {}", ACTIVE_REQUEST_COUNT.get());
      super.onCancel();
    }

    @Override
    public void onComplete() {
      ACTIVE_REQUEST_COUNT.decrementAndGet();
      LOGGER.trace("Decrease Request count on onComplete()");
      LOGGER.trace("Active Request count {}", ACTIVE_REQUEST_COUNT.get());
      super.onComplete();
    }
  };
}
 
Example #23
Source File: HandlerRegistryBenchmark.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
/**
 * Set up the registry.
 */
@Setup(Level.Trial)
public void setup() throws Exception {
  registry = new MutableHandlerRegistry();
  fullMethodNames = new ArrayList<>(serviceCount * methodCountPerService);
  for (int serviceIndex = 0; serviceIndex < serviceCount; ++serviceIndex) {
    String serviceName = randomString();
    ServerServiceDefinition.Builder serviceBuilder = ServerServiceDefinition.builder(serviceName);
    for (int methodIndex = 0; methodIndex < methodCountPerService; ++methodIndex) {
      String methodName = randomString();

      MethodDescriptor<Void, Void> methodDescriptor = MethodDescriptor.<Void, Void>newBuilder()
          .setType(MethodDescriptor.MethodType.UNKNOWN)
          .setFullMethodName(MethodDescriptor.generateFullMethodName(serviceName, methodName))
          .setRequestMarshaller(TestMethodDescriptors.voidMarshaller())
          .setResponseMarshaller(TestMethodDescriptors.voidMarshaller())
          .build();
      serviceBuilder.addMethod(methodDescriptor,
          new ServerCallHandler<Void, Void>() {
            @Override
            public Listener<Void> startCall(ServerCall<Void, Void> call,
                Metadata headers) {
              return null;
            }
          });
      fullMethodNames.add(methodDescriptor.getFullMethodName());
    }
    registry.addService(serviceBuilder.build());
  }
}
 
Example #24
Source File: AltsServerBuilder.java    From grpc-nebula-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 #25
Source File: CompressingHelloWorldServerAllMethods.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
private void start() throws IOException {
  /* The port on which the server should run */
  int port = 50051;
  server = ServerBuilder.forPort(port)
      /* This method call adds the Interceptor to enable compressed server responses for all RPCs */
      .intercept(new ServerInterceptor() {
        @Override
        public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers,
            ServerCallHandler<ReqT, RespT> next) {
          call.setCompression("gzip");
          return next.startCall(call, headers);
        }
      })
      .addService(new GreeterImpl())
      .build()
      .start();
  logger.info("Server started, listening on " + port);
  Runtime.getRuntime().addShutdownHook(new Thread() {
    @Override
    public void run() {
      // Use stderr here since the logger may have been reset by its JVM shutdown hook.
      System.err.println("*** shutting down gRPC server since JVM is shutting down");
      try {
        CompressingHelloWorldServerAllMethods.this.stop();
      } catch (InterruptedException e) {
        e.printStackTrace(System.err);
      }
      System.err.println("*** server shut down");
    }
  });
}
 
Example #26
Source File: BinaryLogProviderTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void wrapMethodDefinition_methodDescriptor() throws Exception {
  ServerMethodDefinition<String, Integer> methodDef =
      ServerMethodDefinition.create(
          method,
          new ServerCallHandler<String, Integer>() {
            @Override
            public Listener<String> startCall(
                ServerCall<String, Integer> call, Metadata headers) {
              throw new UnsupportedOperationException();
            }
          });
  ServerMethodDefinition<?, ?> wMethodDef = binlogProvider.wrapMethodDefinition(methodDef);
  validateWrappedMethod(wMethodDef.getMethodDescriptor());
}
 
Example #27
Source File: ServerInterceptorsTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
    ServerCall<ReqT, RespT> call,
    Metadata headers,
    ServerCallHandler<ReqT, RespT> next) {
  return next.startCall(call, headers);
}
 
Example #28
Source File: Server.java    From africastalking-java with MIT License 5 votes vote down vote up
@Override
public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
    String clientId = headers.get(CLIENT_ID_HEADER_KEY);
    if (clientId == null || !authenticator.authenticate(clientId)) {
        call.close(Status.UNAUTHENTICATED.withDescription("Invalid or unknown client: " + clientId), headers);
        return NOOP_LISTENER;
    }
    Context context = Context.current().withValue(CLIENT_ID_CONTEXT_KEY, clientId);
    return Contexts.interceptCall(context, call, headers, next);
}
 
Example #29
Source File: TracingMetadataUtils.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
@Override
public <ReqT, RespT> Listener<ReqT> interceptCall(
    ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
  RequestMetadata meta = requestMetadataFromHeaders(headers);
  if (meta == null) {
    meta = RequestMetadata.getDefaultInstance();
  }
  Context ctx = Context.current().withValue(CONTEXT_KEY, meta);
  return Contexts.interceptCall(ctx, call, headers, next);
}
 
Example #30
Source File: TracingMetadataUtils.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Override
public <ReqT, RespT> Listener<ReqT> interceptCall(
    ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
  RequestMetadata meta = requestMetadataFromHeaders(headers);
  if (meta == null) {
    throw io.grpc.Status.INVALID_ARGUMENT
        .withDescription(
            "RequestMetadata not received from the client for "
                + call.getMethodDescriptor().getFullMethodName())
        .asRuntimeException();
  }
  Context ctx = Context.current().withValue(CONTEXT_KEY, meta);
  return Contexts.interceptCall(ctx, call, headers, next);
}