jakartaee / jakartaee/rest

Make request URI / UriInfo available in MessageBodyReader for client (and not just server)

Open
#796 6 comments 0 reactions 1 assignee Claimed by @mkarg View on GitHub
enhancement spec
Dominant language
Java
Stars
400
Forks
143
PR merge metrics
No merged PRs in 30d

Description

**tl;dr**: `UriInfo` is not available in a `MessageBodyReader` of a *client* implementation. Thus, I cannot get the request's URI to resolve relative URIs against.

**Long description:** I am implementing a custom `MessageBodyReader` (for processing RDF) 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):
```java
public class MyProvider implements MessageBodyReader {

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

@Override
public Iterable readFrom(Class> 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:
```java
Iterable it = ClientBuilder.newClient().target("http://example.org/").request().get()
.readEntity(new GenericType>(){});
```
**My current workaround:** Having read [Chapter 10.4 "Filter and interceptor execution order"](https://jersey.github.io/documentation/latest/filters-and-interceptors.html#d0e9614) 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(...)`.

**Full disclosure:** A while ago, I posted this issue as a [question](https://stackoverflow.com/questions/53453870/how-to-determine-the-request-uri-in-a-jax-rs-clients-messagebodyreader) on StackOverflow, but did not get much of a response apart from appreciation for my workaround. As I think there may be something fundamental behind it and I think server and client implementations should work analogously, I am filing my problem as an issue here now.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.