From cb2f7e57a8ac1768da8f9c2a11d23118c1564f87 Mon Sep 17 00:00:00 2001 From: =?utf8?q?David=20=E2=80=98Bombe=E2=80=99=20Roden?= Date: Thu, 21 Oct 2010 12:23:31 +0200 Subject: [PATCH] Add page implementation that delivers a JSON object. --- .../net/pterodactylus/sone/web/ajax/JsonPage.java | 80 ++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 src/main/java/net/pterodactylus/sone/web/ajax/JsonPage.java 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)); + } + +} -- 2.7.4