1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.javagen.agile.core.emitter.template;
17
18 import java.io.File;
19 import java.io.IOException;
20 import java.io.Writer;
21 import java.util.Map;
22
23 import org.javagen.agile.core.emitter.DefaultWriterFactory;
24 import org.javagen.agile.core.emitter.WriterFactory;
25
26 import freemarker.template.Configuration;
27 import freemarker.template.DefaultObjectWrapper;
28 import freemarker.template.Template;
29
30 /***
31 * FreeMarker template implementation.
32 * <p>
33 * At the time of this release FreeMarker was a more capable and uptodate template
34 * engine than Velocity and thus the prefered template engine for JavaGen.
35 * <p>
36 * TODO do we need to add support for freemarker.properties configuration?
37 *
38 * @author Richard Easterling
39 */
40 public class FreemarkerCodeGenerator implements TemplateGenerator {
41
42 public static final String DEFAULT_TEMPLATE_LOCATION_PATH = "/";
43
44 protected String templateBasePath = DEFAULT_TEMPLATE_LOCATION_PATH;
45
46 protected Configuration cfg;
47
48 protected WriterFactory writerFactory;
49
50 public FreemarkerCodeGenerator() {
51 }
52
53 protected Configuration getConfiguration() {
54 if (cfg==null) {
55 try {
56 cfg = new Configuration();
57 if (this.getTemplateBasePath().startsWith("file:")) {
58 cfg.setDirectoryForTemplateLoading(new File(this.getTemplateBasePath().substring("file:".length())));
59 } else {
60 int startPos = this.getTemplateBasePath().startsWith("classpath:") ? "classpath:".length() : 0;
61 String basePath = this.getTemplateBasePath().substring(startPos);
62 cfg.setClassForTemplateLoading(this.getClass(), basePath.startsWith("/") ? basePath : "/"+basePath);
63 }
64 cfg.setObjectWrapper(new DefaultObjectWrapper());
65 } catch (IOException e) {
66 throw new RuntimeException(e);
67 }
68 }
69 return cfg;
70 }
71
72 /*** Process templates. */
73 public void gen(String templatePath, File outFile, Map<String, Object> root)
74 {
75 try {
76
77 Template temp = this.getConfiguration().getTemplate(templatePath);
78 Writer writer = getWriterFactory().createWriter(outFile);
79
80 temp.process(root, writer);
81 writer.flush();
82 writer.close();
83 } catch (Exception e) {
84 e.printStackTrace();
85 throw new RuntimeException("running Freemarker template: "+templatePath, e);
86 }
87 }
88
89 /***
90 * Base path to load templates from which can be prefixed
91 * with <code>classpath:</code> or <code>file:</code> and a path to locate the file in any context.
92 */
93 public String getTemplateBasePath() {
94 return templateBasePath;
95 }
96
97 public void setTemplateBasePath(String templateBasePath) {
98 this.templateBasePath = templateBasePath;
99 }
100
101 public void setWriterFactory(WriterFactory writerFactory) {
102 this.writerFactory = writerFactory;
103 }
104
105 public WriterFactory getWriterFactory() {
106 if (writerFactory == null) {
107 writerFactory = new DefaultWriterFactory();
108 }
109 return writerFactory;
110 }
111
112 }