1 16 17 package org.springframework.ui.freemarker; 18 19 import java.io.IOException ; 20 import java.io.InputStreamReader ; 21 import java.io.Reader ; 22 23 import freemarker.cache.TemplateLoader; 24 import org.apache.commons.logging.Log; 25 import org.apache.commons.logging.LogFactory; 26 27 import org.springframework.core.io.Resource; 28 import org.springframework.core.io.ResourceLoader; 29 30 43 public class SpringTemplateLoader implements TemplateLoader { 44 45 protected final Log logger = LogFactory.getLog(getClass()); 46 47 private final ResourceLoader resourceLoader; 48 49 private final String templateLoaderPath; 50 51 52 57 public SpringTemplateLoader(ResourceLoader resourceLoader, String templateLoaderPath) { 58 this.resourceLoader = resourceLoader; 59 if (!templateLoaderPath.endsWith("/")) { 60 templateLoaderPath += "/"; 61 } 62 this.templateLoaderPath = templateLoaderPath; 63 if (logger.isInfoEnabled()) { 64 logger.info("SpringTemplateLoader for FreeMarker: using resource loader [" + this.resourceLoader + 65 "] and template loader path [" + this.templateLoaderPath + "]"); 66 } 67 } 68 69 public Object findTemplateSource(String name) throws IOException { 70 if (logger.isDebugEnabled()) { 71 logger.debug("Looking for FreeMarker template with name [" + name + "]"); 72 } 73 Resource resource = this.resourceLoader.getResource(this.templateLoaderPath + name); 74 return (resource.exists() ? resource : null); 75 } 76 77 public Reader getReader(Object templateSource, String encoding) throws IOException { 78 Resource resource = (Resource) templateSource; 79 try { 80 return new InputStreamReader (resource.getInputStream(), encoding); 81 } 82 catch (IOException ex) { 83 if (logger.isDebugEnabled()) { 84 logger.debug("Could not find FreeMarker template: " + resource); 85 } 86 throw ex; 87 } 88 } 89 90 91 public long getLastModified(Object templateSource) { 92 return -1; 93 } 94 95 public void closeTemplateSource(Object templateSource) throws IOException { 96 } 97 98 } 99 | Popular Tags |