Add interface between templates and toadlets.
[Sone.git] / src / main / java / net / pterodactylus / sone / web / page / PageToadlet.java
1 /*
2  * shortener - PageToadlet.java - Copyright © 2010 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.page;
19
20 import java.io.IOException;
21 import java.net.URI;
22 import java.util.Map.Entry;
23
24 import freenet.client.HighLevelSimpleClient;
25 import freenet.clients.http.LinkEnabledCallback;
26 import freenet.clients.http.Toadlet;
27 import freenet.clients.http.ToadletContext;
28 import freenet.clients.http.ToadletContextClosedException;
29 import freenet.support.MultiValueTable;
30 import freenet.support.api.Bucket;
31 import freenet.support.api.HTTPRequest;
32 import freenet.support.io.BucketTools;
33 import freenet.support.io.Closer;
34
35 /**
36  * {@link Toadlet} implementation that is wrapped around a {@link Page}.
37  * 
38  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
39  */
40 public class PageToadlet extends Toadlet implements LinkEnabledCallback {
41
42         /** The name of the menu item. */
43         private final String menuName;
44
45         /** The page that handles processing. */
46         private final Page page;
47
48         /** The path prefix for the page. */
49         private final String pathPrefix;
50
51         /**
52          * Creates a new toadlet that hands off processing to a {@link Page}.
53          * 
54          * @param highLevelSimpleClient
55          * @param menuName
56          *            The name of the menu item
57          * @param page
58          *            The page to handle processing
59          * @param pathPrefix
60          *            Prefix that is prepended to all {@link Page#getPath()} return
61          *            values
62          */
63         protected PageToadlet(HighLevelSimpleClient highLevelSimpleClient, String menuName, Page page, String pathPrefix) {
64                 super(highLevelSimpleClient);
65                 this.menuName = menuName;
66                 this.page = page;
67                 this.pathPrefix = pathPrefix;
68         }
69
70         /**
71          * Returns the name to display in the menu.
72          * 
73          * @return The name in the menu
74          */
75         public String getMenuName() {
76                 return menuName;
77         }
78
79         /**
80          * {@inheritDoc}
81          */
82         @Override
83         public String path() {
84                 return pathPrefix + page.getPath();
85         }
86
87         /**
88          * Handles a HTTP GET request.
89          * 
90          * @param uri
91          *            The URI of the request
92          * @param httpRequest
93          *            The HTTP request
94          * @param toadletContext
95          *            The toadlet context
96          * @throws IOException
97          *             if an I/O error occurs
98          * @throws ToadletContextClosedException
99          *             if the toadlet context is closed
100          */
101         public void handleMethodGET(URI uri, HTTPRequest httpRequest, ToadletContext toadletContext) throws IOException, ToadletContextClosedException {
102                 handleRequest(new Page.Request(uri, "GET", httpRequest, toadletContext));
103         }
104
105         /**
106          * Handles a HTTP POST request.
107          * 
108          * @param uri
109          *            The URI of the request
110          * @param httpRequest
111          *            The HTTP request
112          * @param toadletContext
113          *            The toadlet context
114          * @throws IOException
115          *             if an I/O error occurs
116          * @throws ToadletContextClosedException
117          *             if the toadlet context is closed
118          */
119         public void handleMethodPOST(URI uri, HTTPRequest httpRequest, ToadletContext toadletContext) throws IOException, ToadletContextClosedException {
120                 handleRequest(new Page.Request(uri, "POST", httpRequest, toadletContext));
121         }
122
123         /**
124          * {@inheritDoc}
125          */
126         @Override
127         public String toString() {
128                 return getClass().getName() + "[path=" + path() + ",page=" + page + "]";
129         }
130
131         /**
132          * Handles a HTTP request.
133          * 
134          * @param pageRequest
135          *            The request to handle
136          * @throws IOException
137          *             if an I/O error occurs
138          * @throws ToadletContextClosedException
139          *             if the toadlet context is closed
140          */
141         private void handleRequest(Page.Request pageRequest) throws IOException, ToadletContextClosedException {
142                 Bucket data = null;
143                 try {
144                         Page.Response pageResponse = page.handleRequest(pageRequest);
145                         MultiValueTable<String, String> headers = new MultiValueTable<String, String>();
146                         if (pageResponse.getHeaders() != null) {
147                                 for (Entry<String, String> headerEntry : pageResponse.getHeaders().entrySet()) {
148                                         headers.put(headerEntry.getKey(), headerEntry.getValue());
149                                 }
150                         }
151                         data = pageRequest.getToadletContext().getBucketFactory().makeBucket(-1);
152                         if (pageResponse.getContent() != null) {
153                                 try {
154                                         BucketTools.copyFrom(data, pageResponse.getContent(), -1);
155                                 } finally {
156                                         Closer.close(pageResponse.getContent());
157                                 }
158                         } else {
159                                 /* get an OutputStream and close it immediately. */
160                                 Closer.close(data.getOutputStream());
161                         }
162                         writeReply(pageRequest.getToadletContext(), pageResponse.getStatusCode(), pageResponse.getContentType(), pageResponse.getStatusText(), headers, data);
163                 } catch (Throwable t1) {
164                         writeInternalError(t1, pageRequest.getToadletContext());
165                 } finally {
166                         Closer.close(data);
167                 }
168         }
169
170         /**
171          * {@inheritDoc}
172          */
173         @Override
174         public boolean isEnabled(ToadletContext toadletContext) {
175                 return true;
176         }
177
178 }