Today, I needed a quick way to parse a POJO into XML in order to do some quick debugging and verification while writing a JUnit. The setup is that I am mapping a source object to a target object (tedious) and I wanted to make sure fields made it to the target. I chose not to use a framework like Dozer since the mappings were not very straightforward so I decided to do it by hand to handle exceptions, logging, etc… As a result, I needed a way to see if my mappings were applied successfully. I figured that it would be nice if I could dump my object to Xml and look at the result of my mapping visually rather than checking it with a series of getter calls. It turns out that there are utilities in the Axis2 distro that help with this. Axis2 supplies a parser that accepts an ordinary object. The end result is that the properties are parsed into an Xml document that can be dropped to file or logged. Using this approach in a JUnit to compare with a control file is pretty straighforward.
I wouldn’t do this within the context of a Hibernate session as not to trip LazyInit exception, but for freestanding objects this might be useful:
XMLStreamReader reader = BeanUtil.getPullParser(bi); StreamWrapper parser = new StreamWrapper(reader); StAXOMBuilder builder = new StAXOMBuilder(OMAbstractFactory.getOMFactory(),parser); OMElement el = builder.getDocumentElement(); log(el.toString);