xref: /aosp_15_r20/external/jsoup/src/test/java/org/jsoup/integration/servlets/FileServlet.java (revision 6da8f8c4bc310ad659121b84dd089062417a2ce2)
1 package org.jsoup.integration.servlets;
2 
3 import org.jsoup.integration.ParseTest;
4 import org.jsoup.integration.TestServer;
5 
6 import javax.servlet.ServletOutputStream;
7 import javax.servlet.http.HttpServletRequest;
8 import javax.servlet.http.HttpServletResponse;
9 import java.io.File;
10 import java.io.IOException;
11 import java.nio.file.Files;
12 
13 public class FileServlet extends BaseServlet {
14     public static final String Url;
15     public static final String TlsUrl;
16     static {
17         TestServer.ServletUrls urls = TestServer.map(FileServlet.class);
18         Url = urls.url;
19         TlsUrl = urls.tlsUrl;
20     }
21     public static final String ContentTypeParam = "contentType";
22     public static final String DefaultType = "text/html";
23 
24     @Override
doIt(HttpServletRequest req, HttpServletResponse res)25     protected void doIt(HttpServletRequest req, HttpServletResponse res) throws IOException {
26         String contentType = req.getParameter(ContentTypeParam);
27         if (contentType == null)
28             contentType = DefaultType;
29         String location = req.getPathInfo();
30 
31         File file = ParseTest.getFile(location);
32         if (file.exists()) {
33             res.setContentType(contentType);
34             if (file.getName().endsWith("gz"))
35                 res.addHeader("Content-Encoding", "gzip");
36             res.setStatus(HttpServletResponse.SC_OK);
37 
38             ServletOutputStream out = res.getOutputStream();
39             Files.copy(file.toPath(), out);
40             out.flush();
41         } else {
42             res.sendError(HttpServletResponse.SC_NOT_FOUND);
43         }
44     }
45 
urlTo(String path)46     public static String urlTo(String path) {
47         return Url + path;
48     }
49 
tlsUrlTo(String path)50     public static String tlsUrlTo(String path) {
51         return TlsUrl + path;
52     }
53 }
54