users@jersey.java.net

usage of third party pojos in restful services

From: Suchitha Koneru (sukoneru) <"Suchitha>
Date: Mon, 7 Dec 2009 22:42:10 -0800

Hello Jersey Users ,

             I have landed into the following exception when trying to
use java beans present in a jar file.

"A message body writer for Java type, class java.util.ArrayList, and
MIME media type, application/xml, was not found"

 

The Restful API is

 

      @GET @Path ("alerts")

      @Produces("application/xml")

      

      public List<AlertMemoryData> getAlertData(){

            

            ArrayList<AlertMemoryData> list = new ArrayList
<AlertMemoryData>();

            Random r = new Random();

 

            for(int i=0;i<5;i++){

                  AlertMemoryData alertMemData = new AlertMemoryData();

                  alertMemData.setAdditionalDataId(r.nextInt());

                  alertMemData.setAmdMemoryId(r.nextLong());

                  alertMemData.setAmdTimestamp(r.nextLong());

                  alertMemData.setAmdValue(r.nextInt());

                  list.add(alertMemData);

            }

            return list;

            

      }

 

Here AlertMemoryData is a java pojo defined elsewhere and is included in
the form of a jar in web-inf/lib. I suspected that something must be
going

wrong with marshalling to xml using JAXB

 

I also tried to explicitly serialize the pojo as follows

 

AlertMemoryData memData = new AlertMemoryData();

JAXBContext jc = JAXBContext.newInstance(AlertMemoryData.class);

Marshaller m = jc.createMarshaller();

ByteArrayOutputStream bos = new ByteArrayOutputStream();

m.marshall(memData, bos);

return new String(bos.toByteArray());

 

This led to an exception

com.sun.istack.SAXException2: unable to marshal type
"com.cisco.ca.ast.service.pollingsvcs.datamodel.AlertMemoryData" as an
element because it is missing an @XmlRootElement annotation]

 

 

The java src code for AlertMemoryData(AlertMemoryData.java) has
@XMlRootElement annotation. I am not sure why the class file does not
have it.

 

 

Finally I tried to serialize without the need for the presence of the
annotation @XMLRootElement , as shown below

 

JAXBContext jc = JAXBContext.newInstance(AlertMemoryData.class);

Marshaller m = jc.createMarshaller();

ByteArrayOutputStream bos = new ByteArrayOutputStream();

m.marshal(new JAXBElement<AlertMemoryData>(new QName("uri","local"),
AlertMemoryData.class, memData),bos);

 

This approach worked

 

 Is this a JAXB or a Jersey issue ? Could you please let me know, if
we can configure Jersey to use the second approach of marshalling as it
does not need @XMlRootElement annotation.

 

I also tried to invoke the same API (getAlertData() shown above) via a
Jaxws webservice and it worked out of box without any issues.

 

Thank you,

Suchitha.