diff --git a/pom.xml b/pom.xml index a98034b22..dc7eddc79 100644 --- a/pom.xml +++ b/pom.xml @@ -20,12 +20,34 @@ test + + org.mockito + mockito-all + 1.9.5 + test + + + + org.mockito + mockito-core + 1.9.5 + test + + + com.google.guava guava 18.0 + + org.apache.httpcomponents + httpclient + 4.5.3 + + + ch.qos.logback diff --git a/src/main/java/common/ParameterConstants.java b/src/main/java/common/ParameterConstants.java new file mode 100644 index 000000000..08de077d9 --- /dev/null +++ b/src/main/java/common/ParameterConstants.java @@ -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"; + + +} diff --git a/src/main/java/controller/UserController.java b/src/main/java/controller/UserController.java new file mode 100644 index 000000000..c6e905bcd --- /dev/null +++ b/src/main/java/controller/UserController.java @@ -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 response = new HashMap(); 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 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 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 userList = userService.findAllUser(); return new HttpResponse(HTTP_STATUS_CODE_200, HTTP_STATUS_MESSAGE_OK, "user/list.html", CONTENT_TYPE_TEXT_HTML); } } \ No newline at end of file diff --git a/src/main/java/controller/dto/UserCreateRequestDto.java b/src/main/java/controller/dto/UserCreateRequestDto.java new file mode 100644 index 000000000..6053a4bdf --- /dev/null +++ b/src/main/java/controller/dto/UserCreateRequestDto.java @@ -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 + '\'' + + '}'; + } +} diff --git a/src/main/java/controller/dto/UserLoginRequestDto.java b/src/main/java/controller/dto/UserLoginRequestDto.java new file mode 100644 index 000000000..1c8c36055 --- /dev/null +++ b/src/main/java/controller/dto/UserLoginRequestDto.java @@ -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 + '\'' + + '}'; + } +} diff --git a/src/main/java/db/DataBase.java b/src/main/java/db/DataBase.java index b9419a4a3..c11f42d2a 100644 --- a/src/main/java/db/DataBase.java +++ b/src/main/java/db/DataBase.java @@ -8,15 +8,14 @@ import model.User; public class DataBase { + private static Map 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 findAll() { return users.values(); diff --git a/src/main/java/model/User.java b/src/main/java/model/User.java index b7abb7304..a9f74ce60 100644 --- a/src/main/java/model/User.java +++ b/src/main/java/model/User.java @@ -1,5 +1,7 @@ package model; +import controller.dto.UserCreateRequestDto; + public class User { private String userId; private String password; @@ -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 + "]"; diff --git a/src/main/java/service/UserService.java b/src/main/java/service/UserService.java new file mode 100644 index 000000000..e03ea471d --- /dev/null +++ b/src/main/java/service/UserService.java @@ -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 findAllUser(){ + log.debug("====================[findAllUser START]===================="); + List userList = DataBase.findAll().stream().collect(Collectors.toCollection(ArrayList::new)); + for (User user : userList) { + log.debug("{}", user); + } + log.debug("====================[findAllUser END]===================="); + return userList; + } + +} diff --git a/src/main/java/util/HttpRequestUtils.java b/src/main/java/util/HttpRequestUtils.java index c4cd95c0d..83b774d57 100644 --- a/src/main/java/util/HttpRequestUtils.java +++ b/src/main/java/util/HttpRequestUtils.java @@ -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 ALLOWED_HTTP_METHOD = new HashSet(Arrays.asList(new String[]{"GET", "POST", "PUT", "DELETE"})); + /** * @param queryString은 * URL에서 ? 이후에 전달되는 field1=value1&field2=value2 형식임 @@ -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; diff --git a/src/main/java/webserver/ControllerDispatcher.java b/src/main/java/webserver/ControllerDispatcher.java new file mode 100644 index 000000000..e1644018c --- /dev/null +++ b/src/main/java/webserver/ControllerDispatcher.java @@ -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); // 어떻게 처리해야되는걸까? + } +} diff --git a/src/main/java/webserver/HttpRequest.java b/src/main/java/webserver/HttpRequest.java new file mode 100644 index 000000000..b9be53d93 --- /dev/null +++ b/src/main/java/webserver/HttpRequest.java @@ -0,0 +1,76 @@ +package webserver; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import util.HttpRequestUtils; +import util.IOUtils; + +import java.io.BufferedReader; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +public class HttpRequest { + + private static final Logger log = LoggerFactory.getLogger(HttpRequest.class); + + private final String requestLine; + private final String httpMethod; + private final String requestUri; + private final String body; + private final Map headers; + + public HttpRequest(BufferedReader br) throws IOException { + this.requestLine = br.readLine(); + this.httpMethod = HttpRequestUtils.getHttpMethod(requestLine); + this.requestUri = HttpRequestUtils.getRequestUri(requestLine); + this.headers = new HashMap(); + log.debug("{}","====================[HTTP REQUEST START]===================="); + log.debug("REQUEST_LINE: {}",requestLine); + log.debug("HTTP_METHOD: {}",httpMethod); + log.debug("REQUEST_URI: {}",requestUri); + log.debug("{}","--------------------[HEADER START]--------------------"); + while(true) { + String header = br.readLine(); + if(header == null || "".equals(header)) break; + HttpRequestUtils.Pair pair = HttpRequestUtils.parseHeader(header); + this.headers.put(pair.getKey(), pair.getValue()); + log.debug("{}: {}", pair.getKey(), pair.getValue()); + } + log.debug("{}","--------------------[HEADER END]--------------------"); + int contentLength = Integer.parseInt(headers.getOrDefault("Content-Length","0")); + this.body = contentLength > 0 ? IOUtils.readData(br, contentLength) : ""; + log.debug("{}","====================[HTTP REQUEST END]===================="); + } + + public String getRequestLine() { + return requestLine; + } + + public String getHttpMethod() { + return httpMethod; + } + + public String getRequestUri() { + return requestUri; + } + + public String getBody() { + return body; + } + + public Map getHeaders() { + return headers; + } + + @Override + public String toString() { + return "HttpRequest{" + + "requestLine='" + requestLine + '\'' + + ", httpMethod='" + httpMethod + '\'' + + ", requestUri='" + requestUri + '\'' + + ", body='" + body + '\'' + + ", headers=" + headers + + '}'; + } +} diff --git a/src/main/java/webserver/HttpResponse.java b/src/main/java/webserver/HttpResponse.java new file mode 100644 index 000000000..966675e2e --- /dev/null +++ b/src/main/java/webserver/HttpResponse.java @@ -0,0 +1,69 @@ +package webserver; + +import common.ParameterConstants; + +import java.util.Map; + +public class HttpResponse { + + private final String httpVersion = ParameterConstants.HTTP_VERSION; + private final String status; + private final String message; + private final String body; + + /* header */ + private final String Content_Type; + private String location; + private String cookies; + + public HttpResponse(String status, String message, String body, String Content_Type) { + this.status = status; + this.message = message; + this.body = body; + this.Content_Type = Content_Type; + } + + public String getHttpVersion() { + return httpVersion; + } + + public String getStatus() { + return status; + } + + public String getMessage() { + return message; + } + + public String getBody() { + return body; + } + + public String getContent_Type() { return Content_Type; } + + public String getLocation() { + return location; + } + + public void setLocation(String location) { + this.location = location; + } + + public String getCookies() { + return cookies; + } + + public void setCookies(String cookies) { + this.cookies = cookies; + } + + @Override + public String toString() { + return "HttpResponse{" + + "httpVersion='" + httpVersion + '\'' + + ", status='" + status + '\'' + + ", message='" + message + '\'' + + ", body='" + body + '\'' + + '}'; + } +} diff --git a/src/main/java/webserver/RequestHandler.java b/src/main/java/webserver/RequestHandler.java index 90195ec4e..57eef03a1 100644 --- a/src/main/java/webserver/RequestHandler.java +++ b/src/main/java/webserver/RequestHandler.java @@ -1,15 +1,17 @@ package webserver; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.Socket; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.*; +import java.net.Socket; +import java.nio.file.Files; + +import static common.ParameterConstants.*; + + public class RequestHandler extends Thread { + private static final Logger log = LoggerFactory.getLogger(RequestHandler.class); private Socket connection; @@ -25,19 +27,45 @@ public void run() { try (InputStream in = connection.getInputStream(); OutputStream out = connection.getOutputStream()) { // TODO 사용자 요청에 대한 처리는 이 곳에 구현하면 된다. DataOutputStream dos = new DataOutputStream(out); - byte[] body = "Hello World".getBytes(); - response200Header(dos, body.length); - responseBody(dos, body); + BufferedReader br = new BufferedReader(new InputStreamReader(in)); + + ControllerDispatcher controllerDispatcher = new ControllerDispatcher(new HttpRequest(br)); + HttpResponse httpResponse = controllerDispatcher.dispatch(); + + log.debug("PATH: {}", STATIC_RESOURCES_PATH+httpResponse.getBody()); + + byte[] content = + Files.readAllBytes(new File(STATIC_RESOURCES_PATH+httpResponse.getBody()).toPath()); + + responseHeader(dos, content.length, httpResponse); + responseBody(dos, content); + } catch (IOException e) { log.error(e.getMessage()); } } - private void response200Header(DataOutputStream dos, int lengthOfBodyContent) { + private void responseHeader(DataOutputStream dos, int lengthOfBodyContent, HttpResponse httpResponse) { try { - dos.writeBytes("HTTP/1.1 200 OK \r\n"); - dos.writeBytes("Content-Type: text/html;charset=utf-8\r\n"); + log.debug("HTTP_VERSION: {}", HTTP_VERSION); + log.debug("HTTP_STATUS: {}", httpResponse.getStatus()); + log.debug("HTTP_MESSAGE: {}", httpResponse.getMessage()); + log.debug("HTTP_CONTENT_TYPE: {}", httpResponse.getContent_Type()); + log.debug("HTTP_CONTENT_LENGTH: {}", lengthOfBodyContent); + log.debug("HTTP_COOKIES: {}", httpResponse.getCookies()); + + dos.writeBytes(HTTP_VERSION+" "+httpResponse.getStatus()+" "+httpResponse.getMessage()+" "+"\r\n"); + dos.writeBytes("Content-Type: "+httpResponse.getContent_Type()+"\r\n"); dos.writeBytes("Content-Length: " + lengthOfBodyContent + "\r\n"); + if(httpResponse.getStatus().equals(HTTP_STATUS_CODE_302)) { + dos.writeBytes("location: " + HOST+httpResponse.getBody() + "\r\n"); + log.debug("location: {}", HOST+httpResponse.getBody()); + } + + if(httpResponse.getCookies() != null) { + dos.writeBytes("Set-Cookie: " + httpResponse.getCookies() + "\r\n"); + log.debug("cookies: {}", httpResponse.getBody()); + } dos.writeBytes("\r\n"); } catch (IOException e) { log.error(e.getMessage()); @@ -52,4 +80,5 @@ private void responseBody(DataOutputStream dos, byte[] body) { log.error(e.getMessage()); } } -} + +} \ No newline at end of file diff --git a/src/main/java/webserver/WebServer.java b/src/main/java/webserver/WebServer.java index 91f4a0fbc..41fe762ca 100644 --- a/src/main/java/webserver/WebServer.java +++ b/src/main/java/webserver/WebServer.java @@ -5,7 +5,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; - +// public class WebServer { private static final Logger log = LoggerFactory.getLogger(WebServer.class); private static final int DEFAULT_PORT = 8080; diff --git a/src/test/java/service/UserServiceTest.java b/src/test/java/service/UserServiceTest.java new file mode 100644 index 000000000..799e593aa --- /dev/null +++ b/src/test/java/service/UserServiceTest.java @@ -0,0 +1,110 @@ +package service; + +import controller.dto.UserLoginRequestDto; +import db.DataBase; +import controller.dto.UserCreateRequestDto; +import model.User; +import org.junit.BeforeClass; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; + +import static org.junit.Assert.assertEquals; + + +public class UserServiceTest { + + private static UserService userService; + private static final Logger log = LoggerFactory.getLogger(UserServiceTest.class); + /* Default Variables */ + private static String first_userId = "test1"; + private static String first_password = "test1"; + private static String first_name = "test1"; + private static String first_email = "test1@gmail.com"; + private static String second_userId = "test2"; + private static String second_password = "test2"; + private static String second_name = "test2"; + private static String second_email = "test2@gmail.com"; + + + @BeforeClass + public static void setUp() { + userService = new UserService(); + DataBase.addUser(new User(first_userId, first_password, first_name, first_email)); + DataBase.addUser(new User(second_userId, second_password, second_name, second_email)); + } + + @Test + public void create_success_회원가입 () { + //given + String userId = "daun"; + String password = "daunpwd"; + String name = "daun"; + String email = "daun@gmail.com"; + UserCreateRequestDto userCreateRequestDto = new UserCreateRequestDto(userId, password, name, email); + + //when + userService.create(userCreateRequestDto); + + //then + User user = DataBase.findUserById("daun"); + assertEquals(user.getUserId(), userId); + assertEquals(user.getPassword(), password); + assertEquals(user.getName(), name); + assertEquals(user.getEmail(), email); + } + + @Test(expected = RuntimeException.class) + public void create_fail_중복_아이디 () { + //given + String userId = "test1"; + String password = "test1"; + String name = "test1"; + String email = "test1@gmail.com"; + UserCreateRequestDto userCreateRequestDto = new UserCreateRequestDto(userId, password, name, email); + + //when + userService.create(userCreateRequestDto); + + //then + + } + + @Test + public void login_success_로그인 () { + //given + + //when + User user = userService.login(new UserLoginRequestDto(first_userId, first_password)); + //then + assertEquals(user.getUserId(), first_userId); + } + + @Test(expected = RuntimeException.class) + public void login_fail_존재하지_않는_아이디 () { + //given + String NOT_EXIST_USER_ID = "NOT_EXIST_USER_ID"; + //when + User user = userService.login(new UserLoginRequestDto(NOT_EXIST_USER_ID, first_password)); + + //then + } + + @Test(expected = RuntimeException.class) + public void login_fail_비밀번호_오류 () { + //given + String WRONG_PASSWORD = "WRONG_PASSWORD"; + //when + User user = userService.login(new UserLoginRequestDto(first_userId, WRONG_PASSWORD)); + //then + } + + @Test + public void findAllUser() { + List userList = userService.findAllUser(); + userList.forEach(user -> log.debug("{}", user)); + assertEquals(3,userList.size()); + } +} \ No newline at end of file diff --git a/src/test/java/webserver/HttpRequestTest.java b/src/test/java/webserver/HttpRequestTest.java new file mode 100644 index 000000000..d24351efa --- /dev/null +++ b/src/test/java/webserver/HttpRequestTest.java @@ -0,0 +1,17 @@ +package webserver; + +import junit.framework.TestCase; +import org.junit.Test; + +import java.io.*; + +public class HttpRequestTest { + private String testDirectory = "./src/test/resources/"; + + @Test + public void request_GET() throws IOException { + InputStream in = new FileInputStream(new File(testDirectory + "Http_GET.txt")); + //HttpRequest request = new HttpRequest(in); + } + +} \ No newline at end of file diff --git a/src/test/java/webserver/RequestHandlerTest.java b/src/test/java/webserver/RequestHandlerTest.java new file mode 100644 index 000000000..42fe7c635 --- /dev/null +++ b/src/test/java/webserver/RequestHandlerTest.java @@ -0,0 +1,64 @@ +package webserver; + + +import org.apache.http.Header; +import org.apache.http.HttpResponse; +import org.apache.http.NoHttpResponseException; +import org.apache.http.client.HttpClient; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpUriRequest; +import org.apache.http.client.utils.URLEncodedUtils; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.junit.BeforeClass; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; + + +public class RequestHandlerTest { + + private static final String HOST = "http://localhost:8080"; + + private static final Logger log = LoggerFactory.getLogger(RequestHandlerTest.class); + + @BeforeClass + public static void setUp() throws IOException { + CloseableHttpClient client = HttpClients.createDefault(); + HttpPost httpPost = new HttpPost(HOST+"/user/create"); + String body = "userId=test&password=test&name=daun&email=daun@daun.com"; + httpPost.setHeader("Accept", "*/*"); + httpPost.setHeader("Connection", "keep-alive"); + httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); + httpPost.setHeader("Host", "localhost:8080"); + httpPost.setEntity(new StringEntity(body)); + HttpResponse response = client.execute(httpPost); + log.debug("{}", response); + client.close(); + } + + @Test + public void login_success() throws IOException { + CloseableHttpClient client = HttpClients.createDefault(); + HttpPost httpPost = new HttpPost(HOST+"/user/login"); + String body = "userId=test&password=test"; + httpPost.setHeader("Accept", "*/*"); + httpPost.setHeader("Connection", "keep-alive"); + httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); + httpPost.setHeader("Host", "localhost:8080"); + httpPost.setEntity(new StringEntity(body)); + HttpResponse response = client.execute(httpPost); + Header[] headers = response.getAllHeaders(); + log.debug("{}", response); + for(Header header : headers) { + log.debug("{}", header); + } + client.close(); + } + +} \ No newline at end of file diff --git a/src/test/resources/Http_GET.txt b/src/test/resources/Http_GET.txt new file mode 100644 index 000000000..bd2324b9d --- /dev/null +++ b/src/test/resources/Http_GET.txt @@ -0,0 +1,4 @@ +GET /user/create?userId=javajigi&password=password&name=JaeSung HTTP/1.1 +Host: localhost:8080 +Connection: keep-alive +Accept: */* diff --git a/webapp/favicon.ico b/webapp/favicon.ico index 5cd1446a1..66417068d 100644 Binary files a/webapp/favicon.ico and b/webapp/favicon.ico differ diff --git a/webapp/user/form.html b/webapp/user/form.html index 96fe1bd3a..f7a3b5612 100644 --- a/webapp/user/form.html +++ b/webapp/user/form.html @@ -75,7 +75,7 @@
-
+