2 * Sone - JsonPage.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.ajax;
20 import static java.util.logging.Logger.getLogger;
22 import java.io.ByteArrayOutputStream;
23 import java.io.IOException;
24 import java.io.OutputStreamWriter;
25 import java.io.PrintWriter;
27 import java.util.logging.Level;
28 import java.util.logging.Logger;
30 import net.pterodactylus.sone.data.Sone;
31 import net.pterodactylus.sone.web.WebInterface;
32 import net.pterodactylus.sone.web.page.FreenetPage;
33 import net.pterodactylus.sone.web.page.FreenetRequest;
34 import net.pterodactylus.util.io.Closer;
35 import net.pterodactylus.util.web.Page;
36 import net.pterodactylus.util.web.Response;
38 import com.fasterxml.jackson.databind.ObjectMapper;
39 import freenet.clients.http.SessionManager.Session;
40 import freenet.clients.http.ToadletContext;
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 = getLogger(JsonPage.class.getName());
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.getCurrentSoneCreatingSession(toadletContext);
91 protected Sone getCurrentSoneWithoutCreatingSession(ToadletContext toadletContext) {
92 return webInterface.getCurrentSoneWithoutCreatingSession(toadletContext);
96 // METHODS FOR SUBCLASSES TO OVERRIDE
100 * This method is called to create the JSON object that is returned back to
104 * The request to handle
105 * @return The created JSON object
107 protected abstract JsonReturnObject createJsonObject(FreenetRequest request);
110 * Returns whether this command needs the form password for authentication
111 * and to prevent abuse.
113 * @return {@code true} if the form password (given as “formPassword”) is
114 * required, {@code false} otherwise
116 @SuppressWarnings("static-method")
117 protected boolean needsFormPassword() {
122 * Returns whether this page requires the user to be logged in.
124 * @return {@code true} if the user needs to be logged in to use this page,
125 * {@code false} otherwise
127 @SuppressWarnings("static-method")
128 protected boolean requiresLogin() {
137 * Creates a success reply.
139 * @return A reply signaling success
141 protected static JsonReturnObject createSuccessJsonObject() {
142 return new JsonReturnObject(true);
146 * Creates an error reply.
149 * The error that has occured
150 * @return The JSON object, signalling failure and the error code
152 protected static JsonReturnObject createErrorJsonObject(String error) {
153 return new JsonErrorReturnObject(error);
164 public String getPath() {
172 public boolean isPrefixPage() {
180 public Response handleRequest(FreenetRequest request, Response response) throws IOException {
181 if (webInterface.getCore().getPreferences().isRequireFullAccess() && !request.getToadletContext().isAllowedFullAccess()) {
182 return response.setStatusCode(403).setStatusText("Forbidden").setContentType("application/json").write(objectMapper.writeValueAsString(new JsonErrorReturnObject("auth-required")));
184 if (needsFormPassword()) {
185 String formPassword = request.getHttpRequest().getParam("formPassword");
186 if (!webInterface.getFormPassword().equals(formPassword)) {
187 return response.setStatusCode(403).setStatusText("Forbidden").setContentType("application/json").write(objectMapper.writeValueAsString(new JsonErrorReturnObject("auth-required")));
190 if (requiresLogin()) {
191 if (getCurrentSoneWithoutCreatingSession(request.getToadletContext()) == null) {
192 return response.setStatusCode(403).setStatusText("Forbidden").setContentType("application/json").write(objectMapper.writeValueAsString(new JsonErrorReturnObject("auth-required")));
196 JsonReturnObject jsonObject = createJsonObject(request);
197 return response.setStatusCode(200).setStatusText("OK").setContentType("application/json").write(objectMapper.writeValueAsString(jsonObject));
198 } catch (Exception e1) {
199 logger.log(Level.WARNING, "Error executing JSON page!", e1);
200 return response.setStatusCode(500).setStatusText(e1.getMessage()).setContentType("text/plain").write(dumpStackTrace(e1));
208 public boolean isLinkExcepted(URI link) {
217 * Returns a byte array containing the stack trace of the given throwable.
220 * The throwable whose stack trace to dump into an array
221 * @return The array with the stack trace, or an empty array if the stack
222 * trace could not be dumped
224 private static byte[] dumpStackTrace(Throwable t) {
225 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
226 OutputStreamWriter writer = null;
227 PrintWriter printWriter = null;
229 writer = new OutputStreamWriter(byteArrayOutputStream, "uTF-8");
230 printWriter = new PrintWriter(writer);
231 t.printStackTrace(printWriter);
232 byteArrayOutputStream.flush();
233 return byteArrayOutputStream.toByteArray();
234 } catch (IOException ioe1) {
235 /* quite not possible. */
238 Closer.close(printWriter);
239 Closer.close(writer);
240 Closer.close(byteArrayOutputStream);