-
-
Notifications
You must be signed in to change notification settings - Fork 389
Expand file tree
/
Copy pathBaseTemplate.java
More file actions
358 lines (313 loc) · 10.7 KB
/
BaseTemplate.java
File metadata and controls
358 lines (313 loc) · 10.7 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
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
/*
* Handlebars.java: https://github.com/jknack/handlebars.java
* Apache License Version 2.0 http://www.apache.org/licenses/LICENSE-2.0
* Copyright (c) 2012 Edgar Espina
*/
package com.github.jknack.handlebars.internal;
import static org.apache.commons.lang3.StringUtils.join;
import static org.apache.commons.lang3.StringUtils.split;
import static org.apache.commons.lang3.Validate.isTrue;
import static org.apache.commons.lang3.Validate.notNull;
import java.io.IOException;
import java.io.Writer;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import com.github.jknack.handlebars.Context;
import com.github.jknack.handlebars.Handlebars;
import com.github.jknack.handlebars.HandlebarsError;
import com.github.jknack.handlebars.HandlebarsException;
import com.github.jknack.handlebars.TagType;
import com.github.jknack.handlebars.Template;
import com.github.jknack.handlebars.TypeSafeTemplate;
/**
* Base class for {@link Template}.
*
* @author edgar.espina
* @since 0.1.0
*/
abstract class BaseTemplate implements Template {
/** The handlebars object. Required. */
protected final Handlebars handlebars;
/** The line of this template. */
protected int line;
/** The column of this template. */
protected int column;
/** The file's name. */
protected String filename;
/** A pre-compiled JavaScript function. */
private String javaScript;
/**
* Creates a new {@link BaseTemplate}.
*
* @param handlebars A handlebars instance.
*/
BaseTemplate(final Handlebars handlebars) {
this.handlebars = notNull(handlebars, "The handlebars can't be null.");
}
/** {@inheritDoc} */
@Override
public final String apply(final Object context) throws IOException {
return apply(wrap(context));
}
/** {@inheritDoc} */
@Override
public final void apply(final Object context, final Writer writer) throws IOException {
apply(wrap(context), writer);
}
@Override
public String apply(final Context context) throws IOException {
FastStringWriter writer = new FastStringWriter();
apply(context, writer);
return writer.toString();
}
@Override
public void apply(final Context context, final Writer writer) throws IOException {
boolean decorate = decorate();
try {
if (decorate) {
before(context, writer);
}
merge(context, writer);
} catch (HandlebarsException ex) {
throw ex;
} catch (Exception ex) {
String evidence = toString();
String reason = ex.toString();
String message = filename + ":" + line + ":" + column + ": " + reason + "\n";
message += " " + join(split(evidence, "\n"), "\n ");
HandlebarsError error =
new HandlebarsError(filename, line, column, reason, evidence, message);
HandlebarsException hex = new HandlebarsException(error, ex);
// Override the stack-trace
hex.setStackTrace(ex.getStackTrace());
throw hex;
} finally {
if (decorate) {
after(context, writer);
}
}
}
/**
* Wrap the candidate object as a Context, or creates a new context.
*
* @param candidate The candidate object.
* @return A context.
*/
private Context wrap(final Object candidate) {
if (candidate instanceof Context) {
return (Context) candidate;
}
return Context.newBuilder(candidate)
.childFirstResolution(handlebars.childFirstResolution())
.build();
}
/**
* Notify that template is going to be processed.
*
* @param context The context object. Required.
* @param writer The writer object. Required.
* @throws IOException If a resource cannot be loaded.
*/
public void before(final Context context, final Writer writer) throws IOException {}
/**
* Notify that template has been processed.
*
* @param context The context object. Required.
* @param writer The writer object. Required.
* @throws IOException If a resource cannot be loaded.
*/
public void after(final Context context, final Writer writer) throws IOException {}
/**
* Merge a child template into the writer.
*
* @param context The scope object.
* @param writer The writer.
* @throws IOException If a resource cannot be loaded.
*/
protected abstract void merge(Context context, Writer writer) throws IOException;
@Override
public String toString() {
return filename + ":" + line + ":" + column;
}
/**
* Set the file's name.
*
* @param filename The file's name.
* @return This template.
*/
public BaseTemplate filename(final String filename) {
this.filename = filename;
return this;
}
@Override
public String filename() {
return filename;
}
@Override
public int[] position() {
return new int[] {line, column};
}
/**
* Set the template position.
*
* @param line The line.
* @param column The column.
* @return This template.
*/
public BaseTemplate position(final int line, final int column) {
this.line = line;
this.column = column;
return this;
}
@Override
public <T, S extends TypeSafeTemplate<T>> S as(final Class<S> rootType) {
notNull(rootType, "The rootType can't be null.");
isTrue(rootType.isInterface(), "Not an interface: %s", rootType.getName());
@SuppressWarnings("unchecked")
S template = (S) newTypeSafeTemplate(rootType, this);
return template;
}
@Override
public <T> TypeSafeTemplate<T> as() {
@SuppressWarnings("unchecked")
TypeSafeTemplate<T> template =
(TypeSafeTemplate<T>) newTypeSafeTemplate(TypeSafeTemplate.class, this);
return template;
}
/**
* Creates a new {@link TypeSafeTemplate}.
*
* @param rootType The target type.
* @param template The target template.
* @return A new {@link TypeSafeTemplate}.
*/
private Object newTypeSafeTemplate(final Class<?> rootType, final Template template) {
return Proxy.newProxyInstance(
rootType.getClassLoader(),
new Class[] {rootType},
new InvocationHandler() {
private final Map<String, Object> attributes = new HashMap<>();
private final Object[] emptyArgs = {};
private boolean isDefault(final Method method) {
return ((method.getModifiers()
& (Modifier.ABSTRACT | Modifier.PUBLIC | Modifier.STATIC))
== Modifier.PUBLIC)
&& method.getDeclaringClass().isInterface();
}
private Object invokeDefaultMethod(
final Method method,
final Class<?> lookupClass,
final Object proxy,
final Object... args)
throws Throwable {
MethodType methodType =
MethodType.methodType(method.getReturnType(), method.getParameterTypes());
return MethodHandles.lookup()
.findSpecial(lookupClass, method.getName(), methodType, lookupClass)
.bindTo(proxy)
.invokeWithArguments(args);
}
@Override
public Object invoke(final Object proxy, final Method method, final Object[] methodArgs)
throws Throwable {
Object[] args = methodArgs == null ? emptyArgs : methodArgs;
if (isDefault(method)) {
return invokeDefaultMethod(method, rootType, proxy, args);
}
String methodName = method.getName();
if (args.length == 0 && methodName.equals("hashCode")) {
return hashCode();
}
if (args.length == 0 && methodName.equals("toString")) {
return String.format("TypeSafeTemplateProxy{interface=%s}", rootType.getSimpleName());
}
if (args.length == 1
&& methodName.equals("equals")
&& method.getParameterTypes()[0] == Object.class) {
return args[0] == proxy;
}
if ("apply".equals(methodName)) {
Context context =
Context.newBuilder(args[0])
.combine(attributes)
.childFirstResolution(handlebars.childFirstResolution())
.build();
attributes.clear();
if (args.length == 2) {
template.apply(context, (Writer) args[1]);
return null;
}
return template.apply(context);
}
if (Modifier.isPublic(method.getModifiers()) && methodName.startsWith("set")) {
String attrName = StringUtils.uncapitalize(methodName.substring("set".length()));
if (args.length == 1 && attrName.length() > 0) {
attributes.put(attrName, args[0]);
if (TypeSafeTemplate.class.isAssignableFrom(method.getReturnType())) {
return proxy;
}
return null;
}
}
String message =
String.format(
"No handler method for: '%s(%s)', expected method signature is:"
+ " 'setXxx(value)'",
methodName, join(args, ", "));
throw new UnsupportedOperationException(message);
}
});
}
@Override
public List<String> collect(final TagType... tagType) {
isTrue(tagType.length > 0, "At least one tag type is required.");
Set<String> tagNames = new LinkedHashSet<>();
for (TagType tt : tagType) {
collect(tagNames, tt);
}
return new ArrayList<>(tagNames);
}
/**
* Child classes might want to check if they apply to the tagtype and append them self to the
* result list.
*
* @param result The result list.
* @param tagType The matching tagtype.
*/
protected void collect(final Collection<String> result, final TagType tagType) {}
@Override
public List<String> collectReferenceParameters() {
Set<String> paramNames = new LinkedHashSet<>();
collectReferenceParameters(paramNames);
return new ArrayList<>(paramNames);
}
/**
* @param result The result list to add new parameters to.
*/
protected void collectReferenceParameters(final Collection<String> result) {}
@Override
public String toJavaScript() {
if (javaScript == null) {
javaScript = handlebars.precompileInline(text());
}
return javaScript;
}
/**
* @return True if this template has decorators.
*/
public boolean decorate() {
return false;
}
}