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
28 import javax.servlet.Filter;
29 import javax.servlet.FilterChain;
30 import javax.servlet.FilterConfig;
31 import javax.servlet.ServletContext;
32 import javax.servlet.ServletException;
33 import javax.servlet.ServletRequest;
34 import javax.servlet.ServletResponse;
35 import javax.servlet.http.HttpServletRequest;
36 import javax.servlet.http.HttpServletResponse;
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
68 public class TryFilesFilter implements Filter
69 {
70 public static final String FILES_INIT_PARAM = "files";
71
72 private String[] files;
73
74 @Override
75 public void init(FilterConfig config) throws ServletException
76 {
77 String param = config.getInitParameter(FILES_INIT_PARAM);
78 if (param == null)
79 throw new ServletException(String.format("Missing mandatory parameter '%s'", FILES_INIT_PARAM));
80 files = param.split(" ");
81 }
82
83 @Override
84 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
85 {
86 HttpServletRequest httpRequest = (HttpServletRequest)request;
87 HttpServletResponse httpResponse = (HttpServletResponse)response;
88
89 for (int i = 0; i < files.length - 1; ++i)
90 {
91 String file = files[i];
92 String resolved = resolve(httpRequest, file);
93
94 URL url = request.getServletContext().getResource(resolved);
95 if (url == null)
96 continue;
97
98 if (Files.isReadable(toPath(url)))
99 {
100 chain.doFilter(httpRequest, httpResponse);
101 return;
102 }
103 }
104
105
106 fallback(httpRequest, httpResponse, chain, files[files.length - 1]);
107 }
108
109 private Path toPath(URL url) throws IOException
110 {
111 try
112 {
113 return Paths.get(url.toURI());
114 }
115 catch (URISyntaxException x)
116 {
117 throw new IOException(x);
118 }
119 }
120
121 protected void fallback(HttpServletRequest request, HttpServletResponse response, FilterChain chain, String fallback) throws IOException, ServletException
122 {
123 String resolved = resolve(request, fallback);
124 request.getServletContext().getRequestDispatcher(resolved).forward(request, response);
125 }
126
127 private String resolve(HttpServletRequest request, String value)
128 {
129 String path = request.getServletPath();
130 String info = request.getPathInfo();
131 if (info != null)
132 path += info;
133 if (!path.startsWith("/"))
134 path = "/" + path;
135 return value.replaceAll("\\$path", path);
136 }
137
138 @Override
139 public void destroy()
140 {
141 }
142 }