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