1 17 18 19 20 package org.apache.fop.servlet; 21 22 import java.io.InputStream ; 23 import java.net.MalformedURLException ; 24 import java.net.URL ; 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 36 public class ServletContextURIResolver implements URIResolver { 37 38 39 public static final String SERVLET_CONTEXT_PROTOCOL = "servlet-context:"; 40 41 private ServletContext servletContext; 42 43 47 public ServletContextURIResolver(ServletContext servletContext) { 48 this.servletContext = servletContext; 49 } 50 51 52 public Source resolve(String href, String base) throws TransformerException { 53 if (href.startsWith(SERVLET_CONTEXT_PROTOCOL)) { 54 return resolveServletContextURI(href.substring(SERVLET_CONTEXT_PROTOCOL.length())); 55 } else { 56 if (base != null 57 && base.startsWith(SERVLET_CONTEXT_PROTOCOL) 58 && (href.indexOf(':') < 0)) { 59 String abs = base + href; 60 return resolveServletContextURI( 61 abs.substring(SERVLET_CONTEXT_PROTOCOL.length())); 62 } else { 63 return null; 64 } 65 } 66 } 67 68 74 protected Source resolveServletContextURI(String path) throws TransformerException { 75 while (path.startsWith("//")) { 76 path = path.substring(1); 77 } 78 try { 79 URL url = this.servletContext.getResource(path); 80 InputStream in = this.servletContext.getResourceAsStream(path); 81 if (in != null) { 82 if (url != null) { 83 return new StreamSource (in, url.toExternalForm()); 84 } else { 85 return new StreamSource (in); 86 } 87 } else { 88 throw new TransformerException ("Resource does not exist. \"" + path 89 + "\" is not accessible through the servlet context."); 90 } 91 } catch (MalformedURLException mfue) { 92 throw new TransformerException ( 93 "Error accessing resource using servlet context: " + path, mfue); 94 } 95 } 96 } 97 | Popular Tags |