Merge branch 'release-0.8.7'
[Sone.git] / src / main / java / net / pterodactylus / sone / web / ajax / JsonPage.java
1 /*
2  * Sone - JsonPage.java - Copyright © 2010–2013 David Roden
3  *
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.
8  *
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.
13  *
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/>.
16  */
17
18 package net.pterodactylus.sone.web.ajax;
19
20 import java.io.ByteArrayOutputStream;
21 import java.io.IOException;
22 import java.io.OutputStreamWriter;
23 import java.io.PrintWriter;
24 import java.net.URI;
25 import java.util.logging.Level;
26 import java.util.logging.Logger;
27
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;
36
37 import com.fasterxml.jackson.databind.ObjectMapper;
38 import freenet.clients.http.SessionManager.Session;
39 import freenet.clients.http.ToadletContext;
40
41 /**
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.
44  *
45  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
46  */
47 public abstract class JsonPage implements FreenetPage {
48
49         /** The logger. */
50         private static final Logger logger = Logging.getLogger(JsonPage.class);
51
52         /** The JSON serializer. */
53         private static final ObjectMapper objectMapper = new ObjectMapper();
54
55         /** The path of the page. */
56         private final String path;
57
58         /** The Sone web interface. */
59         protected final WebInterface webInterface;
60
61         /**
62          * Creates a new JSON page at the given path.
63          *
64          * @param path
65          *            The path of the page
66          * @param webInterface
67          *            The Sone web interface
68          */
69         public JsonPage(String path, WebInterface webInterface) {
70                 this.path = path;
71                 this.webInterface = webInterface;
72         }
73
74         //
75         // ACCESSORS
76         //
77
78         /**
79          * Returns the current session, creating a new session if there is no
80          * current session.
81          *
82          * @param toadletContenxt
83          *            The toadlet context
84          * @return The current session, or {@code null} if there is no current
85          *         session
86          */
87         protected Session getCurrentSession(ToadletContext toadletContenxt) {
88                 return webInterface.getCurrentSession(toadletContenxt);
89         }
90
91         /**
92          * Returns the current session, creating a new session if there is no
93          * current session and {@code create} is {@code true}.
94          *
95          * @param toadletContenxt
96          *            The toadlet context
97          * @param create
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
101          *         session
102          */
103         protected Session getCurrentSession(ToadletContext toadletContenxt, boolean create) {
104                 return webInterface.getCurrentSession(toadletContenxt, create);
105         }
106
107         /**
108          * Returns the currently logged in Sone.
109          *
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
114          */
115         protected Sone getCurrentSone(ToadletContext toadletContext) {
116                 return webInterface.getCurrentSone(toadletContext);
117         }
118
119         /**
120          * Returns the currently logged in Sone.
121          *
122          * @param toadletContext
123          *            The toadlet context
124          * @param create
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
129          */
130         protected Sone getCurrentSone(ToadletContext toadletContext, boolean create) {
131                 return webInterface.getCurrentSone(toadletContext, create);
132         }
133
134         //
135         // METHODS FOR SUBCLASSES TO OVERRIDE
136         //
137
138         /**
139          * This method is called to create the JSON object that is returned back to
140          * the browser.
141          *
142          * @param request
143          *            The request to handle
144          * @return The created JSON object
145          */
146         protected abstract JsonReturnObject createJsonObject(FreenetRequest request);
147
148         /**
149          * Returns whether this command needs the form password for authentication
150          * and to prevent abuse.
151          *
152          * @return {@code true} if the form password (given as “formPassword”) is
153          *         required, {@code false} otherwise
154          */
155         @SuppressWarnings("static-method")
156         protected boolean needsFormPassword() {
157                 return true;
158         }
159
160         /**
161          * Returns whether this page requires the user to be logged in.
162          *
163          * @return {@code true} if the user needs to be logged in to use this page,
164          *         {@code false} otherwise
165          */
166         @SuppressWarnings("static-method")
167         protected boolean requiresLogin() {
168                 return true;
169         }
170
171         //
172         // PROTECTED METHODS
173         //
174
175         /**
176          * Creates a success reply.
177          *
178          * @return A reply signaling success
179          */
180         protected static JsonReturnObject createSuccessJsonObject() {
181                 return new JsonReturnObject(true);
182         }
183
184         /**
185          * Creates an error reply.
186          *
187          * @param error
188          *            The error that has occured
189          * @return The JSON object, signalling failure and the error code
190          */
191         protected static JsonReturnObject createErrorJsonObject(String error) {
192                 return new JsonErrorReturnObject(error);
193         }
194
195         //
196         // PAGE METHODS
197         //
198
199         /**
200          * {@inheritDoc}
201          */
202         @Override
203         public String getPath() {
204                 return path;
205         }
206
207         /**
208          * {@inheritDoc}
209          */
210         @Override
211         public boolean isPrefixPage() {
212                 return false;
213         }
214
215         /**
216          * {@inheritDoc}
217          */
218         @Override
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")));
222                 }
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")));
227                         }
228                 }
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")));
232                         }
233                 }
234                 try {
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));
240                 }
241         }
242
243         /**
244          * {@inheritDoc}
245          */
246         @Override
247         public boolean isLinkExcepted(URI link) {
248                 return false;
249         }
250
251         //
252         // PRIVATE METHODS
253         //
254
255         /**
256          * Returns a byte array containing the stack trace of the given throwable.
257          *
258          * @param t
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
262          */
263         private static byte[] dumpStackTrace(Throwable t) {
264                 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
265                 OutputStreamWriter writer = null;
266                 PrintWriter printWriter = null;
267                 try {
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. */
275                         return new byte[0];
276                 } finally {
277                         Closer.close(printWriter);
278                         Closer.close(writer);
279                         Closer.close(byteArrayOutputStream);
280                 }
281         }
282
283 }