Search code examples
javarpcinterceptorgrpc

How to access message request in gRPC interceptor?


I'd like to user the same interceptor on server side for multiple methods as all of them have the same request type (StateRequest):

rpc apply (StateRequest) returns (StateResponse) {} 
rpc cancel (StateRequest) returns (StateResponse) {}
rpc remove (StateRequest) returns (StateResponse) {}
rpc development (StateRequest) returns (StateResponse) {}
rpc implement (StateRequest) returns (StateResponse) {}
rpc draft (StateRequest) returns (StateResponse) {}

interceptor:

public class ServerUserRoleAuthInterceptor implements ServerInterceptor {

    @Override
    public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
        ServerCall<ReqT, RespT> call,
        Metadata headers,
        ServerCallHandler<ReqT, RespT> next) {
        String callName = call.getMethodDescriptor().getFullMethodName();
        logger.info("Call: {}", callName);

        // TODO: validate request (`StateRequest` instance)

        return next.startCall(call, headers);
    }
}

How can i do it?


Solution

  • You need to observe the onMessage(ReqT) call-back on the Listener.

    return new SimpleForwardingServerCallListener<ReqT>(next.startCall(call, headers)) {
      @Override 
      public void onMessage(ReqT request) {
        // TODO:validate request
        super.onMessage(request);
      }
    };