Skip to content

Commit b14c4b9

Browse files
authored
Merge pull request #4 from 1EVILGUN1/develop
Java sprint 9 v1.0
2 parents 248758c + cbc2767 commit b14c4b9

File tree

11 files changed

+344
-2
lines changed

11 files changed

+344
-2
lines changed

.idea/libraries/gson_2_11_0.xml

Lines changed: 9 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

java-kanban.iml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,5 +42,6 @@
4242
<SOURCES />
4343
</library>
4444
</orderEntry>
45+
<orderEntry type="library" name="gson-2.11.0" level="application" />
4546
</component>
4647
</module>

resources/task.csv

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,4 @@
11
id,type,name,status,description,epic
2+
1,TASK,Дом,NEW,Убраться в кухни и ванной,2024-06-19T20:18:39.706859,2024-06-19T20:58:39.706859
3+
2,TASK,Работа,IN_PROGRESS,Сделать куча рутины и пойти домой:),2024-06-20T20:18:39.719817,2024-06-20T21:08:39.719817
24

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package ru.yandex.javacource.golotin.schedule.server;
2+
3+
public enum Endpoint {
4+
GET_TASKS,
5+
GET_BY_ID,
6+
GET_EPICS_ID_SUBTASKS,
7+
GET_SUBTASKS,
8+
GET_HISTORY,
9+
GET_PRIORITIZED,
10+
11+
12+
POST,
13+
14+
15+
DELETE_BY_ID,
16+
17+
18+
UNKNOWN
19+
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package ru.yandex.javacource.golotin.schedule.server;
2+
3+
public class EndpointHandler {
4+
public Endpoint getEndpoint(String requestPath, String requestMethod) {
5+
if (requestPath.equals("/tasks") && requestMethod.equals("GET")) {
6+
return Endpoint.GET_TASKS;
7+
} else if (requestPath.equals("/tasks") && requestMethod.equals("POST")) {
8+
return Endpoint.POST;
9+
} else if (requestPath.equals("/tasks/" + requestPath.split("/")[2]) && requestMethod.equals("GET")) {
10+
return Endpoint.GET_BY_ID;
11+
} else if (requestPath.equals("/tasks/" + requestPath.split("/")[2]) && requestMethod.equals("DELETE")) {
12+
return Endpoint.DELETE_BY_ID;
13+
} else if (requestPath.equals("/epics") && requestMethod.equals("GET")) {
14+
return Endpoint.GET_TASKS;
15+
} else if (requestPath.equals("/epics") && requestMethod.equals("POST")) {
16+
return Endpoint.POST;
17+
} else if (requestPath.equals("epics/" + requestPath.split("/")[2]) && requestMethod.equals("GET")) {
18+
return Endpoint.GET_BY_ID;
19+
} else if (requestPath.equals("/epics/" + requestPath.split("/")[2]) && requestMethod.equals("DELETE")) {
20+
return Endpoint.DELETE_BY_ID;
21+
} else if (requestPath.equals("/epics/" + requestPath.split("/")[2] + "/subtasks") && requestMethod.equals("GET")) {
22+
return Endpoint.GET_EPICS_ID_SUBTASKS;
23+
} else if (requestPath.equals("/subtasks") && requestMethod.equals("GET")) {
24+
return Endpoint.GET_SUBTASKS;
25+
} else if (requestPath.equals("/subtasks") && requestMethod.equals("POST")) {
26+
return Endpoint.POST;
27+
} else if (requestPath.equals("/subtasks/" + requestPath.split("/")[2]) && requestMethod.equals("GET")) {
28+
return Endpoint.GET_BY_ID;
29+
} else if (requestPath.equals("subtasks/" + requestPath.split("/")[2]) && requestMethod.equals("DELETE")) {
30+
return Endpoint.DELETE_BY_ID;
31+
} else if (requestPath.endsWith("history") && requestMethod.equals("GET")) {
32+
return Endpoint.GET_HISTORY;
33+
} else if (requestPath.endsWith("prioritized") && requestMethod.equals("GET")) {
34+
return Endpoint.GET_PRIORITIZED;
35+
} else {
36+
return Endpoint.UNKNOWN;
37+
}
38+
}
39+
}
Lines changed: 201 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,201 @@
1+
package ru.yandex.javacource.golotin.schedule.server;
2+
3+
import com.google.gson.*;
4+
import com.sun.net.httpserver.HttpExchange;
5+
import ru.yandex.javacource.golotin.schedule.exception.ManagerSaveException;
6+
import ru.yandex.javacource.golotin.schedule.exception.NotFoundException;
7+
import ru.yandex.javacource.golotin.schedule.model.*;
8+
import ru.yandex.javacource.golotin.schedule.service.TaskManager;
9+
10+
import java.io.IOException;
11+
import java.io.InputStream;
12+
import java.nio.charset.StandardCharsets;
13+
14+
public class HttpHandler implements com.sun.net.httpserver.HttpHandler {
15+
TaskManager manager;
16+
TaskHandler taskHandler;
17+
EndpointHandler endpointHandler;
18+
public HttpHandler(TaskManager manager) {
19+
this.manager = manager;
20+
this.taskHandler = new TaskHandler();
21+
this.endpointHandler = new EndpointHandler();
22+
}
23+
24+
@Override
25+
public void handle(HttpExchange h) throws IOException {
26+
GsonBuilder gsonBuilder = new GsonBuilder();
27+
gsonBuilder.setPrettyPrinting();
28+
Gson gson = gsonBuilder.create();
29+
Endpoint endpoint = endpointHandler.getEndpoint(h.getRequestURI().getPath(), h.getRequestMethod());
30+
final String path = h.getRequestURI().getPath();
31+
switch (endpoint) {
32+
case GET_TASKS:
33+
if (path.equals("/tasks")) {
34+
sendText(h, gson.toJson(manager.getTasks().toString()));
35+
break;
36+
}else if(path.equals("/epics")) {
37+
sendText(h, gson.toJson(manager.getEpics().toString()));
38+
break;
39+
}
40+
case GET_BY_ID:
41+
try {
42+
int id = Integer.parseInt(h.getRequestURI().getPath().split("/")[2]);
43+
if(path.equals("/tasks/"+ id)){
44+
sendText(h, gson.toJson(manager.getTask(id).toString()));
45+
break;
46+
}else if(path.equals("/epics/"+ id)){
47+
sendText(h, gson.toJson(manager.getEpic(id).toString()));
48+
break;
49+
}else if(path.equals("/subtasks/"+ id)){
50+
sendText(h, gson.toJson(manager.getSubtask(id).toString()));
51+
break;
52+
}
53+
} catch (NotFoundException e) {
54+
sendNotFound(h, "Данной задачи не существует по id: " + h.getRequestURI().getPath().split("/")[2]);
55+
break;
56+
}
57+
case GET_EPICS_ID_SUBTASKS:
58+
try {
59+
sendText(h, gson.toJson(manager.getEpicSubtasks(Integer.parseInt(h.getRequestURI().getPath().split("/")[2])).toString()));
60+
break;
61+
} catch (NotFoundException e) {
62+
sendNotFound(h, "Данного эпика не существует по id: " + e.getMessage());
63+
break;
64+
}
65+
case GET_HISTORY:
66+
sendText(h, gson.toJson(manager.getHistory().toString()));
67+
break;
68+
case GET_PRIORITIZED:
69+
sendText(h, gson.toJson(manager.getPrioritizedTasks().toString()));
70+
break;
71+
case POST:
72+
convertTask(h);
73+
break;
74+
case DELETE_BY_ID:
75+
try {
76+
int id = Integer.parseInt(h.getRequestURI().getPath().split("/")[2]);
77+
if(path.equals("/tasks/"+id)) {
78+
manager.deleteTask(id);
79+
sendText(h,"");
80+
break;
81+
} else if(path.equals("/epics/"+id)) {
82+
manager.deleteEpic(id);
83+
sendText(h,"");
84+
break;
85+
}else if(path.equals("/subtasks/"+id)) {
86+
manager.deleteSubtask(id);
87+
sendText(h,"");
88+
break;
89+
}
90+
} catch (NotFoundException e) {
91+
sendNotFound(h, "Данной задачи не существует по id: " + e.getMessage());
92+
break;
93+
}
94+
default:
95+
errorServer(h);
96+
break;
97+
}
98+
}
99+
100+
protected void sendText(HttpExchange h, String text) throws IOException {
101+
try (h) {
102+
byte[] resp = text.getBytes(StandardCharsets.UTF_8);
103+
h.getResponseHeaders().add("Content-Type", "application/json;charset=utf-8");
104+
h.sendResponseHeaders(200, resp.length);
105+
h.getResponseBody().write(resp);
106+
}
107+
}
108+
109+
protected void sendNotFound(HttpExchange h, String text) throws IOException {
110+
try (h) {
111+
byte[] resp = text.getBytes(StandardCharsets.UTF_8);
112+
h.getResponseHeaders().add("Content-Type", "application/json;charset=utf-8");
113+
h.sendResponseHeaders(404, resp.length);
114+
h.getResponseBody().write(resp);
115+
}
116+
}
117+
118+
protected void updateText(HttpExchange h) throws IOException {
119+
try (h) {
120+
h.getResponseHeaders().add("Content-Type", "application/json;charset=utf-8");
121+
h.sendResponseHeaders(201, 0);
122+
}
123+
}
124+
protected void errorServer(HttpExchange h) throws IOException {
125+
try (h) {
126+
h.getResponseHeaders().add("Content-Type", "application/json;charset=utf-8");
127+
h.sendResponseHeaders(500, 0);
128+
}
129+
}
130+
131+
protected void sendHasInteractions(HttpExchange h, String text) throws IOException {
132+
try (h) {
133+
byte[] resp = text.getBytes(StandardCharsets.UTF_8);
134+
h.getResponseHeaders().add("Content-Type", "application/json;charset=utf-8");
135+
h.sendResponseHeaders(406, resp.length);
136+
h.getResponseBody().write(resp);
137+
}
138+
}
139+
140+
141+
private void convertTask(HttpExchange h) throws IOException {
142+
InputStream inputStream = h.getRequestBody();
143+
final String path = h.getRequestURI().getPath();
144+
final String[] body = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8).split(",");
145+
Task task = taskHandler.taskFromString(body);
146+
if (path.equals("/tasks")) {
147+
if (body[0].split("=")[0].equals("id")) {
148+
try {
149+
manager.updateTask(task);
150+
updateText(h);
151+
} catch (ManagerSaveException e) {
152+
sendHasInteractions(h, e.getMessage());
153+
}
154+
} else {
155+
try {
156+
manager.createTask(task);
157+
updateText(h);
158+
} catch (ManagerSaveException e) {
159+
sendHasInteractions(h, e.getMessage());
160+
}
161+
}
162+
}
163+
if (path.equals("/epics")) {
164+
if (body[0].split("=")[0].equals("id")) {
165+
int taskId = Integer.parseInt(body[0].split("=")[1]);
166+
try {
167+
manager.updateEpic(new Epic(task.getId(), task.getName(), task.getDescription(), task.getStatus(), task.getStartTime(), task.getDuration()));
168+
updateText(h);
169+
} catch (ManagerSaveException e) {
170+
sendHasInteractions(h, e.getMessage());
171+
}
172+
} else {
173+
try {
174+
manager.createEpic(new Epic(task.getName(), task.getStatus(), task.getDescription(), task.getStartTime(), task.getDuration()));
175+
updateText(h);
176+
} catch (ManagerSaveException e) {
177+
sendHasInteractions(h, e.getMessage());
178+
}
179+
}
180+
}
181+
if (path.equals("/subtasks")) {
182+
final int epicId = Integer.parseInt(body[6].split("=")[1]);
183+
if (body[0].split("=")[0].equals("id")) {
184+
int taskId = Integer.parseInt(body[0].split("=")[1]);
185+
try {
186+
manager.updateSubtask(new Subtask(task.getId(), task.getName(), task.getDescription(), task.getStatus(), task.getStartTime(), task.getDuration(), epicId));
187+
updateText(h);
188+
} catch (ManagerSaveException e) {
189+
sendHasInteractions(h, e.getMessage());
190+
}
191+
} else {
192+
try {
193+
manager.createSubtask(new Subtask(task.getName(), task.getStatus(), task.getDescription(), task.getStartTime(), task.getDuration(), epicId));
194+
updateText(h);
195+
} catch (ManagerSaveException e) {
196+
sendHasInteractions(h, e.getMessage());
197+
}
198+
}
199+
}
200+
}
201+
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package ru.yandex.javacource.golotin.schedule.server;
2+
import com.sun.net.httpserver.HttpServer;
3+
import ru.yandex.javacource.golotin.schedule.model.Status;
4+
import ru.yandex.javacource.golotin.schedule.model.Task;
5+
import ru.yandex.javacource.golotin.schedule.service.Manager;
6+
import ru.yandex.javacource.golotin.schedule.service.TaskManager;
7+
8+
import java.io.IOException;
9+
import java.net.InetSocketAddress;
10+
import java.time.LocalDateTime;
11+
12+
public class HttpTaskServer {
13+
private static final int PORT = 8080;
14+
public static void main(String[] args) throws IOException {
15+
TaskManager taskManager = Manager.getDefault();
16+
17+
taskManager.createTask(new Task("Дом", Status.NEW, "Убраться в кухни и ванной", LocalDateTime.now(),40));
18+
taskManager.createTask(new Task("Работа", Status.IN_PROGRESS, "Сделать куча рутины и пойти домой:)",LocalDateTime.now().plusDays(1),50));
19+
20+
21+
22+
HttpHandler httpHandler = new HttpHandler(taskManager);
23+
24+
HttpServer server = HttpServer.create(new InetSocketAddress(PORT), 0);
25+
server.createContext("/tasks",httpHandler);
26+
server.createContext("/epics",httpHandler);
27+
server.createContext("/subtasks", httpHandler);
28+
server.createContext("/history", httpHandler);
29+
server.createContext("/prioritized", httpHandler);
30+
server.start();
31+
System.out.println("HTTP-сервер запущен на " + PORT + " порту!");
32+
}
33+
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package ru.yandex.javacource.golotin.schedule.server;
2+
3+
import com.sun.net.httpserver.HttpExchange;
4+
import ru.yandex.javacource.golotin.schedule.model.Status;
5+
import ru.yandex.javacource.golotin.schedule.model.Task;
6+
7+
import java.io.IOException;
8+
import java.time.Duration;
9+
import java.time.LocalDateTime;
10+
11+
public class TaskHandler {
12+
public Task taskFromString(String[] body){
13+
if (body[0].split("=")[0].equals("id")) {
14+
int taskId = Integer.parseInt(body[0].split("=")[1]);
15+
final String name = body[1].split("=")[1];
16+
final String description = body[2].split("=")[1];
17+
final Status status = Status.valueOf(body[3].split("=")[1]);
18+
final LocalDateTime startTime = LocalDateTime.parse(body[4].split("=")[1]);
19+
final LocalDateTime endTime = LocalDateTime.parse(body[5].split("=")[1].replaceAll("}\"", "").trim());
20+
final Duration duration = Duration.between(startTime, endTime);
21+
return new Task(taskId, name, description, status, startTime, duration.toMinutesPart());
22+
} else {
23+
final String name = body[0].split("=")[1];
24+
final String description = body[1].split("=")[1];
25+
final Status status = Status.valueOf(body[2].split("=")[1]);
26+
final LocalDateTime startTime = LocalDateTime.parse(body[3].split("=")[1]);
27+
final LocalDateTime endTime = LocalDateTime.parse(body[4].split("=")[1].replaceAll("}\"", "").trim());
28+
final Duration duration = Duration.between(startTime, endTime);
29+
return new Task(name, status, description, startTime, duration.toMinutesPart());
30+
}
31+
}
32+
33+
}

src/ru/yandex/javacource/golotin/schedule/service/FileBackedTaskManager.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ public static Task taskFromString(String value) {
144144
return new Task(id, name, description, status, startTime, duration.toMinutesPart());
145145
}
146146
if (type == TaskType.SUBTASK) {
147-
final int epicId = Integer.parseInt(values[5]);
147+
final int epicId = Integer.parseInt(values[7]);
148148
return new Subtask(id, name, description, status, startTime, duration.toMinutesPart(), epicId);
149149
}
150150

src/ru/yandex/javacource/golotin/schedule/service/InMemoryTaskManager.java

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,10 @@ public List<Epic> getEpics() {
161161

162162
@Override
163163
public List<Subtask> getEpicSubtasks(int epicId) {// получаем список Epic с Subtasks
164-
Epic epic = epics.get(epicId);
164+
final Epic epic = epics.get(epicId);
165+
if (epic == null) {
166+
throw new NotFoundException("Задача с ид=" + epicId);
167+
}
165168
updateEpic(epicId);
166169
return epic.getSubtaskIds().stream().map(subtasks::get).collect(Collectors.toList());
167170
}
@@ -283,6 +286,7 @@ private void addPriorityTask(Task task) {
283286
prioritizedTasks.add(task);
284287
}
285288

289+
@Override
286290
public List<Task> getPrioritizedTasks() {
287291
return new ArrayList<>(prioritizedTasks);
288292
}

0 commit comments

Comments
 (0)