Oroboros102
Oroboros102

Reputation: 2254

Feed byte[] to SAXParser

I'm receiving byte arrays (actually, netty's ByteBufs) from underlying network layer in pipeline handler object like this:

class Handler {
    ...
    private SAXParser parser = ...;
    private ContentHandler handler = ...;
    void process(byte[] request) {
        parser.parse(???, handler);
    }
}

Handler.process() is called multiple times per request (as the data arrives from network). How can I feed data to parser without buffering requests into single huge data unit?

Upvotes: 0

Views: 1202

Answers (2)

trustin
trustin

Reputation: 12351

Almost all XML parsers assumes that the source always gives the bytes it wants when it asks. When there are not enough number of bytes in the source, it expects the source to block until it has the bytes.

This design conflicts with the non-blocking source, such as Netty channel.

To work around this impedence mismatch, you need to ensure that your ByteBuf contains a complete XML document. You can ensure that using XmlFrameDecoder. Once XmlFrameDecoder produces a ByteBuf with a complete XML document, you can feed it to your favorite parser by wrapping the buffer with ByteBufInputStream. For example:

InputStream in = new ByteBufInputStream(buf);
parser.parse(in, handler);

Upvotes: 0

kan
kan

Reputation: 28981

Use new ByteArrayInputStream(request).

Upvotes: 3

Related Questions