1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.apache.tiles.request.mustache;
23
24 import java.io.IOException;
25 import java.util.HashMap;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.regex.Matcher;
29 import java.util.regex.Pattern;
30
31 import com.github.mustachejava.MustacheFactory;
32 import com.github.mustachejava.DefaultMustacheFactory;
33 import com.github.mustachejava.MustacheException;
34 import org.apache.tiles.request.Request;
35 import org.apache.tiles.request.render.CannotRenderException;
36 import org.apache.tiles.request.render.Renderer;
37
38
39
40
41
42
43
44
45 public class MustacheRenderer implements Renderer {
46
47
48 private static final ThreadLocal<Request> REQUEST_HOLDER = new ThreadLocal<Request>();
49
50 private final MustacheFactory factory;
51 private Pattern acceptPattern;
52
53
54 public MustacheRenderer(){
55 this.factory = new DefaultMustacheFactory();
56 }
57
58 public MustacheRenderer(MustacheFactory factory) {
59 this.factory = factory;
60 }
61
62 @Override
63 public void render(String path, Request request) throws IOException {
64 if (path == null) {
65 throw new CannotRenderException("Cannot dispatch a null path");
66 }
67
68 try {
69 REQUEST_HOLDER.set(request);
70 factory
71 .compile(path)
72 .execute(request.getWriter(), buildScope(request));
73 REQUEST_HOLDER.remove();
74
75 } catch(MustacheException ex) {
76 throw new IOException("failed to MustacheRenderer.render(" + path + ",request)", ex);
77 }
78 }
79
80 public static Request getThreadLocalRequest() {
81 return REQUEST_HOLDER.get();
82 }
83
84 protected Map<String,Object> buildScope(Request request) {
85 Map<String,Object> scope = new HashMap<String,Object>();
86 List<String> availableScopes = request.getAvailableScopes();
87 for (int i = availableScopes.size() -1; i >= 0; --i) {
88 scope.putAll(request.getContext(availableScopes.get(i)));
89 }
90 return scope;
91 }
92
93 @Override
94 public boolean isRenderable(String path, Request request) {
95 if (path == null) {
96 return false;
97 }
98 if (acceptPattern != null) {
99 final Matcher matcher = acceptPattern.matcher(path);
100 return matcher.matches();
101 }
102 return true;
103 }
104
105 public final void setAcceptPattern(Pattern acceptPattern) {
106 this.acceptPattern = acceptPattern;
107 }
108 }