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?