5

I have some web-service (JAX-RS, WildFly 9, Resteasy)

@RequestScoped
public class SomeService{
// operations
}

Now I want to extract context information like user agent, which can be done using

@Context
private HttpHeaders httpHeaders;

It seems only be possible to inject this context in JAX-RS-related classes, but not in CDI beans called by the webservice. It is possible to put it into the webservice but this clutters the service with stuff not related to the core response of the service.

After some searching, I ended up using the javax.ws.rs.ext.Provider annotation. It seems that the produced ContextInformation object can then be used in other CDI-beans, not just in JAX-RS beans.

@Provider
public class ContextInformationProducer {
    @Produces
    @RequestScoped
    public ContextInformation create() {
        ContextInformation contextInformation = new ContextInformation();
        contextInformation.setBrowserUserAgent(httpHeaders.getHeaderString("User-Agent"));
    }

The question is if this is good practice? Or is it just a coincidence that this works? If it is not good practice, how can I do that in a better way? After looking at What does Provider in JAX-RS mean?, I am not sure if I am 'extending and customizing the JAX-RS runtime'. Should this used by application developers?

Community
  • 1
  • 1
user140547
  • 7,750
  • 3
  • 28
  • 80
  • Would you be able to provide a complete source file for `ContextInformationProducer`? Which CDI provider were you using? I'm having trouble getting this (even your "trick") to work with Resteasy/Quarkus. – Keeley Hoek Jan 16 '22 at 02:55
  • @KeeleyHoek well it was more that 6 years ago, so unfortunately I don't remember anything apart of that description in the OP, and if that "trick" is portable – user140547 Jan 16 '22 at 21:59
  • No problem! If it helps anyone else I messed around with this and a) with Jersey it works out of the box, and b) with Resteasy the `ContextInformationProducer` gets ignored by `@Provider` discovery unless it implements `ContainerRequestFilter` (with an empty `filter()` method, though I guess it could be any class). (And, probably implementing any JAX-RS standard interface would work.) But in either case at the end of the day you get a working JAX-RS to CDI bridge which is really great. – Keeley Hoek Jan 17 '22 at 08:46

0 Answers0