Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[톰캣 구현하기 - 1, 2단계] 테오(최우성) 미션 제출합니다. #304

Merged
merged 48 commits into from
Sep 5, 2023
Merged
Show file tree
Hide file tree
Changes from 35 commits
Commits
Show all changes
48 commits
Select commit Hold shift + click to select a range
fc81bb1
feat: URL을 통해 정적 자원들을 찾을 수 있도록 구현
woosung1223 Sep 1, 2023
b50186d
feat: 다양한 파일 확장자에 대해서도 응답하도록 구현
woosung1223 Sep 1, 2023
d34a74c
chore: NPE 방지용 favicon 추가
woosung1223 Sep 1, 2023
5eaf636
feat: 로그인 페이지 구현
woosung1223 Sep 1, 2023
4549643
fix: html content type에 charset 추가
woosung1223 Sep 1, 2023
86ff6e0
refactor: startLine 객체 분리
woosung1223 Sep 1, 2023
9bdfa1a
feat: query parameter 출력 기능 추가
woosung1223 Sep 1, 2023
197db66
refactor: RequestURI 객체 분리
woosung1223 Sep 1, 2023
af36f74
refactor: Request, Response 객체 분리
woosung1223 Sep 2, 2023
354787a
refactor: Handler 객체 분리
woosung1223 Sep 2, 2023
dbd86b6
refactor: 로깅을 담당하는 Filter 객체 분리
woosung1223 Sep 2, 2023
1ecc2a4
feat: 페이지를 다루는 핸들러 추상화
woosung1223 Sep 2, 2023
77c4d44
chore: 패키지 분리
woosung1223 Sep 2, 2023
fa47e27
feat: query parameter가 제대로 인식되지 않던 문제 해결
woosung1223 Sep 2, 2023
91cf904
refactor: 로그인 요청을 POST로 처리하도록 변경
woosung1223 Sep 2, 2023
e230ecf
feat: 회원가입 기능 추가
woosung1223 Sep 2, 2023
79d3bba
chore: 코드 리포맷
woosung1223 Sep 2, 2023
cedf579
chore: 코드 리포맷
woosung1223 Sep 2, 2023
ce09638
refactor: HttpVersion, HttpMethod를 객체로 관리
woosung1223 Sep 2, 2023
fee4b62
chore: 코드 리포맷
woosung1223 Sep 2, 2023
931bc51
refactor: 상태코드도 객체로 관리하도록 변경
woosung1223 Sep 2, 2023
8a36595
refactor: responseBody에서도 header, body 등을 커스텀할 수 있도록 변경
woosung1223 Sep 2, 2023
ec3c487
feat: 로그인 시 세션을 쿠키에 저장할 수 있도록 구현
woosung1223 Sep 2, 2023
570d31b
chore: 패키지 정리
woosung1223 Sep 2, 2023
d3ba02f
feat: 세션 처리 기능 구현
woosung1223 Sep 2, 2023
e78934d
chore: 코드 리포맷
woosung1223 Sep 2, 2023
2a4d660
refactor: SESSION ID를 로깅하도록 변경
woosung1223 Sep 2, 2023
a2cdb91
chore: 메소드 네이밍 수정
woosung1223 Sep 2, 2023
99fa106
fix: Cookie가 없을 때 NPE가 발생하지 않도록 수정
woosung1223 Sep 2, 2023
4a1ff62
refactor: 사용하지 않는 메소드 삭제
woosung1223 Sep 2, 2023
7ca2e99
test: 테스트 보완
woosung1223 Sep 2, 2023
d3e153f
refactor: 메소드 시그니처 수정
woosung1223 Sep 2, 2023
cd6c625
chore: 메소드 순서 조정
woosung1223 Sep 2, 2023
25f7e24
refactor: 메소드 분리
woosung1223 Sep 2, 2023
e384ed9
refactor: Code Smell 제거
woosung1223 Sep 2, 2023
31b7491
refactor: 회원가입 성공 시 Location 헤더를 통해 redirect 하도록 변경
woosung1223 Sep 4, 2023
f282124
refactor: 로그인 성공 혹은 실패 시 Location 헤더를 통해 redirect 하도록 변경
woosung1223 Sep 4, 2023
9f2f149
refactor: Content-Length를 통해 RequestBody를 읽도록 변경
woosung1223 Sep 4, 2023
78db48e
fix: RequestBody 파싱 방법 변경에 따른 테스트 수정
woosung1223 Sep 4, 2023
22d4bc1
chore: 사용하지 않는 메소드 제거
woosung1223 Sep 4, 2023
2fffb5b
refactor: Headers 정적 팩토리 메소드 오버로딩
woosung1223 Sep 4, 2023
a737164
refactor: 확장자 제거 기능은 불필요하므로 삭제, 클래스명 변경
woosung1223 Sep 4, 2023
e57fcf7
chore: 리소스 패키지 상수처리
woosung1223 Sep 4, 2023
8f85878
refactor: status code, reason phrase 분리
woosung1223 Sep 4, 2023
61fb186
refactor: HttpHeaders enum 정의
woosung1223 Sep 4, 2023
1fbeb6d
refactor: `@ParameterizedTest` 적용, 코드 중복 제거
woosung1223 Sep 4, 2023
48a456c
refactor: 파일 경로 enum으로 분리
woosung1223 Sep 4, 2023
1ed0ff3
test: 학습 테스트 추가
woosung1223 Sep 4, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 18 additions & 8 deletions study/src/test/java/study/FileTest.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
package study;

import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.Objects;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

Expand Down Expand Up @@ -27,10 +31,10 @@ class FileTest {
void resource_디렉터리에_있는_파일의_경로를_찾는다() {
final String fileName = "nextstep.txt";

// todo
final String actual = "";
ClassLoader classLoader = getClass().getClassLoader();
URL actual = classLoader.getResource(fileName);

assertThat(actual).endsWith(fileName);
assertThat(actual.getFile()).endsWith(fileName);
}

/**
Expand All @@ -40,15 +44,21 @@ class FileTest {
* File, Files 클래스를 사용하여 파일의 내용을 읽어보자.
*/
@Test
void 파일의_내용을_읽는다() {
void 파일의_내용을_읽는다() throws IOException {
final String fileName = "nextstep.txt";

// todo
final Path path = null;
ClassLoader classLoader = getClass().getClassLoader();
URL url = classLoader.getResource(fileName);
File file = new File(url.getPath());

// todo
final List<String> actual = Collections.emptyList();
BufferedReader reader = new BufferedReader(new FileReader(file));

final List<String> actual = new ArrayList<>();

String line;
while (Objects.nonNull(line = reader.readLine())) {
actual.add(line);
}
assertThat(actual).containsOnly("nextstep");
}
}
3 changes: 2 additions & 1 deletion study/src/test/java/study/IOStreamTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,11 @@ class OutputStream_학습_테스트 {
void OutputStream은_데이터를_바이트로_처리한다() throws IOException {
final byte[] bytes = {110, 101, 120, 116, 115, 116, 101, 112};
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

해당 학습 테스트는 고쳐지지 않은 것 같은데 시간 될 때 해보시면 좋을 거 같아요 ˙ᵕ˙ 👍🐤

final OutputStream outputStream = new ByteArrayOutputStream(bytes.length);

/**
* todo
* OutputStream 객체의 write 메서드를 사용해서 테스트를 통과시킨다
*/
outputStream.write(bytes);

final String actual = outputStream.toString();

Expand All @@ -73,6 +73,7 @@ class OutputStream_학습_테스트 {
void BufferedOutputStream을_사용하면_버퍼링이_가능하다() throws IOException {
final OutputStream outputStream = mock(BufferedOutputStream.class);

outputStream.flush();
/**
* todo
* flush를 사용해서 테스트를 통과시킨다.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package nextstep.jwp.db;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

public class InMemorySessionRepository {

private InMemorySessionRepository() {
}

private static final Map<Long, UUID> sessions = new ConcurrentHashMap<>();

public static UUID save(Long userId) {
UUID uuid = UUID.randomUUID();
sessions.put(userId, uuid);
return uuid;
}
}
31 changes: 21 additions & 10 deletions tomcat/src/main/java/nextstep/jwp/db/InMemoryUserRepository.java
Original file line number Diff line number Diff line change
@@ -1,27 +1,38 @@
package nextstep.jwp.db;

import nextstep.jwp.model.User;

import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import nextstep.jwp.model.User;

public class InMemoryUserRepository {

private static final Map<String, User> database = new ConcurrentHashMap<>();
private static final Map<Long, User> database = new ConcurrentHashMap<>();

private static AtomicLong counter = new AtomicLong();

static {
final User user = new User(1L, "gugu", "password", "hkkang@woowahan.com");
database.put(user.getAccount(), user);
final User user = new User("gugu", "password", "hkkang@woowahan.com");
database.put(counter.getAndIncrement(), user);
}

private InMemoryUserRepository() {
}

public static void save(User user) {
database.put(user.getAccount(), user);
database.put(counter.getAndIncrement(), user);
}

public static Optional<User> findByAccount(String account) {
return Optional.ofNullable(database.get(account));
public static Long getIdByCredentials(String account, String password) {
return database.entrySet().stream()
.filter(entry -> entry.getValue().hasSameCredential(account, password))
.findFirst()
.orElseThrow()
.getKey();
}

private InMemoryUserRepository() {}
public static boolean hasSameCredential(String account, String password) {
return database.values().stream()
.anyMatch(user -> user.hasSameCredential(account, password));
}
}
33 changes: 17 additions & 16 deletions tomcat/src/main/java/nextstep/jwp/model/User.java
Original file line number Diff line number Diff line change
@@ -1,38 +1,39 @@
package nextstep.jwp.model;

import java.util.Objects;

public class User {

private final Long id;
private final String account;
private final String password;
private final String email;

public User(Long id, String account, String password, String email) {
this.id = id;
public User(String account, String password, String email) {
this.account = account;
this.password = password;
this.email = email;
}

public User(String account, String password, String email) {
this(null, account, password, email);
}

public boolean checkPassword(String password) {
return this.password.equals(password);
public boolean hasSameCredential(String account, String password) {
return this.account.equals(account) && this.password.equals(password);
}

public String getAccount() {
return account;
}

@Override
public String toString() {
return "User{" +
"id=" + id +
", account='" + account + '\'' +
", email='" + email + '\'' +
", password='" + password + '\'' +
'}';
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return Objects.equals(account, user.account) &&
Objects.equals(password, user.password) &&
Objects.equals(email, user.email);
}

@Override
public int hashCode() {
return Objects.hash(account, password, email);
}
}
13 changes: 5 additions & 8 deletions tomcat/src/main/java/org/apache/catalina/Manager.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package org.apache.catalina;

import jakarta.servlet.http.HttpSession;

import java.io.IOException;

/**
Expand Down Expand Up @@ -36,14 +35,12 @@ public interface Manager {
* specified session id (if any); otherwise return <code>null</code>.
*
* @param id The session id for the session to be returned
*
* @exception IllegalStateException if a new session cannot be
* instantiated for any reason
* @exception IOException if an input/output error occurs while
* processing this request
*
* @return the request session or {@code null} if a session with the
* requested ID could not be found
* requested ID could not be found
* @throws IllegalStateException if a new session cannot be
* instantiated for any reason
* @throws IOException if an input/output error occurs while
* processing this request
*/
HttpSession findSession(String id) throws IOException;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
package org.apache.catalina.connector;

import org.apache.coyote.http11.Http11Processor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.ServerSocket;
import java.net.Socket;
import org.apache.coyote.http11.Http11Processor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Connector implements Runnable {

Expand Down
3 changes: 1 addition & 2 deletions tomcat/src/main/java/org/apache/catalina/startup/Tomcat.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
package org.apache.catalina.startup;

import java.io.IOException;
import org.apache.catalina.connector.Connector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class Tomcat {

private static final Logger log = LoggerFactory.getLogger(Tomcat.class);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package org.apache.coyote.http11;

import java.util.Arrays;

public enum ContentTypeParser {

HTML("text/html;charset=utf-8"),
CSS("text/css"),
JS("text/javascript"),
ICO("image/x-icon");
ezzanzzan marked this conversation as resolved.
Show resolved Hide resolved

private final String contentType;

ContentTypeParser(String contentType) {
this.contentType = contentType;
}

public static String parse(String path) {
int commaLocation = path.lastIndexOf(".");
String resourceExtension = path.substring(commaLocation + 1);

return Arrays.stream(values())
.filter(value -> value.name().toLowerCase().equals(resourceExtension))
.findFirst()
.orElse(HTML)
.contentType;
}
}
21 changes: 10 additions & 11 deletions tomcat/src/main/java/org/apache/coyote/http11/Http11Processor.java
Original file line number Diff line number Diff line change
@@ -1,19 +1,22 @@
package org.apache.coyote.http11;

import java.io.IOException;
import java.net.Socket;
import nextstep.jwp.exception.UncheckedServletException;
import org.apache.coyote.Processor;
import org.apache.coyote.http11.handler.Handlers;
import org.apache.coyote.http11.message.request.Request;
import org.apache.coyote.http11.message.response.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.Socket;

public class Http11Processor implements Runnable, Processor {

private static final Logger log = LoggerFactory.getLogger(Http11Processor.class);

private final Socket connection;


public Http11Processor(final Socket connection) {
this.connection = connection;
}
Expand All @@ -29,17 +32,13 @@ public void process(final Socket connection) {
try (final var inputStream = connection.getInputStream();
final var outputStream = connection.getOutputStream()) {

final var responseBody = "Hello world!";

final var response = String.join("\r\n",
"HTTP/1.1 200 OK ",
"Content-Type: text/html;charset=utf-8 ",
"Content-Length: " + responseBody.getBytes().length + " ",
"",
responseBody);
Request request = RequestExtractor.extract(inputStream);
LoggingFilter.logUserInfoIfExists(request);
Response response = Handlers.handle(request);

outputStream.write(response.getBytes());
outputStream.flush();

} catch (IOException | UncheckedServletException e) {
log.error(e.getMessage(), e);
}
Expand Down
25 changes: 25 additions & 0 deletions tomcat/src/main/java/org/apache/coyote/http11/LoggingFilter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package org.apache.coyote.http11;

import org.apache.coyote.http11.message.Cookie;
import org.apache.coyote.http11.message.Headers;
import org.apache.coyote.http11.message.request.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LoggingFilter {

private static final Logger log = LoggerFactory.getLogger(LoggingFilter.class);

private LoggingFilter() {
}

public static void logUserInfoIfExists(Request request) {
Headers requestHeaders = request.getHeaders();
Cookie cookie = requestHeaders.getCookie();

if (cookie.hasKey("JSESSIONID")) {
String sessionId = cookie.getValue("JSESSIONID");
log.info("session {} is logged in.", sessionId);
}
}
}
Loading