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

2주차 미션 / 서버 1조 이윤정 #24

Open
wants to merge 12 commits into
base: main
Choose a base branch
from
7 changes: 5 additions & 2 deletions src/main/java/http/util/IOUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,16 @@
import java.io.IOException;

public class IOUtils {

/**
* @param BufferedReader br
* @param br
* Request Body를 시작하는 시점이어야
* @param contentLength는
* @param contentLength
* Request Header의 Content-Length 값이다.
* @return
* @throws IOException
* BufferedReader의 offset을 body 값 바로 앞에 위치시켜야한다.
*
*/
public static String readData(BufferedReader br, int contentLength) throws IOException {
char[] body = new char[contentLength];
Expand Down
5 changes: 5 additions & 0 deletions src/main/java/model/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,9 @@ public boolean equals(Object o) {
public int hashCode() {
return Objects.hash(getUserId(), getPassword(), getName(), getEmail());
}

@Override
public String toString() {
return getUserId()+" "+getPassword()+" "+getName()+" "+getEmail();
}
}
126 changes: 123 additions & 3 deletions src/main/java/webserver/RequestHandler.java
Original file line number Diff line number Diff line change
@@ -1,40 +1,160 @@
package webserver;

import db.MemoryUserRepository;
import db.Repository;
import model.User;

import java.io.*;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import static http.util.HttpRequestUtils.parseQueryParameter;
import static http.util.IOUtils.readData;

public class RequestHandler implements Runnable{
Socket connection;
private static final Logger log = Logger.getLogger(RequestHandler.class.getName());

private static final String ROOT_URL = "./webapp";
private static final String HOME_URL = "/index.html";
private static final String LOGIN_URL = "/user/login.html";
private static final String LOGIN_FAILED_URL = "/user/login_failed.html";
private static final String USER_LIST_URL = "/user/list.html";
private final Repository repository;
public RequestHandler(Socket connection) {
this.connection = connection;
repository = MemoryUserRepository.getInstance();
}

@Override
public void run() {
log.log(Level.INFO, "New Client Connect! Connected IP : " + connection.getInetAddress() + ", Port : " + connection.getPort());
//log.log(Level.INFO, "New Client Connect! Connected IP : " + connection.getInetAddress() + ", Port : " + connection.getPort());
try (InputStream in = connection.getInputStream(); OutputStream out = connection.getOutputStream()){
BufferedReader br = new BufferedReader(new InputStreamReader(in));
DataOutputStream dos = new DataOutputStream(out);

byte[] body = "Hello World".getBytes();
String startLine = br.readLine();
String[] startLines = startLine.split(" ");
String method = startLines[0];
String url = startLines[1];

int requestContentLength = 0;
String requestBody = "";
Map<String, String> parsedRequestBody = null;
String[] cookies = new String[0];
while (true) {
final String line = br.readLine();
if (line.isEmpty()) {
break;
}
// header info
if (line.startsWith("Content-Length")) {
requestContentLength = Integer.parseInt(line.split(": ")[1]);
}
if (line.startsWith("Cookie")) {
String cookieString = line.split(": ")[1];
cookies = cookieString.split("; ");

}
}
if (requestContentLength!=0) {
requestBody = readData(br, requestContentLength);
parsedRequestBody = parseQueryParameter(requestBody);
}

log.log(Level.INFO, "method: " + method + ", url: " + url);
byte[] body = new byte[0];

if(url.equals("/")) {
body = Files.readAllBytes(Paths.get(ROOT_URL + HOME_URL));
}

if(method.equals("GET") && url.endsWith(".html")) {
body = Files.readAllBytes(Paths.get(ROOT_URL + url));
}

if(method.equals("POST") && url.equals("/user/signup")) {
repository.addUser(new User(parsedRequestBody.get("userId"), parsedRequestBody.get("password"), parsedRequestBody.get("name"), parsedRequestBody.get("email")));
log.log(Level.INFO, "saved " + repository.findUserById(parsedRequestBody.get("userId")).toString());
response302Header(dos, HOME_URL);
}

if(method.equals("POST") && url.equals("/user/login")) {
User foundUser = repository.findUserById(parsedRequestBody.get("userId"));
if(foundUser!=null && foundUser.getPassword().equals(parsedRequestBody.get("password"))) {
response302HeaderWithCookie(dos, ".."+HOME_URL, "logined=true; path=/;");
} else {
response302Header(dos, LOGIN_FAILED_URL);
}
}

if(url.equals("/user/userList")) {
if(!Arrays.asList(cookies).contains("logined=true")) {
response302Header(dos,LOGIN_URL);
return;
}
body = Files.readAllBytes(Paths.get(ROOT_URL + USER_LIST_URL));
}

if (method.equals("GET") && url.endsWith(".css")) {
body = Files.readAllBytes(Paths.get(ROOT_URL + url));
response200HeaderWithCss(dos, body.length);
responseBody(dos, body);
return;
}

response200Header(dos, body.length);
responseBody(dos, body);

} catch (IOException e) {
log.log(Level.SEVERE,e.getMessage());
}
}
private void response200HeaderWithCss(DataOutputStream dos, int lengthOfBodyContent) {
try {
dos.writeBytes("HTTP/1.1 200 OK \r\n");
dos.writeBytes("Content-Type: text/css;charset=utf-8\r\n");
dos.writeBytes("Content-Length: " + lengthOfBodyContent + "\r\n");
dos.writeBytes("\r\n");
dos.flush();
} catch (IOException e) {
log.log(Level.SEVERE, e.getMessage());
}
}
private void response302HeaderWithCookie(DataOutputStream dos, String location, String cookie) {
try {
dos.writeBytes("HTTP/1.1 302 Redirect \r\n");
dos.writeBytes("Location: " + location + "\r\n");
dos.writeBytes("Set-Cookie: " + cookie + "\r\n");
dos.writeBytes("\r\n");
dos.flush();
} catch (IOException e) {
log.log(Level.SEVERE, e.getMessage());
}
}

private void response302Header(DataOutputStream dos, String location) {
try {
dos.writeBytes("HTTP/1.1 302 Redirect \r\n");
dos.writeBytes("Location: " + location + "\r\n");
dos.writeBytes("\r\n");
dos.flush();
} catch (IOException e) {
log.log(Level.SEVERE, e.getMessage());
}
}

private void response200Header(DataOutputStream dos, int lengthOfBodyContent) {
try {
dos.writeBytes("HTTP/1.1 200 OK \r\n");
dos.writeBytes("Content-Type: text/html;charset=utf-8\r\n");
dos.writeBytes("Content-Length: " + lengthOfBodyContent + "\r\n");
dos.writeBytes("\r\n");
dos.flush();
} catch (IOException e) {
log.log(Level.SEVERE, e.getMessage());
}
Expand Down