Skip to content

Commit

Permalink
[최주형] 14, 15일차 - 테스트 코드 작성, 리팩토링, 예외처리 (#167)
Browse files Browse the repository at this point in the history
* TEST : HtmlServiceTest 추가

* TEST : ListServiceTest 추가

* FIX : ListServiceTest 수정

* TEST : SignUpServiceTest 테스트 케이스 추가

* TEST : SignUpTest assertThat 추가 및 LogInService 추가

* FIX : Reformat Code

* TEST : HttpResponseUtilsTest 코드 추가

* TEST : StaticFileServiceTest 코드 추가

* REFORMAT CODE

* REFACTOR : HttpResponse 쓰지않는 변수와 함수 삭제

* REFACTOR : HttpStatusLine 쓰지 않는 함수 삭제

* REFACTOR : HttpUri 쓰지 않는 함수 삭제

* REFACTOR : HttpStatus 쓰지 않는 함수 삭제

* REFORMAT CODE

* DOCS : README.md 학습 내용 추가

* DOCS : README.md 프로젝트 구조 작성

* 14일차 마무리

* FIX : list.html 더미값 삭제

* FEAT : 회원가입 할 때 이미 user id 가 있을 경우 예외처리
DuplicateSignUpUserException exception 클래스 추가, SignUpService에서 try catch로 잡아서 스트링 하나 간단히 만들어서 200 OK로 리턴

* DOCS : README.md 프로젝트 구조 이상하게 나오는거 수정
  • Loading branch information
jhchoi57 authored Jan 25, 2023
1 parent 4f0941d commit d047e08
Show file tree
Hide file tree
Showing 34 changed files with 410 additions and 195 deletions.
81 changes: 80 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,65 @@ Java Web Application Server 2022
를 참고하여 작성되었습니다.

## 프로젝트 구조
├── controller
│   ├── Controller.java
│   ├── HtmlController.java
│   ├── StaticFileController.java
│   └── UserController.java
├── db
│   ├── Database.java
│   └── Session.java
├── http
│   ├── HttpHeader.java
│   ├── HttpStatus.java
│   ├── HttpUri.java
│   ├── exception
│   │   └── NullHttpRequestException.java
│   ├── request
│   │   ├── HttpRequest.java
│   │   └── HttpRequestLine.java
│   └── response
│   ├── HttpResponse.java
│   └── HttpStatusLine.java
├── model
│   └── User.java
├── service
│   ├── HtmlService.java
│   ├── ListService.java
│   ├── LogInService.java
│   ├── SignUpService.java
│   └── StaticFileService.java
├── util
│   ├── HttpRequestUtils.java
│   └── HttpResponseUtils.java
└── webserver
├── ControllerHandler.java
├── RequestHandler.java
└── WebServer.java

+ RequestHandler
+ HttpRequest 클래스에 입력을 받고 받은 URI로 알맞는 컨트롤러를 골라준다. 고른 컨트롤러로 응답을 만들고 응답을 출력해준다.
+ ControllerHandler
+ Post 요청인 경우를 먼저 확인 - 회원 가입과 로그인을 처리하는 UserController를 리턴
+ Html 파일 요청인 경우인지 확인 - Html파일을 처리하는 HtmlController를 리턴
+ 나머지인 경우 (정적 파일) - 정적 파일을 처리하는 StaticFileController를 리턴
+ UserController
+ HttpRequest 객체로부터 uri와 httpVersion을 받아온다.
+ HttpRequest body의 query string을 파싱해서 Map 객체인 params에 넣어준다.
+ 회원 가입 요청인 경우와 로그인 요청인 경우를 나누어 준다.
+ 각각 params와 httpVersion을 나누어 주며 회원가입일 경우 SignUpService, 로그인일 경우 LogInService를 통해 응답을 생성해 준다.
+ 생성된 응답 HttpResponse 객체를 리턴한다.
+ HtmlController
+ HttpRequest 객체로부터 로그인 유저 정보, ContentType, 파일 경로, uri를 받는다.
+ 유저 리스트 출력 html일 경우 ListService를 통해 응답 생성
+ index.html 로그인 상태일 경우 HtmlService를 통해 응답 생성
+ index.html 로그인 상태가 아닐 경우 정적 파일 요청이므로 StaticFileService를 통해 응답을 생성한다.
+ 생성된 응답 HttpResponse 객체를 리턴한다.
+ StaticFileController
+ 정적 파일들은 모두 /static 폴더 내에 있으므로 기본 파일 경로를 설정해준다.
+ 설정해준 파일 경로에 HttpResquest객체로부터 받은 uri를 더해서 정적 파일 경로를 만들어준다.
+ 만들어진 파일 경로로 StaticFileService를 통해 응답을 생성한다.
+ 생성된 응답 HttpResponse 객체를 리턴한다.


## 프로젝트 학습 내용
Expand Down Expand Up @@ -160,4 +219,24 @@ Java Web Application Server 2022
+ Servlet
+ Java 언어로 작성된 웹 애플리케이션의 컴포넌트
+ 서버 측에서 실행되며 http 요청을 처리
+ 클라이언트의 요청을 처리하고 응답을 생성
+ 클라이언트의 요청을 처리하고 응답을 생성
------------
+ Day 14
+ stateful과 stateless
+ stateful
+ 상태 유지 : 서버가 클라이언트의 상태를 보존한다.
+ 대표적으로 TCP의 3-way handshaking
+ 문제점 : 해당 서버를 못쓰게 되어 다른 서버를 사용해야 할 때 발생 - 이전 서버의 정보가 없음
+ 문제점 해결 : 현업에서는 캐시 서버 Redis 사용
+ stateless
+ 서버가 클라이언트의 상태를 보존하지 않음.
+ 요청이 오면 바로 응답을 보내며 상태 관리는 클라이언트에서 책임을 짐.
+ 대량의 트래픽이 발생했을 때에도 서버 확장을 통해 대처를 수월하게 할 수 있음.
+ (stateful과 다르게 서버가 바뀌어도 정확한 응답에 문제가 없기 때문)
+ 대표적으로 UDP와 HTTP
+ 문제점 : 더 많은 데이터 소모 - 매번 요청할 때마다 부가정보 필요
+ wrapper class
+ 기본 자료타입을 객체로 다루기 위해서 사용하는 클래스
+ git diff
+ add 전과 후의 파일 내용을 비교해줌
2 changes: 0 additions & 2 deletions src/main/java/controller/Controller.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
import http.request.HttpRequest;
import http.response.HttpResponse;

import java.io.IOException;

public interface Controller {
HttpResponse makeResponse(HttpRequest httpRequest);
}
10 changes: 5 additions & 5 deletions src/main/java/controller/HtmlController.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,25 +11,25 @@
import service.ListService;
import service.StaticFileService;

public class HtmlController implements Controller{
public class HtmlController implements Controller {
private static final Logger logger = LoggerFactory.getLogger(HtmlController.class);
private static final String htmlFilePath = "./src/main/resources/templates";

@Override
public HttpResponse makeResponse(HttpRequest httpRequest){
//ContentType, 파일 확장자, uri를 받음
public HttpResponse makeResponse(HttpRequest httpRequest) {
//로그인한 유저 ContentType, 파일 경로, uri를 받음
User logInUser = Database.findUserById(Session.findUserIdBySessionId(httpRequest.getCookie()));
String contentType = httpRequest.getContentType();
String filePath = htmlFilePath + httpRequest.getUri();
String httpVersion = httpRequest.getHttpVersion();

// list service
if(httpRequest.getUri().equals("/user/list.html"))
if (httpRequest.getUri().equals("/user/list.html"))
return ListService.service(
logInUser, filePath, httpVersion, contentType);

// index.html service 로그인 O
if(httpRequest.isLogin())
if (httpRequest.isLogin())
return HtmlService.service(
filePath, logInUser, httpVersion, contentType);

Expand Down
5 changes: 0 additions & 5 deletions src/main/java/controller/StaticFileController.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,7 @@

import http.request.HttpRequest;
import http.response.HttpResponse;
import http.HttpStatus;
import http.response.HttpStatusLine;
import service.StaticFileService;
import util.HttpResponseUtils;

import java.io.IOException;

public class StaticFileController implements Controller {
private static final String staticFilePath = "./src/main/resources/static";
Expand Down
13 changes: 3 additions & 10 deletions src/main/java/controller/UserController.java
Original file line number Diff line number Diff line change
@@ -1,20 +1,13 @@
package controller;

import db.Database;
import db.Session;
import http.HttpStatus;
import http.request.HttpRequest;
import http.response.HttpResponse;
import http.response.HttpStatusLine;
import model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import service.LogInService;
import service.SignUpService;
import util.HttpRequestUtils;
import util.HttpResponseUtils;

import java.io.IOException;
import java.util.Map;

public class UserController implements Controller {
Expand All @@ -34,19 +27,19 @@ public HttpResponse makeResponse(HttpRequest httpRequest) {
}

// 로그인일 때
if(isLoginService(uri)){
if (isLoginService(uri)) {
return LogInService.service(params, httpVersion);
}

//TODO 임시 코드 - return 예외처리 해야됨
return null;
}

public boolean isSignUpService(String uri){
public boolean isSignUpService(String uri) {
return uri.equals("/user/create");
}

public boolean isLoginService(String uri){
public boolean isLoginService(String uri) {
return uri.equals("/user/login");
}

Expand Down
7 changes: 5 additions & 2 deletions src/main/java/db/Database.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package db;

import com.google.common.collect.Maps;
import http.response.HttpResponse;
import model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand All @@ -11,7 +10,7 @@

public class Database {
private static final Logger logger = LoggerFactory.getLogger(Database.class);
private static Map<String, User> users = Maps.newHashMap();
private static final Map<String, User> users = Maps.newHashMap();

public static void addUser(User user) {
logger.debug("Database User input : {}", user);
Expand All @@ -25,4 +24,8 @@ public static User findUserById(String userId) {
public static Collection<User> findAll() {
return users.values();
}

public static boolean checkDuplicate(User user) {
return users.get(user.getUserId()) == null;
}
}
7 changes: 4 additions & 3 deletions src/main/java/db/Session.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package db;

import com.google.common.collect.Maps;
import model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand All @@ -11,7 +10,7 @@

public class Session {
private static final Logger logger = LoggerFactory.getLogger(Session.class);
private static Map<String, String> sessions = Maps.newHashMap();
private static final Map<String, String> sessions = Maps.newHashMap();

public static String makeSessionIdAndAddUserId(String userId) {
String sessionId = UUID.randomUUID().toString();
Expand All @@ -20,7 +19,9 @@ public static String makeSessionIdAndAddUserId(String userId) {
return sessionId;
}

public static String findUserIdBySessionId(String sessionId){ return sessions.get(sessionId); }
public static String findUserIdBySessionId(String sessionId) {
return sessions.get(sessionId);
}

public static Collection<String> findAll() {
return sessions.values();
Expand Down
12 changes: 9 additions & 3 deletions src/main/java/http/HttpHeader.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

public class HttpHeader {

private Map<String, String> headers = new HashMap<>();
private final Map<String, String> headers = new HashMap<>();

public HttpHeader(List<String> headers) {
for (String header : headers) {
Expand All @@ -17,7 +17,7 @@ public HttpHeader(List<String> headers) {
}
}

public void addHeader(String headerKey, String headerValue){
public void addHeader(String headerKey, String headerValue) {
headers.put(headerKey, headerValue);
}

Expand All @@ -39,5 +39,11 @@ public String getContentLength() {
return headers.get("Content-Length");
}

public String getCookie() { return headers.get("Cookie"); }
public String getCookie() {
return headers.get("Cookie");
}

public String getLocation() {
return headers.get("Location");
}
}
12 changes: 2 additions & 10 deletions src/main/java/http/HttpStatus.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ public enum HttpStatus {
OK(200, "OK"),
FOUND(302, "FOUND");

private int statusCode;
private String status;
private final int statusCode;
private final String status;

HttpStatus(int statusCode, String status) {
this.statusCode = statusCode;
Expand All @@ -21,14 +21,6 @@ public static HttpStatus of(int statusCode) {
.orElseThrow();
}

public int getStatusCode() {
return statusCode;
}

public String getStatus() {
return status;
}

public String toString() {
return statusCode + " " + status;
}
Expand Down
8 changes: 1 addition & 7 deletions src/main/java/http/HttpUri.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

public class HttpUri {
private static final Logger logger = LoggerFactory.getLogger(HttpUri.class);
private String uri;
private final String uri;

public HttpUri(String uri) {
this.uri = uri;
Expand All @@ -15,12 +15,6 @@ public String getUri() {
return uri;
}

// uri에 . 이 있으면 정적 파일을 주면 되지 않을까?
// 다른 방법으로 판단 해야 할듯 > 고민중
public boolean isStaticUri() {
return uri.contains(".");
}

public String getFileNameExtension() {
return uri.substring(uri.lastIndexOf(".") + 1);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package http.exception;

public class DuplicateSignUpUserException extends RuntimeException {
public DuplicateSignUpUserException(String message) {
super(message);
}
}
4 changes: 2 additions & 2 deletions src/main/java/http/exception/NullHttpRequestException.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package http.exception;

public class NullHttpRequestException extends RuntimeException{
public NullHttpRequestException(String message){
public class NullHttpRequestException extends RuntimeException {
public NullHttpRequestException(String message) {
super(message);
}
}
12 changes: 6 additions & 6 deletions src/main/java/http/request/HttpRequest.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,16 @@

public class HttpRequest {
private static final Logger logger = LoggerFactory.getLogger(HttpRequest.class);
private HttpRequestLine httpRequestLine;
private HttpHeader httpHeader;
private final HttpRequestLine httpRequestLine;
private final HttpHeader httpHeader;
private String body;

public HttpRequest(BufferedReader br) throws IOException {
String line = br.readLine();
if (line == null) throw new NullHttpRequestException("빈 http request !!================");
this.httpRequestLine = HttpRequestUtils.readRequestLine(line);
this.httpHeader = HttpRequestUtils.readHeaders(br);
if(httpRequestLine.getHttpMethod().equals("POST")) this.body = HttpRequestUtils.readBody(br, httpHeader);
if (httpRequestLine.getHttpMethod().equals("POST")) this.body = HttpRequestUtils.readBody(br, httpHeader);
}

public String getUri() {
Expand All @@ -42,18 +42,18 @@ public boolean isPost() {
return this.httpRequestLine.getHttpMethod().equals("POST");
}

public String getBody(){
public String getBody() {
return this.body;
}

public String getFileNameExtension() {
return httpRequestLine.getHttpUri().getFileNameExtension();
}

public String getCookie(){
public String getCookie() {
logger.debug("Cookie : {}", httpHeader.getCookie());
String cookie = httpHeader.getCookie();
if(cookie == null) return null;
if (cookie == null) return null;
return HttpRequestUtils.parseQueryString(httpHeader.getCookie()).get("sid");
}

Expand Down
Loading

0 comments on commit d047e08

Please sign in to comment.