dev@jsr311.java.net

Context Management

From: Marc Hadley <Marc.Hadley_at_Sun.COM>
Date: Tue, 08 Jan 2008 13:49:33 -0500

Experts,

We've had several requests on the Jersey mailing list for some way of
controlling the JAXBContext used by the JAXB message body reader and
writer. Currently there's no standard way for an application to supply
the JAXBContext so the bundled message body reader and writer just
create and cache their own. Their are several approaches that could
get around this problem without impacting the JAX-RS API, e.g. an
application could supply its own JAXB message body reader and writer
and use an application-specific contract to supply the JAXBContext,
but all of the solutions we've investigated involve some form of
duplication of effort or specification of implementation-specific
contracts. We think that JAXB is an example of a particular kind of
serialization framework that relies on some form of context and rather
than solve this problem in a way specific to JAXB we'd like to solve
it in a more general way that can be applied to other frameworks.

With this background we'd like to propose an addition to JAX-RS to
handle this kind of context management.

We'd add one new generic interface:

ContextResolver<T> {
  class<T> getType();
  T getContext(Class<?> objectType);
}

An application class would implement ContextResolver<JAXBContext> to
supply its own JAXBContext for use by the JAXB MessageBodyReader and
MessageBodyWriter. An application could supply multiple
implementations if different contexts should be used for different
object classes or could implement a single object to manage all
contexts.

Message body readers and writers access application-supplied contexts
via injection:

public class MyReader implements MessageBodyReader<SomeType> {

  @HttpContext
  private ContextResolver<SomeContextType> context;

  ...
}

The injected ContextResolver wouldn't be an instance of an application-
supplied class, rather it would be a proxy responsible for managing
the set of ContextResolver implementations for a specific context
type. E.g. if an application supplied two
ContextResolver<JAXBContext>, the injected instance would be
responsible for calling getContext on each to try to obtain a
JAXBContext for the supplied objectType.

Use of @HttpContext here suggests that a rename might be desirable -
@Context instead ?

The use of injection here highlights another issue: message body
readers, writers and context resolvers are essentially JAX-RS
components much like resource classes. However the specification
currently treats resource classes as the only real component subject
to injection etc. We'd like to unify things such that the other types
of component can also access contextual information like UriInfo -
more on this in a later note.

Thoughts, comments ?
Marc.

---
Marc Hadley <marc.hadley at sun.com>
CTO Office, Sun Microsystems.