Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
dc90fb1
В память пишет, из памяти читает
Aug 13, 2024
e641a14
Добавлено тестирование
Aug 13, 2024
1bca695
Вспомогательный HashMap удалён, добавлено кастомное исключение, убран…
Aug 14, 2024
19347c7
Промежуточно
Sep 3, 2024
291715f
Остались тесты
Sep 3, 2024
6eaf507
Добавлены тесты. Вроде бы исправлен код-стайл
Sep 4, 2024
2ef78a2
Добавлены тесты. Вроде бы исправлен код-стайл
Sep 4, 2024
b2f1f46
Добавлены тесты. Вроде бы исправлен код-стайл
Sep 4, 2024
2098562
CodeStyle Check
Sep 4, 2024
62b47f4
CodeStyle Check
Sep 4, 2024
62ccbd1
Удалены импорты
Sep 4, 2024
e1cbe81
Предперенос
Sep 5, 2024
223cf73
Исправления внесены
Sep 5, 2024
feb3cb1
Work in progress. Please Stand by..
Sep 7, 2024
ea1b339
Приключение на 20 минут кончается поиском адаптера для GSON, потому ч…
Sep 7, 2024
8ad0628
Адаптер найден. Работают методы Task - GET и POST
Sep 8, 2024
94a5eb3
Методы Task работают. Необходимо причесать
Sep 8, 2024
95d985d
Добавлен TimeCrossing.
Sep 8, 2024
d596104
Добавлен TimeCrossing.
Sep 8, 2024
db83c6a
Вроде бы готов адаптер для эпиков. Теперь очередь эпик-хэндлера
Sep 8, 2024
b15a772
В инсомнии всё работает. Добавлю тестов завтра. Пожалуйста глянте, вс…
Sep 8, 2024
7891745
CodeStyle
Sep 8, 2024
cc3af2a
CodeStyle
Sep 8, 2024
9b2183c
CodeStyle
Sep 8, 2024
d32e7a6
Merge remote-tracking branch 'origin/sprint_9-solution-http-api' into…
Sep 8, 2024
b724395
CodeStyle
Sep 8, 2024
9da6ff8
CodeStyle
Sep 8, 2024
df8bd48
CodeStyle
Sep 8, 2024
935cc40
CodeStyle
Sep 8, 2024
f069ca8
CodeStyle
Sep 8, 2024
fb95e68
CodeStyle
Sep 8, 2024
4040d64
CodeStyle
Sep 8, 2024
a9d2aae
CodeStyle
Sep 8, 2024
7cfa7f1
Добавлены тесты
Sep 9, 2024
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
9 changes: 9 additions & 0 deletions .idea/libraries/gson_2_8_2.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions csvTaskFile.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
id,type,name,status,description,epic
1,Task,1,NEW,Task1
2,Task,2,NEW,Task2
3,Epic,3,NEW,Epic1
4,SubTask,6,NEW,Sub 1,3
27 changes: 27 additions & 0 deletions java-kanban.iml
Original file line number Diff line number Diff line change
Expand Up @@ -71,5 +71,32 @@
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library" scope="TEST">
<library name="JUnit4">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/junit/junit/4.13.1/junit-4.13.1.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/org/hamcrest/hamcrest-core/1.3/hamcrest-core-1.3.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library" scope="TEST">
<library name="JUnit5.8.1">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/junit/jupiter/junit-jupiter/5.8.1/junit-jupiter-5.8.1.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/org/junit/jupiter/junit-jupiter-api/5.8.1/junit-jupiter-api-5.8.1.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/org/opentest4j/opentest4j/1.2.0/opentest4j-1.2.0.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/org/junit/platform/junit-platform-commons/1.8.1/junit-platform-commons-1.8.1.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/org/apiguardian/apiguardian-api/1.1.2/apiguardian-api-1.1.2.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/org/junit/jupiter/junit-jupiter-params/5.8.1/junit-jupiter-params-5.8.1.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/org/junit/jupiter/junit-jupiter-engine/5.8.1/junit-jupiter-engine-5.8.1.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/org/junit/platform/junit-platform-engine/1.8.1/junit-platform-engine-1.8.1.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="library" name="gson-2.8.2" level="project" />
</component>
</module>
45 changes: 45 additions & 0 deletions src/adapters/EpicAdapter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package adapters;

import com.google.gson.*;
import model.Epic;
import model.Status;

import java.lang.reflect.Type;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class EpicAdapter implements JsonSerializer<Epic>, JsonDeserializer<Epic> {

private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");

@Override
public JsonElement serialize(Epic task, Type typeOfSrc, JsonSerializationContext context) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("id", task.getId());
jsonObject.addProperty("taskName", task.getTaskName());
jsonObject.addProperty("status", task.getStatus().name());
jsonObject.addProperty("content", task.getContent());
jsonObject.addProperty("startTime", task.getStartTime().format(formatter));
jsonObject.addProperty("duration", task.getDuration().toMinutes());
jsonObject.addProperty("epicSubs", task.getEpicSubs().toString());

return jsonObject;
}

@Override
public Epic deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();

Integer id = jsonObject.get("id").getAsInt();
String taskName = jsonObject.get("taskName").getAsString();
Status status = Status.valueOf(jsonObject.get("status").getAsString());
String content = jsonObject.get("content").getAsString();

LocalDateTime startTime = LocalDateTime.parse(jsonObject.get("startTime").getAsString(), formatter);

Duration duration = Duration.ofMinutes(jsonObject.get("duration").getAsLong());

return new Epic(taskName, content, status, id, startTime, duration);
}
}
46 changes: 46 additions & 0 deletions src/adapters/SubTaskAdapter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package adapters;

import com.google.gson.*;
import model.SubTask;
import model.Status;

import java.lang.reflect.Type;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class SubTaskAdapter implements JsonSerializer<SubTask>, JsonDeserializer<SubTask> {

private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");

@Override
public JsonElement serialize(SubTask task, Type typeOfSrc, JsonSerializationContext context) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("id", task.getId());
jsonObject.addProperty("taskName", task.getTaskName());
jsonObject.addProperty("status", task.getStatus().name());
jsonObject.addProperty("content", task.getContent());
jsonObject.addProperty("startTime", task.getStartTime().format(formatter));
jsonObject.addProperty("duration", task.getDuration().toMinutes());
jsonObject.addProperty("masterId", task.getMasterId());

return jsonObject;
}

@Override
public SubTask deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();

Integer id = jsonObject.get("id").getAsInt();
String taskName = jsonObject.get("taskName").getAsString();
Status status = Status.valueOf(jsonObject.get("status").getAsString());
String content = jsonObject.get("content").getAsString();
Integer masterId = jsonObject.get("masterId").getAsInt();

LocalDateTime startTime = LocalDateTime.parse(jsonObject.get("startTime").getAsString(), formatter);

Duration duration = Duration.ofMinutes(jsonObject.get("duration").getAsLong());

return new SubTask(taskName, content, status, masterId, id, startTime, duration);
}
}
46 changes: 46 additions & 0 deletions src/adapters/TaskAdapter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package adapters;

import com.google.gson.*;
import model.Task;
import model.Status;

import java.lang.reflect.Type;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class TaskAdapter implements JsonSerializer<Task>, JsonDeserializer<Task> {

private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");

@Override
public JsonElement serialize(Task task, Type typeOfSrc, JsonSerializationContext context) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("id", task.getId());
jsonObject.addProperty("taskName", task.getTaskName());
jsonObject.addProperty("status", task.getStatus().name());
jsonObject.addProperty("content", task.getContent());

jsonObject.addProperty("startTime", task.getStartTime().format(formatter));

jsonObject.addProperty("duration", task.getDuration().toMinutes());

return jsonObject;
}

@Override
public Task deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();

Integer id = jsonObject.get("id").getAsInt();
String taskName = jsonObject.get("taskName").getAsString();
Status status = Status.valueOf(jsonObject.get("status").getAsString());
String content = jsonObject.get("content").getAsString();

LocalDateTime startTime = LocalDateTime.parse(jsonObject.get("startTime").getAsString(), formatter);

Duration duration = Duration.ofMinutes(jsonObject.get("duration").getAsLong());

return new Task(taskName, content, status, id, startTime, duration);
}
}
93 changes: 93 additions & 0 deletions src/handlers/EpicHandler.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package handlers;

import adapters.EpicAdapter;
import com.google.gson.GsonBuilder;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import manager.CrossingException;
import manager.FileBackedTaskManager;
import model.Epic;

import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class EpicHandler extends TaskHandler implements HttpHandler {


public EpicHandler(FileBackedTaskManager master) {
super(master);
}

@Override
public void get(HttpExchange exchange) throws IOException {
try {
List<Epic> tasks = new ArrayList<>(master.getAllEpics());
String response = gson.toJson(tasks);
sendResponse(exchange, response, 200);
} catch (Exception e) {
e.getMessage();
}

}

@Override
public void post(HttpExchange exchange) throws IOException {
//Запускаем поток чтения тела запроса и создаём из него новый объект task, который отправляем в менеджер.
InputStreamReader isr = new InputStreamReader(exchange.getRequestBody(), StandardCharsets.UTF_8);
Epic task = gson.fromJson(isr, Epic.class);
try {
master.addEpic(task);
String response = "Задача " + task.getId() + " успешно создана";
sendResponse(exchange, response, 201);
} catch (CrossingException e) {
String response = e.getMessage();
sendResponse(exchange, response, 406);
}
}

@Override
public void delete(HttpExchange exchange) throws IOException {
master.eraseEpicHashMap();
String response = "Все задачи удалены";
sendResponse(exchange, response, 200);
}

@Override
public void getId(Integer id, HttpExchange exchange) throws IOException {
try {
Epic task = master.getEpic(id);
String response = gson.toJson(task);
sendResponse(exchange, response, 200);
} catch (Exception e) {
String response = "Такой задачи не существует";
sendResponse(exchange, response, 404);
}
}

@Override
public void postId(Integer id, HttpExchange exchange) throws IOException {
InputStreamReader isr = new InputStreamReader(exchange.getRequestBody(), StandardCharsets.UTF_8);
Epic task = gson.fromJson(isr, Epic.class);
task.setId(id);
master.updateEpic(task);
String response = "Задача " + task.getId() + " успешно обновлена";
sendResponse(exchange, response, 201);
}

@Override
public void deleteId(Integer id, HttpExchange exchange) throws IOException {
master.removeEpic(id);
String response = "Задача " + id + " удалена";
sendResponse(exchange, response, 200);
}

@Override
protected void gsonInitializator() {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Epic.class, new EpicAdapter());
this.gson = gsonBuilder.create();
}
}
54 changes: 54 additions & 0 deletions src/handlers/HistoryHandler.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package handlers;

import com.google.gson.Gson;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import manager.FileBackedTaskManager;
import model.Task;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;


public class HistoryHandler implements HttpHandler {

Gson gson;
FileBackedTaskManager master;


public HistoryHandler(FileBackedTaskManager master) {
this.master = master;
}

@Override
public void handle(HttpExchange exchange) throws IOException {
String method = exchange.getRequestMethod();
if (method.toString().toLowerCase().equals("get")) {
get(exchange);
} else {
String response = "У нас пока нет таких методов";
sendResponse(exchange, response, 406);
}
}

public void get(HttpExchange exchange) throws IOException {
List<Task> tasks = new ArrayList<>(master.getHistory());
String response = tasks.toString();
sendResponse(exchange, response, 200);
}


public void sendResponse(HttpExchange httpExchange, String response, int statusCode) throws IOException {
httpExchange.getResponseHeaders().set("Content-Type", "application/json");
httpExchange.sendResponseHeaders(statusCode, response.getBytes().length);
OutputStream stream = httpExchange.getResponseBody();
stream.write(response.getBytes());
stream.close();
}

protected void gsonInitializator() {
this.gson = new Gson();
}
}
48 changes: 48 additions & 0 deletions src/handlers/PriorityHandler.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package handlers;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import manager.FileBackedTaskManager;
import model.Task;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;


public class PriorityHandler implements HttpHandler {

FileBackedTaskManager master;

public PriorityHandler(FileBackedTaskManager master) {
this.master = master;
}

@Override
public void handle(HttpExchange exchange) throws IOException {
String method = exchange.getRequestMethod();
if (method.toString().toLowerCase().equals("get")) {
get(exchange);
} else {
String response = "У нас пока нет таких методов";
sendResponse(exchange, response, 406);
}
}

public void get(HttpExchange exchange) throws IOException {
List<Task> tasks = new ArrayList<>(master.getPrioritizedTasks());
String response = tasks.toString();
sendResponse(exchange, response, 200);
}


public void sendResponse(HttpExchange httpExchange, String response, int statusCode) throws IOException {
httpExchange.getResponseHeaders().set("Content-Type", "application/json");
httpExchange.sendResponseHeaders(statusCode, response.getBytes().length);
OutputStream stream = httpExchange.getResponseBody();
stream.write(response.getBytes());
stream.close();
}

}
Loading