1 52 53 package freemarker.cache; 54 55 import java.io.File ; 56 import java.io.FileInputStream ; 57 import java.io.IOException ; 58 import java.io.InputStreamReader ; 59 import java.io.Reader ; 60 import java.net.MalformedURLException ; 61 import java.net.URL ; 62 63 import javax.servlet.ServletContext ; 64 65 import freemarker.log.Logger; 66 67 73 public class WebappTemplateLoader implements TemplateLoader 74 { 75 private static final Logger logger = Logger.getLogger("freemarker.cache"); 76 77 private final ServletContext servletContext; 78 private final String path; 79 80 89 public WebappTemplateLoader(ServletContext servletContext) { 90 this(servletContext, "/"); 91 } 92 93 105 public WebappTemplateLoader(ServletContext servletContext, String path) { 106 if(servletContext == null) { 107 throw new IllegalArgumentException ("servletContext == null"); 108 } 109 if(path == null) { 110 throw new IllegalArgumentException ("path == null"); 111 } 112 113 path = path.replace('\\', '/'); 114 if(!path.endsWith("/")) { 115 path += "/"; 116 } 117 if (!path.startsWith("/")) { 118 path = "/" + path; 119 } 120 this.path = path; 121 this.servletContext = servletContext; 122 } 123 124 public Object findTemplateSource(String name) throws IOException { 125 String fullPath = path + name; 126 try { 128 String realPath = servletContext.getRealPath(fullPath); 129 if (realPath != null) { 130 File file = new File (realPath); 131 if(!file.isFile()) { 132 return null; 133 } 134 if(file.canRead()) { 135 return file; 136 } 137 } 138 } catch (SecurityException e) { 139 ; } 141 142 URL url = null; 144 try { 145 url = servletContext.getResource(fullPath); 146 } catch(MalformedURLException e) { 147 logger.warn("Could not retrieve resource " + fullPath, e); 148 return null; 149 } 150 return url == null ? null : new URLTemplateSource(url); 151 } 152 153 public long getLastModified(Object templateSource) { 154 if (templateSource instanceof File ) { 155 return ((File ) templateSource).lastModified(); 156 } else { 157 return ((URLTemplateSource) templateSource).lastModified(); 158 } 159 } 160 161 public Reader getReader(Object templateSource, String encoding) 162 throws IOException { 163 if (templateSource instanceof File ) { 164 return new InputStreamReader ( 165 new FileInputStream ((File ) templateSource), 166 encoding); 167 } else { 168 return new InputStreamReader ( 169 ((URLTemplateSource) templateSource).getInputStream(), 170 encoding); 171 } 172 } 173 174 public void closeTemplateSource(Object templateSource) throws IOException { 175 if (templateSource instanceof File ) { 176 } else { 178 ((URLTemplateSource) templateSource).close(); 179 } 180 } 181 } | Popular Tags |