Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate XML Response from Classes with Generic Templates(<T>) in RESTEasy?

I have a generic ServiceResponse class as follows:

@XMLRootElement
public class ServiceResponse<T>
{
    private T data;
    private String error;
    //setters n getters

}

From my RESTEasy Service, i want to generate xml response as:

List<Customer> customers = someDAO.getCustomers();
ServiceResponse<List<Customer>> resp = new ServiceResponse<List<Customer>>();
resp.setData(customers);
resp.setError("No Error");
return resp;
or return Response.ok().entity(resp).build();

But this is throwing error as there is no JaxbMarshallWriter for java.util.List.

I can marshall List usinig GenericEntity class.

GenericEntity<List<Customer>> entity = new GenericEntity<List<Customer>>(customers){};
Response.ok(entity).build();

But GenericEntity<ServiceResponse<List<Customer>>> is not working saying no JaxbMarshallWriter for java.util.List.

Is there any work around to marshall/unmarshall classes with generic templates(, )?

like image 888
K. Siva Prasad Reddy Avatar asked May 25 '12 11:05

K. Siva Prasad Reddy


1 Answers

I'm not sure if it makes a difference that your class uses generic templates, but this is how I would generate an XML response using RESTEasy

This is the class that would hold your service response

public class ServiceResponse<T>
{
    private T data;
    private String error;
    //setters n getters
}

This is the class that would actually transform your response into XML. This class really doesn't do much other than take in and produce XML/JSON or whatever you are using. It then passes the request on to the class that does the real work. This however is the class that would answer your specific question (I believe).

@Path("/myrestservice")
public class SomeRestService
{
    private SomeCoreService coreService;
    //getters and setters here

    @POST
    @Path("/examples/")
    @Consumes({MediaType.APPLICATION_XML}) //this consumes XML
    @Produces({MediaType.APPLICATION_XML}) //this produces XML
    public ServiceResponse<T> exampleFunction(Request request)
    {
        try
        {
            //Unwrap the request and take only what you need out
            //of the request object here
            return this.coreService.examples(request.getStringFromRequest());
        }
        catch(Exception ex)
        {
            return new ServiceResponse<T>(Put response error message here);
        }
    }
}

This is the class that does all of the real work.

public class SomeCoreService
{
    public ServiceResponse<T> examples(String stringFromRequest)
    {
        //do whatever work you need to do here.
        return new ServiceResponse<T>(put whatever you need in the service response here)
    }
}

Also, I haven't tested any of this. Hopefully it is enough for you to get the pattern.

like image 134
j.jerrod.taylor Avatar answered Sep 22 '22 02:09

j.jerrod.taylor