1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.creadur.tentacles;
20
21 import java.io.File;
22 import java.io.IOException;
23 import java.io.Reader;
24 import java.io.StringWriter;
25 import java.io.Writer;
26 import java.util.Map;
27 import java.util.concurrent.ConcurrentHashMap;
28
29 import org.apache.velocity.VelocityContext;
30 import org.apache.velocity.app.VelocityEngine;
31
32 public class TemplateBuilder {
33 private static final String LOG_TAG_NAME = TemplateBuilder.class.getName();
34
35 private final TentaclesResources tentaclesResources;
36 private final VelocityEngine engine;
37 private final IOSystem ioSystem;
38 private final String templateName;
39 private final Map<String, Object> templateContextMap =
40 new ConcurrentHashMap<String, Object>();
41
42 public TemplateBuilder(final String template, final IOSystem ioSystem,
43 final VelocityEngine engine,
44 final TentaclesResources tentaclesResources) {
45 this.templateName = template;
46 this.ioSystem = ioSystem;
47 this.engine = engine;
48 this.tentaclesResources = tentaclesResources;
49 }
50
51 public TemplateBuilder add(final String key, final Object value) {
52 this.templateContextMap.put(key, value);
53 return this;
54 }
55
56 public TemplateBuilder addAll(final Map<String, Object> map) {
57 this.templateContextMap.putAll(map);
58 return this;
59 }
60
61 public String apply() {
62 final StringWriter writer = new StringWriter();
63
64 evaluate(writer);
65
66 return writer.toString();
67 }
68
69 public File write(final File file) throws IOException {
70 this.ioSystem.writeString(file, apply());
71 return file;
72 }
73
74 private void evaluate(final Writer writer) {
75 try {
76 final Reader templateReader =
77 this.tentaclesResources.read(this.templateName);
78
79 final VelocityContext context =
80 new VelocityContext(this.templateContextMap);
81 this.engine.evaluate(context, writer, LOG_TAG_NAME, templateReader);
82
83 } catch (final IOException ioe) {
84 throw new RuntimeException("can't apply template "
85 + this.templateName, ioe);
86 }
87 }
88
89 }