2 * Sone - JsonPage.java - Copyright © 2010–2013 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.ajax;
20 import java.io.ByteArrayOutputStream;
21 import java.io.IOException;
22 import java.io.OutputStreamWriter;
23 import java.io.PrintWriter;
25 import java.util.logging.Level;
26 import java.util.logging.Logger;
28 import net.pterodactylus.sone.data.Sone;
29 import net.pterodactylus.sone.web.WebInterface;
30 import net.pterodactylus.sone.web.page.FreenetPage;
31 import net.pterodactylus.sone.web.page.FreenetRequest;
32 import net.pterodactylus.util.io.Closer;
33 import net.pterodactylus.util.logging.Logging;
34 import net.pterodactylus.util.web.Page;
35 import net.pterodactylus.util.web.Response;
37 import freenet.clients.http.SessionManager.Session;
38 import freenet.clients.http.ToadletContext;
40 import com.fasterxml.jackson.databind.ObjectMapper;
43 * A JSON page is a specialized {@link Page} that will always return a JSON
44 * object to the browser, e.g. for use with AJAX or other scripting frameworks.
46 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
48 public abstract class JsonPage implements FreenetPage {
51 private static final Logger logger = Logging.getLogger(JsonPage.class);
53 /** The JSON serializer. */
54 private static final ObjectMapper objectMapper = new ObjectMapper();
56 /** The path of the page. */
57 private final String path;
59 /** The Sone web interface. */
60 protected final WebInterface webInterface;
63 * Creates a new JSON page at the given path.
66 * The path of the page
68 * The Sone web interface
70 public JsonPage(String path, WebInterface webInterface) {
72 this.webInterface = webInterface;
80 * Returns the currently logged in Sone.
82 * @param toadletContext
84 * @return The currently logged in Sone, or {@code null} if no Sone is
87 protected Sone getCurrentSone(ToadletContext toadletContext) {
88 return webInterface.getCurrentSone(toadletContext);
92 * Returns the currently logged in Sone.
94 * @param toadletContext
97 * {@code true} to create a new session if no session exists,
98 * {@code false} to not create a new session
99 * @return The currently logged in Sone, or {@code null} if no Sone is
100 * currently logged in
102 protected Sone getCurrentSone(ToadletContext toadletContext, boolean create) {
103 return webInterface.getCurrentSone(toadletContext, create);
107 // METHODS FOR SUBCLASSES TO OVERRIDE
111 * This method is called to create the JSON object that is returned back to
115 * The request to handle
116 * @return The created JSON object
118 protected abstract JsonReturnObject createJsonObject(FreenetRequest request);
121 * Returns whether this command needs the form password for authentication
122 * and to prevent abuse.
124 * @return {@code true} if the form password (given as “formPassword”) is
125 * required, {@code false} otherwise
127 @SuppressWarnings("static-method")
128 protected boolean needsFormPassword() {
133 * Returns whether this page requires the user to be logged in.
135 * @return {@code true} if the user needs to be logged in to use this page,
136 * {@code false} otherwise
138 @SuppressWarnings("static-method")
139 protected boolean requiresLogin() {
148 * Creates a success reply.
150 * @return A reply signaling success
152 protected static JsonReturnObject createSuccessJsonObject() {
153 return new JsonReturnObject(true);
157 * Creates an error reply.
160 * The error that has occured
161 * @return The JSON object, signalling failure and the error code
163 protected static JsonReturnObject createErrorJsonObject(String error) {
164 return new JsonErrorReturnObject(error);
172 public String getPath() {
177 public boolean isPrefixPage() {
182 public Response handleRequest(FreenetRequest request, Response response) throws IOException {
183 if (webInterface.getCore().getPreferences().isRequireFullAccess() && !request.getToadletContext().isAllowedFullAccess()) {
184 return response.setStatusCode(403).setStatusText("Forbidden").setContentType("application/json").write(objectMapper.writeValueAsString(new JsonErrorReturnObject("auth-required")));
186 if (needsFormPassword()) {
187 String formPassword = request.getHttpRequest().getParam("formPassword");
188 if (!webInterface.getFormPassword().equals(formPassword)) {
189 return response.setStatusCode(403).setStatusText("Forbidden").setContentType("application/json").write(objectMapper.writeValueAsString(new JsonErrorReturnObject("auth-required")));
192 if (requiresLogin()) {
193 if (getCurrentSone(request.getToadletContext(), false) == null) {
194 return response.setStatusCode(403).setStatusText("Forbidden").setContentType("application/json").write(objectMapper.writeValueAsString(new JsonErrorReturnObject("auth-required")));
198 JsonReturnObject jsonObject = createJsonObject(request);
199 return response.setStatusCode(200).setStatusText("OK").setContentType("application/json").write(objectMapper.writeValueAsString(jsonObject));
200 } catch (Exception e1) {
201 logger.log(Level.WARNING, "Error executing JSON page!", e1);
202 return response.setStatusCode(500).setStatusText(e1.getMessage()).setContentType("text/plain").write(dumpStackTrace(e1));
207 public boolean isLinkExcepted(URI link) {
216 * Returns a byte array containing the stack trace of the given throwable.
219 * The throwable whose stack trace to dump into an array
220 * @return The array with the stack trace, or an empty array if the stack
221 * trace could not be dumped
223 private static byte[] dumpStackTrace(Throwable t) {
224 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
225 OutputStreamWriter writer = null;
226 PrintWriter printWriter = null;
228 writer = new OutputStreamWriter(byteArrayOutputStream, "uTF-8");
229 printWriter = new PrintWriter(writer);
230 t.printStackTrace(printWriter);
231 byteArrayOutputStream.flush();
232 return byteArrayOutputStream.toByteArray();
233 } catch (IOException ioe1) {
234 /* quite not possible. */
237 Closer.close(printWriter);
238 Closer.close(writer);
239 Closer.close(byteArrayOutputStream);