io.grpc.ServerInterceptor Java Examples

The following examples show how to use io.grpc.ServerInterceptor. 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: GrpcContainer.java    From quarkus with Apache License 2.0 6 votes vote down vote up
List<ServerInterceptor> getSortedInterceptors() {
    if (interceptors.isUnsatisfied()) {
        return Collections.emptyList();
    }

    return interceptors.stream().sorted(new Comparator<ServerInterceptor>() { // NOSONAR
        @Override
        public int compare(ServerInterceptor si1, ServerInterceptor si2) {
            int p1 = 0;
            int p2 = 0;
            if (si1 instanceof Prioritized) {
                p1 = ((Prioritized) si1).getPriority();
            }
            if (si2 instanceof Prioritized) {
                p2 = ((Prioritized) si2).getPriority();
            }
            if (si1.equals(si2)) {
                return 0;
            }
            return Integer.compare(p1, p2);
        }
    }).collect(Collectors.toList());
}
 
Example #2
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 unexpectedExceptionCanMatchStreaming() {
    GreeterGrpc.GreeterImplBase svc = new GreeterGrpc.GreeterImplBase() {
        @Override
        public void sayHelloStream(HelloRequest request, StreamObserver<HelloResponse> responseObserver) {
            responseObserver.onNext(HelloResponse.getDefaultInstance());
            responseObserver.onNext(HelloResponse.getDefaultInstance());
            throw 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());

    Iterator<HelloResponse> it = stub.sayHelloStream(HelloRequest.newBuilder().setName("World").build());
    it.next();
    it.next();
    assertThatThrownBy(it::next)
            .isInstanceOf(StatusRuntimeException.class)
            .matches(sre -> ((StatusRuntimeException) sre).getStatus().getCode().equals(Status.INTERNAL.getCode()), "is Status.INTERNAL")
            .hasMessageContaining("Divide by zero");
}
 
Example #3
Source File: TestServiceImpl.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
/**
 * Echo the request headers from a client into response headers and trailers. Useful for
 * testing end-to-end metadata propagation.
 */
private static ServerInterceptor echoRequestHeadersInterceptor(final Metadata.Key<?>... keys) {
  final Set<Metadata.Key<?>> keySet = new HashSet<>(Arrays.asList(keys));
  return new ServerInterceptor() {
    @Override
    public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
        ServerCall<ReqT, RespT> call,
        final Metadata requestHeaders,
        ServerCallHandler<ReqT, RespT> next) {
      return next.startCall(new SimpleForwardingServerCall<ReqT, RespT>(call) {
            @Override
            public void sendHeaders(Metadata responseHeaders) {
              responseHeaders.merge(requestHeaders, keySet);
              super.sendHeaders(responseHeaders);
            }

            @Override
            public void close(Status status, Metadata trailers) {
              trailers.merge(requestHeaders, keySet);
              super.close(status, trailers);
            }
          }, requestHeaders);
    }
  };
}
 
Example #4
Source File: TestServiceImpl.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
/**
 * Echoes request headers with the specified key(s) from a client into response headers only.
 */
private static ServerInterceptor echoRequestMetadataInHeaders(final Metadata.Key<?>... keys) {
  final Set<Metadata.Key<?>> keySet = new HashSet<>(Arrays.asList(keys));
  return new ServerInterceptor() {
    @Override
    public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
        ServerCall<ReqT, RespT> call,
        final Metadata requestHeaders,
        ServerCallHandler<ReqT, RespT> next) {
      return next.startCall(new SimpleForwardingServerCall<ReqT, RespT>(call) {
        @Override
        public void sendHeaders(Metadata responseHeaders) {
          responseHeaders.merge(requestHeaders, keySet);
          super.sendHeaders(responseHeaders);
        }

        @Override
        public void close(Status status, Metadata trailers) {
          super.close(status, trailers);
        }
      }, requestHeaders);
    }
  };
}
 
Example #5
Source File: TestServiceImpl.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
/**
 * Echoes request headers with the specified key(s) from a client into response trailers only.
 */
private static ServerInterceptor echoRequestMetadataInTrailers(final Metadata.Key<?>... keys) {
  final Set<Metadata.Key<?>> keySet = new HashSet<>(Arrays.asList(keys));
  return new ServerInterceptor() {
    @Override
    public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
        ServerCall<ReqT, RespT> call,
        final Metadata requestHeaders,
        ServerCallHandler<ReqT, RespT> next) {
      return next.startCall(new SimpleForwardingServerCall<ReqT, RespT>(call) {
        @Override
        public void sendHeaders(Metadata responseHeaders) {
          super.sendHeaders(responseHeaders);
        }

        @Override
        public void close(Status status, Metadata trailers) {
          trailers.merge(requestHeaders, keySet);
          super.close(status, trailers);
        }
      }, requestHeaders);
    }
  };
}
 
Example #6
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 unexpectedExceptionCanNotMatch() {
    GreeterGrpc.GreeterImplBase svc = new GreeterGrpc.GreeterImplBase() {
        @Override
        public void sayHello(HelloRequest request, StreamObserver<HelloResponse> responseObserver) {
            throw new ArithmeticException("Divide by zero");
        }
    };

    ServerInterceptor interceptor = new TransmitUnexpectedExceptionInterceptor().forExactType(NullPointerException.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.UNKNOWN.getCode()), "is Status.UNKNOWN")
            .hasMessageContaining("UNKNOWN");
}
 
Example #7
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 unexpectedExceptionCanMatch() {
    GreeterGrpc.GreeterImplBase svc = new GreeterGrpc.GreeterImplBase() {
        @Override
        public void sayHello(HelloRequest request, StreamObserver<HelloResponse> responseObserver) {
            throw 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 #8
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 #9
Source File: BinaryLogProvider.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
/**
 * Wraps a {@link ServerMethodDefinition} such that it performs binary logging if needed.
 */
@Override
public final <ReqT, RespT> ServerMethodDefinition<?, ?> wrapMethodDefinition(
    ServerMethodDefinition<ReqT, RespT> oMethodDef) {
  ServerInterceptor binlogInterceptor =
      getServerInterceptor(oMethodDef.getMethodDescriptor().getFullMethodName());
  if (binlogInterceptor == null) {
    return oMethodDef;
  }
  MethodDescriptor<byte[], byte[]> binMethod =
      BinaryLogProvider.toByteBufferMethod(oMethodDef.getMethodDescriptor());
  ServerMethodDefinition<byte[], byte[]> binDef =
      InternalServerInterceptors.wrapMethod(oMethodDef, binMethod);
  ServerCallHandler<byte[], byte[]> binlogHandler =
      InternalServerInterceptors.interceptCallHandlerCreate(
          binlogInterceptor, binDef.getServerCallHandler());
  return ServerMethodDefinition.create(binMethod, binlogHandler);
}
 
Example #10
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 alleMatches() {
    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().forAllExceptions();

    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 #11
Source File: TLSCertGenTest.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
private ServerInterceptor mutualTLSInterceptor(byte[] expectedClientCert, AtomicBoolean toggleHandshakeOccured) {
    return new ServerInterceptor() {
        @Override
        public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> serverCall, Metadata metadata, ServerCallHandler<ReqT, RespT> serverCallHandler) {
            SSLSession sslSession = serverCall.getAttributes().get(Grpc.TRANSPORT_ATTR_SSL_SESSION);
            try {
                javax.security.cert.X509Certificate[] certChain = sslSession.getPeerCertificateChain();
                Assert.assertFalse("Client didn't send TLS certificate", certChain == null || certChain.length == 0);
                byte[] clientRawCert = certChain[0].getEncoded();
                // Ensure the client TLS cert matches the expected one - the one it was created with
                boolean equalCerts = Arrays.equals(clientRawCert, expectedClientCert);
                Assert.assertTrue("Expected certificate doesn't match actual", equalCerts);
                toggleHandshakeOccured.set(true);
            } catch (Exception e) {
                Assert.fail(String.format("Uncaught exception: %s", e.toString()));
                e.printStackTrace();
            }
            return serverCallHandler.startCall(serverCall, metadata);
        }
    };
}
 
Example #12
Source File: DefaultServerInterceptorTest.java    From grpc-spring-boot-starter with MIT License 6 votes vote down vote up
@Test
void testOrderingOfTheDefaultInterceptors() {
    List<ServerInterceptor> expected = new ArrayList<>();
    expected.add(this.applicationContext.getBean(GrpcRequestScope.class));
    expected.add(this.applicationContext.getBean(MetricCollectingServerInterceptor.class));
    expected.add(this.applicationContext.getBean(ExceptionTranslatingServerInterceptor.class));
    expected.add(this.applicationContext.getBean(AuthenticatingServerInterceptor.class));
    expected.add(this.applicationContext.getBean(AuthorizationCheckingServerInterceptor.class));

    List<ServerInterceptor> actual = new ArrayList<>(this.registry.getServerInterceptors());
    assertEquals(expected, actual);

    Collections.shuffle(actual);
    AnnotationAwareOrderComparator.sort(actual);
    assertEquals(expected, actual);
}
 
Example #13
Source File: ServerImpl.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
/**
 * Construct a server.
 *
 * @param builder builder with configuration for server
 * @param transportServer transport server that will create new incoming transports
 * @param rootContext context that callbacks for new RPCs should be derived from
 */
ServerImpl(
    AbstractServerImplBuilder<?> builder,
    InternalServer transportServer,
    Context rootContext) {
  this.executorPool = Preconditions.checkNotNull(builder.executorPool, "executorPool");
  this.registry = Preconditions.checkNotNull(builder.registryBuilder.build(), "registryBuilder");
  this.fallbackRegistry =
      Preconditions.checkNotNull(builder.fallbackRegistry, "fallbackRegistry");
  this.transportServer = Preconditions.checkNotNull(transportServer, "transportServer");
  // Fork from the passed in context so that it does not propagate cancellation, it only
  // inherits values.
  this.rootContext = Preconditions.checkNotNull(rootContext, "rootContext").fork();
  this.decompressorRegistry = builder.decompressorRegistry;
  this.compressorRegistry = builder.compressorRegistry;
  this.transportFilters = Collections.unmodifiableList(
      new ArrayList<>(builder.transportFilters));
  this.interceptors =
      builder.interceptors.toArray(new ServerInterceptor[builder.interceptors.size()]);
  this.handshakeTimeoutMillis = builder.handshakeTimeoutMillis;
  this.binlog = builder.binlog;
  this.channelz = builder.channelz;
  this.serverCallTracer = builder.callTracerFactory.create();

  channelz.addServer(this);
}
 
Example #14
Source File: ServerImpl.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
/** Never returns {@code null}. */
private <ReqT, RespT> ServerStreamListener startCall(ServerStream stream, String fullMethodName,
    ServerMethodDefinition<ReqT, RespT> methodDef, Metadata headers,
    Context.CancellableContext context, StatsTraceContext statsTraceCtx) {
  // TODO(ejona86): should we update fullMethodName to have the canonical path of the method?
  statsTraceCtx.serverCallStarted(
      new ServerCallInfoImpl<ReqT, RespT>(
          methodDef.getMethodDescriptor(), // notify with original method descriptor
          stream.getAttributes(),
          stream.getAuthority()));
  ServerCallHandler<ReqT, RespT> handler = methodDef.getServerCallHandler();
  for (ServerInterceptor interceptor : interceptors) {
    handler = InternalServerInterceptors.interceptCallHandler(interceptor, handler);
  }
  ServerMethodDefinition<ReqT, RespT> interceptedDef = methodDef.withServerCallHandler(handler);
  ServerMethodDefinition<?, ?> wMethodDef = binlog == null
      ? interceptedDef : binlog.wrapMethodDefinition(interceptedDef);
  return startWrappedCall(fullMethodName, wMethodDef, stream, headers, context);
}
 
Example #15
Source File: AnnotationGrpcServiceDiscoverer.java    From grpc-spring-boot-starter with MIT License 6 votes vote down vote up
private ServerServiceDefinition bindInterceptors(final ServerServiceDefinition serviceDefinition,
        final GrpcService grpcServiceAnnotation,
        final GlobalServerInterceptorRegistry globalServerInterceptorRegistry) {
    final List<ServerInterceptor> interceptors = Lists.newArrayList();
    interceptors.addAll(globalServerInterceptorRegistry.getServerInterceptors());
    for (final Class<? extends ServerInterceptor> interceptorClass : grpcServiceAnnotation.interceptors()) {
        final ServerInterceptor serverInterceptor;
        if (this.applicationContext.getBeanNamesForType(interceptorClass).length > 0) {
            serverInterceptor = this.applicationContext.getBean(interceptorClass);
        } else {
            try {
                serverInterceptor = interceptorClass.getConstructor().newInstance();
            } catch (final Exception e) {
                throw new BeanCreationException("Failed to create interceptor instance", e);
            }
        }
        interceptors.add(serverInterceptor);
    }
    for (final String interceptorName : grpcServiceAnnotation.interceptorNames()) {
        interceptors.add(this.applicationContext.getBean(interceptorName, ServerInterceptor.class));
    }
    if (grpcServiceAnnotation.sortInterceptors()) {
        globalServerInterceptorRegistry.sortInterceptors(interceptors);
    }
    return ServerInterceptors.interceptForward(serviceDefinition, interceptors);
}
 
Example #16
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 #17
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 noExceptionDoesNotInterfere() {
    GreeterGrpc.GreeterImplBase svc = new GreeterGrpc.GreeterImplBase() {
        @Override
        public void sayHello(HelloRequest request, StreamObserver<HelloResponse> responseObserver) {
            responseObserver.onNext(HelloResponse.newBuilder().setMessage("Hello " + request.getName()).build());
            responseObserver.onCompleted();
        }
    };

    ServerInterceptor interceptor = new TransmitUnexpectedExceptionInterceptor();

    serverRule.getServiceRegistry().addService(ServerInterceptors.intercept(svc, interceptor));
    GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(serverRule.getChannel());

    stub.sayHello(HelloRequest.newBuilder().setName("World").build());
}
 
Example #18
Source File: DefaultServerInterceptorTest.java    From grpc-spring-boot-starter with MIT License 6 votes vote down vote up
@Test
void testOrderingOfTheDefaultInterceptors() {
    List<ServerInterceptor> expected = new ArrayList<>();
    expected.add(this.applicationContext.getBean(GrpcRequestScope.class));
    expected.add(this.applicationContext.getBean(MetricCollectingServerInterceptor.class));
    expected.add(this.applicationContext.getBean(ExceptionTranslatingServerInterceptor.class));
    expected.add(this.applicationContext.getBean(AuthenticatingServerInterceptor.class));
    expected.add(this.applicationContext.getBean(AuthorizationCheckingServerInterceptor.class));

    List<ServerInterceptor> actual = new ArrayList<>(this.registry.getServerInterceptors());
    assertEquals(expected, actual);

    Collections.shuffle(actual);
    AnnotationAwareOrderComparator.sort(actual);
    assertEquals(expected, actual);
}
 
Example #19
Source File: TitusGrpcServer.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
public TitusGrpcServer build() {
    Preconditions.checkArgument(port >= 0, "Port number is negative");
    Preconditions.checkNotNull(titusRuntime, "TitusRuntime not set");

    List<ServerInterceptor> commonInterceptors = new ArrayList<>();
    commonInterceptors.add(new CommonErrorCatchingServerInterceptor(new GrpcExceptionMapper(serviceExceptionMappers)));
    GrpcFitInterceptor.getIfFitEnabled(titusRuntime).ifPresent(commonInterceptors::add);
    commonInterceptors.addAll(interceptors);

    ServerBuilder serverBuilder = ServerBuilder.forPort(port);
    if (serverConfigurer != null) {
        serverBuilder = serverConfigurer.apply(serverBuilder);
    }
    for (ServiceBuilder serviceBuilder : serviceBuilders.values()) {
        serverBuilder.addService(serviceBuilder.build(commonInterceptors));
    }

    return new TitusGrpcServer(serverBuilder.build(), shutdownTime);
}
 
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 parentTypeMatchesExactly() {
    GreeterGrpc.GreeterImplBase svc = new GreeterGrpc.GreeterImplBase() {
        @Override
        public void sayHello(HelloRequest request, StreamObserver<HelloResponse> responseObserver) {
            responseObserver.onError(new RuntimeException("Divide by zero"));
        }
    };

    ServerInterceptor interceptor = new TransmitUnexpectedExceptionInterceptor().forParentType(RuntimeException.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: AnnotationGrpcServiceDiscoverer.java    From grpc-spring-boot-starter with MIT License 6 votes vote down vote up
private ServerServiceDefinition bindInterceptors(final ServerServiceDefinition serviceDefinition,
        final GrpcService grpcServiceAnnotation,
        final GlobalServerInterceptorRegistry globalServerInterceptorRegistry) {
    final List<ServerInterceptor> interceptors = Lists.newArrayList();
    interceptors.addAll(globalServerInterceptorRegistry.getServerInterceptors());
    for (final Class<? extends ServerInterceptor> interceptorClass : grpcServiceAnnotation.interceptors()) {
        final ServerInterceptor serverInterceptor;
        if (this.applicationContext.getBeanNamesForType(interceptorClass).length > 0) {
            serverInterceptor = this.applicationContext.getBean(interceptorClass);
        } else {
            try {
                serverInterceptor = interceptorClass.getConstructor().newInstance();
            } catch (final Exception e) {
                throw new BeanCreationException("Failed to create interceptor instance", e);
            }
        }
        interceptors.add(serverInterceptor);
    }
    for (final String interceptorName : grpcServiceAnnotation.interceptorNames()) {
        interceptors.add(this.applicationContext.getBean(interceptorName, ServerInterceptor.class));
    }
    if (grpcServiceAnnotation.sortInterceptors()) {
        globalServerInterceptorRegistry.sortInterceptors(interceptors);
    }
    return ServerInterceptors.interceptForward(serviceDefinition, interceptors);
}
 
Example #22
Source File: GrpcServer.java    From spring-boot-starter-grpc with MIT License 6 votes vote down vote up
/**
 * 启动服务
 * @throws Exception 异常
 */
public void start() throws Exception{
    int port = grpcProperties.getPort();
    if (serverInterceptor != null){
        server = ServerBuilder.forPort(port).addService(ServerInterceptors.intercept(commonService, serverInterceptor)).build().start();
    }else {
        Class clazz = grpcProperties.getServerInterceptor();
        if (clazz == null){
            server = ServerBuilder.forPort(port).addService(commonService).build().start();
        }else {
            server = ServerBuilder.forPort(port).addService(ServerInterceptors.intercept(commonService, (ServerInterceptor) clazz.newInstance())).build().start();
        }
    }
    log.info("gRPC Server started, listening on port " + server.getPort());
    startDaemonAwaitThread();
}
 
Example #23
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 parentTypeMatches() {
    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().forParentType(RuntimeException.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 #24
Source File: AnnotationGlobalServerInterceptorConfigurer.java    From grpc-spring-boot-starter with MIT License 5 votes vote down vote up
@Override
public void addServerInterceptors(final GlobalServerInterceptorRegistry registry) {
    this.context.getBeansWithAnnotation(GrpcGlobalServerInterceptor.class)
            .forEach((name, bean) -> {
                ServerInterceptor interceptor = (ServerInterceptor) bean;
                log.debug("Registering GlobalServerInterceptor: {} ({})", name, interceptor);
                registry.addServerInterceptors(interceptor);
            });
}
 
Example #25
Source File: GlobalServerInterceptorRegistry.java    From grpc-spring-boot-starter with MIT License 5 votes vote down vote up
/**
 * Gets the immutable and sorted list of global server interceptors.
 *
 * @return The list of globally registered server interceptors.
 */
public ImmutableList<ServerInterceptor> getServerInterceptors() {
    if (this.sortedServerInterceptors == null) {
        List<ServerInterceptor> temp = Lists.newArrayList(this.serverInterceptors);
        sortInterceptors(temp);
        this.sortedServerInterceptors = ImmutableList.copyOf(temp);
    }
    return this.sortedServerInterceptors;
}
 
Example #26
Source File: HelloServer.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
protected ServerInterceptor getInterceptor() {
    return new ServerInterceptor() {
        @Override
        public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
            return new TestServerListener<ReqT>(next.startCall(call, headers), listenerExceptionMethod);
        }
    };
}
 
Example #27
Source File: DebugInterceptorTest.java    From grpc-java-contrib with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void debugServerInterceptTest() {
    LinkedList<String> logs = new LinkedList<String>();
    Metadata requestHeaders = new Metadata();
    requestHeaders.put(Metadata.Key.of("request_header", Metadata.ASCII_STRING_MARSHALLER), "request_header_value");
    // Setup
    serverRule.getServiceRegistry().addService(ServerInterceptors.intercept(svc, new ServerInterceptor() {
        @Override
        public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers,
                ServerCallHandler<ReqT, RespT> next) {
            return next.startCall(new SimpleForwardingServerCall<ReqT, RespT>(call) {
                @Override
                public void sendHeaders(Metadata responseHeaders) {
                    responseHeaders.put(Metadata.Key.of("response_header", Metadata.ASCII_STRING_MARSHALLER),
                            "response_header_value");
                    super.sendHeaders(responseHeaders);
                }
            }, headers);
        }
    }, new DebugServerInterceptor(DebugServerInterceptor.Level.METHOD, DebugServerInterceptor.Level.MESSAGE,
            DebugServerInterceptor.Level.HEADERS) {
        @Override
        protected void log(String logmessage) {
            logs.add(logmessage);
        }
    }));
    GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(serverRule.getChannel())
            .withInterceptors(MetadataUtils.newAttachHeadersInterceptor(requestHeaders));
    stub.sayHello(HelloRequest.newBuilder().setName("World").build());
    assertThat(logs.poll()).contains("SayHello"); // request method name
    assertThat(logs.poll()).contains("request_header_value"); // request header value
    assertThat(logs.poll()).contains("World"); // request message
    assertThat(logs.poll()).contains("SayHello"); // response method name
    assertThat(logs.poll()).contains("response_header_value"); // response header
    assertThat(logs.poll()).contains("Hello World"); // response message

}
 
Example #28
Source File: TitusFederationGrpcServer.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
/**
 * Override to add server side interceptors.
 */
protected List<ServerInterceptor> createInterceptors(ServiceDescriptor serviceDescriptor) {
    return Arrays.asList(
            admissionController,
            new ErrorCatchingServerInterceptor(),
            new V3HeaderInterceptor()
    );
}
 
Example #29
Source File: TitusGatewayGrpcServer.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
/**
 * Override to add server side interceptors.
 */
protected List<ServerInterceptor> createInterceptors(ServiceDescriptor serviceDescriptor) {
    return GrpcFitInterceptor.appendIfFitEnabled(
            asList(new ErrorCatchingServerInterceptor(), new V3HeaderInterceptor()),
            titusRuntime
    );
}
 
Example #30
Source File: TitusMasterGrpcServer.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
/**
 * Override to add server side interceptors.
 */
protected List<ServerInterceptor> createInterceptors(ServiceDescriptor serviceDescriptor) {
    List<ServerInterceptor> interceptors = new ArrayList<ServerInterceptor>();
    interceptors.add(admissionControllerServerInterceptor);
    interceptors.add(new ErrorCatchingServerInterceptor());
    interceptors.add(leaderServerInterceptor);
    interceptors.add(new V3HeaderInterceptor());
    return GrpcFitInterceptor.appendIfFitEnabled(interceptors, titusRuntime);
}