You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@mina.apache.org by Ashish <pa...@gmail.com> on 2009/04/13 16:05:12 UTC

XML Pull Parser based XML Decoder implementation

Based on Emmanuel's recommendation of using a pull parser, tried to
implement a basic XML Decoder.

Managed to got the implementation work, but with a problem, getting
some junk character's at the end in my IoHandler
I think I am messing something up while working with IoBuffer. Using MINA 2.0 M4

Input
MINA pom.xml

steps
1. provide IoBuffer as stream to parser
2. Pull events from parser, till END of Document is detected
3. If EOF Exception is there, means we need more data, reset IoBuffer
and return false
4. Once end of Document is detected, convert to String and write to
decoder output

Here is the code

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

public class StaxXMLDecoder extends CumulativeProtocolDecoder {
	
	XmlPullParserFactory factory = null;

	
	public StaxXMLDecoder() {
		try {
			factory = XmlPullParserFactory.newInstance();
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		}
		factory.setNamespaceAware(true);
	}
	

	@Override
	protected boolean doDecode(IoSession ioSession, IoBuffer ioBuffer,
			ProtocolDecoderOutput decoderOutput) throws Exception {
		int startPosition = ioBuffer.position();
		XmlPullParser xpp = factory.newPullParser();

        xpp.setInput(ioBuffer.asInputStream(), null);
        int eventType = xpp.getEventType();
        while (eventType != XmlPullParser.END_DOCUMENT) {
            try {
            	eventType = xpp.next();
            	if(eventType == XmlPullParser.END_DOCUMENT) {
            		String xml = new String(ioBuffer.array(), xpp.getInputEncoding());
            		decoderOutput.write(xml);
                    return true;
            	}
            } catch (EOFException eofEx) {
            	break;
            }catch (XmlPullParserException pullEx) {
            	break;
            }

        }
        ioBuffer.position(startPosition);
		return false;
	}

}

Used XPP3 parser. Woodstox based implementation is yet to be done.

This could have been a little better. Any suggestions on how to make
it more efficient???

-- 
thanks
ashish

Blog: http://www.ashishpaliwal.com/blog
My Photo Galleries: http://www.pbase.com/ashishpaliwal