Merge branch 'release-0.6.2'
[Sone.git] / src / main / java / net / pterodactylus / sone / web / page / FreenetTemplatePage.java
1 /*
2  * Sone - FreenetTemplatePage.java - Copyright © 2010 David Roden
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 package net.pterodactylus.sone.web.page;
19
20 import java.io.StringWriter;
21 import java.util.Collection;
22 import java.util.Collections;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Map.Entry;
26 import java.util.logging.Level;
27 import java.util.logging.Logger;
28
29 import net.pterodactylus.sone.web.page.Page.Request.Method;
30 import net.pterodactylus.util.logging.Logging;
31 import net.pterodactylus.util.template.Template;
32 import net.pterodactylus.util.template.TemplateContext;
33 import net.pterodactylus.util.template.TemplateContextFactory;
34 import freenet.clients.http.LinkEnabledCallback;
35 import freenet.clients.http.PageMaker;
36 import freenet.clients.http.PageNode;
37 import freenet.clients.http.ToadletContext;
38 import freenet.support.HTMLNode;
39
40 /**
41  * Base class for all {@link Page}s that are rendered with {@link Template}s and
42  * fit into Freenet’s web interface.
43  *
44  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
45  */
46 public class FreenetTemplatePage implements Page, LinkEnabledCallback {
47
48         /** The logger. */
49         private static final Logger logger = Logging.getLogger(FreenetTemplatePage.class);
50
51         /** The path of the page. */
52         private final String path;
53
54         /** The template context factory. */
55         private final TemplateContextFactory templateContextFactory;
56
57         /** The template to render. */
58         private final Template template;
59
60         /** Where to redirect for invalid form passwords. */
61         private final String invalidFormPasswordRedirectTarget;
62
63         /**
64          * Creates a new template page.
65          *
66          * @param path
67          *            The path of the page
68          * @param templateContextFactory
69          *            The template context factory
70          * @param template
71          *            The template to render
72          * @param invalidFormPasswordRedirectTarget
73          *            The target to redirect to if a POST request does not contain
74          *            the correct form password
75          */
76         public FreenetTemplatePage(String path, TemplateContextFactory templateContextFactory, Template template, String invalidFormPasswordRedirectTarget) {
77                 this.path = path;
78                 this.templateContextFactory = templateContextFactory;
79                 this.template = template;
80                 this.invalidFormPasswordRedirectTarget = invalidFormPasswordRedirectTarget;
81         }
82
83         /**
84          * {@inheritDoc}
85          */
86         @Override
87         public String getPath() {
88                 return path;
89         }
90
91         /**
92          * Returns the title of the page.
93          *
94          * @param request
95          *            The request to serve
96          * @return The title of the page
97          */
98         protected String getPageTitle(Request request) {
99                 return null;
100         }
101
102         /**
103          * {@inheritDoc}
104          */
105         @Override
106         public Response handleRequest(Request request) {
107                 String redirectTarget = getRedirectTarget(request);
108                 if (redirectTarget != null) {
109                         return new RedirectResponse(redirectTarget);
110                 }
111
112                 ToadletContext toadletContext = request.getToadletContext();
113                 if (request.getMethod() == Method.POST) {
114                         /* require form password. */
115                         String formPassword = request.getHttpRequest().getPartAsStringFailsafe("formPassword", 32);
116                         if (!formPassword.equals(toadletContext.getContainer().getFormPassword())) {
117                                 return new RedirectResponse(invalidFormPasswordRedirectTarget);
118                         }
119                 }
120                 PageMaker pageMaker = toadletContext.getPageMaker();
121                 PageNode pageNode = pageMaker.getPageNode(getPageTitle(request), toadletContext);
122                 for (String styleSheet : getStyleSheets()) {
123                         pageNode.addCustomStyleSheet(styleSheet);
124                 }
125                 for (Map<String, String> linkNodeParameters : getAdditionalLinkNodes(request)) {
126                         HTMLNode linkNode = pageNode.headNode.addChild("link");
127                         for (Entry<String, String> parameter : linkNodeParameters.entrySet()) {
128                                 linkNode.addAttribute(parameter.getKey(), parameter.getValue());
129                         }
130                 }
131                 String shortcutIcon = getShortcutIcon();
132                 if (shortcutIcon != null) {
133                         pageNode.addForwardLink("icon", shortcutIcon);
134                 }
135
136                 TemplateContext templateContext = templateContextFactory.createTemplateContext();
137                 templateContext.mergeContext(template.getInitialContext());
138                 try {
139                         long start = System.nanoTime();
140                         processTemplate(request, templateContext);
141                         long finish = System.nanoTime();
142                         logger.log(Level.FINEST, "Template was rendered in " + ((finish - start) / 1000) / 1000.0 + "ms.");
143                 } catch (RedirectException re1) {
144                         return new RedirectResponse(re1.getTarget());
145                 }
146
147                 StringWriter stringWriter = new StringWriter();
148                 template.render(templateContext, stringWriter);
149                 pageNode.content.addChild("%", stringWriter.toString());
150
151                 postProcess(request, templateContext);
152
153                 return new Response(200, "OK", "text/html", pageNode.outer.generate());
154         }
155
156         /**
157          * Can be overridden to return a custom set of style sheets that are to be
158          * included in the page’s header.
159          *
160          * @return Additional style sheets to load
161          */
162         protected Collection<String> getStyleSheets() {
163                 return Collections.emptySet();
164         }
165
166         /**
167          * Returns the name of the shortcut icon to include in the page’s header.
168          *
169          * @return The URL of the shortcut icon, or {@code null} for no icon
170          */
171         protected String getShortcutIcon() {
172                 return null;
173         }
174
175         /**
176          * Can be overridden when extending classes need to set variables in the
177          * template before it is rendered.
178          *
179          * @param request
180          *            The request that is rendered
181          * @param templateContext
182          *            The template context to set variables in
183          * @throws RedirectException
184          *             if the processing page wants to redirect after processing
185          */
186         protected void processTemplate(Request request, TemplateContext templateContext) throws RedirectException {
187                 /* do nothing. */
188         }
189
190         /**
191          * This method will be called after
192          * {@link #processTemplate(net.pterodactylus.sone.web.page.Page.Request, TemplateContext)}
193          * has processed the template and the template was rendered. This method
194          * will not be called if
195          * {@link #processTemplate(net.pterodactylus.sone.web.page.Page.Request, TemplateContext)}
196          * throws a {@link RedirectException}!
197          *
198          * @param request
199          *            The request being processed
200          * @param templateContext
201          *            The template context that supplied the rendered data
202          */
203         protected void postProcess(Request request, TemplateContext templateContext) {
204                 /* do nothing. */
205         }
206
207         /**
208          * Can be overridden to redirect the user to a different page, in case a log
209          * in is required, or something else is wrong.
210          *
211          * @param request
212          *            The request that is processed
213          * @return The URL to redirect to, or {@code null} to not redirect
214          */
215         protected String getRedirectTarget(Page.Request request) {
216                 return null;
217         }
218
219         /**
220          * Returns additional &lt;link&gt; nodes for the HTML’s &lt;head&gt; node.
221          *
222          * @param request
223          *            The request for which to return the link nodes
224          * @return All link nodes that should be added to the HTML head
225          */
226         protected List<Map<String, String>> getAdditionalLinkNodes(Request request) {
227                 return Collections.emptyList();
228         }
229
230         //
231         // INTERFACE LinkEnabledCallback
232         //
233
234         /**
235          * {@inheritDoc}
236          */
237         @Override
238         public boolean isEnabled(ToadletContext toadletContext) {
239                 return true;
240         }
241
242         /**
243          * Exception that can be thrown to signal that a subclassed {@link Page}
244          * wants to redirect the user during the
245          * {@link FreenetTemplatePage#processTemplate(net.pterodactylus.sone.web.page.Page.Request, TemplateContext)}
246          * method call.
247          *
248          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
249          */
250         public static class RedirectException extends Exception {
251
252                 /** The target to redirect to. */
253                 private final String target;
254
255                 /**
256                  * Creates a new redirect exception.
257                  *
258                  * @param target
259                  *            The target of the redirect
260                  */
261                 public RedirectException(String target) {
262                         this.target = target;
263                 }
264
265                 /**
266                  * Returns the target to redirect to.
267                  *
268                  * @return The target to redirect to
269                  */
270                 public String getTarget() {
271                         return target;
272                 }
273
274         }
275
276 }