From 09e10dd6e554ce4af6b35e0f56251c6c26bc018e Mon Sep 17 00:00:00 2001 From: =?utf8?q?David=20=E2=80=98Bombe=E2=80=99=20Roden?= Date: Fri, 17 May 2019 18:38:51 +0200 Subject: [PATCH] =?utf8?q?=E2=99=BB=EF=B8=8F=20Replace=20FreenetTemplatePa?= =?utf8?q?ge=20with=20Kotlin=20version?= MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit --- .../sone/web/page/FreenetTemplatePage.java | 309 --------------------- .../sone/web/page/FreenetTemplatePage.kt | 113 ++++++++ .../sone/web/pages/SoneTemplatePage.kt | 5 +- .../net/pterodactylus/sone/web/AllPagesTest.kt | 5 +- .../kotlin/net/pterodactylus/sone/test/Guice.kt | 1 + .../sone/web/page/FreenetTemplatePageTest.kt | 23 +- 6 files changed, 132 insertions(+), 324 deletions(-) delete mode 100644 src/main/java/net/pterodactylus/sone/web/page/FreenetTemplatePage.java create mode 100644 src/main/kotlin/net/pterodactylus/sone/web/page/FreenetTemplatePage.kt diff --git a/src/main/java/net/pterodactylus/sone/web/page/FreenetTemplatePage.java b/src/main/java/net/pterodactylus/sone/web/page/FreenetTemplatePage.java deleted file mode 100644 index c4b1813..0000000 --- a/src/main/java/net/pterodactylus/sone/web/page/FreenetTemplatePage.java +++ /dev/null @@ -1,309 +0,0 @@ -/* - * Sone - FreenetTemplatePage.java - Copyright © 2010–2019 David Roden - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.pterodactylus.sone.web.page; - -import static java.lang.String.format; -import static java.util.logging.Logger.getLogger; - -import java.io.IOException; -import java.io.StringWriter; -import java.net.URI; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.logging.Level; -import java.util.logging.Logger; - -import net.pterodactylus.sone.main.Loaders; -import net.pterodactylus.util.template.Template; -import net.pterodactylus.util.template.TemplateContext; -import net.pterodactylus.util.template.TemplateContextFactory; -import net.pterodactylus.util.web.Method; -import net.pterodactylus.util.web.Page; -import net.pterodactylus.util.web.RedirectResponse; -import net.pterodactylus.util.web.Response; -import freenet.clients.http.LinkEnabledCallback; -import freenet.clients.http.PageMaker; -import freenet.clients.http.PageNode; -import freenet.clients.http.ToadletContext; -import freenet.support.HTMLNode; - -/** - * Base class for all {@link Page}s that are rendered with {@link Template}s and - * fit into Freenet’s web interface. - */ -public class FreenetTemplatePage implements FreenetPage, LinkEnabledCallback { - - /** The logger. */ - private static final Logger logger = getLogger(FreenetTemplatePage.class.getName()); - - /** The path of the page. */ - private final String path; - - /** The template context factory. */ - private final TemplateContextFactory templateContextFactory; - - /** The template to render. */ - private final Template template; - private final Loaders loaders; - - /** Where to redirect for invalid form passwords. */ - private final String invalidFormPasswordRedirectTarget; - - public FreenetTemplatePage(String path, TemplateContextFactory templateContextFactory, Loaders loaders, Template template, String invalidFormPasswordRedirectTarget) { - this.path = path; - this.templateContextFactory = templateContextFactory; - this.loaders = loaders; - this.template = template; - this.invalidFormPasswordRedirectTarget = invalidFormPasswordRedirectTarget; - } - - /** - * {@inheritDoc} - */ - @Override - public String getPath() { - return path; - } - - /** - * Returns the title of the page. - * - * @param request - * The request to serve - * @return The title of the page - */ - @SuppressWarnings("static-method") - protected String getPageTitle(FreenetRequest request) { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isPrefixPage() { - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public final Response handleRequest(FreenetRequest request, Response response) throws IOException { - String redirectTarget = getRedirectTarget(request); - if (redirectTarget != null) { - return new RedirectResponse(redirectTarget); - } - - if (isFullAccessOnly() && !request.getToadletContext().isAllowedFullAccess()) { - return response.setStatusCode(401).setStatusText("Not authorized").setContentType("text/html"); - } - ToadletContext toadletContext = request.getToadletContext(); - if (request.getMethod() == Method.POST) { - /* require form password. */ - String formPassword = request.getHttpRequest().getPartAsStringFailsafe("formPassword", 32); - if (!formPassword.equals(toadletContext.getContainer().getFormPassword())) { - return new RedirectResponse(invalidFormPasswordRedirectTarget); - } - } - PageMaker pageMaker = toadletContext.getPageMaker(); - PageNode pageNode = pageMaker.getPageNode(getPageTitle(request), toadletContext); - for (String styleSheet : getStyleSheets()) { - pageNode.addCustomStyleSheet(styleSheet); - } - for (Map linkNodeParameters : getAdditionalLinkNodes(request)) { - HTMLNode linkNode = pageNode.headNode.addChild("link"); - for (Entry parameter : linkNodeParameters.entrySet()) { - linkNode.addAttribute(parameter.getKey(), parameter.getValue()); - } - } - String shortcutIcon = getShortcutIcon(); - if (shortcutIcon != null) { - pageNode.addForwardLink("icon", shortcutIcon); - } - - TemplateContext templateContext = templateContextFactory.createTemplateContext(); - templateContext.mergeContext(template.getInitialContext()); - try { - long start = System.nanoTime(); - processTemplate(request, templateContext); - long finish = System.nanoTime(); - logger.log(Level.FINEST, format("Template was rendered in %.2fms.", (finish - start) / 1000000.0)); - } catch (RedirectException re1) { - return new RedirectResponse(re1.getTarget()); - } - - StringWriter stringWriter = new StringWriter(); - template.render(templateContext, stringWriter); - pageNode.content.addChild("%", stringWriter.toString()); - - postProcess(request, templateContext); - - return response.setStatusCode(200).setStatusText("OK").setContentType("text/html").write(pageNode.outer.generate()); - } - - /** - * Can be overridden to return a custom set of style sheets that are to be - * included in the page’s header. - * - * @return Additional style sheets to load - */ - @SuppressWarnings("static-method") - protected Collection getStyleSheets() { - return Collections.emptySet(); - } - - /** - * Returns the name of the shortcut icon to include in the page’s header. - * - * @return The URL of the shortcut icon, or {@code null} for no icon - */ - @SuppressWarnings("static-method") - protected String getShortcutIcon() { - return null; - } - - /** - * Can be overridden when extending classes need to set variables in the - * template before it is rendered. - * - * @param request - * The request that is rendered - * @param templateContext - * The template context to set variables in - * @throws RedirectException - * if the processing page wants to redirect after processing - */ - protected void processTemplate(FreenetRequest request, TemplateContext templateContext) throws RedirectException { - /* do nothing. */ - } - - /** - * This method will be called after - * {@link #processTemplate(FreenetRequest, TemplateContext)} has processed - * the template and the template was rendered. This method will not be - * called if {@link #processTemplate(FreenetRequest, TemplateContext)} - * throws a {@link RedirectException}! - * - * @param request - * The request being processed - * @param templateContext - * The template context that supplied the rendered data - */ - protected void postProcess(FreenetRequest request, TemplateContext templateContext) { - /* do nothing. */ - } - - /** - * Can be overridden to redirect the user to a different page, in case a log - * in is required, or something else is wrong. - * - * @param request - * The request that is processed - * @return The URL to redirect to, or {@code null} to not redirect - */ - @SuppressWarnings("static-method") - protected String getRedirectTarget(FreenetRequest request) { - return null; - } - - /** - * Returns additional <link> nodes for the HTML’s <head> node. - * - * @param request - * The request for which to return the link nodes - * @return All link nodes that should be added to the HTML head - */ - @SuppressWarnings("static-method") - protected List> getAdditionalLinkNodes(FreenetRequest request) { - return Collections.emptyList(); - } - - /** - * Returns whether this page should only be allowed for requests from hosts - * with full access. - * - * @return {@code true} if this page should only be allowed for hosts with - * full access, {@code false} to allow this page for any host - */ - @SuppressWarnings("static-method") - protected boolean isFullAccessOnly() { - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isLinkExcepted(URI link) { - return false; - } - - // - // INTERFACE LinkEnabledCallback - // - - /** - * {@inheritDoc} - */ - @Override - public boolean isEnabled(ToadletContext toadletContext) { - return !isFullAccessOnly(); - } - - /** - * Exception that can be thrown to signal that a subclassed {@link Page} - * wants to redirect the user during the - * {@link FreenetTemplatePage#processTemplate(FreenetRequest, TemplateContext)} - * method call. - */ - public static class RedirectException extends Exception { - - /** The target to redirect to. */ - private final String target; - - /** - * Creates a new redirect exception. - * - * @param target - * The target of the redirect - */ - public RedirectException(String target) { - this.target = target; - } - - /** - * Returns the target to redirect to. - * - * @return The target to redirect to - */ - public String getTarget() { - return target; - } - - @Override - public String toString() { - return format("RedirectException{target='%s'}", target); - } - - } - -} diff --git a/src/main/kotlin/net/pterodactylus/sone/web/page/FreenetTemplatePage.kt b/src/main/kotlin/net/pterodactylus/sone/web/page/FreenetTemplatePage.kt new file mode 100644 index 0000000..d93e7d1 --- /dev/null +++ b/src/main/kotlin/net/pterodactylus/sone/web/page/FreenetTemplatePage.kt @@ -0,0 +1,113 @@ +/* + * Sone - FreenetTemplatePage.java - Copyright © 2010–2019 David Roden + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.pterodactylus.sone.web.page + +import freenet.clients.http.* +import net.pterodactylus.sone.main.* +import net.pterodactylus.util.template.* +import net.pterodactylus.util.web.* +import java.io.* +import java.lang.String.* +import java.net.* +import java.util.logging.* +import java.util.logging.Logger.* + +/** + * Base class for all [Page]s that are rendered with [Template]s and + * fit into Freenet’s web interface. + */ +open class FreenetTemplatePage( + private val path: String, + private val templateContextFactory: TemplateContextFactory, + private val loaders: Loaders, + private val template: Template, + private val invalidFormPasswordRedirectTarget: String +) : FreenetPage, LinkEnabledCallback { + + open val styleSheets: Collection = emptySet() + open val shortcutIcon: String? get() = null + open val isFullAccessOnly get() = false + + override fun getPath() = path + + open fun getPageTitle(request: FreenetRequest) = "" + + override fun isPrefixPage() = false + + open fun getRedirectTarget(request: FreenetRequest): String? = null + + open fun getAdditionalLinkNodes(request: FreenetRequest): List> = emptyList() + + override fun isLinkExcepted(link: URI) = false + + override fun isEnabled(toadletContext: ToadletContext) = !isFullAccessOnly + + override fun handleRequest(request: FreenetRequest, response: Response): Response { + getRedirectTarget(request)?.let { redirectTarget -> return RedirectResponse(redirectTarget) } + + if (isFullAccessOnly && !request.toadletContext.isAllowedFullAccess) { + return response.setStatusCode(401).setStatusText("Not authorized").setContentType("text/html") + } + val toadletContext = request.toadletContext + if (request.method == Method.POST) { + /* require form password. */ + val formPassword = request.httpRequest.getPartAsStringFailsafe("formPassword", 32) + if (formPassword != toadletContext.container.formPassword) { + return RedirectResponse(invalidFormPasswordRedirectTarget) + } + } + val pageMaker = toadletContext.pageMaker + val pageNode = pageMaker.getPageNode(getPageTitle(request), toadletContext) + + styleSheets.forEach(pageNode::addCustomStyleSheet) + getAdditionalLinkNodes(request) + .map { it to pageNode.headNode.addChild("link") } + .forEach { (linkNodeParameters, linkNode) -> + linkNodeParameters.forEach(linkNode::addAttribute) + } + shortcutIcon?.let { pageNode.addForwardLink("icon", it) } + + val templateContext = templateContextFactory.createTemplateContext() + templateContext.mergeContext(template.initialContext) + try { + val start = System.nanoTime() + processTemplate(request, templateContext) + val finish = System.nanoTime() + logger.log(Level.FINEST, format("Template was rendered in %.2fms.", (finish - start) / 1000000.0)) + } catch (re1: RedirectException) { + return RedirectResponse(re1.target ?: "") + } + + val stringWriter = StringWriter() + template.render(templateContext, stringWriter) + pageNode.content.addChild("%", stringWriter.toString()) + + return response.setStatusCode(200).setStatusText("OK").setContentType("text/html").write(pageNode.outer.generate()) + } + + open fun processTemplate(request: FreenetRequest, templateContext: TemplateContext) { + /* do nothing. */ + } + + class RedirectException(val target: String?) : Exception() { + override fun toString(): String = format("RedirectException{target='%s'}", target) + } + +} + +private val logger: Logger = getLogger(FreenetTemplatePage::class.java.name) diff --git a/src/main/kotlin/net/pterodactylus/sone/web/pages/SoneTemplatePage.kt b/src/main/kotlin/net/pterodactylus/sone/web/pages/SoneTemplatePage.kt index 7efd2bd..1d1ccf1 100644 --- a/src/main/kotlin/net/pterodactylus/sone/web/pages/SoneTemplatePage.kt +++ b/src/main/kotlin/net/pterodactylus/sone/web/pages/SoneTemplatePage.kt @@ -41,10 +41,9 @@ open class SoneTemplatePage @JvmOverloads constructor( open fun getPageTitle(soneRequest: SoneRequest) = pageTitle(soneRequest) - override public fun getStyleSheets() = - listOf("css/sone.css") + override val styleSheets = listOf("css/sone.css") - override public fun getShortcutIcon() = "images/icon.png" + override val shortcutIcon = "images/icon.png" override public fun getAdditionalLinkNodes(request: FreenetRequest) = listOf(mapOf( diff --git a/src/test/java/net/pterodactylus/sone/web/AllPagesTest.kt b/src/test/java/net/pterodactylus/sone/web/AllPagesTest.kt index d360b2f..30286a3 100644 --- a/src/test/java/net/pterodactylus/sone/web/AllPagesTest.kt +++ b/src/test/java/net/pterodactylus/sone/web/AllPagesTest.kt @@ -6,8 +6,7 @@ import net.pterodactylus.sone.core.FreenetInterface import net.pterodactylus.sone.main.PluginHomepage import net.pterodactylus.sone.main.PluginVersion import net.pterodactylus.sone.main.PluginYear -import net.pterodactylus.sone.test.getInstance -import net.pterodactylus.sone.test.isProvidedByMock +import net.pterodactylus.sone.test.* import net.pterodactylus.sone.web.pages.* import net.pterodactylus.util.template.Template import org.hamcrest.Matcher @@ -247,6 +246,6 @@ val baseInjector by lazy { Core::class.isProvidedByMock(), FreenetInterface::class.isProvidedByMock(), Template::class.isProvidedByMock(), - WebInterface::class.isProvidedByMock() + WebInterface::class.isProvidedByDeepMock() )!! } diff --git a/src/test/kotlin/net/pterodactylus/sone/test/Guice.kt b/src/test/kotlin/net/pterodactylus/sone/test/Guice.kt index e27ad07..abf0476 100644 --- a/src/test/kotlin/net/pterodactylus/sone/test/Guice.kt +++ b/src/test/kotlin/net/pterodactylus/sone/test/Guice.kt @@ -10,6 +10,7 @@ fun KClass.isProvidedBy(instance: T) = Module { it.bind(this.java). fun KClass.isProvidedBy(provider: com.google.inject.Provider) = Module { it.bind(this.java).toProvider(provider) } fun KClass.isProvidedBy(provider: KClass>) = Module { it.bind(this.java).toProvider(provider.java) } inline fun KClass.isProvidedByMock() = Module { it.bind(this.java).toProvider(Provider { mock() }) } +inline fun KClass.isProvidedByDeepMock() = Module { it.bind(this.java).toProvider(Provider { deepMock() }) } inline fun Injector.getInstance() = getInstance(T::class.java)!! diff --git a/src/test/kotlin/net/pterodactylus/sone/web/page/FreenetTemplatePageTest.kt b/src/test/kotlin/net/pterodactylus/sone/web/page/FreenetTemplatePageTest.kt index 35d4afd..d992b30 100644 --- a/src/test/kotlin/net/pterodactylus/sone/web/page/FreenetTemplatePageTest.kt +++ b/src/test/kotlin/net/pterodactylus/sone/web/page/FreenetTemplatePageTest.kt @@ -1,6 +1,8 @@ package net.pterodactylus.sone.web.page +import net.pterodactylus.sone.main.* import net.pterodactylus.sone.test.* +import net.pterodactylus.util.template.* import net.pterodactylus.util.web.* import net.pterodactylus.util.web.Method.* import org.hamcrest.MatcherAssert.* @@ -10,7 +12,10 @@ import org.mockito.ArgumentMatchers.* class FreenetTemplatePageTest { - private val page = FreenetTemplatePage("/test/path", null, null, null, "invalid-form-password") + private val templateContextFactory = mock() + private val loaders = mock() + private val template = mock