The same case exists for custom exceptions. Is there anywhere in the
exception handling chain I can determine mime type and do one of the
following?:
1. Have the custom response object generate either XML or JSON based on the
requested media type
2. Get CXF to use a status code plus an entity that will be serialized to
the client (in this case a "response" or "error" object of some form)
You can have
@Context HttpHeaders headers;
injected into a custom ExceptionMapper and get
headers.getAcceptableMediaTypes();
So if say it's application/json which is expected then in your exception mapper
you can do
// presuming the browser does not like codes > 200
return
Response.status(200).type("application/json").entity(customResponse).build();
and then the JAX-RS runtime will find a provider which understand JSON...The default JSON provider assumes a custom response is JAXB
annotated...
Cheers, Sergey
----- Original Message -----
From: "Sergey Beryozkin" <[email protected]>
To: <[email protected]>
Sent: Friday, May 15, 2009 12:46 PM
Subject: Re: JAX-RS: Media Type Determination - Exceptions & Custom Responses
Hi David
if you add @Produces("application/xml", "application/json") then it should do the trick..., provided Accept headers specifies
either "application/xml" or "application/json"
Give it a try please
Cheers, Sergey
----- Original Message -----
From: "David Castro" <[email protected]>
To: <[email protected]>
Sent: Friday, May 15, 2009 8:33 AM
Subject: JAX-RS: Media Type Determination - Exceptions & Custom Responses
I have services that are returning either XML or JSON data (based on user
Accept headers). However, when an exception occurs or when I want to return
a custom response, I want to respond with the appropriate media type. Take
the example below:
========
@PUT
@Path("/{id}")
public CustomResponse updateContact(@PathParam("id") int id, Contact
contact);
If I PUT as XML, I want to return the following response:
<?xml version="1.0" encoding="utf-8"?>
<response>
<statusCode>200</statusCode>
<message>Success</message>
</response>
However with JSON, I want to return the equivalent JSON response:
{"response":{"statusCode":200,"message":"Success"}}
========
Can I do one of the following?:
1. Easily determine the current media type for the response so that I can
properly serialize.
2. Somehow get CXF to do the serialization to the appropriate type for me.
The same case exists for custom exceptions. Is there anywhere in the
exception handling chain I can determine mime type and do one of the
following?:
1. Have the custom response object generate either XML or JSON based on the
requested media type
2. Get CXF to use a status code plus an entity that will be serialized to
the client (in this case a "response" or "error" object of some form)
Not sure if there is a way to do either of these things?
Cheers,
David