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