6ee7389e4014256d03c67acaa1a7d260e4971f7a
[utils] / support / general / src / main / java / org / wamblee / xml / ClasspathUriResolver.java
1 /*
2  * Copyright 2005-2010 the original author or authors.
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 org.wamblee.xml;
17
18 import org.w3c.dom.ls.DOMImplementationLS;
19 import org.w3c.dom.ls.LSInput;
20 import org.w3c.dom.ls.LSResourceResolver;
21 import org.wamblee.io.ClassPathResource;
22 import org.wamblee.io.InputResource;
23
24 import java.io.IOException;
25 import java.io.InputStream;
26
27 import javax.xml.transform.Source;
28 import javax.xml.transform.TransformerException;
29 import javax.xml.transform.URIResolver;
30 import javax.xml.transform.stream.StreamSource;
31
32 /**
33  * URI resolver that resolves stylesheets through the classpath.
34  */
35 public class ClasspathUriResolver implements URIResolver, LSResourceResolver {
36     /**
37      * Constructs the resolver.
38      * 
39      */
40     public ClasspathUriResolver() {
41         // Empty.
42     }
43
44     /*
45      * (non-Javadoc)
46      * 
47      * @see javax.xml.transform.URIResolver#resolve(java.lang.String,
48      * java.lang.String)
49      */
50     public Source resolve(String aHref, String aBase)
51         throws TransformerException {
52         InputResource xslt = new ClassPathResource(aHref);
53
54         try {
55             return new StreamSource(xslt.getInputStream());
56         } catch (IOException e) {
57             throw new TransformerException(
58                 "Could not get XSLT style sheet in classpath '" + aHref + "'",
59                 e);
60         }
61     }
62
63     @Override
64     public LSInput resolveResource(String aType, String aNamespaceURI,
65         String aPublicId, String aSystemId, String aBaseURI) {
66         try {
67             InputStream xslt = new ClassPathResource(aSystemId)
68                 .getInputStream();
69             DOMImplementationLS impl = DomUtils.getDomImplementationLS();
70             LSInput input = impl.createLSInput();
71             input.setPublicId(aPublicId);
72             input.setSystemId(aSystemId);
73             input.setByteStream(xslt);
74             return input;
75         } catch (IOException e) {
76             return null;
77         }
78        
79        
80     }
81
82 }