1 package org.apache.turbine.services.velocity;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 import java.io.ByteArrayOutputStream;
25 import java.io.OutputStream;
26 import java.io.OutputStreamWriter;
27 import java.io.Writer;
28 import java.nio.charset.Charset;
29 import java.util.Iterator;
30 import java.util.List;
31
32 import org.apache.commons.configuration2.Configuration;
33 import org.apache.logging.log4j.LogManager;
34 import org.apache.logging.log4j.Logger;
35 import org.apache.turbine.Turbine;
36 import org.apache.turbine.pipeline.PipelineData;
37 import org.apache.turbine.services.InitializationException;
38 import org.apache.turbine.services.TurbineServices;
39 import org.apache.turbine.services.pull.PullService;
40 import org.apache.turbine.services.template.BaseTemplateEngineService;
41 import org.apache.turbine.util.LocaleUtils;
42 import org.apache.turbine.util.RunData;
43 import org.apache.turbine.util.TurbineException;
44 import org.apache.velocity.VelocityContext;
45 import org.apache.velocity.app.VelocityEngine;
46 import org.apache.velocity.app.event.EventCartridge;
47 import org.apache.velocity.app.event.MethodExceptionEventHandler;
48 import org.apache.velocity.context.Context;
49 import org.apache.velocity.runtime.RuntimeConstants;
50 import org.apache.velocity.util.introspection.Info;
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 public class TurbineVelocityService
81 extends BaseTemplateEngineService
82 implements VelocityService,
83 MethodExceptionEventHandler
84 {
85
86 private static final String RESOURCE_LOADER_PATH = ".resource.loader.path";
87
88
89 private static final String JAR_PREFIX = "jar:";
90
91
92 private static final String ABSOLUTE_PREFIX = "file://";
93
94
95 private static final Logger log = LogManager.getLogger(TurbineVelocityService.class);
96
97
98 private Charset defaultInputEncoding;
99
100
101 private Charset defaultOutputEncoding;
102
103
104 private boolean pullModelActive = false;
105
106
107 private boolean catchErrors = true;
108
109
110 private VelocityEngine velocity = null;
111
112
113 private PullService pullService = null;
114
115
116
117
118
119
120
121
122
123
124 @Override
125 public void init()
126 throws InitializationException
127 {
128 try
129 {
130 velocity = getInitializedVelocityEngine();
131
132
133
134
135 if (TurbineServices.getInstance().isRegistered(PullService.SERVICE_NAME))
136 {
137 pullModelActive = true;
138 pullService = (PullService)TurbineServices.getInstance().getService(PullService.SERVICE_NAME);
139
140 log.debug("Activated Pull Tools");
141 }
142
143
144 registerConfiguration(VelocityService.VELOCITY_EXTENSION);
145
146 String inputEncoding = getConfiguration().getString("input.encoding", LocaleUtils.getDefaultInputEncoding());
147 defaultInputEncoding = Charset.forName(inputEncoding);
148
149 String outputEncodingString = getConfiguration().getString("output.encoding");
150 if (outputEncodingString == null)
151 {
152 Charset outputEncoding = LocaleUtils.getOverrideCharset();
153 if (outputEncoding == null)
154 {
155 outputEncoding = defaultInputEncoding;
156 }
157
158 defaultOutputEncoding = outputEncoding;
159 }
160 else
161 {
162 defaultOutputEncoding = Charset.forName(outputEncodingString);
163 }
164
165 setInit(true);
166 }
167 catch (Exception e)
168 {
169 throw new InitializationException(
170 "Failed to initialize TurbineVelocityService", e);
171 }
172 }
173
174
175
176
177
178
179 @Override
180 public Context getContext()
181 {
182 Context globalContext =
183 pullModelActive ? pullService.getGlobalContext() : null;
184
185 Context ctx = new VelocityContext(globalContext);
186 return ctx;
187 }
188
189
190
191
192
193
194 @Override
195 public Context getNewContext()
196 {
197 Context ctx = new VelocityContext();
198
199
200
201 EventCartridge ec = new EventCartridge();
202 ec.addEventHandler(this);
203 ec.attachToContext(ctx);
204 return ctx;
205 }
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221 @Override
222 public Object methodException(Context context, @SuppressWarnings("rawtypes") Class clazz, String method, Exception e, Info info)
223 {
224 log.error("Class {}.{} threw Exception", clazz.getName(), method, e);
225
226 if (!catchErrors)
227 {
228 throw new RuntimeException(e);
229 }
230
231 return "[Turbine caught an Error in template " + info.getTemplateName()
232 + ", l:" + info.getLine()
233 + ", c:" + info.getColumn()
234 + ". Look into the turbine.log for further information]";
235 }
236
237
238
239
240
241
242
243
244
245 @Override
246 public Context getContext(PipelineData pipelineData)
247 {
248
249 RunData"../../../../../org/apache/turbine/util/RunData.html#RunData">RunData data = (RunData)pipelineData;
250
251
252 Context context = (Context)
253 data.getTemplateInfo().getTemplateContext(VelocityService.CONTEXT);
254
255 if (context == null)
256 {
257 context = getContext();
258 context.put(VelocityService.RUNDATA_KEY, data);
259
260 context.put(VelocityService.PIPELINEDATA_KEY, pipelineData);
261
262 if (pullModelActive)
263 {
264
265
266
267
268 pullService.populateContext(context, pipelineData);
269 }
270
271 data.getTemplateInfo().setTemplateContext(
272 VelocityService.CONTEXT, context);
273 }
274 return context;
275 }
276
277
278
279
280
281
282
283
284
285
286
287
288 @Override
289 public String handleRequest(Context context, String filename)
290 throws TurbineException
291 {
292 String results = null;
293 OutputStreamWriter writer = null;
294 Charset charset = getOutputCharSet(context);
295
296 try (ByteArrayOutputStream bytes = new ByteArrayOutputStream())
297 {
298 writer = new OutputStreamWriter(bytes, charset);
299
300 executeRequest(context, filename, writer);
301 writer.flush();
302 results = bytes.toString(charset.name());
303 }
304 catch (Exception e)
305 {
306 renderingError(filename, e);
307 }
308
309 return results;
310 }
311
312
313
314
315
316
317
318
319
320
321
322
323
324 @Override
325 public void handleRequest(Context context, String filename,
326 OutputStream output)
327 throws TurbineException
328 {
329 Charset charset = getOutputCharSet(context);
330
331 try (OutputStreamWriter writer = new OutputStreamWriter(output, charset))
332 {
333 executeRequest(context, filename, writer);
334 }
335 catch (Exception e)
336 {
337 renderingError(filename, e);
338 }
339 }
340
341
342
343
344
345
346
347
348
349
350
351
352
353 @Override
354 public void handleRequest(Context context, String filename, Writer writer)
355 throws TurbineException
356 {
357 try
358 {
359 executeRequest(context, filename, writer);
360 }
361 catch (Exception e)
362 {
363 renderingError(filename, e);
364 }
365 finally
366 {
367 try
368 {
369 if (writer != null)
370 {
371 writer.flush();
372 }
373 }
374 catch (Exception ignored)
375 {
376
377 }
378 }
379 }
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394 private void executeRequest(Context context, String filename,
395 Writer writer)
396 throws Exception
397 {
398 Charset encoding = getTemplateEncoding(context);
399
400 if (encoding == null)
401 {
402 encoding = defaultOutputEncoding;
403 }
404
405 velocity.mergeTemplate(filename, encoding.name(), context, writer);
406 }
407
408
409
410
411
412
413
414 private Charset getOutputCharSet(Context context)
415 {
416 Charset charset = null;
417
418 Object data = context.get(VelocityService.RUNDATA_KEY);
419 if ((data != null) && (data instanceof RunData))
420 {
421 charset = ((RunData) data).getCharset();
422 }
423
424 return charset == null ? defaultOutputEncoding : charset;
425 }
426
427
428
429
430
431
432
433 private Charset getTemplateEncoding(Context context)
434 {
435 Charset encoding = null;
436
437 Object data = context.get(VelocityService.RUNDATA_KEY);
438 if ((data != null) && (data instanceof RunData../../../org/apache/turbine/util/RunData.html#RunData">RunData) && (((RunData) data).getTemplateEncoding() != null) )
439 {
440 encoding = Charset.forName(((RunData) data).getTemplateEncoding());
441 }
442
443 return encoding != null ? encoding : defaultInputEncoding;
444 }
445
446
447
448
449
450
451
452
453
454
455 private static final void renderingError(String filename, Exception e)
456 throws TurbineException
457 {
458 String err = "Error rendering Velocity template: " + filename;
459 log.error(err, e);
460 throw new TurbineException(err, e);
461 }
462
463
464
465
466
467
468
469
470 private VelocityEngine getInitializedVelocityEngine()
471 throws Exception
472 {
473
474 Configuration conf = getConfiguration();
475
476 catchErrors = conf.getBoolean(CATCH_ERRORS_KEY, CATCH_ERRORS_DEFAULT);
477
478
479 conf.setProperty(RuntimeConstants.RUNTIME_LOG_NAME, "velocity");
480
481 VelocityEngine velocity = new VelocityEngine();
482 setVelocityProperties(velocity, conf);
483 velocity.init();
484
485 return velocity;
486 }
487
488
489
490
491
492
493
494
495
496
497
498
499
500 protected void setVelocityProperties(VelocityEngine velocity, Configuration conf)
501 throws Exception
502 {
503
504
505
506
507 for (Iterator<String> i = conf.getKeys(); i.hasNext();)
508 {
509 String key = i.next();
510 if (!key.endsWith(RESOURCE_LOADER_PATH))
511 {
512 Object value = conf.getProperty(key);
513 if (value instanceof List<?>)
514 {
515 for (Object name2 : ((List<?>) value))
516 {
517 velocity.addProperty(key, name2);
518 }
519 }
520 else
521 {
522 velocity.addProperty(key, value);
523 }
524 log.debug("Adding {} -> {}", key, value);
525 continue;
526 }
527
528 List<Object> paths = conf.getList(key, null);
529 if (paths == null)
530 {
531
532
533 continue;
534 }
535
536
537
538
539
540
541
542
543 for (Object p : paths)
544 {
545 String path = (String)p;
546 log.debug("Translating {}", path);
547
548 if (path.startsWith(JAR_PREFIX))
549 {
550
551 if (path.substring(4).startsWith(ABSOLUTE_PREFIX))
552 {
553
554 int jarSepIndex = path.indexOf("!/");
555
556
557 path = (jarSepIndex < 0)
558 ? Turbine.getRealPath(path.substring(11))
559
560 : (Turbine.getRealPath(path.substring(11, jarSepIndex)) + path.substring(jarSepIndex));
561
562 log.debug("Result (absolute jar path): {}", path);
563 }
564 }
565 else if(path.startsWith(ABSOLUTE_PREFIX))
566 {
567
568 path = Turbine.getRealPath(path.substring(7));
569
570 log.debug("Result (absolute URL Path): {}", path);
571 }
572
573 else if(path.indexOf("://") < 0)
574 {
575 path = Turbine.getRealPath(path);
576
577 log.debug("Result (normal fs reference): {}", path);
578 }
579
580 log.debug("Adding {} -> {}", key, path);
581
582 velocity.addProperty(key, path);
583 }
584 }
585 }
586
587
588
589
590
591
592
593
594
595 @Override
596 public boolean templateExists(String template)
597 {
598 return velocity.resourceExists(template);
599 }
600
601
602
603
604
605
606
607 @Override
608 public void requestFinished(Context context)
609 {
610 if (pullModelActive)
611 {
612 pullService.releaseTools(context);
613 }
614 }
615 }