Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Identify Files Not Requested
package com.fileNotRequested;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FilesListServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Files Not Requested</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Files Not Requested</h1>");
out.println("</ul>");
for (String file : FilesNotRequestedFilter.FILES) {
out.println("<li>" + file + "</li>");
}
out.println("</ul>");
out.println("</body>");
out.println("</html>");
}
}
}
package com.fileNotRequested;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.HashSet;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
public class FilesNotRequestedFilter implements Filter {
public static final HashSet<String> FILES = new HashSet<>();
private static final String FOLDER = "/";
private static final String URI = "/FilesNotRequested/";
private static boolean ERROR = false;
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if (FILES.isEmpty()) {
populateFileList(request);
}
if (request instanceof HttpServletRequest) {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String fileUrl = httpRequest.getRequestURI().substring(URI.length());
FILES.remove("/" + fileUrl);
}
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
private static void populateFileList(ServletRequest request) {
if (ERROR) {
return;
}
try {
URL resource = request.getServletContext().getResource(FOLDER);
File rootFile = new File(resource.toURI());
populateFileList(rootFile, rootFile);
} catch (Exception ex) {
ERROR = true;
}
}
private static void populateFileList(File folder, File root) {
File[] list = folder.listFiles();
if (list == null) {
return;
}
for (File f : list) {
if (f.isDirectory()) {
populateFileList(f, root);
} else {
FILES.add(f.getAbsolutePath().substring(root.getAbsolutePath().length()));
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.