001package jmri.web.servlet.directory; 002 003import java.io.IOException; 004import java.nio.charset.StandardCharsets; 005import javax.servlet.http.HttpServletRequest; 006import javax.servlet.http.HttpServletResponse; 007import jmri.web.servlet.ServletUtil; 008import org.eclipse.jetty.server.ResourceService; 009import org.eclipse.jetty.util.resource.Resource; 010import org.slf4j.Logger; 011import org.slf4j.LoggerFactory; 012 013/** 014 * Service that returns a directory listing that matches the JMRI web site 015 * theme. 016 * 017 * @author Randall Wood Copyright 2016, 2017 018 */ 019public class DirectoryService extends ResourceService { 020 021 private static final Logger log = LoggerFactory.getLogger(DirectoryService.class); 022 023 @Override 024 protected void notFound(HttpServletRequest request, HttpServletResponse response) throws IOException { 025 // do nothing so this request gets passed on 026 } 027 028 @Override 029 protected void sendDirectory(HttpServletRequest request, HttpServletResponse response, Resource resource, String pathInContext) throws IOException { 030 if (this.isDirAllowed()) { 031 log.debug("Sending !! {} for {} in context {}", request.getRequestURI(), resource.getName(), pathInContext); 032 response.setStatus(HttpServletResponse.SC_OK); 033 response.setContentType(ServletUtil.UTF8_TEXT_HTML); 034 035 try (DirectoryResource r = new DirectoryResource(request.getLocale(), resource)) { 036 String dir = r.getListHTML(request.getRequestURI(), 037 request.getPathInfo().lastIndexOf('/') > 0, 038 request.getRequestURI()); 039 byte[] data = dir.getBytes(StandardCharsets.UTF_8); 040 response.setContentLength(data.length); 041 response.getOutputStream().write(data); 042 } 043 044 } else { 045 response.sendError(HttpServletResponse.SC_FORBIDDEN); 046 } 047 } 048}