2

I am implementing a custom MessageBodyReader that needs to resolve URIs against the request URI during processing. If the MessageBodyReader is used in a JAX-RS server implementation, which eg. processes incoming POST requests, I can obtain the request URI from a UriInfo object that is injected at runtime using @Context (as described eg. at https://stackoverflow.com/a/3314076):

public class MyProvider implements MessageBodyReader {

  @javax.ws.rs.core.Context
  javax.ws.rs.core.UriInfo uriInfo;

  @Override
  public Iterable<URI> readFrom(Class<Iterable<URI>> clazz, Type genericType,
      Annotation annotations[], MediaType mediaType,
      MultivaluedMap httpHeaders, InputStream entityStream)
        throws IOException, WebApplicationException {

    URI requestURI = uriinfo.getAbsolutePath(); // NPE if called in a client

    // Parsing entityStream resolving relative URIs using requestURI

  }
}

If the MessageBodyReader is called in a JAX-RS client implementation during the reading of an Response's entity, the injection does not happen, hence I get a NullPointerException (see above for the line) when I write a client using JAX-RS like:

Iterable<URI> it = ClientBuilder.newClient().target("http://example.org/").request().get()
    .readEntity(new GenericType<Iterable<URI>>(){});

With the aim of resolving URIs, my question is:

How do I find out the request URI in readFrom(...) in the case that the MessageBodyReader is called in a JAX-RS client implementation?

My current workaround: Having read Chapter 10.4 "Filter and interceptor execution order" of the Jersey documentation, I found that in step 16, the ClientResponseFilter, I have access to both the request URI and the response headers. Hence I wrote a ClientResponseFilter that puts the request URI in a custom response header. Then, I can retrieve that custom header from the 5th parameter of readFrom(...).

kaefer3000
  • 23
  • 4
  • Why can't you just do a null check on the UriInfo? – Paul Samsotha Nov 24 '18 at 00:25
  • Then I would know that I don't have UriInfo, but where do I get the URI from? – kaefer3000 Nov 24 '18 at 10:20
  • OiC. I overlooked that part of the question. You're workaround seems like your best bet. Probably something I would have thought of if faced with the same problem. – Paul Samsotha Nov 25 '18 at 09:14
  • I have the same problem and I think methods in `MessageBody(Reader|Writer)` are badly designed. They should have been designed like the interceptors and filters which only have some `*Context`s parameters. An hypothetic `MessageBodyReaderContext` could have contained all parameters + properties (like other contexts) that could have been filled by some `ClientRequestFilter` which has access to the URI. – Xavier Dury Oct 17 '19 at 15:44

0 Answers0