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