-
Notifications
You must be signed in to change notification settings - Fork 9
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Добавлен FileBackedTaskManager, тесты и обновлён Main для сохранения …
…и загрузки задач из файла
- Loading branch information
Showing
6 changed files
with
211 additions
and
22 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,25 +1,45 @@ | ||
import tasktracker.manager.InMemoryTaskManager; | ||
import tasktracker.manager.TaskManager; | ||
import tasktracker.manager.FileBackedTaskManager; | ||
import tasktracker.model.Epic; | ||
import tasktracker.model.Subtask; | ||
import tasktracker.model.Task; | ||
import tasktracker.model.TaskStatus; | ||
|
||
import java.io.File; | ||
|
||
public class Main { | ||
public static void main(String[] args) { | ||
TaskManager manager = new InMemoryTaskManager(); | ||
File file = new File("tasks.csv"); | ||
FileBackedTaskManager manager = new FileBackedTaskManager(file); | ||
|
||
// Создаём задачи | ||
Task task1 = new Task("Task 1", "Description 1", manager.generateId(), TaskStatus.NEW); | ||
manager.createTask(task1); | ||
|
||
Task task2 = new Task("Task 2", "Description 2", manager.generateId(), TaskStatus.NEW); | ||
manager.createTask(task2); | ||
|
||
// Создаём эпик | ||
Epic epic1 = new Epic("Epic 1", "Epic Description", manager.generateId(), TaskStatus.NEW); | ||
manager.createEpic(epic1); | ||
|
||
// Добавляем подзадачи к эпику | ||
Subtask subtask1 = new Subtask("Subtask 1", "Subtask Description", manager.generateId(), TaskStatus.NEW, epic1.getId()); | ||
manager.createSubtask(subtask1); | ||
|
||
Task task = new Task("Task 1", "Description 1", manager.generateId(), TaskStatus.NEW); | ||
manager.createTask(task); | ||
Subtask subtask2 = new Subtask("Subtask 2", "Subtask Description", manager.generateId(), TaskStatus.IN_PROGRESS, epic1.getId()); | ||
manager.createSubtask(subtask2); | ||
|
||
Epic epic = new Epic("Epic 1", "Epic Description", manager.generateId(), TaskStatus.NEW); | ||
manager.createEpic(epic); | ||
// Выводим задачи перед сохранением | ||
System.out.println("Tasks before loading: " + manager.getAllTasks()); | ||
System.out.println("Epics before loading: " + manager.getAllEpics()); | ||
System.out.println("Subtasks before loading: " + manager.getAllSubtasks()); | ||
|
||
Subtask subtask = new Subtask("Subtask 1", "Description 1", manager.generateId(), TaskStatus.NEW, epic.getId()); | ||
manager.createSubtask(subtask); | ||
// Загружаем задачи из файла | ||
FileBackedTaskManager loadedManager = FileBackedTaskManager.loadFromFile(file); | ||
|
||
System.out.println("Tasks: " + manager.getAllTasks()); | ||
System.out.println("Epics: " + manager.getAllEpics()); | ||
System.out.println("Subtasks: " + manager.getAllSubtasks()); | ||
// Выводим загруженные данные | ||
System.out.println("Tasks after loading: " + loadedManager.getAllTasks()); | ||
System.out.println("Epics after loading: " + loadedManager.getAllEpics()); | ||
System.out.println("Subtasks after loading: " + loadedManager.getAllSubtasks()); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,148 @@ | ||
package tasktracker.manager; | ||
|
||
import tasktracker.model.Epic; | ||
import tasktracker.model.Subtask; | ||
import tasktracker.model.Task; | ||
import tasktracker.model.TaskStatus; | ||
|
||
import java.io.*; | ||
import java.util.HashMap; | ||
import java.util.Map; | ||
|
||
public class FileBackedTaskManager extends InMemoryTaskManager { | ||
|
||
private final File file; | ||
|
||
public FileBackedTaskManager(File file) { | ||
this.file = file; | ||
} | ||
|
||
// Метод сохранения данных в файл | ||
private void save() { | ||
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) { | ||
writer.write("id,type,name,status,description,epic\n"); // Заголовок CSV | ||
|
||
for (Task task : getAllTasks()) { | ||
writer.write(toString(task) + "\n"); | ||
} | ||
for (Epic epic : getAllEpics()) { | ||
writer.write(toString(epic) + "\n"); | ||
} | ||
for (Subtask subtask : getAllSubtasks()) { | ||
writer.write(toString(subtask) + "\n"); | ||
} | ||
} catch (IOException e) { | ||
throw new ManagerSaveException("Error saving to file", e); | ||
} | ||
} | ||
|
||
// Метод конвертации задачи в строку CSV | ||
private String toString(Task task) { | ||
return String.format("%d,%s,%s,%s,%s,%s", | ||
task.getId(), | ||
task instanceof Epic ? "EPIC" : | ||
task instanceof Subtask ? "SUBTASK" : "TASK", | ||
task.getTitle(), | ||
task.getStatus(), | ||
task.getDescription(), | ||
task instanceof Subtask ? ((Subtask) task).getEpicId() : ""); | ||
} | ||
|
||
// Метод конвертации строки CSV в задачу | ||
private Task fromString(String value) { | ||
String[] fields = value.split(","); | ||
int id = Integer.parseInt(fields[0]); | ||
String type = fields[1]; | ||
String title = fields[2]; | ||
TaskStatus status = TaskStatus.valueOf(fields[3]); | ||
String description = fields[4]; | ||
|
||
if ("EPIC".equals(type)) { | ||
return new Epic(title, description, id, status); | ||
} else if ("SUBTASK".equals(type)) { | ||
int epicId = Integer.parseInt(fields[5]); | ||
return new Subtask(title, description, id, status, epicId); | ||
} else { | ||
return new Task(title, description, id, status); | ||
} | ||
} | ||
|
||
// Метод загрузки менеджера из файла | ||
public static FileBackedTaskManager loadFromFile(File file) { | ||
FileBackedTaskManager manager = new FileBackedTaskManager(file); | ||
Map<Integer, Subtask> subtasks = new HashMap<>(); | ||
|
||
try (BufferedReader reader = new BufferedReader(new FileReader(file))) { | ||
reader.readLine(); // Пропускаем заголовок | ||
String line; | ||
|
||
while ((line = reader.readLine()) != null) { | ||
Task task = manager.fromString(line); | ||
if (task instanceof Epic) { | ||
manager.createEpic((Epic) task); | ||
} else if (task instanceof Subtask) { | ||
subtasks.put(task.getId(), (Subtask) task); | ||
} else { | ||
manager.createTask(task); | ||
} | ||
} | ||
|
||
// Восстановление связи подзадач с эпиками | ||
for (Subtask subtask : subtasks.values()) { | ||
manager.createSubtask(subtask); | ||
Epic epic = manager.getEpic(subtask.getEpicId()); | ||
if (epic != null) { | ||
epic.addSubtaskId(subtask.getId()); | ||
} | ||
} | ||
|
||
} catch (IOException e) { | ||
throw new ManagerSaveException("Error loading from file", e); | ||
} | ||
|
||
return manager; | ||
} | ||
|
||
// Переопределение методов для сохранения после каждой модификации | ||
@Override | ||
public void createTask(Task task) { | ||
super.createTask(task); | ||
save(); | ||
} | ||
|
||
@Override | ||
public void createEpic(Epic epic) { | ||
super.createEpic(epic); | ||
save(); | ||
} | ||
|
||
@Override | ||
public void createSubtask(Subtask subtask) { | ||
super.createSubtask(subtask); | ||
save(); | ||
} | ||
|
||
@Override | ||
public void updateTask(Task task) { | ||
super.updateTask(task); | ||
save(); | ||
} | ||
|
||
@Override | ||
public void deleteTaskById(int id) { | ||
super.deleteTaskById(id); | ||
save(); | ||
} | ||
|
||
@Override | ||
public void deleteEpicById(int id) { | ||
super.deleteEpicById(id); | ||
save(); | ||
} | ||
|
||
@Override | ||
public void deleteSubtaskById(int id) { | ||
super.deleteSubtaskById(id); | ||
save(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
package tasktracker.manager; | ||
|
||
public class ManagerSaveException extends RuntimeException { | ||
public ManagerSaveException(String message, Throwable cause) { | ||
super(message, cause); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,17 +1,12 @@ | ||
package tasktracker.utils; | ||
|
||
import tasktracker.manager.HistoryManager; | ||
import tasktracker.manager.InMemoryHistoryManager; | ||
import tasktracker.manager.InMemoryTaskManager; | ||
import tasktracker.manager.FileBackedTaskManager; | ||
import tasktracker.manager.TaskManager; | ||
|
||
import java.io.File; | ||
|
||
public class Managers { | ||
public static TaskManager getDefault() { | ||
return new InMemoryTaskManager(); | ||
} | ||
|
||
public static HistoryManager getDefaultHistory() { | ||
return new InMemoryHistoryManager(); | ||
return new FileBackedTaskManager(new File("tasks.csv")); | ||
} | ||
} | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
import org.junit.jupiter.api.Test; | ||
import tasktracker.manager.FileBackedTaskManager; | ||
|
||
import java.io.File; | ||
|
||
import static org.junit.jupiter.api.Assertions.*; | ||
|
||
public class FileBackedTaskManagerTest { | ||
|
||
@Test | ||
public void shouldLoadFromEmptyFile() { | ||
File file = new File("empty_tasks.csv"); | ||
FileBackedTaskManager loadedManager = FileBackedTaskManager.loadFromFile(file); | ||
|
||
assertTrue(loadedManager.getAllTasks().isEmpty(), "Tasks list should be empty"); | ||
assertTrue(loadedManager.getAllEpics().isEmpty(), "Epics list should be empty"); | ||
assertTrue(loadedManager.getAllSubtasks().isEmpty(), "Subtasks list should be empty"); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -34,4 +34,4 @@ public void getHistoryTest() { | |
public void testInitialization() { | ||
assertNotNull(taskManager); | ||
} | ||
} | ||
} |