Replace get status AJAX page with Kotlin version
[Sone.git] / src / main / java / net / pterodactylus / sone / web / ajax / JsonPage.java
1 /*
2  * Sone - JsonPage.java - Copyright © 2010–2016 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 static java.util.logging.Logger.getLogger;
21
22 import java.io.ByteArrayOutputStream;
23 import java.io.IOException;
24 import java.io.OutputStreamWriter;
25 import java.io.PrintWriter;
26 import java.net.URI;
27 import java.util.logging.Level;
28 import java.util.logging.Logger;
29
30 import javax.annotation.Nonnull;
31
32 import net.pterodactylus.sone.data.Sone;
33 import net.pterodactylus.sone.web.WebInterface;
34 import net.pterodactylus.sone.web.page.FreenetPage;
35 import net.pterodactylus.sone.web.page.FreenetRequest;
36 import net.pterodactylus.util.io.Closer;
37 import net.pterodactylus.util.web.Page;
38 import net.pterodactylus.util.web.Response;
39
40 import com.fasterxml.jackson.databind.ObjectMapper;
41 import freenet.clients.http.SessionManager.Session;
42 import freenet.clients.http.ToadletContext;
43
44 /**
45  * A JSON page is a specialized {@link Page} that will always return a JSON
46  * object to the browser, e.g. for use with AJAX or other scripting frameworks.
47  *
48  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
49  */
50 public abstract class JsonPage implements FreenetPage {
51
52         /** The logger. */
53         private static final Logger logger = getLogger(JsonPage.class.getName());
54
55         /** The JSON serializer. */
56         private static final ObjectMapper objectMapper = new ObjectMapper();
57
58         /** The path of the page. */
59         private final String path;
60
61         /** The Sone web interface. */
62         protected final WebInterface webInterface;
63
64         /**
65          * Creates a new JSON page at the given path.
66          *
67          * @param path
68          *            The path of the page
69          * @param webInterface
70          *            The Sone web interface
71          */
72         public JsonPage(String path, WebInterface webInterface) {
73                 this.path = path;
74                 this.webInterface = webInterface;
75         }
76
77         //
78         // ACCESSORS
79         //
80
81         /**
82          * Returns the currently logged in Sone.
83          *
84          * @param toadletContext
85          *            The toadlet context
86          * @return The currently logged in Sone, or {@code null} if no Sone is
87          *         currently logged in
88          */
89         protected Sone getCurrentSone(ToadletContext toadletContext) {
90                 return webInterface.getCurrentSoneCreatingSession(toadletContext);
91         }
92
93         protected Sone getCurrentSoneWithoutCreatingSession(ToadletContext toadletContext) {
94                 return webInterface.getCurrentSoneWithoutCreatingSession(toadletContext);
95         }
96
97         //
98         // METHODS FOR SUBCLASSES TO OVERRIDE
99         //
100
101         /**
102          * This method is called to create the JSON object that is returned back to
103          * the browser.
104          *
105          * @param request
106          *            The request to handle
107          * @return The created JSON object
108          */
109         protected abstract JsonReturnObject createJsonObject(FreenetRequest request);
110
111         /**
112          * Returns whether this command needs the form password for authentication
113          * and to prevent abuse.
114          *
115          * @return {@code true} if the form password (given as “formPassword”) is
116          *         required, {@code false} otherwise
117          */
118         @SuppressWarnings("static-method")
119         protected boolean needsFormPassword() {
120                 return true;
121         }
122
123         /**
124          * Returns whether this page requires the user to be logged in.
125          *
126          * @return {@code true} if the user needs to be logged in to use this page,
127          *         {@code false} otherwise
128          */
129         @SuppressWarnings("static-method")
130         protected boolean requiresLogin() {
131                 return true;
132         }
133
134         //
135         // PROTECTED METHODS
136         //
137
138         /**
139          * Creates a success reply.
140          *
141          * @return A reply signaling success
142          */
143         @Nonnull
144         protected static JsonReturnObject createSuccessJsonObject() {
145                 return new JsonReturnObject(true);
146         }
147
148         /**
149          * Creates an error reply.
150          *
151          * @param error
152          *            The error that has occured
153          * @return The JSON object, signalling failure and the error code
154          */
155         @Nonnull
156         protected static JsonReturnObject createErrorJsonObject(String error) {
157                 return new JsonErrorReturnObject(error);
158         }
159
160         //
161         // PAGE METHODS
162         //
163
164         /**
165          * {@inheritDoc}
166          */
167         @Override
168         public String getPath() {
169                 return path;
170         }
171
172         /**
173          * {@inheritDoc}
174          */
175         @Override
176         public boolean isPrefixPage() {
177                 return false;
178         }
179
180         /**
181          * {@inheritDoc}
182          */
183         @Override
184         public Response handleRequest(FreenetRequest request, Response response) throws IOException {
185                 if (webInterface.getCore().getPreferences().isRequireFullAccess() && !request.getToadletContext().isAllowedFullAccess()) {
186                         return response.setStatusCode(403).setStatusText("Forbidden").setContentType("application/json").write(objectMapper.writeValueAsString(new JsonErrorReturnObject("auth-required")));
187                 }
188                 if (needsFormPassword()) {
189                         String formPassword = request.getHttpRequest().getParam("formPassword");
190                         if (!webInterface.getFormPassword().equals(formPassword)) {
191                                 return response.setStatusCode(403).setStatusText("Forbidden").setContentType("application/json").write(objectMapper.writeValueAsString(new JsonErrorReturnObject("auth-required")));
192                         }
193                 }
194                 if (requiresLogin()) {
195                         if (getCurrentSoneWithoutCreatingSession(request.getToadletContext()) == null) {
196                                 return response.setStatusCode(403).setStatusText("Forbidden").setContentType("application/json").write(objectMapper.writeValueAsString(new JsonErrorReturnObject("auth-required")));
197                         }
198                 }
199                 try {
200                         JsonReturnObject jsonObject = createJsonObject(request);
201                         return response.setStatusCode(200).setStatusText("OK").setContentType("application/json").write(objectMapper.writeValueAsString(jsonObject));
202                 } catch (Exception e1) {
203                         logger.log(Level.WARNING, "Error executing JSON page!", e1);
204                         return response.setStatusCode(500).setStatusText(e1.getMessage()).setContentType("text/plain").write(dumpStackTrace(e1));
205                 }
206         }
207
208         /**
209          * {@inheritDoc}
210          */
211         @Override
212         public boolean isLinkExcepted(URI link) {
213                 return false;
214         }
215
216         //
217         // PRIVATE METHODS
218         //
219
220         /**
221          * Returns a byte array containing the stack trace of the given throwable.
222          *
223          * @param t
224          *            The throwable whose stack trace to dump into an array
225          * @return The array with the stack trace, or an empty array if the stack
226          *         trace could not be dumped
227          */
228         private static byte[] dumpStackTrace(Throwable t) {
229                 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
230                 OutputStreamWriter writer = null;
231                 PrintWriter printWriter = null;
232                 try {
233                         writer = new OutputStreamWriter(byteArrayOutputStream, "uTF-8");
234                         printWriter = new PrintWriter(writer);
235                         t.printStackTrace(printWriter);
236                         byteArrayOutputStream.flush();
237                         return byteArrayOutputStream.toByteArray();
238                 } catch (IOException ioe1) {
239                         /* quite not possible. */
240                         return new byte[0];
241                 } finally {
242                         Closer.close(printWriter);
243                         Closer.close(writer);
244                         Closer.close(byteArrayOutputStream);
245                 }
246         }
247
248 }