Here is the safe version. You can add several MIME types, depending on which of them are common (or use a different method if your platform has this ).
package de.phihag.miniticker; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.HashMap; import java.util.Map; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; public class StaticFileHandler implements HttpHandler { private static final Map<String,String> MIME_MAP = new HashMap<>(); static { MIME_MAP.put("appcache", "text/cache-manifest"); MIME_MAP.put("css", "text/css"); MIME_MAP.put("gif", "image/gif"); MIME_MAP.put("html", "text/html"); MIME_MAP.put("js", "application/javascript"); MIME_MAP.put("json", "application/json"); MIME_MAP.put("jpg", "image/jpeg"); MIME_MAP.put("jpeg", "image/jpeg"); MIME_MAP.put("mp4", "video/mp4"); MIME_MAP.put("pdf", "application/pdf"); MIME_MAP.put("png", "image/png"); MIME_MAP.put("svg", "image/svg+xml"); MIME_MAP.put("xlsm", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); MIME_MAP.put("xml", "application/xml"); MIME_MAP.put("zip", "application/zip"); MIME_MAP.put("md", "text/plain"); MIME_MAP.put("txt", "text/plain"); MIME_MAP.put("php", "text/plain"); }; private String filesystemRoot; private String urlPrefix; private String directoryIndex; public StaticFileHandler(String urlPrefix, String filesystemRoot, String directoryIndex) { if (!urlPrefix.startsWith("/")) { throw new RuntimeException("pathPrefix does not start with a slash"); } if (!urlPrefix.endsWith("/")) { throw new RuntimeException("pathPrefix does not end with a slash"); } this.urlPrefix = urlPrefix; assert filesystemRoot.endsWith("/"); try { this.filesystemRoot = new File(filesystemRoot).getCanonicalPath(); } catch (IOException e) { throw new RuntimeException(e); } this.directoryIndex = directoryIndex; } public static void create(HttpServer hs, String path, String filesystemRoot, String directoryIndex) { StaticFileHandler sfh = new StaticFileHandler(path, filesystemRoot, directoryIndex); hs.createContext(path, sfh); } public void handle(HttpExchange he) throws IOException { String method = he.getRequestMethod(); if (! ("HEAD".equals(method) || "GET".equals(method))) { sendError(he, 501, "Unsupported HTTP method"); return; } String wholeUrlPath = he.getRequestURI().getPath(); if (wholeUrlPath.endsWith("/")) { wholeUrlPath += directoryIndex; } if (! wholeUrlPath.startsWith(urlPrefix)) { throw new RuntimeException("Path is not in prefix - incorrect routing?"); } String urlPath = wholeUrlPath.substring(urlPrefix.length()); File f = new File(filesystemRoot, urlPath); File canonicalFile; try { canonicalFile = f.getCanonicalFile(); } catch (IOException e) {
phihag
source share