/
HttpUtils.java
388 lines (304 loc) · 10.6 KB
/
HttpUtils.java
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
package org.rapidoid.http;
import org.rapidoid.RapidoidThing;
import org.rapidoid.annotation.Authors;
import org.rapidoid.annotation.Since;
import org.rapidoid.bytes.Bytes;
import org.rapidoid.bytes.BytesUtil;
import org.rapidoid.commons.Str;
import org.rapidoid.config.BasicConfig;
import org.rapidoid.config.Conf;
import org.rapidoid.ctx.Ctxs;
import org.rapidoid.ctx.UserInfo;
import org.rapidoid.data.BufRanges;
import org.rapidoid.gui.reqinfo.ReqInfo;
import org.rapidoid.http.customize.Customization;
import org.rapidoid.http.customize.MediaResponseRenderer;
import org.rapidoid.http.impl.MaybeReq;
import org.rapidoid.io.Res;
import org.rapidoid.lambda.Mapper;
import org.rapidoid.u.U;
import org.rapidoid.util.*;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.Serializable;
import java.util.Map;
import java.util.regex.Pattern;
/*
* #%L
* rapidoid-http-fast
* %%
* Copyright (C) 2014 - 2017 Nikolche Mihajlovski and contributors
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
@Authors("Nikolche Mihajlovski")
@Since("5.0.0")
public class HttpUtils extends RapidoidThing implements HttpMetadata {
private static final MediaType DEFAULT_CONTENT_TYPE = MscOpts.hasRapidoidHTML() ? MediaType.HTML_UTF_8 : MediaType.JSON;
private static final String PAGE_RELOAD = "<h2> Reloading...</h2><script>location.reload();</script>";
private static final byte[] EMPTY_RESPONSE = {};
private static final MaybeReq NO_REQ = new MaybeReq() {
@Override
public Req getReqOrNull() {
return null;
}
};
private static volatile Pattern REGEX_VALID_HTTP_RESOURCE = Pattern.compile("(?U)(?:/[ \\w\\-\\.]+)*/?");
private static final Mapper<String[], String> PATH_PARAM_EXTRACTOR = new Mapper<String[], String>() {
@Override
public String map(String[] src) throws Exception {
return src[1].split(":", 2)[0];
}
};
public static Map<String, Serializable> initAndDeserializeToken(Req req) {
String token = req.cookie(TOKEN, null);
if (U.isEmpty(token)) {
token = req.data(TOKEN, null);
}
return Tokens.deserialize(token);
}
public static void saveTokenBeforeRenderingHeaders(Req req, Map<String, Serializable> tokenData) {
String token = Tokens.serialize(tokenData);
setResponseTokenCookie(req.response(), token);
}
public static boolean isGetReq(Req req) {
return req.verb().equals(GET);
}
public static boolean isPostReq(Req req) {
return req.verb().equals(POST);
}
public static String resName(Req req) {
String resName = resName(req.path());
U.notNull(resName, "resource name");
return resName;
}
public static String resName(String path) {
if (U.notEmpty(path) && REGEX_VALID_HTTP_RESOURCE.matcher(path).matches() && !path.contains("..")) {
String res = Str.triml(path, "/");
return res.isEmpty() ? "index" : Str.trimr(res, ".html");
} else {
throw U.rte("Invalid path!");
}
}
public static String viewName(Req req) {
//return req.route() != null ? inferViewNameFromRoutePath(req.route().path()) : resName(req.path());
return resName(req.path());
}
public static boolean hasExtension(String name) {
int pos = name.lastIndexOf('.');
return pos > 0 && pos < name.length() - 1;
}
public static void setContentTypeForFile(Resp resp, File file) {
U.must(file.exists());
setContentType(resp, MediaType.getByFileName(file.getAbsolutePath()));
}
public static void setContentTypeForResource(Resp resp, Res resource) {
U.must(resource.exists());
setContentType(resp, MediaType.getByFileName(resource.getName()));
}
public static void setContentType(Resp resp, MediaType mediaType) {
resp.contentType(mediaType);
}
public static Res staticResource(Req req, String... possibleLocations) {
String resName = resName(req);
if (resName == null) return null;
if (hasExtension(resName)) {
return Res.from(resName, possibleLocations);
} else {
Res res = Res.from(resName, possibleLocations);
if (!res.exists()) {
res = Res.from(resName + ".html", possibleLocations);
}
return res;
}
}
public static String getErrorMessageAndSetCode(Resp resp, Throwable err) {
ErrCodeAndMsg codeAndMsg = Msc.getErrorCodeAndMsg(err);
resp.code(codeAndMsg.code());
return codeAndMsg.msg();
}
public static Map<String, ?> getErrorInfo(Resp resp, Throwable error) {
String errorMessage = getErrorMessageAndSetCode(resp, error);
return U.map("error", errorMessage, "code", resp.code(), "status", HttpResponseCodes.status(resp.code()));
}
public static void postProcessResponse(Resp resp) {
postProcessRedirect(resp);
postProcessFile(resp);
postProcessFilename(resp);
}
private static void postProcessFile(Resp resp) {
File file = resp.file();
if (file != null) {
U.must(file.exists());
if (resp.filename() == null) {
resp.filename();
}
setContentTypeForFile(resp, file);
resp.result(Res.from(file).getBytes());
}
}
private static void postProcessFilename(Resp resp) {
String filename = resp.filename();
if (filename != null) {
resp.headers().put(HttpHeaders.CONTENT_DISPOSITION.name(), "attachment; filename=\"" + filename + "\"");
resp.headers().put(HttpHeaders.CACHE_CONTROL.name(), "private");
}
}
private static void postProcessRedirect(Resp resp) {
String redirect = resp.redirect();
if (redirect != null) {
if (resp.code() < 300 || resp.code() >= 400) {
resp.code(303);
}
resp.headers().put(HttpHeaders.LOCATION.name(), redirect);
if (resp.result() == null && resp.body() == null) {
resp.body(EMPTY_RESPONSE);
}
}
}
public static void reload(Req x) {
Map<String, String> sel = U.map("body", PAGE_RELOAD);
x.response().json(U.map("_sel_", sel));
}
public static String constructUrl(Req x, String path) {
return (Conf.ROOT.is("https") ? "https://" : "http://") + x.host() + path;
}
public static byte[] responseToBytes(Req req, Object result, MediaType contentType, MediaResponseRenderer responseRenderer) {
if (U.eq(contentType, MediaType.JSON) || U.eq(contentType, MediaType.XML_UTF_8)) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
responseRenderer.render(req, result, out);
} catch (Exception e) {
throw U.rte(e);
}
return out.toByteArray();
} else {
return Msc.toBytes(result);
}
}
public static void resultToResponse(Req req, Object result) {
if (result instanceof Req) {
if (req != result) {
req.response().result("Unknown request instance was received as result!");
}
} else if (result instanceof Resp) {
if (req.response() != result) {
req.response().result("Unknown response instance was received as result!");
}
} else if (!(result instanceof HttpStatus)) {
req.response().result(result);
}
}
public static String getContextPath(Req req) {
return zone(req).entry("contextPath").or("");
}
public static BasicConfig zone(Customization custom, String zone) {
BasicConfig defaultConfig = custom.config().sub("gui").or(custom.config().sub("app"));
if (zone != null) {
String zoneKey = zone + "-zone";
return custom.config().sub(zoneKey).or(defaultConfig);
} else {
return defaultConfig;
}
}
public static BasicConfig zone(Req req) {
Customization custom = Customization.of(req);
return zone(custom, req.zone());
}
public static void setResponseTokenCookie(Resp resp, String token) {
resp.cookie(TOKEN, token, "HttpOnly");
}
public static String cookiePath() {
String ctxPath = ReqInfo.get().contextPath();
return U.notEmpty(ctxPath) ? ctxPath : "/";
}
public static void clearUserData(Req req) {
if (Ctxs.hasContext()) {
Ctxs.required().setUser(UserInfo.ANONYMOUS);
}
if (req.hasToken()) {
Map<String, Serializable> token = req.token();
token.remove(Tokens._USER);
token.remove(Tokens._SCOPE);
}
}
public static TokenAuthData getAuth(Req req) {
TokenAuthData auth = req.hasToken() ? Tokens.getAuth(req.token()) : null;
// check if the route is outside of scope
if (auth != null && U.notEmpty(auth.scope) && !auth.scope.contains(req.verb() + " " + req.path())) auth = null;
return auth;
}
public static String inferRealIpAddress(Req req) {
// // FIXME if CloudFlare is detected, use req.header("cf-connecting-ip")
return req.clientIpAddress();
}
public static MaybeReq noReq() {
return NO_REQ;
}
public static MaybeReq maybe(Req req) {
return req != null ? (MaybeReq) req : noReq();
}
public static MaybeReq req(Req req) {
U.notNull(req, "HTTP request");
return (MaybeReq) req;
}
public static int findBodyStart(byte[] response) {
Bytes bytes = BytesUtil.from(response);
BufRanges lines = new BufRanges(100);
int pos = BytesUtil.parseLines(bytes, lines, 0, bytes.limit());
U.must(pos > 0, "Invalid HTTP response!");
return pos;
}
private static boolean ignoreResponseHeaderInProxy(String name) {
return name.equalsIgnoreCase("Transfer-encoding")
|| name.equalsIgnoreCase("Content-length")
|| name.equalsIgnoreCase("Connection")
|| name.equalsIgnoreCase("Date")
|| name.equalsIgnoreCase("Server");
}
public static void proxyResponseHeaders(Map<String, String> respHeaders, SimpleHttpResp resp) {
for (Map.Entry<String, String> hdr : respHeaders.entrySet()) {
String name = hdr.getKey();
String value = hdr.getValue();
if (name.equalsIgnoreCase("Content-type")) {
resp.contentType = MediaType.of(value);
} else if (name.equalsIgnoreCase("Set-Cookie")) {
String[] parts = value.split("=", 2);
U.must(parts.length == 2, "Invalid value of the Set-Cookie header!");
if (resp.cookies == null) {
resp.cookies = U.map();
}
resp.cookies.put(parts[0], parts[1]);
} else if (!ignoreResponseHeaderInProxy(name)) {
if (resp.headers == null) {
resp.headers = U.map();
}
resp.headers.put(name, value);
}
}
}
public static MediaType getDefaultContentType() {
return DEFAULT_CONTENT_TYPE;
}
public static void validateViewName(String view) {
U.must(!view.startsWith("/"), "Invalid view name: '%s'", view);
}
public static Map<String, WebData> webParams(Req req) {
Map<String, WebData> webParams = U.map();
for (Map.Entry<String, String> e : req.params().entrySet()) {
webParams.put(e.getKey(), new WebData(e.getValue()));
}
return webParams;
}
}