1 /*
2  * Copyright (C) 2010 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package com.android.tradefed.util.xml;
17 
18 import com.android.ddmlib.Log;
19 
20 import org.xml.sax.InputSource;
21 import org.xml.sax.SAXException;
22 import org.xml.sax.helpers.DefaultHandler;
23 
24 import java.io.IOException;
25 import java.io.InputStream;
26 
27 import javax.xml.parsers.ParserConfigurationException;
28 import javax.xml.parsers.SAXParser;
29 import javax.xml.parsers.SAXParserFactory;
30 
31 /**
32  * Helper base class for parsing xml files
33  */
34 public abstract class AbstractXmlParser {
35 
36     private static final String LOG_TAG = "XmlDefsParser";
37 
38     /**
39      * Thrown if XML input could not be parsed
40      */
41     @SuppressWarnings("serial")
42     public static class ParseException extends Exception {
ParseException(Throwable cause)43         public ParseException(Throwable cause) {
44             super(cause);
45         }
46     }
47 
48     /**
49      * Parses out xml data contained in given input.
50      *
51      * @param xmlInput
52      * @throws ParseException if input could not be parsed
53      */
parse(InputStream xmlInput)54     public void parse(InputStream xmlInput) throws ParseException  {
55         try {
56             SAXParserFactory parserFactory = SAXParserFactory.newInstance();
57             parserFactory.setNamespaceAware(true);
58             SAXParser parser;
59             parser = parserFactory.newSAXParser();
60 
61             DefaultHandler handler = createXmlHandler();
62             parser.parse(new InputSource(xmlInput), handler);
63         } catch (ParserConfigurationException | SAXException | IOException e) {
64             Log.e(LOG_TAG, e);
65             throw new ParseException(e);
66         }
67     }
68 
69     /**
70      * Creates a {@link DefaultHandler} to process the xml
71      */
createXmlHandler()72     protected abstract DefaultHandler createXmlHandler();
73 
74 }
75