-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimpleProxyServlet.java
More file actions
157 lines (133 loc) · 5.15 KB
/
SimpleProxyServlet.java
File metadata and controls
157 lines (133 loc) · 5.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class SimpleProxyServlet extends HttpServlet {
private static class Mapping {
String type;
String path;
String url;
}
private List<Mapping> mappings;
@Override
public void init() throws ServletException {
mappings = new ArrayList<>();
String baseUrl = getServletConfig().getInitParameter("baseUrl");
for (int i = 1; ; i++) {
String type = getServletConfig().getInitParameter("mapping." + i + ".type");
String path = getServletConfig().getInitParameter("mapping." + i + ".path");
if (type == null || path == null) {
break;
}
Mapping mapping = new Mapping();
mapping.type = type;
mapping.path = path;
if (!"block".equals(type)) {
String url = getServletConfig().getInitParameter("mapping." + i + ".url");
if (url == null) {
throw new ServletException("url init-param not configured for mapping " + i);
}
if (baseUrl != null && url.contains("${baseUrl}")) {
url = url.replace("${baseUrl}", baseUrl);
}
mapping.url = url;
}
mappings.add(mapping);
}
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String requestUri = req.getRequestURI();
String queryString = req.getQueryString();
String fullRequestUrl = requestUri + (queryString != null ? "?" + queryString : "");
String targetUrl = null;
for (Mapping mapping : mappings) {
if ("block".equals(mapping.type) && fullRequestUrl.startsWith(mapping.path)) {
resp.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
} else if ("prefix".equals(mapping.type) && requestUri.startsWith(mapping.path)) {
String restOfThePath = requestUri.substring(mapping.path.length());
targetUrl = mapping.url + restOfThePath + (queryString != null ? "?" + queryString : "");
break;
} else if ("contains".equals(mapping.type) && fullRequestUrl.contains(mapping.path)) {
targetUrl = mapping.url;
if (queryString != null && !targetUrl.contains("?")) {
targetUrl += "?" + queryString;
}
break;
}
}
if (targetUrl == null) {
resp.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
log("Proxying " + req.getMethod() + " request to: " + targetUrl);
URL url = new URL(targetUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod(req.getMethod());
conn.setDoInput(true);
conn.setDoOutput("POST".equalsIgnoreCase(req.getMethod()));
// Forward headers (excluding Content-Length)
Enumeration<String> headerNames = req.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
if (!headerName.equalsIgnoreCase("Content-Length")) {
conn.setRequestProperty(headerName, req.getHeader(headerName));
}
}
// Forward cookies
Cookie[] cookies = req.getCookies();
if (cookies != null) {
StringBuilder cookieHeader = new StringBuilder();
for (Cookie cookie : cookies) {
cookieHeader.append(cookie.getName()).append("=").append(cookie.getValue()).append("; ");
}
conn.setRequestProperty("Cookie", cookieHeader.toString());
}
// Forward POST body
if ("POST".equalsIgnoreCase(req.getMethod())) {
try (InputStream in = req.getInputStream(); OutputStream out = conn.getOutputStream()) {
byte[] buffer = new byte[8192];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.flush();
}
}
int responseCode = conn.getResponseCode();
log("Received response code: " + responseCode);
resp.setStatus(responseCode);
// Forward response headers (excluding Transfer-Encoding)
Map<String, List<String>> responseHeaders = conn.getHeaderFields();
for (Map.Entry<String, List<String>> entry : responseHeaders.entrySet()) {
String headerName = entry.getKey();
if (headerName != null && !headerName.equalsIgnoreCase("Transfer-Encoding")) {
for (String value : entry.getValue()) {
resp.addHeader(headerName, value);
}
}
}
// Forward response body (handle error stream if needed)
InputStream responseStream;
try {
responseStream = conn.getInputStream();
} catch (IOException e) {
responseStream = conn.getErrorStream();
}
if (responseStream != null) {
try (InputStream in = responseStream; OutputStream out = resp.getOutputStream()) {
byte[] buffer = new byte[8192];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.flush();
}
} else {
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "No response stream available");
}
}
}