forked from playframework/play1
/
FastTags.java
445 lines (418 loc) · 20.5 KB
/
FastTags.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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
package play.templates;
import groovy.lang.Closure;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import play.cache.Cache;
import play.data.validation.Error;
import play.data.validation.Validation;
import play.exceptions.TagInternalException;
import play.exceptions.TemplateExecutionException;
import play.exceptions.TemplateNotFoundException;
import play.libs.Codec;
import play.mvc.Http;
import play.mvc.Router.ActionDefinition;
import play.mvc.Scope.Flash;
import play.mvc.Scope.Session;
import play.templates.BaseTemplate.RawData;
import play.templates.GroovyTemplate.ExecutableTemplate;
import play.utils.HTML;
/**
* Fast tags implementation
*/
public class FastTags {
public static void _cache(Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) {
String key = args.get("arg").toString();
String duration = null;
if (args.containsKey("for")) {
duration = args.get("for").toString();
}
Object cached = Cache.get(key);
if (cached != null) {
out.print(cached);
return;
}
String result = JavaExtensions.toString(body);
Cache.set(key, result, duration);
out.print(result);
}
public static void _verbatim(Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) {
out.println(JavaExtensions.toString(body));
}
public static void _jsAction(Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) {
out.println("function(options) {var pattern = '" + args.get("arg").toString().replace("&", "&") + "';");
out.println(" var argsStart = pattern.indexOf('?') + 1;");
out.println(" var notNullOptions = new Array();");
out.println(" if (argsStart >= 0) {");
out.println(" for (key in options) {");
out.println(" var val = options[key];");
out.println(" if (val != null) {");
out.println(" notNullOptions[key] = val;");
out.println(" } else {");
out.println(" var nullArgPlaceHolder = key + '=:' + key;");
out.println(" var argIndexInPattern = pattern.indexOf(nullArgPlaceHolder, argsStart);");
out.println(" var beforeNullArg = pattern.substring(0, argIndexInPattern);");
out.println(" var afterNullArg = pattern.substring(argIndexInPattern + nullArgPlaceHolder.length);");
out.println(" var charBeforeNullArg = beforeNullArg.charAt(beforeNullArg.length - 1);");
out.println(" if (charBeforeNullArg == '&') {");
out.println(" beforeNullArg = beforeNullArg.substring(0, beforeNullArg.length - 1);");
out.println(" } else if (afterNullArg.charAt(0) == '&') {");
out.println(" afterNullArg = afterNullArg.substring(1);");
out.println(" } else if (charBeforeNullArg == '?' && afterNullArg.length == 0) {");
out.println(" beforeNullArg = beforeNullArg.substring(0, beforeNullArg.length - 1);");
out.println(" }");
out.println(" pattern = beforeNullArg + afterNullArg;");
out.println(" }");
out.println(" }");
out.println(" } else {");
out.println(" notNullOptions = options;");
out.println(" }");
out.println(" for (key in notNullOptions) {");
out.println(" var val = options[key];");
out.println(" pattern = pattern.replace(':' + key, options[key]);");
out.println(" }");
out.println(" return pattern;");
out.println("}");
}
public static void _jsRoute(Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) {
final Object arg = args.get("arg");
if (!(arg instanceof ActionDefinition)) {
throw new TemplateExecutionException(template.template, fromLine, "Wrong parameter type, try #{jsRoute @Application.index() /}", new TagInternalException("Wrong parameter type"));
}
final ActionDefinition action = (ActionDefinition)arg;
out.print("{");
if (action.args.isEmpty()) {
out.print("url: function() { return '" + action.url.replace("&", "&") + "'; },");
} else {
out.print("url: function(args) { var pattern = '" + action.url.replace("&", "&") + "'; for (var key in args) { pattern = pattern.replace(':'+key, args[key]); } return pattern; },");
}
out.print("method: '" + action.method + "'");
out.print("}");
}
public static void _authenticityToken(Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) {
out.println("<input type=\"hidden\" name=\"authenticityToken\" value=\"" + Session.current().getAuthenticityToken() + "\">");
}
public static void _option(Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) {
Object value = args.get("arg");
Object selectedValue = TagContext.parent("select").data.get("selected");
boolean selected = selectedValue != null && value != null && (selectedValue.toString()).equals(value.toString());
out.print("<option value=\"" + (value == null ? "" : value) + "\" " + (selected ? "selected=\"selected\"" : "") + " " + serialize(args, "selected", "value") + ">");
out.println(JavaExtensions.toString(body));
out.print("</option>");
}
/**
* Generates a html form element linked to a controller action
* @param args tag attributes
* @param body tag inner body
* @param out the output writer
* @param template enclosing template
* @param fromLine template line number where the tag is defined
*/
public static void _form(Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) {
ActionDefinition actionDef = (ActionDefinition) args.get("arg");
if (actionDef == null) {
actionDef = (ActionDefinition) args.get("action");
}
String enctype = (String) args.get("enctype");
if (enctype == null) {
enctype = "application/x-www-form-urlencoded";
}
if (actionDef.star) {
actionDef.method = "POST"; // prefer POST for form ....
}
if (args.containsKey("method")) {
actionDef.method = args.get("method").toString();
}
if (!("GET".equals(actionDef.method) || "POST".equals(actionDef.method))) {
String separator = actionDef.url.indexOf('?') != -1 ? "&" : "?";
actionDef.url += separator + "x-http-method-override=" + actionDef.method.toUpperCase();
actionDef.method = "POST";
}
String encoding = Http.Response.current().encoding;
out.print("<form action=\"" + actionDef.url + "\" method=\"" + actionDef.method.toLowerCase() + "\" accept-charset=\""+encoding+"\" enctype=\"" + enctype + "\" " + serialize(args, "action", "method", "accept-charset", "enctype") + ">");
if (!("GET".equals(actionDef.method))) {
_authenticityToken(args, body, out, template, fromLine);
}
out.println(JavaExtensions.toString(body));
out.print("</form>");
}
/**
* The field tag is a helper, based on the spirit of Don't Repeat Yourself.
* @param args tag attributes
* @param body tag inner body
* @param out the output writer
* @param template enclosing template
* @param fromLine template line number where the tag is defined
*/
public static void _field(Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) {
Map<String,Object> field = new HashMap<String,Object>();
String _arg = args.get("arg").toString();
field.put("name", _arg);
field.put("id", _arg.replace('.','_'));
field.put("flash", Flash.current().get(_arg));
field.put("flashArray", field.get("flash") != null && !StringUtils.isEmpty(field.get("flash").toString()) ? field.get("flash").toString().split(",") : new String[0]);
field.put("error", Validation.error(_arg));
field.put("errorClass", field.get("error") != null ? "hasError" : "");
String[] pieces = _arg.split("\\.");
Object obj = body.getProperty(pieces[0]);
if(obj != null){
if(pieces.length > 1){
for(int i = 1; i < pieces.length; i++){
try{
Field f = obj.getClass().getField(pieces[i]);
if(i == (pieces.length-1)){
try{
Method getter = obj.getClass().getMethod("get"+JavaExtensions.capFirst(f.getName()));
field.put("value", getter.invoke(obj, new Object[0]));
}catch(NoSuchMethodException e){
field.put("value",f.get(obj).toString());
}
}else{
obj = f.get(obj);
}
}catch(Exception e){
// if there is a problem reading the field we dont set any value
}
}
}else{
field.put("value", obj);
}
}
body.setProperty("field", field);
body.call();
}
/**
* Generates a html link to a controller action
* @param args tag attributes
* @param body tag inner body
* @param out the output writer
* @param template enclosing template
* @param fromLine template line number where the tag is defined
*/
public static void _a(Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) {
ActionDefinition actionDef = (ActionDefinition) args.get("arg");
if (actionDef == null) {
actionDef = (ActionDefinition) args.get("action");
}
if (!("GET".equals(actionDef.method))) {
if (!("POST".equals(actionDef.method))) {
String separator = actionDef.url.indexOf('?') != -1 ? "&" : "?";
actionDef.url += separator + "x-http-method-override=" + actionDef.method;
actionDef.method = "POST";
}
String id = Codec.UUID();
out.print("<form method=\"POST\" id=\"" + id + "\" " +(args.containsKey("target") ? "target=\"" + args.get("target") + "\"" : "")+ " style=\"display:none\" action=\"" + actionDef.url + "\">");
_authenticityToken(args, body, out, template, fromLine);
out.print("</form>");
out.print("<a href=\"javascript:document.getElementById('" + id + "').submit();\" " + serialize(args, "href") + ">");
out.print(JavaExtensions.toString(body));
out.print("</a>");
} else {
out.print("<a href=\"" + actionDef.url + "\" " + serialize(args, "href") + ">");
out.print(JavaExtensions.toString(body));
out.print("</a>");
}
}
public static void _ifErrors(Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) {
if (Validation.hasErrors()) {
body.call();
TagContext.parent().data.put("_executeNextElse", false);
} else {
TagContext.parent().data.put("_executeNextElse", true);
}
}
public static void _ifError(Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) {
if (args.get("arg") == null) {
throw new TemplateExecutionException(template.template, fromLine, "Please specify the error key", new TagInternalException("Please specify the error key"));
}
if (Validation.hasError(args.get("arg").toString())) {
body.call();
TagContext.parent().data.put("_executeNextElse", false);
} else {
TagContext.parent().data.put("_executeNextElse", true);
}
}
public static void _errorClass(Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) {
if (args.get("arg") == null) {
throw new TemplateExecutionException(template.template, fromLine, "Please specify the error key", new TagInternalException("Please specify the error key"));
}
if (Validation.hasError(args.get("arg").toString())) {
out.print("hasError");
}
}
public static void _error(Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) {
if (args.get("arg") == null && args.get("key") == null) {
throw new TemplateExecutionException(template.template, fromLine, "Please specify the error key", new TagInternalException("Please specify the error key"));
}
String key = args.get("arg") == null ? args.get("key") + "" : args.get("arg") + "";
Error error = Validation.error(key);
if (error != null) {
if (args.get("field") == null) {
out.print(error.message());
} else {
out.print(error.message(args.get("field") + ""));
}
}
}
static boolean _evaluateCondition(Object test) {
if (test != null) {
if (test instanceof Boolean) {
return ((Boolean) test).booleanValue();
} else if (test instanceof String) {
return ((String) test).length() > 0;
} else if (test instanceof Number) {
return ((Number) test).intValue() != 0;
} else if (test instanceof Collection) {
return !((Collection) test).isEmpty();
} else {
return true;
}
}
return false;
}
static String __safe(Template template, Object val) {
if (val instanceof RawData) {
return ((RawData) val).data;
}
if (!template.name.endsWith(".html") || TagContext.hasParentTag("verbatim")) {
return val.toString();
}
return HTML.htmlEscape(val.toString());
}
public static void _doLayout(Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) {
out.print("____%LAYOUT%____");
}
public static void _get(Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) {
Object name = args.get("arg");
if (name == null) {
throw new TemplateExecutionException(template.template, fromLine, "Specify a variable name", new TagInternalException("Specify a variable name"));
}
Object value = BaseTemplate.layoutData.get().get(name);
if (value != null) {
out.print(value);
} else {
if (body != null) {
out.print(JavaExtensions.toString(body));
}
}
}
public static void _set(Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) {
// Simple case : #{set title:'Yop' /}
for (Map.Entry<?, ?> entry : args.entrySet()) {
Object key = entry.getKey();
if (!key.toString().equals("arg")) {
BaseTemplate.layoutData.get().put(key, (entry.getValue() != null && entry.getValue() instanceof String) ? __safe(template.template, entry.getValue()) : entry.getValue());
return;
}
}
// Body case
Object name = args.get("arg");
if (name != null && body != null) {
Object oldOut = body.getProperty("out");
StringWriter sw = new StringWriter();
body.setProperty("out", new PrintWriter(sw));
body.call();
BaseTemplate.layoutData.get().put(name, sw.toString());
body.setProperty("out", oldOut);
}
}
public static void _extends(Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) {
try {
if (!args.containsKey("arg") || args.get("arg") == null) {
throw new TemplateExecutionException(template.template, fromLine, "Specify a template name", new TagInternalException("Specify a template name"));
}
String name = args.get("arg").toString();
if (name.startsWith("./")) {
String ct = BaseTemplate.currentTemplate.get().name;
if (ct.matches("^/lib/[^/]+/app/views/.*")) {
ct = ct.substring(ct.indexOf("/", 5));
}
ct = ct.substring(0, ct.lastIndexOf("/"));
name = ct + name.substring(1);
}
BaseTemplate.layout.set((BaseTemplate) TemplateLoader.load(name));
} catch (TemplateNotFoundException e) {
throw new TemplateNotFoundException(e.getPath(), template.template, fromLine);
}
}
@SuppressWarnings("unchecked")
public static void _include(Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) {
try {
if (!args.containsKey("arg") || args.get("arg") == null) {
throw new TemplateExecutionException(template.template, fromLine, "Specify a template name", new TagInternalException("Specify a template name"));
}
String name = args.get("arg").toString();
if (name.startsWith("./")) {
String ct = BaseTemplate.currentTemplate.get().name;
if (ct.matches("^/lib/[^/]+/app/views/.*")) {
ct = ct.substring(ct.indexOf("/", 5));
}
ct = ct.substring(0, ct.lastIndexOf("/"));
name = ct + name.substring(1);
}
BaseTemplate t = (BaseTemplate) TemplateLoader.load(name);
Map<String, Object> newArgs = new HashMap<String, Object>();
newArgs.putAll(template.getBinding().getVariables());
newArgs.put("_isInclude", true);
t.internalRender(newArgs);
} catch (TemplateNotFoundException e) {
throw new TemplateNotFoundException(e.getPath(), template.template, fromLine);
}
}
@SuppressWarnings("unchecked")
public static void _render(Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) {
try {
if (!args.containsKey("arg") || args.get("arg") == null) {
throw new TemplateExecutionException(template.template, fromLine, "Specify a template name", new TagInternalException("Specify a template name"));
}
String name = args.get("arg").toString();
if (name.startsWith("./")) {
String ct = BaseTemplate.currentTemplate.get().name;
if (ct.matches("^/lib/[^/]+/app/views/.*")) {
ct = ct.substring(ct.indexOf("/", 5));
}
ct = ct.substring(0, ct.lastIndexOf("/"));
name = ct + name.substring(1);
}
args.remove("arg");
BaseTemplate t = (BaseTemplate) TemplateLoader.load(name);
Map<String, Object> newArgs = new HashMap<String, Object>();
newArgs.putAll((Map<? extends String, ? extends Object>) args);
newArgs.put("_isInclude", true);
newArgs.put("out", out);
t.internalRender(newArgs);
} catch (TemplateNotFoundException e) {
throw new TemplateNotFoundException(e.getPath(), template.template, fromLine);
}
}
public static String serialize(Map<?, ?> args, String... unless) {
StringBuilder attrs = new StringBuilder();
Arrays.sort(unless);
for (Object o : args.keySet()) {
String attr = o.toString();
String value = args.get(o) == null ? "" : args.get(o).toString();
if (Arrays.binarySearch(unless, attr) < 0 && !attr.equals("arg")) {
attrs.append(attr);
attrs.append("=\"");
attrs.append(value);
attrs.append("\" ");
}
}
return attrs.toString();
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public static @interface Namespace {
String value() default "";
}
}