Remove unused methods.
[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 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 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;
37
38 import com.fasterxml.jackson.databind.ObjectMapper;
39
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 FreenetPage {
49
50         /** The logger. */
51         private static final Logger logger = getLogger("Sone.Web.Ajax");
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
62         /**
63          * Creates a new JSON page at the given path.
64          *
65          * @param path
66          *            The path of the page
67          * @param webInterface
68          *            The Sone web interface
69          */
70         public JsonPage(String path, WebInterface webInterface) {
71                 this.path = path;
72                 this.webInterface = webInterface;
73         }
74
75         //
76         // ACCESSORS
77         //
78
79         /**
80          * Returns the currently logged in Sone.
81          *
82          * @param toadletContext
83          *            The toadlet context
84          * @return The currently logged in Sone, or {@code null} if no Sone is
85          *         currently logged in
86          */
87         protected Sone getCurrentSone(ToadletContext toadletContext) {
88                 return webInterface.getCurrentSone(toadletContext);
89         }
90
91         /**
92          * Returns the currently logged in Sone.
93          *
94          * @param toadletContext
95          *            The toadlet context
96          * @param create
97          *            {@code true} to create a new session if no session exists,
98          *            {@code false} to not create a new session
99          * @return The currently logged in Sone, or {@code null} if no Sone is
100          *         currently logged in
101          */
102         protected Sone getCurrentSone(ToadletContext toadletContext, boolean create) {
103                 return webInterface.getCurrentSone(toadletContext, create);
104         }
105
106         //
107         // METHODS FOR SUBCLASSES TO OVERRIDE
108         //
109
110         /**
111          * This method is called to create the JSON object that is returned back to
112          * the browser.
113          *
114          * @param request
115          *            The request to handle
116          * @return The created JSON object
117          */
118         protected abstract JsonReturnObject createJsonObject(FreenetRequest request);
119
120         /**
121          * Returns whether this command needs the form password for authentication
122          * and to prevent abuse.
123          *
124          * @return {@code true} if the form password (given as “formPassword”) is
125          *         required, {@code false} otherwise
126          */
127         @SuppressWarnings("static-method")
128         protected boolean needsFormPassword() {
129                 return true;
130         }
131
132         /**
133          * Returns whether this page requires the user to be logged in.
134          *
135          * @return {@code true} if the user needs to be logged in to use this page,
136          *         {@code false} otherwise
137          */
138         @SuppressWarnings("static-method")
139         protected boolean requiresLogin() {
140                 return true;
141         }
142
143         //
144         // PROTECTED METHODS
145         //
146
147         /**
148          * Creates a success reply.
149          *
150          * @return A reply signaling success
151          */
152         protected static JsonReturnObject createSuccessJsonObject() {
153                 return new JsonReturnObject(true);
154         }
155
156         /**
157          * Creates an error reply.
158          *
159          * @param error
160          *            The error that has occured
161          * @return The JSON object, signalling failure and the error code
162          */
163         protected static JsonReturnObject createErrorJsonObject(String error) {
164                 return new JsonErrorReturnObject(error);
165         }
166
167         //
168         // PAGE METHODS
169         //
170
171         /**
172          * {@inheritDoc}
173          */
174         @Override
175         public String getPath() {
176                 return path;
177         }
178
179         /**
180          * {@inheritDoc}
181          */
182         @Override
183         public boolean isPrefixPage() {
184                 return false;
185         }
186
187         /**
188          * {@inheritDoc}
189          */
190         @Override
191         public Response handleRequest(FreenetRequest request, Response response) throws IOException {
192                 if (webInterface.getCore().getPreferences().isRequireFullAccess() && !request.getToadletContext().isAllowedFullAccess()) {
193                         return response.setStatusCode(403).setStatusText("Forbidden").setContentType("application/json").write(objectMapper.writeValueAsString(new JsonErrorReturnObject("auth-required")));
194                 }
195                 if (needsFormPassword()) {
196                         String formPassword = request.getHttpRequest().getParam("formPassword");
197                         if (!webInterface.getFormPassword().equals(formPassword)) {
198                                 return response.setStatusCode(403).setStatusText("Forbidden").setContentType("application/json").write(objectMapper.writeValueAsString(new JsonErrorReturnObject("auth-required")));
199                         }
200                 }
201                 if (requiresLogin()) {
202                         if (getCurrentSone(request.getToadletContext(), false) == null) {
203                                 return response.setStatusCode(403).setStatusText("Forbidden").setContentType("application/json").write(objectMapper.writeValueAsString(new JsonErrorReturnObject("auth-required")));
204                         }
205                 }
206                 try {
207                         JsonReturnObject jsonObject = createJsonObject(request);
208                         return response.setStatusCode(200).setStatusText("OK").setContentType("application/json").write(objectMapper.writeValueAsString(jsonObject));
209                 } catch (Exception e1) {
210                         logger.log(Level.WARNING, "Error executing JSON page!", e1);
211                         return response.setStatusCode(500).setStatusText(e1.getMessage()).setContentType("text/plain").write(dumpStackTrace(e1));
212                 }
213         }
214
215         /**
216          * {@inheritDoc}
217          */
218         @Override
219         public boolean isLinkExcepted(URI link) {
220                 return false;
221         }
222
223         //
224         // PRIVATE METHODS
225         //
226
227         /**
228          * Returns a byte array containing the stack trace of the given throwable.
229          *
230          * @param t
231          *            The throwable whose stack trace to dump into an array
232          * @return The array with the stack trace, or an empty array if the stack
233          *         trace could not be dumped
234          */
235         private static byte[] dumpStackTrace(Throwable t) {
236                 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
237                 OutputStreamWriter writer = null;
238                 PrintWriter printWriter = null;
239                 try {
240                         writer = new OutputStreamWriter(byteArrayOutputStream, "uTF-8");
241                         printWriter = new PrintWriter(writer);
242                         t.printStackTrace(printWriter);
243                         byteArrayOutputStream.flush();
244                         return byteArrayOutputStream.toByteArray();
245                 } catch (IOException ioe1) {
246                         /* quite not possible. */
247                         return new byte[0];
248                 } finally {
249                         Closer.close(printWriter);
250                         Closer.close(writer);
251                         Closer.close(byteArrayOutputStream);
252                 }
253         }
254
255 }