View Javadoc

1   /*
2    * $Id: ServletURIResolver.java 439747 2006-09-03 09:22:46Z mrdon $
3    *
4    * Copyright 2006 The Apache Software Foundation.
5    *
6    * Licensed under the Apache License, Version 2.0 (the "License");
7    * you may not use this file except in compliance with the License.
8    * You may obtain a copy of the License at
9    *
10   *      http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.struts2.views.xslt;
19  
20  import java.io.InputStream;
21  
22  import javax.servlet.ServletContext;
23  import javax.xml.transform.Source;
24  import javax.xml.transform.TransformerException;
25  import javax.xml.transform.URIResolver;
26  import javax.xml.transform.stream.StreamSource;
27  
28  import org.apache.commons.logging.Log;
29  import org.apache.commons.logging.LogFactory;
30  
31  
32  /***
33   * ServletURIResolver is a URIResolver that can retrieve resources from the servlet context using the scheme "response".
34   * e.g.
35   *
36   * A URI resolver is called when a stylesheet uses an xsl:include, xsl:import, or document() function to find the
37   * resource (file).
38   */
39  public class ServletURIResolver implements URIResolver {
40  
41      private Log log = LogFactory.getLog(getClass());
42      static final String PROTOCOL = "response:";
43  
44      private ServletContext sc;
45  
46      public ServletURIResolver(ServletContext sc) {
47          log.trace("ServletURIResolver: " + sc);
48          this.sc = sc;
49      }
50  
51      public Source resolve(String href, String base) throws TransformerException {
52          log.debug("ServletURIResolver resolve(): href=" + href + ", base=" + base);
53          if (href.startsWith(PROTOCOL)) {
54              String res = href.substring(PROTOCOL.length());
55              log.debug("Resolving resource <" + res + ">");
56  
57              InputStream is = sc.getResourceAsStream(res);
58  
59              if (is == null) {
60                  throw new TransformerException(
61                          "Resource " + res + " not found in resources.");
62              }
63  
64              return new StreamSource(is);
65          }
66  
67          throw new TransformerException(
68                  "Cannot handle procotol of resource " + href);
69      }
70  }