OSDN Git Service

SAX対応
[mikutoga/Pmd2XML.git] / src / main / java / jp / sfjp / mikutoga / pmd / model / xml / XmlPmdLoader.java
1 /*
2  * xml to pmd loader
3  *
4  * License : The MIT License
5  * Copyright(c) 2013 MikuToga Partners
6  */
7
8 package jp.sfjp.mikutoga.pmd.model.xml;
9
10 import java.io.IOException;
11 import jp.sfjp.mikutoga.pmd.model.PmdModel;
12 import jp.sfjp.mikutoga.xml.TogaXmlException;
13 import org.xml.sax.InputSource;
14 import org.xml.sax.SAXException;
15 import org.xml.sax.XMLReader;
16
17 /**
18  * XMLモデルファイルを読み込むためのローダ。
19  */
20 public class XmlPmdLoader {
21
22     private static final String SAXFEATURES_NAMESPACES =
23             "http://xml.org/sax/features/namespaces";
24
25     private final XMLReader reader;
26
27
28     /**
29      * コンストラクタ。
30      * <p>XMLリーダは名前空間をサポートしていなければならない。
31      * @param reader XMLリーダ
32      * @throws NullPointerException 引数がnull
33      * @throws SAXException 機能不足のXMLリーダが渡された
34      */
35     public XmlPmdLoader(XMLReader reader)
36             throws NullPointerException, SAXException {
37         super();
38
39         if(reader == null) throw new NullPointerException();
40         if( ! reader.getFeature(SAXFEATURES_NAMESPACES) ){
41             throw new SAXException();
42         }
43
44         this.reader = reader;
45
46         return;
47     }
48
49
50     /**
51      * XMLのパースを開始する。
52      * @param source XML入力
53      * @return モデルデータ
54      * @throws SAXException 構文エラー
55      * @throws IOException 入力エラー
56      * @throws TogaXmlException 構文エラー
57      */
58     public PmdModel parse(InputSource source)
59             throws SAXException, IOException, TogaXmlException{
60         XmlHandler saxHandler = new XmlHandler();
61         this.reader.setContentHandler(saxHandler);
62
63         try{
64             this.reader.parse(source);
65         }catch(SAXException e){
66             Throwable cause = e.getCause();
67             if(cause instanceof TogaXmlException){
68                 throw (TogaXmlException) cause;
69             }
70             throw e;
71         }
72
73         return saxHandler.getPmdModel();
74     }
75
76 }