1package com.android.hotspot2.osu;
2
3import com.android.hotspot2.omadm.XMLNode;
4
5import org.xml.sax.Attributes;
6import org.xml.sax.InputSource;
7import org.xml.sax.SAXException;
8import org.xml.sax.helpers.DefaultHandler;
9
10import java.io.BufferedReader;
11import java.io.IOException;
12import java.io.InputStream;
13import java.io.InputStreamReader;
14import java.nio.charset.StandardCharsets;
15
16import javax.xml.parsers.ParserConfigurationException;
17import javax.xml.parsers.SAXParser;
18import javax.xml.parsers.SAXParserFactory;
19
20public class XMLParser extends DefaultHandler {
21    private final SAXParser mParser;
22    private final InputSource mInputSource;
23
24    private XMLNode mRoot;
25    private XMLNode mCurrent;
26
27    public XMLParser(InputStream in) throws ParserConfigurationException, SAXException {
28        mParser = SAXParserFactory.newInstance().newSAXParser();
29        mInputSource = new InputSource(new BufferedReader(
30                new InputStreamReader(in, StandardCharsets.UTF_8)));
31    }
32
33    public XMLNode getRoot() throws SAXException, IOException {
34        mParser.parse(mInputSource, this);
35        return mRoot;
36    }
37
38    @Override
39    public void startElement(String uri, String localName, String qName, Attributes attributes)
40            throws SAXException {
41        XMLNode parent = mCurrent;
42
43        mCurrent = new XMLNode(mCurrent, qName, attributes);
44        //System.out.println("Added " + mCurrent.getTag() + ", atts " + mCurrent.getAttributes());
45
46        if (mRoot == null)
47            mRoot = mCurrent;
48        else
49            parent.addChild(mCurrent);
50    }
51
52    @Override
53    public void endElement(String uri, String localName, String qName) throws SAXException {
54        if (!qName.equals(mCurrent.getTag()))
55            throw new SAXException("End tag '" + qName + "' doesn't match current node: " +
56                    mCurrent);
57
58        try {
59            mCurrent.close();
60        } catch (IOException ioe) {
61            throw new SAXException("Failed to close element", ioe);
62        }
63
64        mCurrent = mCurrent.getParent();
65    }
66
67    @Override
68    public void characters(char[] ch, int start, int length) throws SAXException {
69        mCurrent.addText(ch, start, length);
70    }
71}
72