View Javadoc

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