1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.eclipse.jetty.fcgi.server.proxy;
20
21 import java.io.IOException;
22 import java.net.URISyntaxException;
23 import java.net.URL;
24 import java.nio.file.Files;
25 import java.nio.file.Path;
26 import java.nio.file.Paths;
27 import javax.servlet.Filter;
28 import javax.servlet.FilterChain;
29 import javax.servlet.FilterConfig;
30 import javax.servlet.ServletContext;
31 import javax.servlet.ServletException;
32 import javax.servlet.ServletRequest;
33 import javax.servlet.ServletResponse;
34 import javax.servlet.http.HttpServletRequest;
35 import javax.servlet.http.HttpServletResponse;
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67 public class TryFilesFilter implements Filter
68 {
69 public static final String FILES_INIT_PARAM = "files";
70
71 private String[] files;
72
73 @Override
74 public void init(FilterConfig config) throws ServletException
75 {
76 String param = config.getInitParameter(FILES_INIT_PARAM);
77 if (param == null)
78 throw new ServletException(String.format("Missing mandatory parameter '%s'", FILES_INIT_PARAM));
79 files = param.split(" ");
80 }
81
82 @Override
83 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
84 {
85 HttpServletRequest httpRequest = (HttpServletRequest)request;
86 HttpServletResponse httpResponse = (HttpServletResponse)response;
87
88 for (int i = 0; i < files.length - 1; ++i)
89 {
90 String file = files[i];
91 String resolved = resolve(httpRequest, file);
92
93 URL url = request.getServletContext().getResource(resolved);
94 if (url == null)
95 continue;
96
97 if (Files.isReadable(toPath(url)))
98 {
99 chain.doFilter(httpRequest, httpResponse);
100 return;
101 }
102 }
103
104
105 fallback(httpRequest, httpResponse, chain, files[files.length - 1]);
106 }
107
108 private Path toPath(URL url) throws IOException
109 {
110 try
111 {
112 return Paths.get(url.toURI());
113 }
114 catch (URISyntaxException x)
115 {
116 throw new IOException(x);
117 }
118 }
119
120 protected void fallback(HttpServletRequest request, HttpServletResponse response, FilterChain chain, String fallback) throws IOException, ServletException
121 {
122 String resolved = resolve(request, fallback);
123 request.getServletContext().getRequestDispatcher(resolved).forward(request, response);
124 }
125
126 private String resolve(HttpServletRequest request, String value)
127 {
128 String path = request.getServletPath();
129 String info = request.getPathInfo();
130 if (info != null)
131 path += info;
132 if (!path.startsWith("/"))
133 path = "/" + path;
134 return value.replaceAll("\\$path", path);
135 }
136
137 @Override
138 public void destroy()
139 {
140 }
141 }