2 * Sone - FreenetTemplatePage.java - Copyright © 2010–2016 David Roden
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.
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.
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/>.
18 package net.pterodactylus.sone.web.page;
20 import static java.util.logging.Logger.getLogger;
22 import java.io.IOException;
23 import java.io.StringWriter;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.List;
29 import java.util.Map.Entry;
30 import java.util.logging.Level;
31 import java.util.logging.Logger;
33 import net.pterodactylus.util.template.Template;
34 import net.pterodactylus.util.template.TemplateContext;
35 import net.pterodactylus.util.template.TemplateContextFactory;
36 import net.pterodactylus.util.web.Method;
37 import net.pterodactylus.util.web.Page;
38 import net.pterodactylus.util.web.RedirectResponse;
39 import net.pterodactylus.util.web.Response;
40 import freenet.clients.http.LinkEnabledCallback;
41 import freenet.clients.http.PageMaker;
42 import freenet.clients.http.PageNode;
43 import freenet.clients.http.ToadletContext;
44 import freenet.support.HTMLNode;
47 * Base class for all {@link Page}s that are rendered with {@link Template}s and
48 * fit into Freenet’s web interface.
50 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
52 public class FreenetTemplatePage implements FreenetPage, LinkEnabledCallback {
55 private static final Logger logger = getLogger(FreenetTemplatePage.class.getName());
57 /** The path of the page. */
58 private final String path;
60 /** The template context factory. */
61 private final TemplateContextFactory templateContextFactory;
63 /** The template to render. */
64 private final Template template;
66 /** Where to redirect for invalid form passwords. */
67 private final String invalidFormPasswordRedirectTarget;
70 * Creates a new template page.
73 * The path of the page
74 * @param templateContextFactory
75 * The template context factory
77 * The template to render
78 * @param invalidFormPasswordRedirectTarget
79 * The target to redirect to if a POST request does not contain
80 * the correct form password
82 public FreenetTemplatePage(String path, TemplateContextFactory templateContextFactory, Template template, String invalidFormPasswordRedirectTarget) {
84 this.templateContextFactory = templateContextFactory;
85 this.template = template;
86 this.invalidFormPasswordRedirectTarget = invalidFormPasswordRedirectTarget;
93 public String getPath() {
98 * Returns the title of the page.
101 * The request to serve
102 * @return The title of the page
104 @SuppressWarnings("static-method")
105 protected String getPageTitle(FreenetRequest request) {
113 public boolean isPrefixPage() {
121 public Response handleRequest(FreenetRequest request, Response response) throws IOException {
122 String redirectTarget = getRedirectTarget(request);
123 if (redirectTarget != null) {
124 return new RedirectResponse(redirectTarget);
127 if (isFullAccessOnly() && !request.getToadletContext().isAllowedFullAccess()) {
128 return response.setStatusCode(401).setStatusText("Not authorized").setContentType("text/html");
130 ToadletContext toadletContext = request.getToadletContext();
131 if (request.getMethod() == Method.POST) {
132 /* require form password. */
133 String formPassword = request.getHttpRequest().getPartAsStringFailsafe("formPassword", 32);
134 if (!formPassword.equals(toadletContext.getContainer().getFormPassword())) {
135 return new RedirectResponse(invalidFormPasswordRedirectTarget);
138 PageMaker pageMaker = toadletContext.getPageMaker();
139 PageNode pageNode = pageMaker.getPageNode(getPageTitle(request), toadletContext);
140 for (String styleSheet : getStyleSheets()) {
141 pageNode.addCustomStyleSheet(styleSheet);
143 for (Map<String, String> linkNodeParameters : getAdditionalLinkNodes(request)) {
144 HTMLNode linkNode = pageNode.headNode.addChild("link");
145 for (Entry<String, String> parameter : linkNodeParameters.entrySet()) {
146 linkNode.addAttribute(parameter.getKey(), parameter.getValue());
149 String shortcutIcon = getShortcutIcon();
150 if (shortcutIcon != null) {
151 pageNode.addForwardLink("icon", shortcutIcon);
154 TemplateContext templateContext = templateContextFactory.createTemplateContext();
155 templateContext.mergeContext(template.getInitialContext());
157 long start = System.nanoTime();
158 processTemplate(request, templateContext);
159 long finish = System.nanoTime();
160 logger.log(Level.FINEST, String.format("Template was rendered in %.2fms.", (finish - start) / 1000000.0));
161 } catch (RedirectException re1) {
162 return new RedirectResponse(re1.getTarget());
165 StringWriter stringWriter = new StringWriter();
166 template.render(templateContext, stringWriter);
167 pageNode.content.addChild("%", stringWriter.toString());
169 postProcess(request, templateContext);
171 return response.setStatusCode(200).setStatusText("OK").setContentType("text/html").write(pageNode.outer.generate());
175 * Can be overridden to return a custom set of style sheets that are to be
176 * included in the page’s header.
178 * @return Additional style sheets to load
180 @SuppressWarnings("static-method")
181 protected Collection<String> getStyleSheets() {
182 return Collections.emptySet();
186 * Returns the name of the shortcut icon to include in the page’s header.
188 * @return The URL of the shortcut icon, or {@code null} for no icon
190 @SuppressWarnings("static-method")
191 protected String getShortcutIcon() {
196 * Can be overridden when extending classes need to set variables in the
197 * template before it is rendered.
200 * The request that is rendered
201 * @param templateContext
202 * The template context to set variables in
203 * @throws RedirectException
204 * if the processing page wants to redirect after processing
206 protected void processTemplate(FreenetRequest request, TemplateContext templateContext) throws RedirectException {
211 * This method will be called after
212 * {@link #processTemplate(FreenetRequest, TemplateContext)} has processed
213 * the template and the template was rendered. This method will not be
214 * called if {@link #processTemplate(FreenetRequest, TemplateContext)}
215 * throws a {@link RedirectException}!
218 * The request being processed
219 * @param templateContext
220 * The template context that supplied the rendered data
222 protected void postProcess(FreenetRequest request, TemplateContext templateContext) {
227 * Can be overridden to redirect the user to a different page, in case a log
228 * in is required, or something else is wrong.
231 * The request that is processed
232 * @return The URL to redirect to, or {@code null} to not redirect
234 @SuppressWarnings("static-method")
235 protected String getRedirectTarget(FreenetRequest request) {
240 * Returns additional <link> nodes for the HTML’s <head> node.
243 * The request for which to return the link nodes
244 * @return All link nodes that should be added to the HTML head
246 @SuppressWarnings("static-method")
247 protected List<Map<String, String>> getAdditionalLinkNodes(FreenetRequest request) {
248 return Collections.emptyList();
252 * Returns whether this page should only be allowed for requests from hosts
255 * @return {@code true} if this page should only be allowed for hosts with
256 * full access, {@code false} to allow this page for any host
258 @SuppressWarnings("static-method")
259 protected boolean isFullAccessOnly() {
267 public boolean isLinkExcepted(URI link) {
272 // INTERFACE LinkEnabledCallback
279 public boolean isEnabled(ToadletContext toadletContext) {
280 return !isFullAccessOnly();
284 * Exception that can be thrown to signal that a subclassed {@link Page}
285 * wants to redirect the user during the
286 * {@link FreenetTemplatePage#processTemplate(FreenetRequest, TemplateContext)}
289 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
291 public static class RedirectException extends Exception {
293 /** The target to redirect to. */
294 private final String target;
297 * Creates a new redirect exception.
300 * The target of the redirect
302 public RedirectException(String target) {
303 this.target = target;
307 * Returns the target to redirect to.
309 * @return The target to redirect to
311 public String getTarget() {