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);
....
}