Compare commits

..

8 Commits

Author SHA1 Message Date
Gian-Andrea Hutter 2e12c3f868 Merge remote-tracking branch 'origin/feature_json-task-db_M2' into feature_json-task-db_M2 2022-10-31 13:19:31 +01:00
Gian-Andrea Hutter 29ad2fdae2 #17 Bug Mismatchexception fixed 2022-10-31 13:19:14 +01:00
Elias Csomor 5c6528a038 Update JsonTaskDatabaseTest.java 2022-10-31 12:54:52 +01:00
Gian-Andrea Hutter afac3ba855 #17 Serialization implemented 2022-10-31 12:45:24 +01:00
Gian-Andrea Hutter a87f3da9d2 Merge branch 'feature_plantlist-gui_M2' into feature_json-task-db_M2 2022-10-31 12:43:43 +01:00
schrom01 d0cef1fe82 fixed problems with file Path
#43
2022-10-31 12:43:13 +01:00
Elias Csomor 2510608117 Extended taskDb tests 2022-10-31 11:55:20 +01:00
David Guler 7a060be84a case insensitive serarch, images 2022-10-31 10:06:17 +01:00
8 changed files with 203 additions and 97 deletions

View File

@ -10,10 +10,16 @@ import javafx.scene.layout.AnchorPane;
import java.io.IOException; import java.io.IOException;
import java.net.URL; import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.ResourceBundle; import java.util.ResourceBundle;
public class MainFXMLController implements Initializable { public class MainFXMLController implements Initializable {
/**
* Caching the panes
*/
private final Map<String, Node> panes = new HashMap<>();
@FXML @FXML
private Button home_button; private Button home_button;
@ -63,13 +69,18 @@ public class MainFXMLController implements Initializable {
*/ */
public void loadPane(String fxmlFile) throws IOException { public void loadPane(String fxmlFile) throws IOException {
//ToDo HGrow and VGrow of new node //ToDo HGrow and VGrow of new node
Node node; Node node = panes.get(fxmlFile);
System.out.println(node);
if (node == null) {
FXMLLoader loader = new FXMLLoader(Objects.requireNonNull(HelloApplication.class.getResource(fxmlFile))); FXMLLoader loader = new FXMLLoader(Objects.requireNonNull(HelloApplication.class.getResource(fxmlFile)));
node = (Node)loader.load(); node = loader.load();
panes.put(fxmlFile, node);
if(fxmlFile.equals("MyPlants.fxml")) { if(fxmlFile.equals("MyPlants.fxml")) {
MyPlantsController myPlantsController = loader.getController(); MyPlantsController myPlantsController = loader.getController();
myPlantsController.getMainController(this); myPlantsController.getMainController(this);
} }
}
mainPane.getChildren().setAll(node); mainPane.getChildren().setAll(node);
} }

View File

@ -4,19 +4,23 @@ import ch.zhaw.gartenverwaltung.io.HardinessZoneNotSetException;
import ch.zhaw.gartenverwaltung.plantList.PlantListModel; import ch.zhaw.gartenverwaltung.plantList.PlantListModel;
import ch.zhaw.gartenverwaltung.types.HardinessZone; import ch.zhaw.gartenverwaltung.types.HardinessZone;
import ch.zhaw.gartenverwaltung.types.Plant; import ch.zhaw.gartenverwaltung.types.Plant;
import javafx.application.Platform;
import javafx.beans.property.ListProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.beans.value.ChangeListener; import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue; import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent; import javafx.event.ActionEvent;
import javafx.fxml.FXML; import javafx.fxml.FXML;
import javafx.fxml.Initializable; import javafx.fxml.Initializable;
import javafx.geometry.Bounds;
import javafx.scene.control.*; import javafx.scene.control.*;
import javafx.scene.image.ImageView; import javafx.scene.image.ImageView;
import javafx.scene.input.InputMethodEvent; import javafx.scene.input.KeyEvent;
import javafx.scene.layout.VBox; import javafx.scene.layout.VBox;
import java.io.IOException; import java.io.IOException;
import java.net.URL; import java.net.URL;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.ResourceBundle; import java.util.ResourceBundle;
@ -25,6 +29,9 @@ public class PlantsController implements Initializable {
private Plant selectedPlant = null; private Plant selectedPlant = null;
private final HardinessZone DEFAULT_HARDINESS_ZONE = HardinessZone.ZONE_8A; private final HardinessZone DEFAULT_HARDINESS_ZONE = HardinessZone.ZONE_8A;
// TODO: move to model
private final ListProperty<Plant> plantListProperty = new SimpleListProperty<>(FXCollections.observableArrayList());
@FXML @FXML
private CheckBox autum_filter; private CheckBox autum_filter;
@ -85,7 +92,7 @@ public class PlantsController implements Initializable {
} }
@FXML @FXML
void searchForPlant(InputMethodEvent event) { void searchForPlant(KeyEvent event) {
viewFilteredListBySearch(search_plants.getText()); viewFilteredListBySearch(search_plants.getText());
} }
@ -94,13 +101,20 @@ public class PlantsController implements Initializable {
*/ */
@Override @Override
public void initialize(URL url, ResourceBundle resourceBundle) { public void initialize(URL url, ResourceBundle resourceBundle) {
List<Plant> plantList = new LinkedList<>(); setListCellFactory();
try { try {
plantList = plantListModel.getPlantList(DEFAULT_HARDINESS_ZONE); plantListProperty.addAll(plantListModel.getPlantList(DEFAULT_HARDINESS_ZONE));
} catch (HardinessZoneNotSetException | IOException e) { } catch (HardinessZoneNotSetException | IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
fillListViewWithData(plantList);
list_plants.itemsProperty().bind(plantListProperty);
list_plants.getSelectionModel().selectedItemProperty()
.addListener((observable, oldPlant, newPlant) -> {
if (newPlant != null) {
img_plant.setImage(newPlant.image());
}
});
description_plant.setText(""); description_plant.setText("");
saveToMyPlant_button.setDisable(true); saveToMyPlant_button.setDisable(true);
@ -109,16 +123,12 @@ public class PlantsController implements Initializable {
lookForSelectedListEntry(); lookForSelectedListEntry();
} }
/** private void centerImage() {
* update the ListView according to the plant list provided
* Entry in ListView is plant name //img_plant.setX(0.3);
* @param list plantList which fill the ListView //img_plant.setX(-100);
*/
private void fillListViewWithData(List<Plant> list) {
clearListView();
for (Plant plant : list) {
list_plants.getItems().add(plant);
} }
private void setListCellFactory() {
list_plants.setCellFactory(param -> new ListCell<Plant>() { list_plants.setCellFactory(param -> new ListCell<Plant>() {
@Override @Override
protected void updateItem(Plant plant, boolean empty) { protected void updateItem(Plant plant, boolean empty) {
@ -133,6 +143,19 @@ public class PlantsController implements Initializable {
}); });
} }
/**
* update the ListView according to the plant list provided
* Entry in ListView is plant name
* @param list plantList which fill the ListView
*/
private void fillListViewWithData(List<Plant> list) {
clearListView();
for (Plant plant : list) {
list_plants.getItems().add(plant);
}
}
private void viewFilteredListByFilters() { private void viewFilteredListByFilters() {
boolean springValue = spring_filter.isSelected(); boolean springValue = spring_filter.isSelected();
boolean sommerValue = sommer_filter.isSelected(); boolean sommerValue = sommer_filter.isSelected();
@ -145,8 +168,14 @@ public class PlantsController implements Initializable {
private void viewFilteredListBySearch(String query) { private void viewFilteredListBySearch(String query) {
//ToDo getFilteredPlantList with (plantListModel.getFilteredPlantList(DEFAULT_HARDINESS_ZONE, <predicate>)) //ToDo getFilteredPlantList with (plantListModel.getFilteredPlantList(DEFAULT_HARDINESS_ZONE, <predicate>))
//List<Plant> plantList = new LinkedList<>(); try {
//fillListViewWithData(plantList); List<Plant> filteredPlants = plantListModel.getFilteredPlantListByString(DEFAULT_HARDINESS_ZONE, query);
clearListView();
plantListProperty.addAll(filteredPlants);
} catch (HardinessZoneNotSetException | IOException e) {
e.printStackTrace();
}
} }
private void createFilterHardinessZone() { private void createFilterHardinessZone() {
@ -181,6 +210,6 @@ public class PlantsController implements Initializable {
* clears the ListView of entries * clears the ListView of entries
*/ */
private void clearListView() { private void clearListView() {
list_plants.getItems().clear(); plantListProperty.clear();
} }
} }

View File

@ -5,9 +5,11 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL; import java.net.URL;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
@ -24,6 +26,7 @@ import java.util.Map;
public class JsonTaskDatabase implements TaskDatabase{ public class JsonTaskDatabase implements TaskDatabase{
IdProvider idProvider; IdProvider idProvider;
private final URL dataSource = getClass().getResource("taskdb.json"); private final URL dataSource = getClass().getResource("taskdb.json");
private final static String INVALID_DATASOURCE_MSG = "Invalid datasource specified!";
private Map<Long, Task> taskMap = Collections.emptyMap(); private Map<Long, Task> taskMap = Collections.emptyMap();
@ -34,7 +37,10 @@ public class JsonTaskDatabase implements TaskDatabase{
static { static {
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd"); DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDateDeserializer dateDeserializer = new LocalDateDeserializer(dateFormat); LocalDateDeserializer dateDeserializer = new LocalDateDeserializer(dateFormat);
LocalDateSerializer dateSerializer = new LocalDateSerializer(dateFormat);
timeModule.addDeserializer(LocalDate.class, dateDeserializer); timeModule.addDeserializer(LocalDate.class, dateDeserializer);
timeModule.addSerializer(LocalDate.class, dateSerializer);
} }
/** /**
@ -95,12 +101,16 @@ public class JsonTaskDatabase implements TaskDatabase{
* @throws IOException If the database cannot be accessed * @throws IOException If the database cannot be accessed
*/ */
private void writeTaskListToFile() throws IOException { private void writeTaskListToFile() throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(timeModule)
.registerModule(new Jdk8Module());
if(dataSource != null) { if(dataSource != null) {
mapper.writeValue(new File(dataSource.getFile()), taskMap); try {
new ObjectMapper()
.registerModule(timeModule)
.registerModule(new Jdk8Module())
.writeValue(new File(dataSource.toURI()), taskMap.values());
} catch (URISyntaxException e) {
throw new IOException(INVALID_DATASOURCE_MSG, e);
}
} }
} }
@ -112,7 +122,8 @@ public class JsonTaskDatabase implements TaskDatabase{
private void loadTaskListFromFile() throws IOException { private void loadTaskListFromFile() throws IOException {
if (dataSource != null) { if (dataSource != null) {
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(timeModule); mapper.registerModule(timeModule)
.registerModule(new Jdk8Module());
List<Task> result; List<Task> result;
result = mapper.readerForListOf(Task.class).readValue(dataSource); result = mapper.readerForListOf(Task.class).readValue(dataSource);

View File

@ -6,9 +6,11 @@ import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonDeserializer;
import javafx.scene.image.Image; import javafx.scene.image.Image;
import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL; import java.net.URL;
public class PlantImageDeserializer extends JsonDeserializer<Image> { public class PlantImageDeserializer extends JsonDeserializer<Image> {
@ -18,9 +20,9 @@ public class PlantImageDeserializer extends JsonDeserializer<Image> {
Image result = null; Image result = null;
URL imageUrl = PlantDatabase.class.getResource(String.format("images/%s", parser.getText())); URL imageUrl = PlantDatabase.class.getResource(String.format("images/%s", parser.getText()));
if (imageUrl != null) { if (imageUrl != null) {
try (InputStream is = new FileInputStream(imageUrl.getFile())) { try (InputStream is = new FileInputStream(new File(imageUrl.toURI()))) {
result = new Image(is); result = new Image(is);
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException | URISyntaxException e) {
// TODO: Log // TODO: Log
e.printStackTrace(); e.printStackTrace();
System.err.printf("Cannot find Image \"%s\"\n", imageUrl.getFile()); System.err.printf("Cannot find Image \"%s\"\n", imageUrl.getFile());

View File

@ -52,6 +52,7 @@ public class PlantListModel {
/** /**
* Method to get actual Plant List in alphabetic Order * Method to get actual Plant List in alphabetic Order
*
* @return actual Plant List in alphabetic Order * @return actual Plant List in alphabetic Order
*/ */
public List<Plant> getPlantList(HardinessZone zone) throws HardinessZoneNotSetException, IOException { public List<Plant> getPlantList(HardinessZone zone) throws HardinessZoneNotSetException, IOException {
@ -62,6 +63,7 @@ public class PlantListModel {
/** /**
* Method to get the actual Plant list in custom Order * Method to get the actual Plant list in custom Order
*
* @param zone selected hardiness zone * @param zone selected hardiness zone
* @param comparator comparator to sort the list * @param comparator comparator to sort the list
* @return sorted list with plants in the given hardiness zone * @return sorted list with plants in the given hardiness zone
@ -75,6 +77,7 @@ public class PlantListModel {
/** /**
* Method to get Filtered plant list * Method to get Filtered plant list
*
* @param predicate predicate to filter the list * @param predicate predicate to filter the list
* @param zone selected hardiness zone * @param zone selected hardiness zone
* @return filterd list with plants in the hardinness zone * @return filterd list with plants in the hardinness zone
@ -88,6 +91,7 @@ public class PlantListModel {
/** /**
* Method to get Filtered plant list by id by exact match * Method to get Filtered plant list by id by exact match
*
* @param zone selected hardiness zone * @param zone selected hardiness zone
* @param id id of plant * @param id id of plant
* @return if id doesn't exist: empty List, else list with 1 plant entry. * @return if id doesn't exist: empty List, else list with 1 plant entry.
@ -102,7 +106,6 @@ public class PlantListModel {
} }
/** /**
*
* @param zone selected hardiness zone * @param zone selected hardiness zone
* @param searchString the string to search plant List, set '#' as first char the search by id. * @param searchString the string to search plant List, set '#' as first char the search by id.
* @return List of plants found in Plant List which contain the search String in the name or description * @return List of plants found in Plant List which contain the search String in the name or description
@ -119,12 +122,16 @@ public class PlantListModel {
return new ArrayList<>(); return new ArrayList<>();
} }
} else { } else {
return getFilteredPlantList(zone, plant -> plant.name().contains(searchString) || plant.description().contains(searchString)); String caseInsensitiveSearchString = searchString.toLowerCase();
return getFilteredPlantList(zone, plant ->
plant.name().toLowerCase().contains(caseInsensitiveSearchString) ||
plant.description().toLowerCase().contains(caseInsensitiveSearchString)
);
} }
} }
/** /**
*
* @param type GrowPhaseType to filter * @param type GrowPhaseType to filter
* @param zone selected hardiness zone * @param zone selected hardiness zone
* @param from the earliest date to for the filter * @param from the earliest date to for the filter
@ -138,7 +145,6 @@ public class PlantListModel {
} }
/** /**
*
* @param zone selected hardiness zone * @param zone selected hardiness zone
* @param from the earliest date to for the filter * @param from the earliest date to for the filter
* @param to the lastest date for the filter * @param to the lastest date for the filter
@ -151,7 +157,6 @@ public class PlantListModel {
} }
/** /**
*
* @param zone selected hardiness zone * @param zone selected hardiness zone
* @param from the earliest date to for the filter * @param from the earliest date to for the filter
* @param to the lastest date for the filter * @param to the lastest date for the filter

View File

@ -30,7 +30,7 @@
<Font name="System Bold" size="30.0" /> <Font name="System Bold" size="30.0" />
</font> </font>
</Label> </Label>
<TextField fx:id="search_plants" onInputMethodTextChanged="#searchForPlant" promptText="Search for Plant Name" /> <TextField fx:id="search_plants" onKeyTyped="#searchForPlant" promptText="Search for Plant Name" />
<HBox alignment="CENTER_LEFT" prefHeight="480.0" prefWidth="881.0" VBox.vgrow="ALWAYS"> <HBox alignment="CENTER_LEFT" prefHeight="480.0" prefWidth="881.0" VBox.vgrow="ALWAYS">
<children> <children>
<ListView fx:id="list_plants" maxWidth="1.7976931348623157E308" prefHeight="497.0" prefWidth="580.0" HBox.hgrow="ALWAYS" /> <ListView fx:id="list_plants" maxWidth="1.7976931348623157E308" prefHeight="497.0" prefWidth="580.0" HBox.hgrow="ALWAYS" />

View File

@ -6,32 +6,80 @@ import org.junit.jupiter.api.*;
import java.io.IOException; import java.io.IOException;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Optional;
public class JsonTaskDatabaseTest { public class JsonTaskDatabaseTest {
TaskDatabase testDatabase; TaskDatabase testDatabase;
SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy"); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
@BeforeEach @BeforeEach
void connectToDb() { void connectToDb() {
// testDatabase = new JsonTaskDatabase(); testDatabase = new JsonTaskDatabase();
} }
@Test @Test
@DisplayName("Check if results are retrieved completely") @DisplayName("Check if results are retrieved completely")
void getTasks(){ void getTasks(){
/*
List<Task> taskList=null; List<Task> taskList=null;
try { try {
taskList = testDatabase.getTaskList(formatter.parse("01.05.2022"), formatter.parse("01.08.2022")); taskList = testDatabase.getTaskList(LocalDate.parse("30.04.2022",formatter),
LocalDate.parse("31.05.2022",formatter));
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} catch (ParseException e) {
throw new RuntimeException(e);
} }
Assertions.assertTrue(taskList.size()>0); Assertions.assertEquals(3,taskList.size());
*/
}
//@Disabled("disabled until idProvider works")
@Test
@DisplayName("Add task.")
void addTask(){
Task task = new Task("Testtask","This is a test Task.",LocalDate.parse("01.05.2022",formatter));
try {
testDatabase.saveTask(task);
List<Task> taskList=null;
try {
taskList = testDatabase.getTaskList(LocalDate.parse("30.04.2022",formatter),
LocalDate.parse("31.05.2022",formatter));
} catch (IOException e) {
throw new RuntimeException(e);
}
Assertions.assertEquals(4,taskList.size());
} catch (IOException e) {
throw new RuntimeException(e);
} }
} }
@Test
@DisplayName("Remove task.")
void removeTask(){
Task task = new Task("Dummy","Dummy",LocalDate.parse("31.05.2022",formatter)).withId(2);
try {
testDatabase.removeTask(task);
List<Task> taskList=null;
try {
taskList = testDatabase.getTaskList(LocalDate.parse("30.04.2022",formatter),
LocalDate.parse("31.05.2022",formatter));
} catch (IOException e) {
throw new RuntimeException(e);
}
Assertions.assertEquals(2,taskList.size());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}