-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathResponse.java
More file actions
68 lines (52 loc) · 1.87 KB
/
Response.java
File metadata and controls
68 lines (52 loc) · 1.87 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
package core;
import java.util.stream.Collectors;
import static core.HttpRequestRegEx.CRLF;
import static util.Helper.getServerTime;
import static util.StringUtils.addPostfix;
import static util.StringUtils.defaultString;
public class Response extends HttpMessage {
public Response() {
httpVersion = "HTTP/1.1";
}
public Response(Request request) {
this();
if (request.httpVersion != null)
httpVersion = request.httpVersion;
requestMethod = request.requestMethod;
if (request.responseStatusCode != null) {
generateStandardResponse(request.responseStatusCode);
return;
}
}
@Override
public void setBody(String body) {
super.setBody(body);
setHeader("Content-Length", "" + calculateContentLength());
if ("HEAD".equals(requestMethod))
super.setBody(null);
}
public String generateMessage() {
validateResponse();
String headersString = headers.entrySet().stream()
.map((entry) -> entry.getKey() + ": " + entry.getValue())
.collect(Collectors.joining(CRLF));
return httpVersion + " " + responseStatusCode + CRLF +
addPostfix(headersString, CRLF) +
CRLF +
defaultString(body);
}
public void generateStandardResponse(HttpStatusCode code) {
responseStatusCode = code;
setBody(responseStatusCode.toString());
setHeader("Content-Type", "text/html; charset=" + bodyCharset);
setHeader("Last-modified", getServerTime());
}
public void validateResponse() {
if (responseStatusCode == null)
throw new RuntimeException("Cannot generate a valid HTTP response without status code");
if (httpVersion == null)
throw new RuntimeException("Cannot generate a valid HTTP response without HTTP version");
if (!contentHeadersAreCorrect())
throw new RuntimeException("Content-* headers are not allowed without body in response to non-HEAD requests");
}
}