Skip to content

Commit

Permalink
refactor: 상수 추출
Browse files Browse the repository at this point in the history
  • Loading branch information
hanueleee committed Sep 4, 2023
1 parent e7e3769 commit 258c1b6
Show file tree
Hide file tree
Showing 10 changed files with 74 additions and 35 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
import java.util.stream.Collectors;

public class HttpHeaders {
public static final String DELIMITER = ": ";
public static final String COOKIE = "Cookie";
private Map<String, String> headers;

public HttpHeaders() {
Expand All @@ -19,7 +21,7 @@ private HttpHeaders(final Map<String, String> headers) {
public static HttpHeaders create(final List<String> lines) {
Map<String, String> headers = new LinkedHashMap<>();
for (String line : lines) {
String[] split = line.split(": ");
String[] split = line.split(DELIMITER);
headers.put(split[0], split[1]);
}

Expand All @@ -31,22 +33,22 @@ public static HttpHeaders create(final Map<String, String> headers) {
}

public void addHeader(HttpHeaderName header, String value) {
headers.put(header.getName(), value); // map의 key로 string? httpheader?
headers.put(header.getName(), value);
}

public String getHeader(String name) {
return headers.get(name);
}

public Cookies getCookies() {
String cookieLine = headers.get("Cookie");
String cookieLine = headers.get(COOKIE);
return Cookies.create(cookieLine);
}

@Override
public String toString() {
return headers.entrySet().stream()
.map(entry -> entry.getKey() + ": " + entry.getValue() + " ")
.map(entry -> entry.getKey() + DELIMITER + entry.getValue() + " ")
.collect(Collectors.joining(System.lineSeparator()));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,16 @@
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.apache.coyote.http11.common.HttpHeaderName;
import org.apache.coyote.http11.common.HttpHeaders;
import org.apache.coyote.http11.common.MessageBody;
import org.apache.coyote.http11.common.Session;
import org.apache.coyote.http11.common.SessionManger;

public class HttpRequest {

public static final String SESSIONID = "JSESSIONID";

private final StartLine startLine;
private final HttpHeaders headers;
private final MessageBody body;
Expand Down Expand Up @@ -46,7 +50,7 @@ private static HttpHeaders findHeaders(BufferedReader br) throws IOException {
}

private static MessageBody findBody(HttpHeaders headers, BufferedReader br) throws IOException {
final String contentLength = headers.getHeader("Content-Length");
final String contentLength = headers.getHeader(HttpHeaderName.CONTENT_LENGTH.getName());
if (contentLength == null) {
return MessageBody.empty();
}
Expand All @@ -71,7 +75,7 @@ public MessageBody getBody() {
public Session getSession() {
Session session = null;
try {
String sessionId = headers.getCookies().getCookie("JSESSIONID");
String sessionId = headers.getCookies().getCookie(SESSIONID);
session = sessionManger.findSession(sessionId);
} catch (Exception e) {
return makeNewSession();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,18 @@

public class QueryParams {

public static final String START_MARK_OF_QUERY_PARAMS = "?";
public static final int HAS_NO_QUERY_PARAMS = -1;

private final Map<String, String> params;

public QueryParams(final Map<String, String> params) {
this.params = params;
}

public static QueryParams create(String line) {
int questionMarkIdx = line.indexOf("?");
if (questionMarkIdx == -1) {
int questionMarkIdx = line.indexOf(START_MARK_OF_QUERY_PARAMS);
if (questionMarkIdx == HAS_NO_QUERY_PARAMS) {
return QueryParams.empty();
}
String paramLine = line.substring(questionMarkIdx + 1);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,24 +1,30 @@
package org.apache.coyote.http11.common.request;

public class RequestUri {

public static final int START_OF_LINE = 0;
public static final String START_MARK_OF_QUERY_PARAMS = "?";
public static final int HAS_NO_QUERY_PARAMS = -1;
public static final String START_MARK_OF_EXTENSION = ".";
public static final int HAS_NO_EXTENSION = -1;

private final String detail;

private RequestUri(final String detail) {
this.detail = detail;
}

public static RequestUri create(String line) {
int idx = line.indexOf("?");
if (idx == -1) {
int idx = line.indexOf(START_MARK_OF_QUERY_PARAMS);
if (idx == HAS_NO_QUERY_PARAMS) {
return new RequestUri(line);
}

return new RequestUri(line.substring(0, idx));
return new RequestUri(line.substring(START_OF_LINE, idx));
}

public String getExtension() {
int idx = detail.indexOf(".");
if (idx == -1) {
int idx = detail.indexOf(START_MARK_OF_EXTENSION);
if (idx == HAS_NO_EXTENSION) {
return "";
}
return detail.substring(idx);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@
import org.apache.coyote.http11.common.HttpVersion;

public class StartLine {
public static final String DELIMITER = " ";
public static final int METHOD_IDX = 0;
public static final int URI_IDX = 1;
public static final int VERSION_IDX = 2;
private final HttpMethod method;
private final RequestUri uri;
private final QueryParams params;
Expand All @@ -17,15 +21,15 @@ private StartLine(final HttpMethod method, final RequestUri uri, final QueryPara
}

public static StartLine create(final String line) {
String[] targets = line.split(" ");
String[] targets = line.split(DELIMITER);

HttpMethod method = HttpMethod.valueOf(targets[0]);
HttpMethod method = HttpMethod.valueOf(targets[METHOD_IDX]);

String uriWithParams = targets[1];
String uriWithParams = targets[URI_IDX];
RequestUri uri = RequestUri.create(uriWithParams);
QueryParams params = QueryParams.create(uriWithParams);

HttpVersion httpVersion = HttpVersion.fromDetail(targets[2]);
HttpVersion httpVersion = HttpVersion.fromDetail(targets[VERSION_IDX]);

return new StartLine(method, uri, params, httpVersion);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,11 @@

public class HelloWorldHandler implements Handler {

public static final String HELLO_WORLD = "Hello world!";

@Override
public HttpResponse handle(final HttpRequest request) {
String body = "Hello world!";
String body = HELLO_WORLD;

HttpHeaders headers = new HttpHeaders();
headers.addHeader(HttpHeaderName.CONTENT_TYPE, ContentType.TEXT_PLAIN.getDetail());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,25 +20,31 @@
public class LoginHandler implements Handler {

private static final Logger log = LoggerFactory.getLogger(LoginHandler.class);
public static final String ACCOUNT = "account";
public static final String PASSWORD = "password";
public static final String USER = "user";
public static final String INDEX_PAGE = "/index.html";
public static final String LOGIN_PAGE = "/login.html";
public static final String LOGIN_FAIL_PAGE = "/401.html";

@Override
public HttpResponse handle(final HttpRequest request) throws IOException {
if (request.getMethod() == HttpMethod.GET) {
if (isLoggedIn(request)) {
HttpHeaders headers = new HttpHeaders();
headers.addHeader(HttpHeaderName.LOCATION, "/index.html");
headers.addHeader(HttpHeaderName.LOCATION, INDEX_PAGE);
return HttpResponse.create(StatusCode.FOUND, headers);
}
String content = StaticFileLoader.load("/login.html");
String content = StaticFileLoader.load(LOGIN_PAGE);
HttpHeaders headers = new HttpHeaders();
headers.addHeader(HttpHeaderName.CONTENT_TYPE, ContentType.TEXT_HTML.getDetail());
headers.addHeader(HttpHeaderName.CONTENT_LENGTH, String.valueOf(content.getBytes().length));
return HttpResponse.create(StatusCode.OK, headers, content);
}
if (request.getMethod() == HttpMethod.POST) {
QueryParams params = Parser.parseToQueryParams(request.getBody().getContent());
String account = params.getParam("account");
String password = params.getParam("password");
String account = params.getParam(ACCOUNT);
String password = params.getParam(PASSWORD);

return InMemoryUserRepository.findByAccount(account)
.filter(user -> user.checkPassword(password))
Expand All @@ -49,7 +55,7 @@ public HttpResponse handle(final HttpRequest request) throws IOException {
}

private boolean isLoggedIn(HttpRequest request) {
Object value = request.getSession().getAttribute("user"); // TODO : 세션 새로만들었을 경우..?
Object value = request.getSession().getAttribute(USER); // TODO : 세션 새로만들었을 경우..?
if (value == null) {
return false;
}
Expand All @@ -62,17 +68,17 @@ private boolean isLoggedIn(HttpRequest request) {
private HttpResponse loginSuccess(HttpRequest request, User user) {
log.info("로그인 성공 : {}", user);
Session session = request.getSession();
session.setAttribute("user", user);
session.setAttribute(USER, user);

HttpHeaders headers = new HttpHeaders();
headers.addHeader(HttpHeaderName.LOCATION, "/index.html");
headers.addHeader(HttpHeaderName.LOCATION, INDEX_PAGE);
headers.addHeader(HttpHeaderName.SET_COOKIE, "JSESSIONID=" + session.getId());
return HttpResponse.create(StatusCode.FOUND, headers);
}

private HttpResponse loginFail() {
HttpHeaders headers = new HttpHeaders();
headers.addHeader(HttpHeaderName.LOCATION, "/401.html");
headers.addHeader(HttpHeaderName.LOCATION, LOGIN_FAIL_PAGE);
return HttpResponse.create(StatusCode.FOUND, headers);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,16 @@

public class RegisterHandler implements Handler {

public static final String REGISTER_PAGE = "/register.html";
public static final String ACCOUNT = "account";
public static final String PASSWORD = "password";
public static final String EMAIL = "email";
public static final String INDEX_PAGE = "/index.html";

@Override
public HttpResponse handle(final HttpRequest request) throws IOException {
if (request.getMethod() == HttpMethod.GET) {
String content = StaticFileLoader.load("/register.html");
String content = StaticFileLoader.load(REGISTER_PAGE);

HttpHeaders headers = new HttpHeaders();
headers.addHeader(HttpHeaderName.CONTENT_TYPE, ContentType.TEXT_HTML.getDetail());
Expand All @@ -29,11 +35,11 @@ public HttpResponse handle(final HttpRequest request) throws IOException {
if (request.getMethod() == HttpMethod.POST) {
QueryParams params = Parser.parseToQueryParams(request.getBody().getContent());

User user = new User(params.getParam("account"), params.getParam("password"), params.getParam("email"));
User user = new User(params.getParam(ACCOUNT), params.getParam(PASSWORD), params.getParam(EMAIL));
InMemoryUserRepository.save(user);

HttpHeaders headers = new HttpHeaders();
headers.addHeader(HttpHeaderName.LOCATION, "/index.html");
headers.addHeader(HttpHeaderName.LOCATION, INDEX_PAGE);
return HttpResponse.create(StatusCode.FOUND, headers);
}
return null;
Expand Down
12 changes: 8 additions & 4 deletions tomcat/src/main/java/org/apache/coyote/http11/util/Parser.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,22 @@

public class Parser {

public static final String QUERY_PARAM_REGEX = "&";
public static final String DELIMITER = "=";
public static final String COOKIE_REGEX = "; ";

private Parser() {
}

public static QueryParams parseToQueryParams(String line) {
if (line == null) {
return QueryParams.empty();
}
String[] split = line.split("&");
String[] split = line.split(QUERY_PARAM_REGEX);

Map<String, String> params = new HashMap<>();
for (String piece : split) {
int idx = piece.indexOf("=");
int idx = piece.indexOf(DELIMITER);
params.put(piece.substring(0, idx), piece.substring(idx + 1));
}

Expand All @@ -30,11 +34,11 @@ public static Cookies parseToCookie(String line) {
if (line == null) {
return Cookies.empty();
}
String[] split = line.split("; ");
String[] split = line.split(COOKIE_REGEX);

Map<String, String> cookies = new LinkedHashMap<>();
for (String piece : split) {
int idx = piece.indexOf("=");
int idx = piece.indexOf(DELIMITER);
cookies.put(piece.substring(0, idx), piece.substring(idx + 1));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@

public class StaticFileLoader {

public static final String STATIC = "static";

public static String load(String fileName) throws IOException {
URL resource = StaticFileLoader.class.getClassLoader().getResource("static" + fileName);
URL resource = StaticFileLoader.class.getClassLoader().getResource(STATIC + fileName);
Path path = new File(resource.getPath()).toPath();
return new String(Files.readAllBytes(path));
}
Expand Down

0 comments on commit 258c1b6

Please sign in to comment.