Converters

Converters can be thought of as "post-processors" for POJOs before they get passed to the serializers.

Converters are associated with resource classes and methods via the following:

- {@link oajr.annotation.RestResource#converters()}
- {@link oajr.annotation.RestMethod#converters()}
- {@link oajr.RestContextBuilder#converters(Class...)}

##### Example:

// Associate the Traversable converter to all Java REST methods in this servlet @RestResource(converters=Traversable. class) public MyRestServlet extends BasicRestServlet { ... }

They can also be defined at the method level:

// GET person request handler. // Traversable conversion enabled to allow nodes in returned POJO tree to be addressed. // Queryable conversion enabled to allow returned POJO to be searched/viewed/sorted. @RestMethod( name=GET, path="/people/{id}/*", converters={Traversable. class,Queryable. class} ) public Person getPerson(@Path("id") int id) { return findPerson(id); }

The following converter is used to provide support for addressing child nodes in a POJO tree with URL path remainders.
In this code, the 3rd parameter is the object that was returned by the Java method.
The converter uses the {@link oaj.utils.PojoRest} wrapper class to address nodes in the tree.

/** * Converter for enablement of PojoRest support on response objects returned by a @RestMethod method. * When enabled, objects in a POJO tree returned by the REST method can be addressed through additional URL path information. */ public class Traversable implements RestConverter { @Override /* RestConverter */ public Object convert(RestRequest req, Object o) throws RestException { if (o == null) return null; String pathRemainder = req.getPathMatch().getRemainder(); if (pathRemainder != null) { try { // Use the PojoRest class to traverse our POJO model. PojoRest p = new PojoRest(o); o = p.get(pathRemainder); } catch (PojoRestException e) { throw new RestException(e.getStatus(), e); } catch (Exception e) { throw new RestException(HttpServletResponse. SC_INTERNAL_SERVER_ERROR, e); } } return o; } }

Juneau defines the following converters out-of-the-box:

- {@link oajr.RestConverter}
  - {@link oajr.converters.Queryable}
    Provides query parameters that can be used to transform the response (i.e. search/view/sort the POJO response before being serialized).
  - {@link oajr.converters.Traversable}
    Allows nodes in the POJO response tree to be individually accessed through additional path info on the request.
  - {@link oajr.converters.Introspectable}
    Allows method calls to be made on the response POJO, and for the result of that method call to be serialized as the response.

##### See Also:

- {@link oajr.RestContext#REST_converters}