OMAParser.java revision 71a988c8e9859244b83cd55bb6b6ee913fcaf95c
1package com.android.server.wifi.hotspot2.omadm;
2
3import org.xml.sax.Attributes;
4import org.xml.sax.InputSource;
5import org.xml.sax.SAXException;
6import org.xml.sax.helpers.DefaultHandler;
7
8import javax.xml.parsers.ParserConfigurationException;
9import javax.xml.parsers.SAXParser;
10import javax.xml.parsers.SAXParserFactory;
11import java.io.*;
12
13/**
14 * Parses an OMA-DM XML tree.
15 */
16public class OMAParser extends DefaultHandler
17{
18    private XMLNode mRoot;
19    private XMLNode mCurrent;
20
21    public MOTree parse( String text, String urn ) throws IOException, SAXException
22    {
23        try
24        {
25            SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
26            parser.parse( new InputSource( new StringReader( text ) ), this );
27            return new MOTree(mRoot, urn );
28        }
29        catch ( ParserConfigurationException pce )
30        {
31            throw new SAXException( pce );
32        }
33    }
34
35    public MOTree parse( InputStream in, String urn ) throws IOException, SAXException
36    {
37        try
38        {
39            SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
40            parser.parse( new InputSource( in ), this );
41            return new MOTree(mRoot, urn );
42        }
43        catch ( ParserConfigurationException pce )
44        {
45            throw new SAXException( pce );
46        }
47    }
48
49    @Override
50    public void startElement( String uri, String localName, String qName, Attributes attributes ) throws SAXException
51    {
52        XMLNode parent = mCurrent;
53
54        mCurrent = new XMLNode(mCurrent, qName, attributes );
55
56        if ( mRoot == null )
57            mRoot = mCurrent;
58        else
59            parent.addChild(mCurrent);
60    }
61
62    @Override
63    public void endElement( String uri, String localName, String qName ) throws SAXException
64    {
65        if ( ! qName.equals(mCurrent.getTag()) )
66            throw new SAXException( "End tag '" + qName + "' doesn't match current node: " + mCurrent);
67
68        try {
69            mCurrent.close();
70        }
71        catch ( IOException ioe ) {
72            throw new SAXException("Failed to close element", ioe);
73        }
74
75        mCurrent = mCurrent.getParent();
76    }
77
78    @Override
79    public void characters( char[] ch, int start, int length ) throws SAXException
80    {
81        mCurrent.addText(ch, start, length);
82    }
83}
84