Skip to content

Commit 4abd423

Browse files
committed
Refactor the exact handling of the String to Method enum
1 parent 5665135 commit 4abd423

File tree

2 files changed

+14
-5
lines changed

2 files changed

+14
-5
lines changed

src/main/java/httpserver/request/RequestParser.java

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,15 @@ public RequestParser(AppConfig appConfig) {
1818
this.contentLength = 0;
1919
}
2020

21-
public Request parse(InputStream inputStream) throws IOException {
21+
public Request parse(InputStream inputStream)
22+
throws IOException, IllegalArgumentException {
2223
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
2324

2425
RequestLine requestLine = getRequestLine(bufferedReader);
2526

27+
Method method;
2628
try {
27-
Method.valueOf(requestLine.getMethod());
29+
method = requestLine.getMethod();
2830
} catch (IllegalArgumentException e) {
2931
throw new IllegalArgumentException();
3032
}
@@ -33,7 +35,7 @@ public Request parse(InputStream inputStream) throws IOException {
3335

3436
String body = getBody(bufferedReader);
3537

36-
return new Request(Method.valueOf(requestLine.getMethod()),
38+
return new Request(method,
3739
requestLine.getPath(),
3840
headers,
3941
requestLine.getQueryString(),
@@ -51,8 +53,8 @@ private class RequestLine {
5153
private final String path;
5254
private final String queryString;
5355

54-
private String getMethod() {
55-
return method;
56+
private Method getMethod() throws IllegalArgumentException {
57+
return Method.valueOf(method);
5658
}
5759

5860
private String getPath() {

src/test/java/httpserver/request/RequestParserTest.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,4 +79,11 @@ public void callsLogOnLogger() throws Exception {
7979
verify(loggerMock).log("GET /text-file?key1=value1%3C%2C%3F&key2=value2 HTTP/1.1");
8080
}
8181

82+
@Test(expected = IllegalArgumentException.class)
83+
public void throwsIllegalArgumentExceptionWhenBadMethod() throws Exception {
84+
String input = "ABCXYZ /text-file HTTP/1.1\r\n" +
85+
"Host: 0.0.0.0:5000\r\n\r\n";
86+
InputStream inputStream = new ByteArrayInputStream(input.getBytes());
87+
requestParser.parse(inputStream);
88+
}
8289
}

0 commit comments

Comments
 (0)