2 * Sone - ReloadingPage.java - Copyright © 2010–2016 David Roden
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.
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.
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/>.
18 package net.pterodactylus.sone.web;
21 import java.io.FileInputStream;
22 import java.io.FileNotFoundException;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.io.OutputStream;
27 import net.pterodactylus.util.io.Closer;
28 import net.pterodactylus.util.io.StreamCopier;
29 import net.pterodactylus.util.web.Page;
30 import net.pterodactylus.util.web.Request;
31 import net.pterodactylus.util.web.Response;
34 * {@link Page} implementation that delivers static files from the filesystem.
37 * The type of the request
38 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
40 public class ReloadingPage<REQ extends Request> implements Page<REQ> {
42 private final String pathPrefix;
43 private final String filesystemPath;
44 private final String mimeType;
46 public ReloadingPage(String pathPrefix, String filesystemPathPrefix, String mimeType) {
47 this.pathPrefix = pathPrefix;
48 this.filesystemPath = filesystemPathPrefix;
49 this.mimeType = mimeType;
56 public String getPath() {
64 public boolean isPrefixPage() {
72 public Response handleRequest(REQ request, Response response) throws IOException {
73 String path = request.getUri().getPath();
74 int lastSlash = path.lastIndexOf('/');
75 String filename = path.substring(lastSlash + 1);
76 InputStream fileInputStream;
78 fileInputStream = new FileInputStream(new File(filesystemPath, filename));
79 } catch (FileNotFoundException fnfe1) {
80 return response.setStatusCode(404).setStatusText("Not found.");
82 OutputStream contentOutputStream = response.getContent();
84 StreamCopier.copy(fileInputStream, contentOutputStream);
86 Closer.close(fileInputStream);
87 Closer.close(contentOutputStream);
89 return response.setStatusCode(200).setStatusText("OK").setContentType(mimeType);