1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.nuxeo.build.ant.ftl;
18
19 import java.io.File;
20 import java.io.Writer;
21 import java.util.HashMap;
22 import java.util.Map;
23
24 import org.apache.tools.ant.BuildException;
25 import org.apache.tools.ant.Project;
26 import org.nuxeo.build.maven.AntBuildMojo;
27
28 import freemarker.cache.FileTemplateLoader;
29 import freemarker.template.Configuration;
30 import freemarker.template.Template;
31
32
33
34
35 public class FreemarkerEngine {
36
37 protected Configuration cfg;
38
39 public FreemarkerEngine() {
40 cfg = getDefaultConfiguration();
41 }
42
43 public void setBaseDir(File baseDir) throws BuildException {
44 try {
45 cfg.setTemplateLoader(new FileTemplateLoader(baseDir));
46 } catch (Exception e) {
47 throw new BuildException("Failed to create FreeMarker configuration", e);
48 }
49 }
50
51 public Configuration getConfiguration() {
52 return cfg;
53 }
54
55 protected Configuration getDefaultConfiguration() {
56 Configuration configuration = new Configuration(Configuration.getVersion());
57 configuration.setWhitespaceStripping(true);
58 configuration.setLocalizedLookup(false);
59 configuration.setClassicCompatible(true);
60 return configuration;
61 }
62
63 public Object createInput(Project project) {
64 Map<String, Object> root = new HashMap<>();
65 root.putAll(project.getProperties());
66 root.put("ant", project.getProperties());
67 root.put("system", System.getProperties());
68 root.put("profiles", AntBuildMojo.getInstance().getAntProfileManager());
69 root.put("graph", AntBuildMojo.getInstance().getGraph());
70 return root;
71 }
72
73 public Template getTemplate(String name) {
74 try {
75 return cfg.getTemplate(name);
76 } catch (Exception e) {
77 throw new BuildException("Failed to create template " + name, e);
78 }
79 }
80
81 public void process(Project project, String name, Writer writer) {
82 process(createInput(project), name, writer);
83 }
84
85 public void process(Object input, String name, Writer writer) {
86 try {
87 Template tpl = cfg.getTemplate(name);
88 tpl.process(input, writer);
89 } catch (Exception e) {
90 throw new BuildException("Failed to process template " + name, e);
91 }
92 }
93
94 }