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;
11
12import java.io.*;
13
14/**
15 * Parses an OMA-DM XML tree.
16 */
17public class OMAParser extends DefaultHandler {
18    private XMLNode mRoot;
19    private XMLNode mCurrent;
20
21    public MOTree parse(String text, String urn) throws IOException, SAXException {
22        try {
23            SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
24            parser.parse(new InputSource(new StringReader(text)), this);
25            return new MOTree(mRoot, urn);
26        } catch (ParserConfigurationException pce) {
27            throw new SAXException(pce);
28        }
29    }
30
31    @Override
32    public void startElement(String uri, String localName, String qName, Attributes attributes)
33            throws SAXException {
34        XMLNode parent = mCurrent;
35
36        mCurrent = new XMLNode(mCurrent, qName, attributes);
37
38        if (mRoot == null)
39            mRoot = mCurrent;
40        else
41            parent.addChild(mCurrent);
42    }
43
44    @Override
45    public void endElement(String uri, String localName, String qName) throws SAXException {
46        if (!qName.equals(mCurrent.getTag()))
47            throw new SAXException("End tag '" + qName + "' doesn't match current node: " +
48                    mCurrent);
49
50        try {
51            mCurrent.close();
52        } catch (IOException ioe) {
53            throw new SAXException("Failed to close element", ioe);
54        }
55
56        mCurrent = mCurrent.getParent();
57    }
58
59    @Override
60    public void characters(char[] ch, int start, int length) throws SAXException {
61        mCurrent.addText(ch, start, length);
62    }
63}
64