summaryrefslogtreecommitdiffstats
path: root/service/java/com/android/server/wifi/hotspot2/omadm/OMAParser.java
blob: cbcd81d1606e90bea376f894f47031b3e3a9bc66 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package com.android.server.wifi.hotspot2.omadm;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

/**
 * Parses an OMA-DM XML tree.
 * OMA-DM = Open Mobile Association Device Management
 */
public class OMAParser extends DefaultHandler {
    private XMLNode mRoot;
    private XMLNode mCurrent;

    public OMAParser() {
        mRoot = null;
        mCurrent = null;
    }

    public MOTree parse(String text, String urn) throws IOException, SAXException {
        try {
            SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
            parser.parse(new InputSource(new StringReader(text)), this);
            return new MOTree(mRoot, urn);
        } catch (ParserConfigurationException pce) {
            throw new SAXException(pce);
        }
    }

    public XMLNode getRoot() {
        return mRoot;
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes)
            throws SAXException {
        XMLNode parent = mCurrent;

        mCurrent = new XMLNode(mCurrent, qName, attributes);

        if (mRoot == null)
            mRoot = mCurrent;
        else
            parent.addChild(mCurrent);
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        if (!qName.equals(mCurrent.getTag()))
            throw new SAXException("End tag '" + qName + "' doesn't match current node: " +
                    mCurrent);

        try {
            mCurrent.close();
        } catch (IOException ioe) {
            throw new SAXException("Failed to close element", ioe);
        }

        mCurrent = mCurrent.getParent();
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        mCurrent.addText(ch, start, length);
    }
}