/
SimpleTemplateEngine.java
372 lines (344 loc) · 12.9 KB
/
SimpleTemplateEngine.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package groovy.text;
import groovy.lang.Binding;
import groovy.lang.GroovyRuntimeException;
import groovy.lang.GroovyShell;
import groovy.lang.Script;
import groovy.lang.Writable;
import org.apache.groovy.io.StringBuilderWriter;
import org.codehaus.groovy.control.CompilationFailedException;
import org.codehaus.groovy.runtime.InvokerHelper;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.util.Map;
/**
* Processes template source files substituting variables and expressions into
* placeholders in a template source text to produce the desired output.
* <p>
* The template engine uses JSP style <% %> script and <%= %> expression syntax
* or GString style expressions. The variable '<code>out</code>' is bound to the writer that the template
* is being written to.
* <p>
* Frequently, the template source will be in a file but here is a simple
* example providing the template as a string:
* <pre>
* def binding = [
* firstname : "Grace",
* lastname : "Hopper",
* accepted : true,
* title : 'Groovy for COBOL programmers'
* ]
* def engine = new groovy.text.SimpleTemplateEngine()
* def text = '''\
* Dear <%= firstname %> $lastname,
*
* We <% if (accepted) print 'are pleased' else print 'regret' %> \
* to inform you that your paper entitled
* '$title' was ${ accepted ? 'accepted' : 'rejected' }.
*
* The conference committee.
* '''
* def template = engine.createTemplate(text).make(binding)
* println template.toString()
* </pre>
* This example uses a mix of the JSP style and GString style placeholders
* but you can typically use just one style if you wish. Running this
* example will produce this output:
* <pre>
* Dear Grace Hopper,
*
* We are pleased to inform you that your paper entitled
* 'Groovy for COBOL programmers' was accepted.
*
* The conference committee.
* </pre>
* The template engine can also be used as the engine for {@link groovy.servlet.TemplateServlet} by placing the
* following in your <code>web.xml</code> file (plus a corresponding servlet-mapping element):
* <pre>
* <servlet>
* <servlet-name>SimpleTemplate</servlet-name>
* <servlet-class>groovy.servlet.TemplateServlet</servlet-class>
* <init-param>
* <param-name>template.engine</param-name>
* <param-value>groovy.text.SimpleTemplateEngine</param-value>
* </init-param>
* </servlet>
* </pre>
* In this case, your template source file should be HTML with the appropriate embedded placeholders.
*
* @author sam
* @author Christian Stein
* @author Paul King
* @author Alex Tkachman
*/
public class SimpleTemplateEngine extends TemplateEngine {
private boolean verbose;
private static int counter = 1;
private GroovyShell groovyShell;
private boolean escapeBackslash;
public SimpleTemplateEngine() {
this(GroovyShell.class.getClassLoader());
}
public SimpleTemplateEngine(boolean verbose) {
this(GroovyShell.class.getClassLoader());
setVerbose(verbose);
}
public SimpleTemplateEngine(ClassLoader parentLoader) {
this(new GroovyShell(parentLoader));
}
public SimpleTemplateEngine(GroovyShell groovyShell) {
this.groovyShell = groovyShell;
}
public Template createTemplate(Reader reader) throws CompilationFailedException, IOException {
SimpleTemplate template = new SimpleTemplate(escapeBackslash);
String script = template.parse(reader);
if (verbose) {
System.out.println("\n-- script source --");
System.out.print(script);
System.out.println("\n-- script end --\n");
}
try {
template.script = groovyShell.parse(script, "SimpleTemplateScript" + counter++ + ".groovy");
} catch (Exception e) {
throw new GroovyRuntimeException("Failed to parse template script (your template may contain an error or be trying to use expressions not currently supported): " + e.getMessage());
}
return template;
}
/**
* @param verbose true if you want the engine to display the template source file for debugging purposes
*/
public void setVerbose(boolean verbose) {
this.verbose = verbose;
}
public boolean isVerbose() {
return verbose;
}
private static class SimpleTemplate implements Template {
protected Script script;
private boolean escapeBackslash;
public SimpleTemplate() {
this(false);
}
public SimpleTemplate(boolean escapeBackslash) {
this.escapeBackslash = escapeBackslash;
}
public Writable make() {
return make(null);
}
public Writable make(final Map map) {
return new Writable() {
/**
* Write the template document with the set binding applied to the writer.
*
* @see groovy.lang.Writable#writeTo(java.io.Writer)
*/
public Writer writeTo(Writer writer) {
Binding binding;
if (map == null)
binding = new Binding();
else
binding = new Binding(map);
Script scriptObject = InvokerHelper.createScript(script.getClass(), binding);
PrintWriter pw = new PrintWriter(writer);
scriptObject.setProperty("out", pw);
scriptObject.run();
pw.flush();
return writer;
}
/**
* Convert the template and binding into a result String.
*
* @see java.lang.Object#toString()
*/
public String toString() {
Writer sw = new StringBuilderWriter();
writeTo(sw);
return sw.toString();
}
};
}
/**
* Parse the text document looking for <% or <%= and then call out to the appropriate handler, otherwise copy the text directly
* into the script while escaping quotes.
*
* @param reader a reader for the template text
* @return the parsed text
* @throws IOException if something goes wrong
*/
protected String parse(Reader reader) throws IOException {
if (!reader.markSupported()) {
reader = new BufferedReader(reader);
}
StringBuilderWriter sw = new StringBuilderWriter();
startScript(sw);
int c;
while ((c = reader.read()) != -1) {
if (c == '<') {
reader.mark(1);
c = reader.read();
if (c != '%') {
sw.write('<');
reader.reset();
} else {
reader.mark(1);
c = reader.read();
if (c == '=') {
groovyExpression(reader, sw);
} else {
reader.reset();
groovySection(reader, sw);
}
}
continue; // at least '<' is consumed ... read next chars.
}
if (c == '$') {
reader.mark(1);
c = reader.read();
if (c != '{') {
sw.write('$');
reader.reset();
} else {
reader.mark(1);
sw.write("${");
processGSstring(reader, sw);
}
continue; // at least '$' is consumed ... read next chars.
}
if (c == '\"') {
sw.write('\\');
}
/*
* GROOVY-4585
* Handle backslash characters.
*/
if (escapeBackslash) {
if (c == '\\') {
reader.mark(1);
c = reader.read();
if (c != '$') {
sw.write("\\\\");
reader.reset();
} else {
sw.write("\\$");
}
continue;
}
}
/*
* Handle raw new line characters.
*/
if (c == '\n' || c == '\r') {
if (c == '\r') { // on Windows, "\r\n" is a new line.
reader.mark(1);
c = reader.read();
if (c != '\n') {
reader.reset();
}
}
sw.write("\n");
continue;
}
sw.write(c);
}
endScript(sw);
return sw.toString();
}
private void startScript(StringBuilderWriter sw) {
sw.write("out.print(\"\"\"");
}
private void endScript(StringBuilderWriter sw) {
sw.write("\"\"\");\n");
sw.write("\n/* Generated by SimpleTemplateEngine */");
}
private void processGSstring(Reader reader, StringBuilderWriter sw) throws IOException {
int c;
while ((c = reader.read()) != -1) {
if (c != '\n' && c != '\r') {
sw.write(c);
}
if (c == '}') {
break;
}
}
}
/**
* Closes the currently open write and writes out the following text as a GString expression until it reaches an end %>.
*
* @param reader a reader for the template text
* @param sw a StringBuilderWriter to write expression content
* @throws IOException if something goes wrong
*/
private void groovyExpression(Reader reader, StringBuilderWriter sw) throws IOException {
sw.write("${");
int c;
while ((c = reader.read()) != -1) {
if (c == '%') {
c = reader.read();
if (c != '>') {
sw.write('%');
} else {
break;
}
}
if (c != '\n' && c != '\r') {
sw.write(c);
}
}
sw.write("}");
}
/**
* Closes the currently open write and writes the following text as normal Groovy script code until it reaches an end %>.
*
* @param reader a reader for the template text
* @param sw a StringBuilderWriter to write expression content
* @throws IOException if something goes wrong
*/
private void groovySection(Reader reader, StringBuilderWriter sw) throws IOException {
sw.write("\"\"\");");
int c;
while ((c = reader.read()) != -1) {
if (c == '%') {
c = reader.read();
if (c != '>') {
sw.write('%');
} else {
break;
}
}
/* Don't eat EOL chars in sections - as they are valid instruction separators.
* See https://issues.apache.org/jira/browse/GROOVY-980
*/
// if (c != '\n' && c != '\r') {
sw.write(c);
//}
}
sw.write(";\nout.print(\"\"\"");
}
}
public boolean isEscapeBackslash() {
return escapeBackslash;
}
public void setEscapeBackslash(boolean escapeBackslash) {
this.escapeBackslash = escapeBackslash;
}
}