Rename TemplatePage to FreenetTemplatePage, which fits a lot better.
[Sone.git] / src / main / java / net / pterodactylus / sone / web / page / FreenetTemplatePage.java
1 /*
2  * shortener - TemplatePage.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.logging.Level;
24 import java.util.logging.Logger;
25
26 import net.pterodactylus.sone.web.page.Page.Request.Method;
27 import net.pterodactylus.util.logging.Logging;
28 import net.pterodactylus.util.template.Template;
29 import net.pterodactylus.util.template.TemplateContext;
30 import net.pterodactylus.util.template.TemplateContextFactory;
31 import freenet.clients.http.LinkEnabledCallback;
32 import freenet.clients.http.PageMaker;
33 import freenet.clients.http.PageNode;
34 import freenet.clients.http.ToadletContext;
35
36 /**
37  * Base class for all {@link Page}s that are rendered with {@link Template}s and
38  * fit into Freenet’s web interface.
39  *
40  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
41  */
42 public class FreenetTemplatePage implements Page, LinkEnabledCallback {
43
44         /** The logger. */
45         private static final Logger logger = Logging.getLogger(FreenetTemplatePage.class);
46
47         /** The path of the page. */
48         private final String path;
49
50         /** The template context factory. */
51         private final TemplateContextFactory templateContextFactory;
52
53         /** The template to render. */
54         private final Template template;
55
56         /** Where to redirect for invalid form passwords. */
57         private final String invalidFormPasswordRedirectTarget;
58
59         /**
60          * Creates a new template page.
61          *
62          * @param path
63          *            The path of the page
64          * @param templateContextFactory
65          *            The template context factory
66          * @param template
67          *            The template to render
68          * @param invalidFormPasswordRedirectTarget
69          *            The target to redirect to if a POST request does not contain
70          *            the correct form password
71          */
72         public FreenetTemplatePage(String path, TemplateContextFactory templateContextFactory, Template template, String invalidFormPasswordRedirectTarget) {
73                 this.path = path;
74                 this.templateContextFactory = templateContextFactory;
75                 this.template = template;
76                 this.invalidFormPasswordRedirectTarget = invalidFormPasswordRedirectTarget;
77         }
78
79         /**
80          * {@inheritDoc}
81          */
82         @Override
83         public String getPath() {
84                 return path;
85         }
86
87         /**
88          * Returns the title of the page.
89          *
90          * @param request
91          *            The request to serve
92          * @return The title of the page
93          */
94         protected String getPageTitle(Request request) {
95                 return null;
96         }
97
98         /**
99          * {@inheritDoc}
100          */
101         @Override
102         public Response handleRequest(Request request) {
103                 String redirectTarget = getRedirectTarget(request);
104                 if (redirectTarget != null) {
105                         return new RedirectResponse(redirectTarget);
106                 }
107
108                 ToadletContext toadletContext = request.getToadletContext();
109                 if (request.getMethod() == Method.POST) {
110                         /* require form password. */
111                         String formPassword = request.getHttpRequest().getPartAsStringFailsafe("formPassword", 32);
112                         if (!formPassword.equals(toadletContext.getContainer().getFormPassword())) {
113                                 return new RedirectResponse(invalidFormPasswordRedirectTarget);
114                         }
115                 }
116                 PageMaker pageMaker = toadletContext.getPageMaker();
117                 PageNode pageNode = pageMaker.getPageNode(getPageTitle(request), toadletContext);
118                 for (String styleSheet : getStyleSheets()) {
119                         pageNode.addCustomStyleSheet(styleSheet);
120                 }
121                 String shortcutIcon = getShortcutIcon();
122                 if (shortcutIcon != null) {
123                         pageNode.addForwardLink("icon", shortcutIcon);
124                 }
125
126                 TemplateContext templateContext = templateContextFactory.createTemplateContext();
127                 templateContext.mergeContext(template.getInitialContext());
128                 try {
129                         long start = System.nanoTime();
130                         processTemplate(request, templateContext);
131                         long finish = System.nanoTime();
132                         logger.log(Level.FINEST, "Template was rendered in " + ((finish - start) / 1000) / 1000.0 + "ms.");
133                 } catch (RedirectException re1) {
134                         return new RedirectResponse(re1.getTarget());
135                 }
136
137                 StringWriter stringWriter = new StringWriter();
138                 template.render(templateContext, stringWriter);
139                 pageNode.content.addChild("%", stringWriter.toString());
140
141                 postProcess(request, templateContext);
142
143                 return new Response(200, "OK", "text/html", pageNode.outer.generate());
144         }
145
146         /**
147          * Can be overridden to return a custom set of style sheets that are to be
148          * included in the page’s header.
149          *
150          * @return Additional style sheets to load
151          */
152         protected Collection<String> getStyleSheets() {
153                 return Collections.emptySet();
154         }
155
156         /**
157          * Returns the name of the shortcut icon to include in the page’s header.
158          *
159          * @return The URL of the shortcut icon, or {@code null} for no icon
160          */
161         protected String getShortcutIcon() {
162                 return null;
163         }
164
165         /**
166          * Can be overridden when extending classes need to set variables in the
167          * template before it is rendered.
168          *
169          * @param request
170          *            The request that is rendered
171          * @param templateContext
172          *            The template context to set variables in
173          * @throws RedirectException
174          *             if the processing page wants to redirect after processing
175          */
176         protected void processTemplate(Request request, TemplateContext templateContext) throws RedirectException {
177                 /* do nothing. */
178         }
179
180         /**
181          * This method will be called after
182          * {@link #processTemplate(net.pterodactylus.sone.web.page.Page.Request, TemplateContext)}
183          * has processed the template and the template was rendered. This method
184          * will not be called if
185          * {@link #processTemplate(net.pterodactylus.sone.web.page.Page.Request, TemplateContext)}
186          * throws a {@link RedirectException}!
187          *
188          * @param request
189          *            The request being processed
190          * @param templateContext
191          *            The template context that supplied the rendered data
192          */
193         protected void postProcess(Request request, TemplateContext templateContext) {
194                 /* do nothing. */
195         }
196
197         /**
198          * Can be overridden to redirect the user to a different page, in case a log
199          * in is required, or something else is wrong.
200          *
201          * @param request
202          *            The request that is processed
203          * @return The URL to redirect to, or {@code null} to not redirect
204          */
205         protected String getRedirectTarget(Page.Request request) {
206                 return null;
207         }
208
209         //
210         // INTERFACE LinkEnabledCallback
211         //
212
213         /**
214          * {@inheritDoc}
215          */
216         @Override
217         public boolean isEnabled(ToadletContext toadletContext) {
218                 return true;
219         }
220
221         /**
222          * Exception that can be thrown to signal that a subclassed {@link Page}
223          * wants to redirect the user during the
224          * {@link FreenetTemplatePage#processTemplate(net.pterodactylus.sone.web.page.Page.Request, TemplateContext)}
225          * method call.
226          *
227          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
228          */
229         public static class RedirectException extends Exception {
230
231                 /** The target to redirect to. */
232                 private final String target;
233
234                 /**
235                  * Creates a new redirect exception.
236                  *
237                  * @param target
238                  *            The target of the redirect
239                  */
240                 public RedirectException(String target) {
241                         this.target = target;
242                 }
243
244                 /**
245                  * Returns the target to redirect to.
246                  *
247                  * @return The target to redirect to
248                  */
249                 public String getTarget() {
250                         return target;
251                 }
252
253         }
254
255 }