Merge pull request #79 from schrom01/feature_updaeTaskListViewOnUpdate_M3

update tasks with subscription from JsonTaskList
This commit is contained in:
giavaphi 2022-12-09 14:18:56 +01:00 committed by GitHub Enterprise
commit 035f5d7fcd
10 changed files with 70 additions and 34 deletions

View File

@ -3,6 +3,7 @@ package ch.zhaw.gartenverwaltung;
import ch.zhaw.gartenverwaltung.bootstrap.AppLoader; import ch.zhaw.gartenverwaltung.bootstrap.AppLoader;
import ch.zhaw.gartenverwaltung.bootstrap.Inject; import ch.zhaw.gartenverwaltung.bootstrap.Inject;
import ch.zhaw.gartenverwaltung.io.PlantList; import ch.zhaw.gartenverwaltung.io.PlantList;
import ch.zhaw.gartenverwaltung.io.TaskList;
import ch.zhaw.gartenverwaltung.models.Garden; import ch.zhaw.gartenverwaltung.models.Garden;
import ch.zhaw.gartenverwaltung.io.HardinessZoneNotSetException; import ch.zhaw.gartenverwaltung.io.HardinessZoneNotSetException;
import ch.zhaw.gartenverwaltung.models.GardenSchedule; import ch.zhaw.gartenverwaltung.models.GardenSchedule;
@ -128,7 +129,14 @@ public class CropDetailController {
} }
area_label.setText(String.valueOf(crop.getArea())); area_label.setText(String.valueOf(crop.getArea()));
setTaskListProperty(crop); initializeTaskListProperty(crop);
TaskList.TaskListObserver taskListObserver = newTaskList -> {
taskListProperty.clear();
taskListProperty.addAll(gardenSchedule.getTaskListForCrop(crop.getCropId().get()));
};
gardenSchedule.setTaskListObserver(taskListObserver);
taskList_listView.itemsProperty().bind(taskListProperty); taskList_listView.itemsProperty().bind(taskListProperty);
pestListProperty.addAll(plant.pests()); pestListProperty.addAll(plant.pests());
@ -185,10 +193,10 @@ public class CropDetailController {
} }
/** /**
* update task list * initialize task list
* @param crop {@link Crop} that is selected * @param crop {@link Crop} that is selected
*/ */
private void setTaskListProperty(Crop crop) { private void initializeTaskListProperty(Crop crop) {
crop.getCropId().ifPresent(id -> { crop.getCropId().ifPresent(id -> {
List<Task> taskList; List<Task> taskList;
try { try {
@ -326,13 +334,15 @@ public class CropDetailController {
if (newTask) { if (newTask) {
try { try {
gardenSchedule.addTask(task); gardenSchedule.addTask(task);
setTaskListProperty(this.crop);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} else { } else {
//ToDo method to edit task try {
setTaskListProperty(this.crop); gardenSchedule.addTask(givenTask.updateTask(task));
} catch (IOException e) {
throw new RuntimeException(e);
}
} }
}); });
} }
@ -387,7 +397,7 @@ public class CropDetailController {
if (buttonType == ButtonType.OK) { if (buttonType == ButtonType.OK) {
try { try {
gardenSchedule.removeTask(task); gardenSchedule.removeTask(task);
setTaskListProperty(this.crop); //setTaskListProperty(this.crop);
} catch (IOException e) { } catch (IOException e) {
// TODO: Show error alert // TODO: Show error alert
LOG.log(Level.SEVERE, "Could not remove crop.", e); LOG.log(Level.SEVERE, "Could not remove crop.", e);

View File

@ -22,13 +22,14 @@ public class Main extends Application {
AppLoader appLoader = new AppLoader(); AppLoader appLoader = new AppLoader();
backgroundTasks = new BackgroundTasks((TaskList) appLoader.getAppDependency(TaskList.class),(CropList) appLoader.getAppDependency(CropList.class), (PlantList) appLoader.getAppDependency(PlantList.class)); backgroundTasks = new BackgroundTasks((TaskList) appLoader.getAppDependency(TaskList.class),(CropList) appLoader.getAppDependency(CropList.class), (PlantList) appLoader.getAppDependency(PlantList.class));
// TODO reduce period
backGroundTaskTimer.scheduleAtFixedRate(backgroundTasks, 0, 1000);
appLoader.loadSceneToStage("MainFXML.fxml", stage); appLoader.loadSceneToStage("MainFXML.fxml", stage);
stage.setTitle("Gartenverwaltung"); stage.setTitle("Gartenverwaltung");
stage.show(); stage.show();
backGroundTaskTimer.scheduleAtFixedRate(backgroundTasks, 0, 60000);
} }
@Override @Override

View File

@ -32,7 +32,6 @@ import java.util.logging.Logger;
*/ */
public class MyScheduleController { public class MyScheduleController {
private static final Logger LOG = Logger.getLogger(MyScheduleController.class.getName()); private static final Logger LOG = Logger.getLogger(MyScheduleController.class.getName());
private final ListProperty<List<Task>> taskListProperty = new SimpleListProperty<>(FXCollections.observableArrayList());
private Crop selectedCrop = null; private Crop selectedCrop = null;
@ -58,14 +57,10 @@ public class MyScheduleController {
setCellFactoryCropListView(); setCellFactoryCropListView();
setCellFactoryTaskListView(); setCellFactoryTaskListView();
scheduledPlants_listview.itemsProperty().bind(garden.getPlantedCrops()); scheduledPlants_listview.itemsProperty().bind(garden.getPlantedCrops());
ListProperty<List<Task>> taskListProperty = gardenSchedule.getWeeklyTaskListProperty();
week_listView.itemsProperty().bind(taskListProperty); week_listView.itemsProperty().bind(taskListProperty);
lookForSelectedListEntries(); lookForSelectedListEntries();
information_label.setText(""); information_label.setText("");
try {
loadTaskList();
} catch (IOException e) {
e.printStackTrace();
}
} }
/** /**
@ -117,8 +112,8 @@ public class MyScheduleController {
super.updateItem(taskList, empty); super.updateItem(taskList, empty);
if (empty || taskList == null) { if (empty || taskList == null) {
setGraphic(null);
setText(null); setText(null);
setGraphic(null);
} else { } else {
setText(""); setText("");
setGraphic(weekTaskVBox(taskList, this.getIndex())); setGraphic(weekTaskVBox(taskList, this.getIndex()));
@ -134,12 +129,12 @@ public class MyScheduleController {
private void loadTaskList() throws IOException { private void loadTaskList() throws IOException {
List<List<Task>> taskLists; List<List<Task>> taskLists;
if (selectedCrop != null) { if (selectedCrop != null) {
taskLists = gardenSchedule.getTasksUpcomingWeekForCrop(selectedCrop.getCropId().get()); gardenSchedule.getTasksUpcomingWeekForCrop(selectedCrop.getCropId().get());
} else { } else {
taskLists = gardenSchedule.getTasksUpcomingWeek(); gardenSchedule.getTasksUpcomingWeek();
} }
taskListProperty.clear(); //taskListProperty.clear();
taskListProperty.addAll(taskLists); //taskListProperty.addAll(taskLists);
} }
/** /**

View File

@ -59,7 +59,7 @@ public class TaskFormularController implements Initializable {
*/ */
public Task returnResult(Crop crop) { public Task returnResult(Crop crop) {
int interval = 0; int interval = 0;
if (!(interval_field.getText().isEmpty() || interval_field.getText().equals(""))) { if (interval_field.getText() != null && !(interval_field.getText().isEmpty() || interval_field.getText().equals(""))) {
interval = Integer.parseInt(interval_field.getText()); interval = Integer.parseInt(interval_field.getText());
} }
Task task = new Task(taskName_field.getText(), description_area.getText(), Task task = new Task(taskName_field.getText(), description_area.getText(),
@ -159,7 +159,7 @@ public class TaskFormularController implements Initializable {
*/ */
public void initSaveButton(Button button) { public void initSaveButton(Button button) {
interval_field.textProperty().addListener((observable, oldValue, newValue) -> { interval_field.textProperty().addListener((observable, oldValue, newValue) -> {
if (!newValue.matches("\\d*")) { if (newValue != null && !newValue.matches("\\d*")) {
interval_field.setText(newValue.replaceAll("[^\\d]", "")); interval_field.setText(newValue.replaceAll("[^\\d]", ""));
} }
}); });

View File

@ -43,7 +43,8 @@ public class WeatherGradenTaskPlanner {
private void getSevereWeatherEvents() throws IOException { private void getSevereWeatherEvents() throws IOException {
SevereWeather actualWeather = weatherService.causeSevereWeather(1); SevereWeather actualWeather = weatherService.causeSevereWeather(1);
if (SevereWeather.HAIL.equals(actualWeather)) { if (SevereWeather.HAIL.equals(actualWeather)) {
createPreHailTask(); //ToDo creates hail task all 3 seconds, pls fix
//createPreHailTask();
} else if (SevereWeather.FROST.equals(actualWeather)) { } else if (SevereWeather.FROST.equals(actualWeather)) {
createPreFrostTask(); createPreFrostTask();
} else if (SevereWeather.SNOW.equals(actualWeather)) { } else if (SevereWeather.SNOW.equals(actualWeather)) {

View File

@ -67,7 +67,7 @@ public class JsonTaskList implements TaskList {
* @see TaskList#getTaskList(LocalDate, LocalDate) * @see TaskList#getTaskList(LocalDate, LocalDate)
*/ */
@Override @Override
public List<Task> getTaskList(LocalDate start, LocalDate end) throws IOException{ public synchronized List<Task> getTaskList(LocalDate start, LocalDate end) throws IOException{
if(taskMap.isEmpty()) { if(taskMap.isEmpty()) {
loadTaskListFromFile(); loadTaskListFromFile();
} }
@ -80,7 +80,7 @@ public class JsonTaskList implements TaskList {
* @return List of Tasks for given Crop * @return List of Tasks for given Crop
*/ */
@Override @Override
public List<Task> getTaskForCrop(long cropId) throws IOException { public synchronized List<Task> getTaskForCrop(long cropId) throws IOException {
if(taskMap.isEmpty()) { if(taskMap.isEmpty()) {
loadTaskListFromFile(); loadTaskListFromFile();
} }
@ -111,7 +111,7 @@ public class JsonTaskList implements TaskList {
* @see TaskList#saveTask(Task) * @see TaskList#saveTask(Task)
*/ */
@Override @Override
public void saveTask(Task task) throws IOException { public synchronized void saveTask(Task task) throws IOException {
if(taskMap.isEmpty()) { if(taskMap.isEmpty()) {
loadTaskListFromFile(); loadTaskListFromFile();
} }
@ -154,7 +154,7 @@ public class JsonTaskList implements TaskList {
/** /**
* Calls the change handler method on all registered observers. * Calls the change handler method on all registered observers.
*/ */
private void notifySubscribers() { private void notifySubscribers() throws IOException {
for (TaskListObserver subscriber : subscribers) { for (TaskListObserver subscriber : subscribers) {
subscriber.onChange(taskMap.values().stream().toList()); subscriber.onChange(taskMap.values().stream().toList());
} }

View File

@ -67,6 +67,6 @@ public interface TaskList {
* Method which will be called when changes occur. * Method which will be called when changes occur.
* @param newTaskList The new values * @param newTaskList The new values
*/ */
void onChange(List<Task> newTaskList); void onChange(List<Task> newTaskList) throws IOException;
} }
} }

View File

@ -3,6 +3,10 @@ package ch.zhaw.gartenverwaltung.models;
import ch.zhaw.gartenverwaltung.Settings; import ch.zhaw.gartenverwaltung.Settings;
import ch.zhaw.gartenverwaltung.io.*; import ch.zhaw.gartenverwaltung.io.*;
import ch.zhaw.gartenverwaltung.types.*; import ch.zhaw.gartenverwaltung.types.*;
import javafx.application.Platform;
import javafx.beans.property.ListProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.collections.FXCollections;
import java.io.IOException; import java.io.IOException;
import java.time.LocalDate; import java.time.LocalDate;
@ -20,13 +24,36 @@ public class GardenSchedule {
*/ */
static final Comparator<Task> sortByStartDate = Comparator.comparing(Task::getStartDate); static final Comparator<Task> sortByStartDate = Comparator.comparing(Task::getStartDate);
static final Comparator<Task> sortByNextExecution = Comparator.comparing(Task::getNextExecution); static final Comparator<Task> sortByNextExecution = Comparator.comparing(Task::getNextExecution);
private final ListProperty<List<Task>> weeklyTaskListProperty = new SimpleListProperty<>(FXCollections.observableArrayList());
/** /**
* Constructor to create Database Objects. * Constructor to create Database Objects.
*/ */
public GardenSchedule(TaskList taskList, PlantList plantList) { public GardenSchedule(TaskList taskList, PlantList plantList) throws IOException {
this.taskList = taskList; this.taskList = taskList;
this.plantList = plantList; this.plantList = plantList;
TaskList.TaskListObserver taskListObserver = newTaskList -> {
Platform.runLater(() -> {
try {
getTasksUpcomingWeek();
} catch (IOException e) {
throw new RuntimeException(e);
}
});
};
setTaskListObserver(taskListObserver);
}
public ListProperty<List<Task>> getWeeklyTaskListProperty() {
return weeklyTaskListProperty;
}
/**
* subscribe task list observer to get notifications
* @param observer the task list which will be ovserved
*/
public void setTaskListObserver(TaskList.TaskListObserver observer) {
taskList.subscribe(observer);
} }
/** /**
@ -163,18 +190,20 @@ public class GardenSchedule {
} }
}); });
} }
weeklyTaskListProperty.clear();
weeklyTaskListProperty.addAll(dayTaskList);
return dayTaskList; return dayTaskList;
} }
/** /**
* Method to get an List of 7 Tasklists for the next 7 days. (Filtered Index 0 is Tasklist for Today. * Method to get an List of 7 Tasklists for the next 7 days. (Filtered Index 0 is Tasklist for Today.
* @return List with length 7 (List<List<Task>>)
* @throws IOException If the database cannot be accessed * @throws IOException If the database cannot be accessed
*/ */
public List<List<Task>> getTasksUpcomingWeekForCrop(Long cropId) throws IOException { public void getTasksUpcomingWeekForCrop(Long cropId) throws IOException {
List<List<Task>> dayTaskList = getTasksUpcomingWeek(); List<List<Task>> dayTaskList = getTasksUpcomingWeek();
dayTaskList.forEach(taskList -> taskList.removeIf(task -> task.getCropId() != cropId)); dayTaskList.forEach(taskList -> taskList.removeIf(task -> task.getCropId() != cropId));
return dayTaskList; weeklyTaskListProperty.clear();
weeklyTaskListProperty.addAll(dayTaskList);
} }
/** /**

View File

@ -105,7 +105,7 @@ public class Task {
* @return Whether the Task is within the given range * @return Whether the Task is within the given range
*/ */
public boolean isInTimePeriod(LocalDate searchStartDate, LocalDate searchEndDate) { public boolean isInTimePeriod(LocalDate searchStartDate, LocalDate searchEndDate) {
return endDate.isAfter(searchStartDate) && startDate.isBefore(searchEndDate); return endDate.isAfter(searchStartDate) && startDate.isBefore(searchEndDate) || (nextExecution != null && nextExecution.isBefore(searchEndDate) && nextExecution.isAfter(searchStartDate));
} }
/** /**

View File

@ -130,7 +130,7 @@ public class JsonTaskListTest {
} }
@Test @Test
void testSubscription() { void testSubscription() throws IOException {
TaskList.TaskListObserver mockObs = Mockito.mock(TaskList.TaskListObserver.class); TaskList.TaskListObserver mockObs = Mockito.mock(TaskList.TaskListObserver.class);
testDatabase.subscribe(mockObs); testDatabase.subscribe(mockObs);
try { try {