I think, what Jerome is talking about is moving the logic from Resource#getRepresentation(Variant) into the ConverterService and doing the same type of branching, just at a higher level. I like the fact that I can declare my ConverterService as a Singleton and thus instantiate it and all of its collaborators once (e.g. XStream or Freemarker converters). However, the voluminous if blocks and the lack of access to the Request and Response turned me off. What I've done is create an application-specific base AbstractResource class. It handles generic conversion to JSON and XML, while the concrete Resource does the HTML (because HTML requires metadata that can't be handled generically). In the abstract class, I've got a template method,

    Representation getCustomRepresentation(Variant)

that, by default, returns null. AbstractResource#getRepresentation (Variant) checks if the implementing class has handled the selected variant (i.e. when getCustomRepresentation returns a non-null Representation) and passes it along. Otherwise, it tries to create the Representation itself:

@Override
public final Representation getRepresentation(Variant variant) {
    Representation r = getCustomRepresentation(variant);
    if (null != r) {
        return r;
    }
    if (MediaType.TEXT_XML.equals(variant.getMediaType())) {
        return new XStreamRepresentation(variant.getMediaType(), …);
    }
    …
    return null;
}

I'm not sure this is the most elegant way to handle things, though. Any comments would be appreciated.

Justin

On Sep 24, 2007, at 10:16 AM, Sumit Lohia wrote:

Jerome Louvel <contact <at> noelios.com> writes:

It seems indeed like this service would help you to centralize your
conversion logic. But nothing is done automatically, you still need to manually call getEntityAsObject() or setEntity(Object) methods in order to
trigger the converter service.


But if I need to support both XML and JSON representations, I would need two converter services, right? Or do you see the toRepresentation() method on
ConverterService accepting a MediaType/Variant parameter?

Thanks.

Sumit

Reply via email to