0

I am developing a jax-rs web service which will consume XML. Because of a business requirement I need both the XML and the unmarshalled java object. So instead of adding the java type as the method parameter, I am using String as the type and injecting the XML stream into the string.

private static JAXBContext context;
public StudentFacade() throws JAXBException {
    if(context == null) {
        context = JAXBContext.newInstance(Student.class);
    }
}

@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
public Response sendSms(final String xml) throws JAXBException {
    XMLInputFactory xif = XMLInputFactory.newFactory();
    XMLStreamReader xsr = xif.createXMLStreamReader(new ByteArrayInputStream(xml.getBytes()));
    Unmarshaller unmarshaller = context.createUnmarshaller();
    unmarshaller.unmarshal(xsr);
    ....
}

My question, should I create a new XMLInputFactory and Unmarshaller always?

Is the below code valid if I move XMLInputFactory and Unmarshaller to constructor and initialize them only once like the JAXBContext

private static  Unmarshaller unmarshaller;
private static XMLInputFactory xif;
    public StudentFacade() throws JAXBException {
        if(unmarshaller == null) {
            JAXBContext context = JAXBContext.newInstance(Student.class);
            unmarshaller = context.createUnmarshaller();
            xif = XMLInputFactory.newFactory();
        }
    }

@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
public Response sendSms(final String xml) throws JAXBException {

    XMLStreamReader xsr = xif.createXMLStreamReader(new ByteArrayInputStream(xml.getBytes()));

    unmarshaller.unmarshal(xsr);
    ....
}
Krishna Chaitanya
  • 2,533
  • 4
  • 40
  • 74
  • I think I found my answer here http://stackoverflow.com/questions/7400422/jaxb-creating-context-and-marshallers-cost. The answer says to create a new marshaller or Unmarshaller always. – Krishna Chaitanya Mar 15 '17 at 09:21
  • Possible duplicate of [JAXB creating context and marshallers cost](http://stackoverflow.com/questions/7400422/jaxb-creating-context-and-marshallers-cost) – Krishna Chaitanya Mar 15 '17 at 09:22

0 Answers0