users@jersey.java.net

Re: [Jersey] entities encoding issues in the response

From: Arul Dhesiaseelan <arul_at_fluxcorp.com>
Date: Thu, 15 May 2008 10:56:47 -0600

Hi Paul,

Thanks for the help.

Do you think if this would work? I implemented XMLStreamWriter as per
Tatu's suggestion.

Do I need to unmarshal first in this case? Please correct me if I am
doing something wrong here.

@ProduceMime("application/xml")
@Provider
public class CDATAProvider implements MessageBodyWriter<CellType> {

    public void writeTo(CellType cellType,
            Class<?> type, Type genericType, Annotation annotations[],
            MediaType mediaType, MultivaluedMap<String, Object> headers,
            OutputStream out) throws IOException {
      try {
        JAXBContext jc = JAXBContext.newInstance();
        Marshaller marshaller = jc.createMarshaller();
        StringWriter writer = new StringWriter();
        XMLStreamWriter swImpl =
XMLOutputFactory.newInstance().createXMLStreamWriter(writer);
        XMLStreamWriter sw = new MyStreamWriter(swImpl);
        marshaller.marshal(cellType, sw);
      } catch (XMLStreamException xse) {
        System.out.println(xse.getMessage());
      } catch (JAXBException je) {
        System.out.println(je.getMessage());
      }
    }

    public boolean isWriteable(Class<?> type, Type genericType,
Annotation annotations[]) {
        return CellType.class.isAssignableFrom(type);
    }

    public long getSize(CellType cellType) {
        return -1;
    }
}

Thanks!
Arul

Paul Sandoz wrote:
> Hi Arul,
>
> The write to method is not going to serialize out any XML. It is just
> going to serialize out the String "value" as UTF-8 encoded characters.
>
> In the writeTo method you need to use JAXB marshalling on the CellType
> object. And you need to use the Apache XML serializer [1] or wrapping
> the XMLStreamWriter as recommended by Tatu. I think the latter is easier.
>
> Tatu, is there a helper class in Woodstox for XMLStreamWriter that is
> the equivalent of javax.xml.stream.util.StreamReaderDelegate ?
>
> Paul.
>
> [1] https://jaxb.dev.java.net/faq/JaxbCDATASample.java
>
>