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.StreamCopier;
28 import net.pterodactylus.util.web.Page;
29 import net.pterodactylus.util.web.Request;
30 import net.pterodactylus.util.web.Response;
33 * {@link Page} implementation that delivers static files from the filesystem.
36 * The type of the request
37 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
39 public class ReloadingPage<REQ extends Request> implements Page<REQ> {
41 private final String pathPrefix;
42 private final String filesystemPath;
43 private final String mimeType;
45 public ReloadingPage(String pathPrefix, String filesystemPathPrefix, String mimeType) {
46 this.pathPrefix = pathPrefix;
47 this.filesystemPath = filesystemPathPrefix;
48 this.mimeType = mimeType;
55 public String getPath() {
63 public boolean isPrefixPage() {
71 public Response handleRequest(REQ request, Response response) throws IOException {
72 String path = request.getUri().getPath();
73 int lastSlash = path.lastIndexOf('/');
74 String filename = path.substring(lastSlash + 1);
75 try (InputStream fileInputStream = new FileInputStream(new File(filesystemPath, filename));
76 OutputStream contentOutputStream = response.getContent()) {
77 StreamCopier.copy(fileInputStream, contentOutputStream);
78 } catch (FileNotFoundException fnfe1) {
79 return response.setStatusCode(404).setStatusText("Not found.");
81 return response.setStatusCode(200).setStatusText("OK").setContentType(mimeType);