How to initialize JAXB with SAX properly?



I have a class where multiple threads access it (Something similar to a servlet). There is a method named onEvent which takes an InputStream and unmarshals the input stream received.


To unmarshal, I initialized JAXB and XMLReader in the constructor like below



try {
jaxbContext = JAXBContext.newInstance(ProductInventory.class);
jaxbUnmarshaller = jaxbContext.createUnmarshaller();
final SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
reader = saxParserFactory.newSAXParser().getXMLReader();
} catch (JAXBException e) {
logger.error("Exception while initializing JAXB", e);
} catch (SAXException | ParserConfigurationException e) {
logger.error("Exception while initializing sax xml reader", e);
}


In the onEvent method I wrote the below code



final InputSource inputSource = new InputSource(inputStream);
final SAXSource saxSource = new SAXSource(reader, inputSource);
SomeClass someClass = (SomeClass) jaxbUnmarshaller.unmarshal(saxSource);


Is the initialization proper? Do I have to initialize the reader evertime a new thread calls onEvent method?


No comments:

Post a Comment