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

pr7 #27

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
Open

pr7 #27

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
22 changes: 22 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,34 @@
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.5</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.9.5</version>
<scope>test</scope>
</dependency>


<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>


<!-- logger -->
<dependency>
<groupId>ch.qos.logback</groupId>
Expand Down
34 changes: 34 additions & 0 deletions src/main/java/common/ParameterConstants.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package common;

public class ParameterConstants {

/* path */
public static final String HOST = "http://localhost:8080/";
public static final String STATIC_RESOURCES_PATH = "./webapp/";
public static final String PATH_HOME = "";
public static final String PATH_INDEX_PAGE = "index.html";
public static final String PATH_LOGIN_PAGE = "user/login.html";
public static final String PATH_LOGIN_FAIL = "user/login_failed.html";

/* HTTP */
public static final String HTTP_VERSION = "HTTP/1.1";

public static final String HTTP_METHOD_GET = "GET";
public static final String HTTP_METHOD_POST = "POST";
public static final String HTTP_METHOD_PUT = "PUT";
public static final String HTTP_METHOD_DELETE = "DELETE";

public static final String CONTENT_TYPE_TEXT_HTML = "text/html;charset=UTF-8";
public static final String CONTENT_TYPE_TEXT_CSS = "text/css";
public static final String CONTENT_TYPE_TEXT_JS = "text/javascript";
public static final String CONTENT_TYPE_APPLICATION_JSON = "application/json;charset=UTF-8";


public static final String HTTP_STATUS_CODE_200 = "200";
public static final String HTTP_STATUS_MESSAGE_OK = "OK";

public static final String HTTP_STATUS_CODE_302 = "302";
public static final String HTTP_STATUS_MESSAGE_FOUND = "FOUND";


}
1 change: 1 addition & 0 deletions src/main/java/controller/UserController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package controller;import controller.dto.UserCreateRequestDto;import controller.dto.UserLoginRequestDto;import model.User;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import service.UserService;import util.HttpRequestUtils;import webserver.HttpRequest;import webserver.HttpResponse;import java.util.HashMap;import java.util.List;import java.util.Map;import static common.ParameterConstants.*;public class UserController { private final HttpRequest httpRequest; private UserService userService = new UserService(); private static final Logger log = LoggerFactory.getLogger(UserController.class); public UserController(HttpRequest httpRequest) { this.httpRequest = httpRequest; } public HttpResponse dispatch() { Map<String, Object> response = new HashMap<String, Object>(); String requestUri = httpRequest.getRequestUri(); String httpMethod = httpRequest.getHttpMethod(); String body = httpRequest.getBody(); if(requestUri.startsWith("/user/create")&&httpMethod.equals(HTTP_METHOD_POST)) { return post_create(body); } if(requestUri.startsWith("/user/login")&&httpMethod.equals(HTTP_METHOD_POST)) { return post_login(body); } if(requestUri.startsWith("/user/list")&&httpMethod.equals(HTTP_METHOD_GET)) { return get_list(body); } return null; } private HttpResponse post_create(String body) { Map<String, String> parameters = HttpRequestUtils.parseQueryString(body); UserCreateRequestDto userCreateRequestDto = new UserCreateRequestDto(parameters.get("userId"), parameters.get("password"), parameters.get("name"), parameters.get("email")); userService.create(userCreateRequestDto); HttpResponse httpResponse = new HttpResponse(HTTP_STATUS_CODE_302, HTTP_STATUS_MESSAGE_FOUND, PATH_INDEX_PAGE, CONTENT_TYPE_TEXT_HTML); return httpResponse; } private HttpResponse post_login(String body) { Map<String, String> parameters = HttpRequestUtils.parseQueryString(body); UserLoginRequestDto userLoginRequestDto = new UserLoginRequestDto(parameters.get("userId"), parameters.get("password")); User user = userService.login(userLoginRequestDto); if(user.getUserId() == null) { HttpResponse httpResponse = new HttpResponse(HTTP_STATUS_CODE_200, HTTP_STATUS_MESSAGE_OK, PATH_LOGIN_FAIL, CONTENT_TYPE_TEXT_HTML); httpResponse.setCookies("logined=false"); return httpResponse; } HttpResponse httpResponse = new HttpResponse(HTTP_STATUS_CODE_200, HTTP_STATUS_MESSAGE_OK, PATH_INDEX_PAGE, CONTENT_TYPE_TEXT_HTML); httpResponse.setCookies("logined=true"); return httpResponse; } private HttpResponse get_list(String body) { ; Boolean logined = Boolean.parseBoolean(HttpRequestUtils.parseCookies(httpRequest.getHeaders().get("Cookie")).get("logined")); log.debug("logined: {}", logined); if(logined == null || logined == false) { return new HttpResponse(HTTP_STATUS_CODE_302, HTTP_STATUS_MESSAGE_FOUND, PATH_LOGIN_PAGE, CONTENT_TYPE_TEXT_HTML); } List<User> userList = userService.findAllUser(); return new HttpResponse(HTTP_STATUS_CODE_200, HTTP_STATUS_MESSAGE_OK, "user/list.html", CONTENT_TYPE_TEXT_HTML); }}
Expand Down
48 changes: 48 additions & 0 deletions src/main/java/controller/dto/UserCreateRequestDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package controller.dto;

import model.User;

public class UserCreateRequestDto {

private String userId;
private String password;
private String name;
private String email;

public String getUserId() {
return userId;
}

public String getPassword() {
return password;
}

public String getName() {
return name;
}

public String getEmail() {
return email;
}

public UserCreateRequestDto(String userId, String password, String name, String email) {
this.userId = userId;
this.password = password;
this.name = name;
this.email = email;
}

public User toEntity() {
return new User(this.userId, this.password, this.name, this.email);
}

@Override
public String toString() {
return "UserCreateRequestDto{" +
"userId='" + userId + '\'' +
", password='" + "[PROTECTED]" + '\'' +
", name='" + name + '\'' +
", email='" + email + '\'' +
'}';
}
}
29 changes: 29 additions & 0 deletions src/main/java/controller/dto/UserLoginRequestDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package controller.dto;

import model.User;

public class UserLoginRequestDto {

private String userId;
private String password;

public String getUserId() {
return userId;
}
public String getPassword() {
return password;
}

public UserLoginRequestDto(String userId, String password) {
this.userId = userId;
this.password = password;
}

@Override
public String toString() {
return "UserLoginRequestDto{" +
"userId='" + userId + '\'' +
", password='" + password + '\'' +
'}';
}
}
5 changes: 2 additions & 3 deletions src/main/java/db/DataBase.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,14 @@
import model.User;

public class DataBase {

private static Map<String, User> users = Maps.newHashMap();

public static void addUser(User user) {
users.put(user.getUserId(), user);
}

public static User findUserById(String userId) {
return users.get(userId);
}
public static User findUserById(String userId) { return users.get(userId); }

public static Collection<User> findAll() {
return users.values();
Expand Down
6 changes: 6 additions & 0 deletions src/main/java/model/User.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package model;

import controller.dto.UserCreateRequestDto;

public class User {
private String userId;
private String password;
Expand Down Expand Up @@ -29,6 +31,10 @@ public String getEmail() {
return email;
}

public UserCreateRequestDto toDto() {
return new UserCreateRequestDto(this.userId, this.password, this.name, this.email);
}

@Override
public String toString() {
return "User [userId=" + userId + ", password=" + password + ", name=" + name + ", email=" + email + "]";
Expand Down
53 changes: 53 additions & 0 deletions src/main/java/service/UserService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package service;

import controller.dto.UserLoginRequestDto;
import db.DataBase;
import controller.dto.UserCreateRequestDto;
import model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;


public class UserService {

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

public UserService() {
}

public User create(UserCreateRequestDto userCreateRequestDto) {
log.debug("====================[USER CREATE START]====================");
if(DataBase.findUserById(userCreateRequestDto.getUserId()) != null) {
throw new RuntimeException("이미 존재하는 아이디 입니다.");
}
DataBase.addUser(userCreateRequestDto.toEntity());
log.debug("USER CREATED: {}",DataBase.findUserById(userCreateRequestDto.getUserId()).toString());
log.debug("====================[USER CREATE END]====================");
return DataBase.findUserById(userCreateRequestDto.getUserId());
}

public User login(UserLoginRequestDto userLoginDto) {
log.debug("====================[USER LOGIN START]====================");
User user = DataBase.findUserById(userLoginDto.getUserId());
if(user.getUserId() == null) throw new RuntimeException("존재하지 않는 아이디 입니다.");
if(!user.getPassword().equals(userLoginDto.getPassword())) throw new RuntimeException("잘못된 패스워드 입니다.");
log.debug("====================[USER LOGIN END]====================");
return user;
}

public List<User> findAllUser(){
log.debug("====================[findAllUser START]====================");
List<User> userList = DataBase.findAll().stream().collect(Collectors.toCollection(ArrayList::new));
for (User user : userList) {
log.debug("{}", user);
}
log.debug("====================[findAllUser END]====================");
return userList;
}

}
24 changes: 24 additions & 0 deletions src/main/java/util/HttpRequestUtils.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
package util;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import com.google.common.base.Strings;
import com.google.common.collect.Maps;

public class HttpRequestUtils {

private static Set<String> ALLOWED_HTTP_METHOD = new HashSet<String>(Arrays.asList(new String[]{"GET", "POST", "PUT", "DELETE"}));

/**
* @param queryString은
* URL에서 ? 이후에 전달되는 field1=value1&field2=value2 형식임
Expand Down Expand Up @@ -53,6 +58,25 @@ public static Pair parseHeader(String header) {
return getKeyValue(header, ": ");
}


public static boolean isHttpRequest(String requestLine) {
String[] arr = requestLine.split(" ");
return arr.length !=3 &&
!arr[2].contains("HTTP") &&
!ALLOWED_HTTP_METHOD.contains(arr[0])
? false : true;
}

public static String getRequestUri(String requestLine) {
if(!isHttpRequest(requestLine)) { throw new RuntimeException("올바른 HTTP 요청이 아닙니다."); }
return requestLine.split(" ")[1];
}

public static String getHttpMethod(String requestLine) {
if(!isHttpRequest(requestLine)) { throw new RuntimeException("올바른 HTTP 요청이 아닙니다."); }
return requestLine.split(" ")[0];
}

public static class Pair {
String key;
String value;
Expand Down
50 changes: 50 additions & 0 deletions src/main/java/webserver/ControllerDispatcher.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package webserver;

import controller.UserController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.List;

import static common.ParameterConstants.*;

public class ControllerDispatcher {

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

private final HttpRequest httpRequest;

public ControllerDispatcher(HttpRequest httpRequest) {
this.httpRequest = httpRequest;
}

public HttpResponse dispatch() {
String requestUri = httpRequest.getRequestUri();
log.debug("requestURi: {}", requestUri);

if(requestUri.equals("/")) {
return new HttpResponse(HTTP_STATUS_CODE_200, HTTP_STATUS_MESSAGE_OK, "index.html", CONTENT_TYPE_TEXT_HTML);
}

else if(httpRequest.getHttpMethod().equals(HTTP_METHOD_GET) &&
httpRequest.getRequestUri().split("\\.").length > 1){
log.debug("{}", "********************STATIC_RESOURCE_REQUEST********************");
String extension = httpRequest.getRequestUri().split("\\.")[1];
String CONTENT_TYPE = CONTENT_TYPE_TEXT_HTML;
if(extension.equals("css")) CONTENT_TYPE = CONTENT_TYPE_TEXT_CSS;
if(extension.equals("js")) CONTENT_TYPE = CONTENT_TYPE_TEXT_JS;


return new HttpResponse(HTTP_STATUS_CODE_200, HTTP_STATUS_MESSAGE_OK, requestUri.substring(1), CONTENT_TYPE);

}

else if(requestUri.startsWith("/user")) {
UserController userController = new UserController(httpRequest);
return userController.dispatch();
}

return new HttpResponse("200", "OK", null, CONTENT_TYPE_TEXT_HTML); // 어떻게 처리해야되는걸까?
}
}
Loading