4 * License : The MIT License
5 * Copyright(c) 2013 MikuToga Partners
8 package jp.sfjp.mikutoga.xml;
10 import java.io.BufferedInputStream;
11 import java.io.IOException;
12 import java.io.InputStream;
13 import java.net.MalformedURLException;
16 import java.util.ArrayList;
17 import java.util.List;
18 import javax.xml.XMLConstants;
19 import javax.xml.transform.Source;
20 import javax.xml.transform.stream.StreamSource;
21 import javax.xml.validation.Schema;
22 import javax.xml.validation.SchemaFactory;
23 import org.w3c.dom.ls.LSResourceResolver;
24 import org.xml.sax.SAXException;
29 public final class SchemaUtil {
36 throw new AssertionError();
41 * XML Schema 用のスキーマファクトリを返す。
44 public static SchemaFactory newSchemaFactory(){
45 SchemaFactory result = newSchemaFactory(null);
50 * XML Schema 用のスキーマファクトリを返す。
51 * @param resolver カスタムリゾルバ。nullも可。
54 public static SchemaFactory newSchemaFactory(
55 LSResourceResolver resolver ){
56 SchemaFactory schemaFactory =
57 SchemaFactory.newInstance(
58 XMLConstants.W3C_XML_SCHEMA_NS_URI
61 // schemaFactory.setFeature(name, value);
62 // schemaFactory.setProperty(name, object);
64 schemaFactory.setErrorHandler(BotherHandler.HANDLER);
65 schemaFactory.setResourceResolver(resolver);
71 * ローカルリソースをSourceに変換する。
72 * @param resource ローカルリソース
74 * @throws MalformedURLException 不正なURI
75 * @throws IOException オープンエラー
77 private static Source toLocalSource(LocalXmlResource resource)
78 throws MalformedURLException, IOException{
79 URI localUri = resource.getLocalResource();
80 URL localUrl = localUri.toURL();
82 InputStream is = localUrl.openStream();
83 is = new BufferedInputStream(is);
85 Source result = new StreamSource(is);
90 * ローカルリソース群をSource群に変換する。
91 * @param resArray ローカルリソースURI並び
92 * @return XML Source並び
93 * @throws MalformedURLException 不正なURI
94 * @throws IOException オープンエラー
96 private static Source[] toLocalSourceArray(LocalXmlResource... resArray)
97 throws MalformedURLException, IOException{
98 List<Source> sourceList = new ArrayList<>(resArray.length);
100 for(LocalXmlResource resource : resArray){
101 Source localSource = toLocalSource(resource);
102 sourceList.add(localSource);
105 Source[] result = new Source[sourceList.size()];
106 result = sourceList.toArray(result);
115 * @param resolver リゾルバ
116 * @param resArray ローカルスキーマ情報並び
119 public static Schema newSchema(XmlResourceResolver resolver,
120 LocalXmlResource... resArray ){
121 for(LocalXmlResource resource : resArray){
122 resolver.putRedirected(resource);
127 sources = toLocalSourceArray(resArray);
128 }catch(IOException e){ // ビルド障害
130 throw new AssertionError(e);
133 SchemaFactory schemaFactory = newSchemaFactory(resolver);
137 if(sources.length <= 0){
138 // ドキュメント埋め込みスキーマURLにリゾルバ経由でアクセス
139 result = schemaFactory.newSchema();
141 result = schemaFactory.newSchema(sources);
143 }catch(SAXException e){ // Build error
145 throw new AssertionError(e);
148 // TODO: Sourceを閉めるのは誰の責務?