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