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 com.fasterxml.jackson.databind.ObjectMapper;
38 import freenet.clients.http.SessionManager.Session;
39 import freenet.clients.http.ToadletContext;
42 * A JSON page is a specialized {@link Page} that will always return a JSON
43 * object to the browser, e.g. for use with AJAX or other scripting frameworks.
45 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
47 public abstract class JsonPage implements FreenetPage {
50 private static final Logger logger = Logging.getLogger(JsonPage.class);
52 /** The JSON serializer. */
53 private static final ObjectMapper objectMapper = new ObjectMapper();
55 /** The path of the page. */
56 private final String path;
58 /** The Sone web interface. */
59 protected final WebInterface webInterface;
62 * Creates a new JSON page at the given path.
65 * The path of the page
67 * The Sone web interface
69 public JsonPage(String path, WebInterface webInterface) {
71 this.webInterface = webInterface;
79 * Returns the current session, creating a new session if there is no
82 * @param toadletContenxt
84 * @return The current session, or {@code null} if there is no current
87 protected Session getCurrentSession(ToadletContext toadletContenxt) {
88 return webInterface.getCurrentSession(toadletContenxt);
92 * Returns the current session, creating a new session if there is no
93 * current session and {@code create} is {@code true}.
95 * @param toadletContenxt
98 * {@code true} to create a new session if there is no current
99 * session, {@code false} otherwise
100 * @return The current session, or {@code null} if there is no current
103 protected Session getCurrentSession(ToadletContext toadletContenxt, boolean create) {
104 return webInterface.getCurrentSession(toadletContenxt, create);
108 * Returns the currently logged in Sone.
110 * @param toadletContext
111 * The toadlet context
112 * @return The currently logged in Sone, or {@code null} if no Sone is
113 * currently logged in
115 protected Sone getCurrentSone(ToadletContext toadletContext) {
116 return webInterface.getCurrentSone(toadletContext);
120 * Returns the currently logged in Sone.
122 * @param toadletContext
123 * The toadlet context
125 * {@code true} to create a new session if no session exists,
126 * {@code false} to not create a new session
127 * @return The currently logged in Sone, or {@code null} if no Sone is
128 * currently logged in
130 protected Sone getCurrentSone(ToadletContext toadletContext, boolean create) {
131 return webInterface.getCurrentSone(toadletContext, create);
135 // METHODS FOR SUBCLASSES TO OVERRIDE
139 * This method is called to create the JSON object that is returned back to
143 * The request to handle
144 * @return The created JSON object
146 protected abstract JsonReturnObject createJsonObject(FreenetRequest request);
149 * Returns whether this command needs the form password for authentication
150 * and to prevent abuse.
152 * @return {@code true} if the form password (given as “formPassword”) is
153 * required, {@code false} otherwise
155 @SuppressWarnings("static-method")
156 protected boolean needsFormPassword() {
161 * Returns whether this page requires the user to be logged in.
163 * @return {@code true} if the user needs to be logged in to use this page,
164 * {@code false} otherwise
166 @SuppressWarnings("static-method")
167 protected boolean requiresLogin() {
176 * Creates a success reply.
178 * @return A reply signaling success
180 protected static JsonReturnObject createSuccessJsonObject() {
181 return new JsonReturnObject(true);
185 * Creates an error reply.
188 * The error that has occured
189 * @return The JSON object, signalling failure and the error code
191 protected static JsonReturnObject createErrorJsonObject(String error) {
192 return new JsonErrorReturnObject(error);
203 public String getPath() {
211 public boolean isPrefixPage() {
219 public Response handleRequest(FreenetRequest request, Response response) throws IOException {
220 if (webInterface.getCore().getPreferences().isRequireFullAccess() && !request.getToadletContext().isAllowedFullAccess()) {
221 return response.setStatusCode(403).setStatusText("Forbidden").setContentType("application/json").write(objectMapper.writeValueAsString(new JsonErrorReturnObject("auth-required")));
223 if (needsFormPassword()) {
224 String formPassword = request.getHttpRequest().getParam("formPassword");
225 if (!webInterface.getFormPassword().equals(formPassword)) {
226 return response.setStatusCode(403).setStatusText("Forbidden").setContentType("application/json").write(objectMapper.writeValueAsString(new JsonErrorReturnObject("auth-required")));
229 if (requiresLogin()) {
230 if (getCurrentSone(request.getToadletContext(), false) == null) {
231 return response.setStatusCode(403).setStatusText("Forbidden").setContentType("application/json").write(objectMapper.writeValueAsString(new JsonErrorReturnObject("auth-required")));
235 JsonReturnObject jsonObject = createJsonObject(request);
236 return response.setStatusCode(200).setStatusText("OK").setContentType("application/json").write(objectMapper.writeValueAsString(jsonObject));
237 } catch (Exception e1) {
238 logger.log(Level.WARNING, "Error executing JSON page!", e1);
239 return response.setStatusCode(500).setStatusText(e1.getMessage()).setContentType("text/plain").write(dumpStackTrace(e1));
247 public boolean isLinkExcepted(URI link) {
256 * Returns a byte array containing the stack trace of the given throwable.
259 * The throwable whose stack trace to dump into an array
260 * @return The array with the stack trace, or an empty array if the stack
261 * trace could not be dumped
263 private static byte[] dumpStackTrace(Throwable t) {
264 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
265 OutputStreamWriter writer = null;
266 PrintWriter printWriter = null;
268 writer = new OutputStreamWriter(byteArrayOutputStream, "uTF-8");
269 printWriter = new PrintWriter(writer);
270 t.printStackTrace(printWriter);
271 byteArrayOutputStream.flush();
272 return byteArrayOutputStream.toByteArray();
273 } catch (IOException ioe1) {
274 /* quite not possible. */
277 Closer.close(printWriter);
278 Closer.close(writer);
279 Closer.close(byteArrayOutputStream);