1
2
3
4
5 package com.jcabi.velocity;
6
7 import java.io.PrintWriter;
8 import java.io.StringWriter;
9 import java.util.Map;
10 import org.apache.velocity.Template;
11 import org.apache.velocity.VelocityContext;
12 import org.apache.velocity.app.VelocityEngine;
13 import org.apache.velocity.runtime.RuntimeConstants;
14 import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33 @SuppressWarnings("PMD.AvoidSynchronizedStatement")
34 public final class VelocityPage {
35
36
37
38
39 private static final VelocityEngine ENGINE = VelocityPage.init();
40
41
42
43
44 private final transient String name;
45
46
47
48
49 private final transient VelocityContext context;
50
51
52
53
54
55
56
57 public VelocityPage(final String res) {
58 this.name = res;
59 this.context = new VelocityContext();
60 }
61
62
63
64
65
66
67
68
69 public VelocityPage set(final String prop, final Object value) {
70 synchronized (this.context) {
71 this.context.put(prop, value);
72 }
73 return this;
74 }
75
76
77
78
79
80
81
82
83 public VelocityPage set(final Map<String, Object> args) {
84 synchronized (this.context) {
85 for (final Map.Entry<String, Object> entry : args.entrySet()) {
86 this.context.put(entry.getKey(), entry.getValue());
87 }
88 }
89 return this;
90 }
91
92 @Override
93 public String toString() {
94 final Template template =
95 VelocityPage.ENGINE.getTemplate(this.name, "UTF-8");
96 final StringWriter writer = new StringWriter();
97 try (PrintWriter print = new PrintWriter(writer)) {
98 template.merge(this.context, print);
99 }
100 return writer.toString();
101 }
102
103 private static VelocityEngine init() {
104 final VelocityEngine engine = new VelocityEngine();
105 engine.setProperty(RuntimeConstants.RESOURCE_LOADERS, "cp");
106 engine.setProperty(
107 "resource.loader.cp.class",
108 ClasspathResourceLoader.class.getName()
109 );
110 engine.init();
111 return engine;
112 }
113 }