1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
31
32
33
34
35
36
37
38
39
40 public class SpringTemplateLoader implements TemplateLoader {
41
42 protected final Log logger = LogFactory.getLog(getClass());
43
44 private final ResourceLoader resourceLoader;
45
46 private final String templateLoaderPath;
47
48
49
50
51
52
53
54 public SpringTemplateLoader(ResourceLoader resourceLoader, String templateLoaderPath) {
55 this.resourceLoader = resourceLoader;
56 if (!templateLoaderPath.endsWith("/")) {
57 templateLoaderPath += "/";
58 }
59 this.templateLoaderPath = templateLoaderPath;
60 if (logger.isInfoEnabled()) {
61 logger.info("SpringTemplateLoader for FreeMarker: using resource loader [" + this.resourceLoader +
62 "] and template loader path [" + this.templateLoaderPath + "]");
63 }
64 }
65
66
67 @Override
68 public Object findTemplateSource(String name) throws IOException {
69 if (logger.isDebugEnabled()) {
70 logger.debug("Looking for FreeMarker template with name [" + name + "]");
71 }
72 Resource resource = this.resourceLoader.getResource(this.templateLoaderPath + name);
73 return (resource.exists() ? resource : null);
74 }
75
76 @Override
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 @Override
91 public long getLastModified(Object templateSource) {
92 Resource resource = (Resource) templateSource;
93 try {
94 return resource.lastModified();
95 }
96 catch (IOException ex) {
97 if (logger.isDebugEnabled()) {
98 logger.debug("Could not obtain last-modified timestamp for FreeMarker template in " +
99 resource + ": " + ex);
100 }
101 return -1;
102 }
103 }
104
105 @Override
106 public void closeTemplateSource(Object templateSource) throws IOException {
107 }
108
109 }