View Javadoc

1   /*
2    * $Id: ServletURIResolver.java 651946 2008-04-27 13:41:38Z apetrelli $
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  
22  package org.apache.struts2.views.xslt;
23  
24  import java.io.InputStream;
25  
26  import javax.servlet.ServletContext;
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  import com.opensymphony.xwork2.util.logging.Logger;
33  import com.opensymphony.xwork2.util.logging.LoggerFactory;
34  
35  
36  /***
37   * ServletURIResolver is a URIResolver that can retrieve resources from the servlet context using the scheme "response".
38   * e.g.
39   *
40   * A URI resolver is called when a stylesheet uses an xsl:include, xsl:import, or document() function to find the
41   * resource (file).
42   */
43  public class ServletURIResolver implements URIResolver {
44  
45      private Logger log = LoggerFactory.getLogger(getClass());
46      static final String PROTOCOL = "response:";
47  
48      private ServletContext sc;
49  
50      public ServletURIResolver(ServletContext sc) {
51          log.trace("ServletURIResolver: " + sc);
52          this.sc = sc;
53      }
54  
55      public Source resolve(String href, String base) throws TransformerException {
56          log.debug("ServletURIResolver resolve(): href=" + href + ", base=" + base);
57          if (href.startsWith(PROTOCOL)) {
58              String res = href.substring(PROTOCOL.length());
59              log.debug("Resolving resource <" + res + ">");
60  
61              InputStream is = sc.getResourceAsStream(res);
62  
63              if (is == null) {
64                  throw new TransformerException(
65                          "Resource " + res + " not found in resources.");
66              }
67  
68              return new StreamSource(is);
69          }
70  
71          throw new TransformerException(
72                  "Cannot handle procotol of resource " + href);
73      }
74  }