How to parse XML to Stanza or XmlFragment in vysper enviroment

236 views Asked by At

To make a nice and readable test case i'd like to parse some hand written XML (copy-paste from xmpp.org), transform it to Stanza or XMLElement and proceed with actual tests. So i'd like to avoid stanza builders at all.

Is such thing possible with Non-blocking XML parser?

1

There are 1 answers

0
Lauri On

In order to obtain XMLElement solution is to use DefaultNonBlockingXMLReader and assign a stanza listener. The trick is to start "stream", so XML of stanza to test should be wrapped to something like ".....

The code:

private Stanza fetchStanza(String xml) throws SAXException {
    try {
        NonBlockingXMLReader reader = new DefaultNonBlockingXMLReader();
        reader.setContentHandler(new XMPPContentHandler(new XMLElementBuilderFactory()));
        XMPPContentHandler contentHandler = (XMPPContentHandler) reader.getContentHandler();
        final ArrayList<Stanza> container = new ArrayList(); // just some container to hold stanza.
        contentHandler.setListener(new XMPPContentHandler.StanzaListener() {
            public void stanza(XMLElement element) {
                Stanza stanza = StanzaBuilder.createClone(element, true, Collections.EMPTY_LIST).build();
                if (!container.isEmpty()) {
                    container.clear(); // we need only last element, so clear the container
                }
                container.add(stanza);
            }
        });
        IoBuffer in = IoBuffer.wrap(("<stream>" + xml + "</stream>").getBytes()); // the trick it to wrap xml to stream
        reader.parse(in, CharsetUtil.UTF8_DECODER);
        Stanza stanza = container.iterator().next();
        return stanza;
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}