1 package net.technearts.rip;
2
3 import java.io.BufferedReader;
4 import java.io.IOException;
5 import java.io.StringReader;
6 import java.net.MalformedURLException;
7 import java.net.URL;
8 import java.util.HashMap;
9
10 import org.eclipse.jetty.http.HttpMethod;
11
12
13
14
15 public class HttpRequestParser {
16 private String reqLine;
17 private final HashMap<String, String> reqHeaders;
18 private final StringBuilder msgBody;
19
20 public HttpRequestParser() {
21 reqHeaders = new HashMap<>();
22 msgBody = new StringBuilder();
23 }
24
25 private void appendHeaderParameter(final String header)
26 throws HttpFormatException {
27 final int idx = header.indexOf(':');
28 if (idx == -1) {
29 throw new HttpFormatException("Invalid Header Parameter: " + header);
30 }
31 reqHeaders.put(header.substring(0, idx),
32 header.substring(idx + 1, header.length()));
33 }
34
35 private void appendMessageBody(final String bodyLine) {
36 msgBody.append(bodyLine).append("\r\n");
37 }
38
39
40
41
42
43
44
45 public String getHeaderParam(final String headerName) {
46 return reqHeaders.get(headerName);
47 }
48
49
50
51
52
53
54
55 public String getMessageBody() {
56 return msgBody.toString();
57 }
58
59
60
61
62
63
64 public HttpMethod getMethod() {
65 final HttpMethod method = HttpMethod
66 .fromString(getRequestLine().split(" ")[0]);
67 if (method == null) {
68 throw new IllegalArgumentException();
69 }
70 return method;
71 }
72
73
74
75
76
77
78
79 public String getRequestLine() {
80 return reqLine;
81 }
82
83
84
85
86
87
88 public URL getUrl() {
89 final String protocol = "HTTP";
90 final String host = getHeaderParam("Host");
91 final int port = 80;
92 final String file = getRequestLine().split(" ")[1];
93 try {
94 return new URL(protocol, host, port, file);
95 } catch (final MalformedURLException ex) {
96 throw new IllegalArgumentException();
97 }
98 }
99
100
101
102
103
104
105
106
107 public void parseRequest(final BufferedReader reader)
108 throws IOException, HttpFormatException {
109 setRequestLine(reader.readLine());
110 String header = reader.readLine();
111 while (header != null && header.length() > 0) {
112 appendHeaderParameter(header);
113 header = reader.readLine();
114 }
115 String bodyLine = reader.readLine();
116 while (bodyLine != null) {
117 appendMessageBody(bodyLine);
118 bodyLine = reader.readLine();
119 }
120 }
121
122
123
124
125
126
127
128
129 public void parseRequest(final String request)
130 throws IOException, HttpFormatException {
131 parseRequest(new BufferedReader(new StringReader(request)));
132 }
133
134 private void setRequestLine(final String requestLine)
135 throws HttpFormatException {
136 if (requestLine == null || requestLine.length() == 0) {
137 throw new HttpFormatException("Invalid Request-Line: " + requestLine);
138 }
139 reqLine = requestLine;
140 }
141 }