View Javadoc
1   /*
2    * Copyright 2009 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.openehealth.ipf.commons.xml;
17  
18  import java.net.URL;
19  
20  import javax.xml.transform.Source;
21  import javax.xml.transform.TransformerException;
22  import javax.xml.transform.URIResolver;
23  import javax.xml.transform.sax.SAXSource;
24  
25  import org.xml.sax.InputSource;
26  
27  /**
28   * URIResolver used to correctly resolve import commands in xslt or xquery
29   * content. The referenced resource (stylesheet or document) can be found
30   * somewhere in the classloader's classpath. If it can't be found, the default
31   * URIResolver is used.
32   * 
33   * @author Christian Ohr
34   */
35  class ClasspathUriResolver implements URIResolver {
36  
37      private final URIResolver standardResolver;
38      
39      public ClasspathUriResolver(URIResolver resolver) {
40          super();
41          standardResolver = resolver;
42      }
43  
44      /**
45       * Resolve by searching the classpath, fallback to default resolution
46       * strategy.
47       * 
48       */
49      @Override
50      public Source resolve(String href, String base) throws TransformerException {
51          ClassLoader cl = getClass().getClassLoader();
52          URL url = cl.getResource(href);
53          if (url != null) {
54              SAXSource saxSource = new SAXSource();
55              saxSource.setInputSource(new InputSource(url.toString()));
56              saxSource.setSystemId(url.toString());
57              return saxSource;
58          } else {
59              return standardResolver.resolve(href, base);
60          }
61      }
62  
63  }