-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHttpServer.java
201 lines (149 loc) · 6.48 KB
/
HttpServer.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
import java.io.*;
import java.net.*;
import java.util.List;
public class HttpServer {
public static void main(String[] args) {
int port = 8080;
try {
final ServerSocket serverSocket = new ServerSocket(port);
System.err.println("Servidor iniciado na porta : " + port);
while (true) {
final Socket clientSocket = serverSocket.accept();
Thread thread = new Thread(new HandlerServerHttp(clientSocket));
thread.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class HandlerServerHttp implements Runnable {
private final Socket clientSocket;
private static String mensagem = "";
private static String httpVersion = "";
public HandlerServerHttp(Socket clientSocket) {
this.clientSocket = clientSocket;
}
@Override
public void run() {
System.out.println("Nova requisicao!!!");
try (
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));) {
String requestLine = in.readLine();
if (requestLine == null || requestLine.isBlank()) {
sendResponse(HTTPStatus.BAD_REQUEST);
return;
}
System.out.println(requestLine);
String[] requestParts = requestLine.split(" ");
if (requestParts.length < 3) {
sendResponse(HTTPStatus.BAD_REQUEST);
return;
}
String requestHttpMethod = requestParts[0]; // Extraindo o metodo http
String uri = requestParts[1]; // Extraindo a URI
httpVersion = requestParts[2]; // Extraindo a versao http da requisicao do cliente
if(!(httpVersion.equalsIgnoreCase("HTTP/1.0") || httpVersion.equalsIgnoreCase("HTTP/1.1"))){
sendResponse(HTTPStatus.VERSION_NOT_SUPPORTED);
return;
}
System.out.println("Metodo: " + requestHttpMethod + "\nURI: " + uri + "\nVersao HTTP: " + httpVersion);
if (!uri.startsWith("/pessoa")) {
sendResponse(HTTPStatus.BAD_REQUEST);
return;
}
String pessoaId = uri.substring("/pessoa".length());
StringBuilder bodyData = new StringBuilder();
String line;
StringBuilder headerData = new StringBuilder();
//Le e armazena os headers
while ((line = in.readLine()) != null && !line.isEmpty()) {
headerData.append(line).append("\r\n");
}
// Lê e armazena o body da requisicao
while (in.ready()) {
bodyData.append((char) in.read());
}
System.err.println("Headers do cliente:\n" + headerData);
System.err.println("Body do cliente:\n" + bodyData);
switch (requestHttpMethod) {
case "GET" -> handleGetMethod(pessoaId);
case "POST" -> handlePostMethod(bodyData);
case "PUT" -> handlePutMethod(pessoaId, bodyData);
default -> sendResponse(HTTPStatus.METHOD_NOT_ALLOWED);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void sendResponse(HTTPStatus status) throws IOException {
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
StringBuilder responseBuilder = new StringBuilder();
responseBuilder.append(httpVersion).append(" ").append(status.getStatusCode()).append(" ").append(status.getReasonText()).append("\r\n");
responseBuilder.append("Date: ").append(new java.util.Date()).append("\r\n");
responseBuilder.append("Server: ServidorHTTP\r\n");
if (!mensagem.isBlank() && !status.isError()) {
responseBuilder.append("Content-Type: application/json\r\n");
responseBuilder.append("Content-Length: ").append(mensagem.length()).append("\r\n");
}
responseBuilder.append("Connection: close\r\n");
responseBuilder.append("\r\n");
if (!status.equals(HTTPStatus.NO_CONTENT) && !status.isError()) {
responseBuilder.append(mensagem);
}
out.write(responseBuilder.toString());
out.flush();
}
private void handlePutMethod(String pessoaId, StringBuilder bodyData) throws IOException {
//Vai editar os dados de uma pessoa (menos o nome, pois eh o identificador).
try {
String nome = pessoaId.split("/")[1];
PersonService.editarPessoa(nome,bodyData);
sendResponse(HTTPStatus.NO_CONTENT);
}
catch (IOException|StringIndexOutOfBoundsException|ArrayIndexOutOfBoundsException e){
sendResponse(HTTPStatus.BAD_REQUEST);
}
}
private void handlePostMethod(StringBuilder bodyData) throws IOException {
//Vai criar uma pessoa, se uma pessoa com um mesmo nome ja existir, ele retornara um method not allowed.
try {
Person person = new Person(bodyData.toString());
if (PersonService.personExists(person)) {
sendResponse(HTTPStatus.CONFLICT);
return;
}
PersonService.salvarPessoa(person);
mensagem = person.toJSON();
} catch (IOException|StringIndexOutOfBoundsException|ArrayIndexOutOfBoundsException e) {
sendResponse(HTTPStatus.BAD_REQUEST);
return;
}
sendResponse(HTTPStatus.CREATED);
}
private void handleGetMethod(String pessoaId) throws IOException {
//Vai Pegar todos as pessoas do banco
if (pessoaId.length() < 2) {
List<Person> people = FileDatabase.resgatarTodasPessoas();
mensagem = PersonService.fromListToJsonArray(people);
sendResponse(HTTPStatus.OK);
return;
}
//Vai pegar uma pessoa especifica, baseada no nome, se nao achar nenhuma retorna not found
try {
String nome = pessoaId.split("/")[1];
Person person = PersonService.resgatarPessoaPorNome(nome);
mensagem = person.toJSON();
} catch (IOException e) {
sendResponse(HTTPStatus.NOT_FOUND);
return;
}
sendResponse(HTTPStatus.OK);
}
}