From: David ‘Bombe’ Roden Date: Thu, 21 Oct 2010 10:23:31 +0000 (+0200) Subject: Add page implementation that delivers a JSON object. X-Git-Tag: 0.1-RC1~127 X-Git-Url: https://git.pterodactylus.net/?a=commitdiff_plain;h=cb2f7e57a8ac1768da8f9c2a11d23118c1564f87;p=Sone.git Add page implementation that delivers a JSON object. --- diff --git a/src/main/java/net/pterodactylus/sone/web/ajax/JsonPage.java b/src/main/java/net/pterodactylus/sone/web/ajax/JsonPage.java new file mode 100644 index 0000000..20ddfc6 --- /dev/null +++ b/src/main/java/net/pterodactylus/sone/web/ajax/JsonPage.java @@ -0,0 +1,80 @@ +/* + * Sone - JsonPage.java - Copyright © 2010 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.ajax; + +import net.pterodactylus.sone.web.page.Page; +import net.pterodactylus.util.json.JsonObject; +import net.pterodactylus.util.json.JsonUtils; + +/** + * A JSON page is a specialized {@link Page} that will always return a JSON + * object to the browser, e.g. for use with AJAX or other scripting frameworks. + * + * @author David ‘Bombe’ Roden + */ +public abstract class JsonPage implements Page { + + /** The path of the page. */ + private final String path; + + /** + * Creates a new JSON page at the given path. + * + * @param path + * The path of the page + */ + public JsonPage(String path) { + this.path = path; + } + + // + // METHODS FOR SUBCLASSES TO OVERRIDE + // + + /** + * This method is called to create the JSON object that is returned back to + * the browser. + * + * @param request + * The request to handle + * @return The created JSON object + */ + protected abstract JsonObject createJsonObject(Request request); + + // + // PAGE METHODS + // + + /** + * {@inheritDoc} + */ + @Override + public String getPath() { + return path; + } + + /** + * {@inheritDoc} + */ + @Override + public Response handleRequest(Request request) { + JsonObject jsonObject = createJsonObject(request); + return new Response(200, "OK", "application/json", JsonUtils.format(jsonObject)); + } + +}