1

I have two ContainerResponseFilter for a request method, of which only one should be run. This is decided based on a particular request header.

I created a DynamicFeature that checks this header and register the filter accordingly.

public class CustomFeature implements DynamicFeature {
    @Context
    HttpHeaders httpHeaders;

    @Override
    public void configure(ResourceInfo resourceInfo, FeatureContext context) {
        String value = httpHeaders.getHeaderString("x-something"); 
        if (value != null && !value.isEmpty()) {
            context.register(SomeFilter.class);
        } else {
            context.register(OtherFilter.class);
        }
    }
}

This throws the following exception:

"java.lang.IllegalStateException: Not inside a request scope.
    at org.glassfish.jersey.internal.guava.Preconditions.checkState(Preconditions.java:169)
    at org.glassfish.jersey.process.internal.RequestScope.current(RequestScope.java:153)
    at org.glassfish.jersey.inject.hk2.RequestContext.findOrCreate(RequestContext.java:55)
    at org.jvnet.hk2.internal.MethodInterceptorImpl.internalInvoke(MethodInterceptorImpl.java:65)
    at org.jvnet.hk2.internal.MethodInterceptorImpl.invoke(MethodInterceptorImpl.java:101)
    ...

I understand that the error is coming as during configuration, there is no request and hence no header. However this is where I am confused. As per this answer here, HttpHeaders is proxieable. Therefore shouldn't a proxy be inserted here and delegated to actual instance when a request is being processed? (It seems this method of @Context injection works perfectly fine in ContainerResponseFilter and ContainerRequestFilter classes).

Also, how to run only one filter based on the header?

Termin4t0r
  • 199
  • 3
  • 10
  • `configure()` is not called during a request. It's called at startup during configuration time. Only once. Whether it's a proxy or not doesn't matter, it's going to be called when there is no request. – Paul Samsotha Aug 27 '19 at 02:52
  • @PaulSamsotha in this case can't we determine which filter to run and which to skip based on some request context? – Termin4t0r Aug 27 '19 at 03:04

0 Answers0