1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.myfaces.renderkit.template;
20
21 import java.io.IOException;
22
23 import javax.faces.component.UIComponent;
24 import javax.faces.context.FacesContext;
25 import javax.faces.render.Renderer;
26
27 import org.apache.commons.logging.Log;
28 import org.apache.commons.logging.LogFactory;
29
30 import freemarker.cache.TemplateLoader;
31 import freemarker.template.Configuration;
32 import freemarker.template.DefaultObjectWrapper;
33 import freemarker.template.Template;
34 import freemarker.template.TemplateException;
35
36
37
38
39 public class DefaultTemplateEncoder implements TemplateEncoder
40 {
41 private static final Log log = LogFactory.getLog(DefaultTemplateEncoder.class);
42 private static final String TEMPLATE_CACHE = "org.apache.myfaces.tomahawk.template.DefaultTemplateEncoder.CACHE";
43 private static final String TEMPLATE_DIRECTORY = "template";
44
45 public void encodeTemplate(FacesContext context, UIComponent component, Renderer renderer, String template, Object dataModel)
46 throws IOException
47 {
48 if(log.isDebugEnabled())
49 {
50 log.debug("Encoding template : " + renderer.getClass().getResource(TEMPLATE_DIRECTORY+"/"+template));
51 }
52 Configuration cfg = getConfig(context, TEMPLATE_CACHE);
53
54 Template temp = cfg.getTemplate('/'
55 +renderer.getClass().getPackage().getName().replace('.','/')
56 +'/'+TEMPLATE_DIRECTORY+'/'+template);
57 try
58 {
59 temp.process(dataModel, context.getResponseWriter());
60 }
61 catch (TemplateException e)
62 {
63 throw new IOException(e.getMessage());
64 }
65 }
66
67
68
69
70
71
72
73
74 protected Configuration getConfig(FacesContext context, String cacheParamName)
75 {
76 Configuration config =
77 (Configuration) context.getExternalContext().getApplicationMap().get(cacheParamName);
78 if(config == null)
79 {
80 config = createConfig(context);
81 context.getExternalContext().getApplicationMap().put(cacheParamName, config);
82 }
83 return config;
84 }
85
86 protected Configuration createConfig(FacesContext context)
87 {
88 Configuration config = new Configuration();
89 TemplateLoader templateLoader = new DefaultTemplateLoader();
90 config.setObjectWrapper(new DefaultObjectWrapper());
91 config.setTemplateLoader(templateLoader);
92 return config;
93 }
94 }