1 package net.sf.jlayercheck.out.html;
2
3 import java.io.Writer;
4 import java.text.SimpleDateFormat;
5 import java.util.Date;
6 import java.util.Map;
7
8 import org.apache.velocity.VelocityContext;
9 import org.apache.velocity.app.Velocity;
10 import org.apache.velocity.exception.MethodInvocationException;
11 import org.apache.velocity.exception.ParseErrorException;
12 import org.apache.velocity.exception.ResourceNotFoundException;
13
14
15
16
17
18
19
20
21 public class VelocityGenerator {
22
23
24 public static final String DEFAULT_ENCODING = "UTF-8";
25
26 static {
27
28 try {
29 Velocity.init();
30 } catch (Exception e) {
31 throw new InternalError("Cannot initialize velocity: " + e);
32 }
33 }
34
35
36
37
38 protected String template;
39
40
41 protected VelocityContext context;
42
43
44
45
46
47
48 public VelocityGenerator() {
49 super();
50 }
51
52
53
54
55
56
57
58
59
60 public VelocityGenerator(String template, Map<String, Object> addCtx) {
61 this();
62 setTemplate(template);
63 addToContext(addCtx);
64 }
65
66
67
68 public String getTemplate() {
69 return template;
70 }
71
72 public void setTemplate(String template) {
73 this.template = template;
74
75 getContext().put("templateName", template);
76
77 }
78
79
80
81
82
83
84 public VelocityContext getContext() {
85 if (context == null) {
86
87 context = new VelocityContext();
88
89
90 Date now = new Date();
91 context.put("now", now);
92 context.put("nowIso", new SimpleDateFormat("yyyy-MM-dd_HH:mm:ssZ")
93 .format(now));
94 context
95 .put("today", SimpleDateFormat.getDateInstance()
96 .format(now));
97 context.put("todayIso", new SimpleDateFormat("yyyy-MM-dd")
98 .format(now));
99
100
101 context.put("context", context);
102
103
104 context.put("generator", this);
105
106 }
107 return context;
108 }
109
110
111
112
113
114
115
116 public void setContext(VelocityContext context) {
117 this.context = context;
118 }
119
120
121
122
123
124
125
126 public void addToContext(Map<String, Object> addCtx) {
127 if (context == null) {
128
129 getContext();
130 }
131 for (Map.Entry<String, Object> entry : addCtx.entrySet()) {
132 context.put(entry.getKey(), entry.getValue());
133 }
134 }
135
136
137
138
139
140
141
142 public void generate(Writer writer) {
143 if (writer == null)
144 throw new NullPointerException("writer must not be null!");
145
146 String templateName = getTemplate();
147 if (templateName == null)
148 throw new NullPointerException("template must not be null!");
149
150 try {
151
152 Velocity.mergeTemplate(templateName, DEFAULT_ENCODING,
153 getContext(), writer);
154 } catch (ResourceNotFoundException e) {
155
156 throw new RuntimeException(e);
157 } catch (ParseErrorException e) {
158
159 throw new RuntimeException(e);
160 } catch (MethodInvocationException e) {
161
162 throw new RuntimeException(e);
163 } catch (Exception e) {
164
165 throw new RuntimeException(e);
166 }
167
168 }
169
170 }