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

3주차 미션 / 서버 2조 - 신희을 #5

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
30 changes: 30 additions & 0 deletions TODO.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# **리팩토링**

## 요구사항 1: Enum 활용
* HttpHeader,
* HttpMethod,
* URL,
* 상태 코드,
* User의 queryKey

## 요구사항 2: HttpRequest 메시지 분리
* HttpRequest 클래스 생성

## 요구사항 3: HttpResponse 메시지 분리
* HttpResponse 클래스 생성
* forward(path) 함수 : 원하는 html 파일을 보여주는 함수
* redirect(path) 함수 : redirect 시켜주는 함수

## 요구사항 4: url마다의 작업 처리 분리
* 각 작업별 Controller Class
* Controller Interface
* ForwardController
* HomeController
* SignUpController
* LoginController
* ListController

## 요구사항 5: 분기문 처리
* Map을 이용한 if문 제거
* 위 Controller들을 Map에 담기

19 changes: 19 additions & 0 deletions src/main/java/Controller/AbstractController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package Controller;

import http.constants.HttpMethod;
import http.request.HttpRequest;
import http.response.HttpResponse;

public abstract class AbstractController implements Controller{
@Override
public void execute(HttpRequest request, HttpResponse response) {
if (request.getMethod().equals(HttpMethod.GET)) {
doGet(request, response);
return;
}
doPost(request, response);
}

abstract void doGet(HttpRequest request, HttpResponse response);
abstract void doPost(HttpRequest request, HttpResponse response);
}
12 changes: 12 additions & 0 deletions src/main/java/Controller/Controller.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package Controller;

import http.request.HttpRequest;
import http.response.HttpResponse;

import java.io.IOException;


//* Controller 인터페이스
public interface Controller {
void execute(HttpRequest request, HttpResponse response) throws IOException;
}
14 changes: 14 additions & 0 deletions src/main/java/Controller/ForwardController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package Controller;

import http.request.HttpRequest;
import http.response.HttpResponse;

import java.io.IOException;

public class ForwardController implements Controller{

@Override
public void execute(HttpRequest request, HttpResponse response) throws IOException {
response.forward(request.getUrl());
}
}
15 changes: 15 additions & 0 deletions src/main/java/Controller/HomeController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package Controller;

import http.request.HttpRequest;
import http.response.HttpResponse;

import java.io.IOException;

import static http.request.RequestURL.INDEX;

public class HomeController implements Controller{
@Override
public void execute(HttpRequest request, HttpResponse response) throws IOException {
response.forward(INDEX.getUrl());
}
}
21 changes: 21 additions & 0 deletions src/main/java/Controller/ListController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package Controller;

import http.constants.HttpHeader;
import http.request.HttpRequest;
import http.response.HttpResponse;

import java.io.IOException;

import static http.request.RequestURL.LOGIN;
import static http.request.RequestURL.USER_LIST_HTML;

public class ListController implements Controller{
@Override
public void execute(HttpRequest request, HttpResponse response) throws IOException {
if (!request.getHeader(HttpHeader.COOKIE).equals("logined=true")) {
response.redirect(LOGIN.getUrl());
return;
}
response.forward(USER_LIST_HTML.getUrl());
}
}
33 changes: 33 additions & 0 deletions src/main/java/Controller/LoginController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package Controller;

import db.MemoryUserRepository;
import http.constants.HttpHeader;
import http.request.HttpRequest;
import http.response.HttpResponse;
import model.User;

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

import static http.request.RequestURL.INDEX;
import static http.request.RequestURL.LOGIN_FAILED;

public class LoginController implements Controller{

private final MemoryUserRepository repository = MemoryUserRepository.getInstance();
@Override
public void execute(HttpRequest request, HttpResponse response) throws IOException {
Map<String, String> queryParameter = request.getQueryParametersFromBody();
User user = repository.findUserById(queryParameter.get("userId"));
login(response, queryParameter, user);
}

private void login(HttpResponse response, Map<String, String> queryParameter, User user) throws IOException {
if (user != null && user.getPassword().equals(queryParameter.get("password"))) {
response.put(HttpHeader.SET_COOKIE,"logined=true");
response.redirect(INDEX.getUrl());
return;
}
response.redirect(LOGIN_FAILED.getUrl());
}
}
29 changes: 29 additions & 0 deletions src/main/java/Controller/SignUpController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package Controller;

import db.MemoryUserRepository;
import http.request.HttpRequest;
import http.response.HttpResponse;
import model.User;
import model.constants.UserQueryKey;

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

import static http.request.RequestURL.INDEX;

public class SignUpController implements Controller{

private final MemoryUserRepository repository = MemoryUserRepository.getInstance();

@Override
public void execute(HttpRequest request, HttpResponse response) throws IOException {
Map<String, String> queryParameter = request.getQueryParametersFromBody();
User user = new User(
queryParameter.get(UserQueryKey.ID.getKey()),
queryParameter.get(UserQueryKey.PASSWORD.getKey()),
queryParameter.get(UserQueryKey.NAME.getKey()),
queryParameter.get(UserQueryKey.EMAIL.getKey()));
repository.addUser(user);
response.redirect(INDEX.getUrl());
}
}
25 changes: 25 additions & 0 deletions src/main/java/http/constants/HttpHeader.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package http.constants;

import java.util.Arrays;
import java.util.Optional;

//Header 정보 Enum 클래스
public enum HttpHeader {
CONTENT_LENGTH("Content-Length"), CONTENT_TYPE("Content-Type"), LOCATION("Location"), COOKIE("Cookie"),SET_COOKIE("Set-Cookie"),CONNECTION("Connection"),HOST("Host");

private String header;

HttpHeader(String header) {
this.header = header;
}

public String getHeader() {
return header;
}

//싱글톤 패턴
public static HttpHeader getHeaderInstance(String headerString) {
Optional<HttpHeader> find = Arrays.stream(HttpHeader.values()).filter(httpHeader -> httpHeader.header.equals(headerString)).findFirst();
return find.orElse(null);
}
}
31 changes: 31 additions & 0 deletions src/main/java/http/constants/HttpMethod.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package http.constants;

import java.util.Arrays;
import java.util.Optional;

//HTTP Method enum 클래스
public enum HttpMethod {
GET("GET"),POST("POST"),DELETE("DELETE");

String method;
HttpMethod(String method) {
this.method = method;
}

public static HttpMethod getHttpMethod(String requestMethod) {
Optional<HttpMethod> method = Arrays.stream(HttpMethod.values()).filter(httpMethod -> httpMethod.method.equals(requestMethod)).findFirst();

if (method.isPresent()) {
return method.get();
}
throw new IllegalArgumentException("지원하지 않는 Http 메소드 입니다.");
}

public String getMethod() {
return method;
}

public boolean isEqual(String method) {
return this.method.equals(method);
}
}
18 changes: 18 additions & 0 deletions src/main/java/http/constants/HttpStatus.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package http.constants;


//HTTP 상태 코드 enum 클래스
public enum HttpStatus {
//200 OK, 302 Redirect
OK("OK"), REDIRECT("Found");

private final String status;

HttpStatus(String status) {
this.status = status;
}

public String getStatus() {
return status;
}
}
94 changes: 94 additions & 0 deletions src/main/java/http/request/HttpHeaders.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package http.request;



import http.constants.HttpHeader;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.*;


//Header 정보를 Map으로 저장하는 클래스
public class HttpHeaders {
//헤더 정보 Map
private Map<HttpHeader, String> headers;
// :을 상수로 정의
private static final String DISCRIMINATOR = ": ";

public HttpHeaders(final Map<HttpHeader, String> headers) {
this.headers = headers;
}

//* HttpHeaders를 생성해주는 함수
// br을 넘겨주면 header를 읽고 Map으로 바꿔서 생성
public static HttpHeaders from(final BufferedReader bufferedReader) throws IOException {
return new HttpHeaders(readAllHeaders(bufferedReader));
}

//* header를 읽는 실질적인 함수
private static Map<HttpHeader, String> readAllHeaders(final BufferedReader bufferedReader) throws IOException {
final Map<HttpHeader, String> headers = new LinkedHashMap<>();


//Header 정보 다 읽어올 때까지 반복
while (true) {
final String line = bufferedReader.readLine();
if (line.equals("")) {
break;
}

//header를 type과 value로 나눠 list에 넣어주고
final List<String> header = parseHeader(line);
//리스트를 통해 type과 value를 key, value로 map에 넣어줌
final String headerType = header.get(0).trim();
HttpHeader headerKey = HttpHeader.getHeaderInstance(headerType);
final String headerValue = header.get(1).trim();
if (headerKey != null) {
headers.put(headerKey, headerValue);
}
}
//헤더 정보가 담긴 map 반환
return headers;
}

//* header 분리 함수
// : 기준으로 데이터를 나눠주고 해당 헤더 값이 정당한 헤더 값인지 검증 후 return
private static List<String> parseHeader(final String line) {
final List<String> header = Arrays.asList(line.split(DISCRIMINATOR));
validateHeader(header);
return header;
}

//* 검증 함수
// header 값에 key 혹은 value 값이 없다면 에러 발생
private static void validateHeader(final List<String> header) {
if (header.size() < 2) {
throw new IllegalArgumentException("요청 정보가 잘못되었습니다.");
}
}

public boolean contains(final HttpHeader httpHeaderType) {
return headers.containsKey(httpHeaderType);
}

public String get(final HttpHeader httpHeaderType) {
return headers.get(httpHeaderType);
}

public Set<HttpHeader> keySet() {
return headers.keySet();
}

public void put(HttpHeader httpHeaderType, final String httpHeader) {
headers.put(httpHeaderType, httpHeader);
}

@Override
public String toString() {
StringBuilder sb = new StringBuilder();
headers.forEach((key,value) -> sb.append(key.getHeader()).append(": ").append(value).append("\r\n"));

return sb.append("\r\n").toString();
}
}
Loading