forked from jooby-project/jooby
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFtl.java
More file actions
224 lines (199 loc) · 5.99 KB
/
Ftl.java
File metadata and controls
224 lines (199 loc) · 5.99 KB
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
/**
* 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 org.jooby.ftl;
import static java.util.Objects.requireNonNull;
import java.util.Properties;
import java.util.function.BiConsumer;
import org.jooby.Env;
import org.jooby.Jooby;
import org.jooby.Renderer;
import org.jooby.internal.ftl.Engine;
import org.jooby.internal.ftl.GuavaCacheStorage;
import org.jooby.internal.ftl.XssDirective;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheBuilderSpec;
import com.google.inject.Binder;
import com.google.inject.multibindings.Multibinder;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.NullCacheStorage;
import freemarker.template.Configuration;
import freemarker.template.TemplateException;
/**
* Exposes a {@link Configuration} and a {@link Renderer}.
*
* <h1>usage</h1>
* <p>
* It is pretty straightforward:
* </p>
*
* <pre>
* {
* use(new Ftl());
*
* get("/", req {@literal ->} Results.html("index").put("model", new MyModel());
* }
* </pre>
* <p>
* public/index.html:
* </p>
*
* <pre>
* ${model}
* </pre>
*
* <p>
* Templates are loaded from root of classpath: <code>/</code> and must end with: <code>.html</code>
* file extension.
* </p>
*
* <h1>configuration</h1>
* <p>
* There are two ways of changing a Freemarker configuration:
* </p>
* <h2>application.conf</h2>
* <p>
* Just add a <code>freemarker.*</code> option to your <code>application.conf</code> file:
* </p>
*
* <pre>
* freemarker.default_encoding = UTF-8
* </pre>
*
* <h2>programmatically</h2>
*
* <pre>
* {
* use(new Ftl().doWith((freemarker, config) {@literal ->} {
* freemarker.setDefaultEncoding("UTF-8");
* });
* }
* </pre>
*
* <p>
* Keep in mind this is just an example and you don't need to set the default encoding. Default
* encoding is set to: <code>application.charset</code> which is <code>UTF-8</code> by default.
* </p>
*
* <h1>template loader</h1>
* <p>
* Templates are loaded from the root of classpath and must end with <code>.html</code>. You can
* change the default template location and extensions too:
* </p>
*
* <pre>
* {
* use(new Ftl("/", ".ftl"));
* }
* </pre>
*
* <h1>cache</h1>
* <p>
* Cache is OFF when <code>env=dev</code> (useful for template reloading), otherwise is ON.
* </p>
* <p>
* Cache is backed by Guava and default cache will expire after <code>100</code> entries.
* </p>
* <p>
* If <code>100</code> entries is not enough or you need a more advanced cache setting, just set the
* <code>freemarker.cache</code> option:
* </p>
*
* <pre>
* freemarker.cache = "expireAfterWrite=1h"
* </pre>
*
* <p>
* See {@link CacheBuilderSpec}.
* </p>
*
* <p>
* That's all folks! Enjoy it!!!
* </p>
*
* @author edgar
* @since 0.5.0
*/
public class Ftl implements Jooby.Module {
/** The logging system. */
private final Logger log = LoggerFactory.getLogger(getClass());
private final String prefix;
private final String suffix;
private BiConsumer<Configuration, Config> configurer;
public Ftl(final String prefix, final String suffix) {
this.prefix = requireNonNull(prefix, "Template prefix is required.");
this.suffix = requireNonNull(suffix, "Template suffix is required.");
}
public Ftl(final String prefix) {
this(prefix, ".html");
}
public Ftl() {
this("/");
}
public Ftl doWith(final BiConsumer<Configuration, Config> configurer) {
this.configurer = requireNonNull(configurer, "Configurer is required.");
return this;
}
@Override
public void configure(final Env env, final Config config, final Binder binder)
throws TemplateException {
Configuration freemarker = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
log.debug("Freemarker: {}", Configuration.getVersion());
freemarker.setSettings(properties(config));
freemarker.setTemplateLoader(new ClassTemplateLoader(getClass().getClassLoader(), prefix));
// cache
if ("dev".equals(env.name()) || config.getString("freemarker.cache").isEmpty()) {
// noop cache
freemarker.setCacheStorage(NullCacheStorage.INSTANCE);
} else {
freemarker.setCacheStorage(
new GuavaCacheStorage(
CacheBuilder
.from(config.getString("freemarker.cache"))
.build()));
}
if (configurer != null) {
configurer.accept(freemarker, config);
}
binder.bind(Configuration.class).toInstance(freemarker);
Engine engine = new Engine(freemarker, suffix, new XssDirective(env));
Multibinder.newSetBinder(binder, Renderer.class)
.addBinding().toInstance(engine);
}
@Override
public Config config() {
return ConfigFactory.parseResources(getClass(), "freemarker.conf");
}
private Properties properties(final Config config) {
Properties props = new Properties();
// dump
config.getConfig("freemarker").entrySet().forEach(e -> {
String name = e.getKey();
String value = e.getValue().unwrapped().toString();
log.debug(" freemarker.{} = {}", name, value);
props.setProperty(name, value);
});
// this is a jooby option
props.remove("cache");
return props;
}
}