From 3814bf2cab2cb1465002d05f68e9b38e9351e014 Mon Sep 17 00:00:00 2001 From: Viktoria Pundy Date: Tue, 22 May 2018 19:49:20 +0200 Subject: Added methods and files --- src/main/resources/fxml/OperationDetails.fxml | 102 ++++++++++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 src/main/resources/fxml/OperationDetails.fxml (limited to 'src/main/resources/fxml/OperationDetails.fxml') diff --git a/src/main/resources/fxml/OperationDetails.fxml b/src/main/resources/fxml/OperationDetails.fxml new file mode 100644 index 0000000..f4d2a17 --- /dev/null +++ b/src/main/resources/fxml/OperationDetails.fxml @@ -0,0 +1,102 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + -- cgit v1.2.3-70-g09d2 From 3e46b43f51cb632bccd3f7d5e69355e1c69f53f0 Mon Sep 17 00:00:00 2001 From: Tharre Date: Thu, 24 May 2018 17:12:21 +0200 Subject: Change package structure/naming #25963 --- .../groupphase/application/MainApplication.java | 2 +- .../controller/ArchiveOperationController.java | 127 +++++++ .../controller/CreateOperationController.java | 365 ++++++++++++++++++++ .../controller/OperationDetailsController.java | 162 +++++++++ .../controller/VehiclePaneController.java | 113 +++++++ .../einsatzverwaltung/dao/DBOperationDAO.java | 217 ------------ .../einsatzverwaltung/dao/EmployeeDatabaseDAO.java | 196 +++++++++++ .../einsatzverwaltung/dao/EmployeeDatabaseDao.java | 196 ----------- .../dao/OperationDatabaseDAO.java | 218 ++++++++++++ .../einsatzverwaltung/dao/VehicleDatabaseDAO.java | 220 +++++++++++++ .../einsatzverwaltung/dao/VehicleDatabaseDao.java | 220 ------------- .../ui/vehiclepane/VehiclePaneController.java | 113 ------- .../userInterface/ArchiveOperationController.java | 127 ------- .../userInterface/CreateOperationController.java | 366 --------------------- .../userInterface/OperationDetailsController.java | 162 --------- src/main/resources/fxml/ArchiveOperation.fxml | 2 +- .../resources/fxml/CreateOperationController.fxml | 2 +- src/main/resources/fxml/OperationDetails.fxml | 2 +- src/main/resources/fxml/vehiclePane.fxml | 2 +- .../einsatzverwaltung/dao/EmployeeDAOTest.java | 254 ++++++++++++++ .../dao/EmployeePersistenceTest.java | 254 -------------- .../einsatzverwaltung/dao/OperationDAOTest.java | 6 +- .../einsatzverwaltung/dao/RegistrationDAOTest.java | 172 ++++++++++ .../dao/RegistrationDatabaseDAOTest.java | 172 ---------- .../einsatzverwaltung/dao/VehicleDAOTest.java | 161 +++++++++ .../dao/VehiclePersistenceTest.java | 161 --------- .../service/EmployeeServiceTest.java | 4 +- .../service/RegistrationServiceImplTest.java | 148 --------- .../service/RegistrationServiceTest.java | 148 +++++++++ 29 files changed, 2146 insertions(+), 2146 deletions(-) create mode 100644 src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/controller/ArchiveOperationController.java create mode 100644 src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/controller/CreateOperationController.java create mode 100644 src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/controller/OperationDetailsController.java create mode 100644 src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/controller/VehiclePaneController.java delete mode 100644 src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/DBOperationDAO.java create mode 100644 src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/EmployeeDatabaseDAO.java delete mode 100644 src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/EmployeeDatabaseDao.java create mode 100644 src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/OperationDatabaseDAO.java create mode 100644 src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/VehicleDatabaseDAO.java delete mode 100644 src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/VehicleDatabaseDao.java delete mode 100644 src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/ui/vehiclepane/VehiclePaneController.java delete mode 100644 src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/userInterface/ArchiveOperationController.java delete mode 100644 src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/userInterface/CreateOperationController.java delete mode 100644 src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/userInterface/OperationDetailsController.java create mode 100644 src/test/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/EmployeeDAOTest.java delete mode 100644 src/test/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/EmployeePersistenceTest.java create mode 100644 src/test/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/RegistrationDAOTest.java delete mode 100644 src/test/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/RegistrationDatabaseDAOTest.java create mode 100644 src/test/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/VehicleDAOTest.java delete mode 100644 src/test/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/VehiclePersistenceTest.java delete mode 100644 src/test/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/service/RegistrationServiceImplTest.java create mode 100644 src/test/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/service/RegistrationServiceTest.java (limited to 'src/main/resources/fxml/OperationDetails.fxml') diff --git a/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/application/MainApplication.java b/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/application/MainApplication.java index 01c04d3..d8365a7 100644 --- a/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/application/MainApplication.java +++ b/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/application/MainApplication.java @@ -1,6 +1,6 @@ package at.ac.tuwien.sepm.assignment.groupphase.application; -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.userInterface.CreateOperationController; +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.controller.CreateOperationController; import at.ac.tuwien.sepm.assignment.groupphase.util.SpringFXMLLoader; import javafx.application.Application; import javafx.application.Platform; diff --git a/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/controller/ArchiveOperationController.java b/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/controller/ArchiveOperationController.java new file mode 100644 index 0000000..80d9fc4 --- /dev/null +++ b/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/controller/ArchiveOperationController.java @@ -0,0 +1,127 @@ +package at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.controller; + +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Operation; +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Operation.Status; +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Vehicle; +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.service.OperationService; +import at.ac.tuwien.sepm.assignment.groupphase.exception.ServiceException; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.util.Collection; +import java.util.EnumSet; +import java.util.LinkedList; +import java.util.Objects; +import java.util.stream.Collectors; +import javafx.fxml.FXML; +import javafx.scene.control.Alert; +import javafx.scene.control.Alert.AlertType; +import javafx.scene.control.Button; +import javafx.scene.control.Hyperlink; +import javafx.scene.control.Label; +import javafx.scene.layout.AnchorPane; +import javafx.scene.layout.FlowPane; +import org.springframework.stereotype.Controller; + +@Controller +public class ArchiveOperationController { + @FXML private AnchorPane apDetails; + @FXML private Label lblCodeHeader; + @FXML private Hyperlink hypBack; + @FXML private Label lblOpCode; + @FXML private Label lblVehicles; + @FXML private Label lblDate; + @FXML private Label lblAddress; + @FXML private FlowPane fpVehicles; + private final OperationService operationService; + @FXML private FlowPane archiveOperationFlowPane; + private LinkedList list = new LinkedList<>(); + + public ArchiveOperationController(OperationService operationService) { + this.operationService = operationService; + } + + @FXML + private void initialize() { + try { + list.addAll(operationService.list(EnumSet.of(Status.CANCELLED, Status.COMPLETED))); + } catch (ServiceException e) { + Alert alert = new Alert(AlertType.ERROR); + alert.setTitle("Fehler"); + alert.setHeaderText("Fehler!"); + alert.setContentText("Die Einsätze konnten nicht geladen werden!"); + alert.showAndWait(); + } + for (Operation operation : list) { + Button b = new Button(); + b.setPrefHeight(200); + b.setPrefWidth(750 / 2); + b.setText(operation.opCode()); + b.setOnAction(event -> buttonClicked(b)); + archiveOperationFlowPane.getChildren().add(b); + } + } + + private Operation detailOperation; + + private void buttonClicked(Button button) { + int size = archiveOperationFlowPane.getChildren().size(); + int index = 0; + for (int i = 0; i < size; i++) { + if (archiveOperationFlowPane.getChildren().get(i) == button) { + index = i; + break; + } + } + detailOperation = list.get(index); + setOperation(); + setDetailsVisible(true); + } + + private void setOperation() { + lblCodeHeader.setText(detailOperation.opCode()); + String date = "am "; + if (detailOperation.created() != null) { + LocalDateTime myDateTime = + LocalDateTime.ofInstant( + Objects.requireNonNull(detailOperation.created()), ZoneOffset.UTC); + date += + myDateTime.getDayOfMonth() + + "." + + myDateTime.getMonth().getValue() + + "." + + myDateTime.getYear(); + lblDate.setText(date); + } else { + lblDate.setText("---"); + } + + lblOpCode.setText(detailOperation.opCode()); + Collection elements = + detailOperation.vehicles().stream().map(Vehicle::name).collect(Collectors.toList()); + String result = String.join(", ", elements); + + lblVehicles.setText(result); + lblAddress.setText(detailOperation.destination()); + + for (Vehicle vehicle : detailOperation.vehicles()) { + Button b = new Button(); + b.setPrefHeight(200); + b.setPrefWidth(600 / 2); + b.setText(vehicle.name()); + fpVehicles.getChildren().add(b); + } + } + + public void setListVisible(boolean b) { + archiveOperationFlowPane.setVisible(b); + } + + private void setDetailsVisible(boolean b) { + apDetails.setVisible(b); + } + + public void backClicked() { + fpVehicles.getChildren().clear(); + setDetailsVisible(false); + } +} diff --git a/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/controller/CreateOperationController.java b/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/controller/CreateOperationController.java new file mode 100644 index 0000000..57759e3 --- /dev/null +++ b/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/controller/CreateOperationController.java @@ -0,0 +1,365 @@ +package at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.controller; + +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Operation; +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Operation.Status; +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Registration; +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Vehicle; +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.service.OperationService; +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.service.VehicleService; +import at.ac.tuwien.sepm.assignment.groupphase.exception.InvalidOperationException; +import at.ac.tuwien.sepm.assignment.groupphase.exception.InvalidVehicleException; +import at.ac.tuwien.sepm.assignment.groupphase.exception.ServiceException; +import at.ac.tuwien.sepm.assignment.groupphase.util.SpringFXMLLoader; +import java.io.IOException; +import java.lang.invoke.MethodHandles; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; +import javafx.collections.FXCollections; +import javafx.event.ActionEvent; +import javafx.fxml.FXML; +import javafx.scene.Parent; +import javafx.scene.Scene; +import javafx.scene.control.Alert; +import javafx.scene.control.Alert.AlertType; +import javafx.scene.control.Button; +import javafx.scene.control.ContextMenu; +import javafx.scene.control.Label; +import javafx.scene.control.ListCell; +import javafx.scene.control.ListView; +import javafx.scene.control.MenuItem; +import javafx.scene.control.TextField; +import javafx.scene.input.KeyCode; +import javafx.scene.input.KeyEvent; +import javafx.scene.input.MouseButton; +import javafx.scene.layout.AnchorPane; +import javafx.scene.layout.FlowPane; +import javafx.stage.Stage; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Controller; + +@Controller +public class CreateOperationController { + + private static final Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); + + public AnchorPane apCreateOperation; + @FXML private TextField txtCode; + @FXML private TextField txtAddress; + @FXML private TextField txtNote; + @FXML private Button btnCreateOperation; + @FXML private ListView lvVehicles; + @FXML private ListView lvActiveOperations; + @FXML private Label lblChosenVehicles; + @FXML private AnchorPane apInvisible; + @FXML private OperationDetailsController operationDetailsController; + @FXML private FlowPane fpVehicles; + + private LinkedList chosenVehicles = new LinkedList<>(); + + private final OperationService operationService; + private final VehicleService vehicleService; + private final SpringFXMLLoader fxmlLoader; + + public CreateOperationController( + OperationService operationService, + VehicleService vehicleService, + SpringFXMLLoader fxmlLoader) { + this.operationService = operationService; + this.vehicleService = vehicleService; + this.fxmlLoader = fxmlLoader; + } + + @FXML + private void initialize() { + lblChosenVehicles.setText("keine ausgewählt"); + lvActiveOperations.setCellFactory( + param -> + new ListCell<>() { + @Override + protected void updateItem(Operation item, boolean empty) { + super.updateItem(item, empty); + + if (empty || item == null || item.opCode() == null) { + setText(null); + } else { + setText(item.opCode()); + } + } + }); + lvActiveOperations.setOnMouseClicked( + event -> { + if (event.getClickCount() == 2) { + if (lvActiveOperations.getSelectionModel().getSelectedItem() == null) { + return; + } + openDetailsWindow(lvActiveOperations.getSelectionModel().getSelectedItem()); + } + }); + } + + public void updateList() { + try { + fpVehicles.getChildren().clear(); + + // TODO: this should probably be handled differently + Set vehicles; + if (txtCode.getText().isEmpty()) { + vehicles = + vehicleService.list( + EnumSet.complementOf(EnumSet.of(Vehicle.Status.ABGEMELDET))); + } else { + vehicles = operationService.rankVehicles(txtCode.getText()); + } + + for (Vehicle vehicle : vehicles) { + VehiclePaneController controller = VehiclePaneController.createVehiclePane(); + + controller.setData(vehicle, true); + controller + .getRootElement() + .setOnMouseClicked( + event -> { + if (event.getButton().equals(MouseButton.SECONDARY)) { + createContextMenu(vehicle, vehicleService) + .show( + controller.getRootElement(), + event.getScreenX(), + event.getScreenY()); + } else { + if (chosenVehicles.contains(vehicle)) { + chosenVehicles.remove(vehicle); + controller.setSelected(false); + } else { + chosenVehicles.add(vehicle); + controller.setSelected(true); + } + + StringBuilder result = new StringBuilder(); + for (int i = 0; i < chosenVehicles.size(); i++) { + if (i == chosenVehicles.size() - 1) { + result.append(chosenVehicles.get(i).name()); + } else { + result.append(chosenVehicles.get(i).name()) + .append(", "); + } + } + if (result.toString().equals("")) { + lblChosenVehicles.setText("keine ausgewählt"); + } else { + lblChosenVehicles.setText(result.toString()); + } + } + }); + + fpVehicles.getChildren().add(controller.getRootElement()); + } + } catch (ServiceException | IOException | InvalidOperationException e) { + LOG.error("Error while updating list.", e); + + Alert alert = new Alert(Alert.AlertType.ERROR); + alert.setTitle("Fehler"); + alert.setHeaderText("Fehler!"); + alert.setContentText(e.getMessage()); + alert.showAndWait(); + } + try { + lvActiveOperations.setItems( + FXCollections.observableArrayList( + operationService.list(EnumSet.of(Status.ACTIVE)))); + } catch (ServiceException e) { + Alert alert = new Alert(Alert.AlertType.ERROR); + alert.setTitle("Fehler - Einsätze"); + alert.setHeaderText("Beim Holen der aktiven Einsätze ist ein Fehler aufgetreten."); + alert.setContentText(e.getMessage()); + alert.showAndWait(); + } + } + + private ContextMenu createContextMenu(Vehicle data, VehicleService vehicleService) { + ContextMenu menu = new ContextMenu(); + + for (Vehicle.Status status : Vehicle.Status.values()) { + if (status == Vehicle.Status.ABGEMELDET) { + continue; + } + + MenuItem mi = new MenuItem(status.name()); + + if (status == Vehicle.Status.FREI_FUNK || status == Vehicle.Status.FREI_WACHE) { + mi.getStyleClass().add("mi-free"); + } else { + mi.getStyleClass().add("mi-other"); + } + + mi.setOnAction( + event -> { + try { + vehicleService.update(data.toBuilder().status(status).build()); + this.updateList(); + } catch (InvalidVehicleException | ServiceException e) { + LOG.error("Error while setting status.", e); + Alert a = new Alert(AlertType.ERROR, e.getMessage()); + a.show(); + } + }); + + menu.getItems().add(mi); + } + + MenuItem abmelden = new MenuItem("abmelden"); + + abmelden.setOnAction( + event -> { + try { + List registrations = data.registrations(); + assert registrations + != null; // Otherwise the element shouldn't be in the list. + + List newRegistrations = new ArrayList<>(); + Instant now = Instant.now(); + + for (Registration registration : registrations) { + if (registration.start().isBefore(now) + && registration.end().isAfter(now)) { + newRegistrations.add( + registration + .toBuilder() + .end(Instant.now().minus(1, ChronoUnit.SECONDS)) + .build()); + } else newRegistrations.add(registration); + } + + vehicleService.update( + data.toBuilder() + .registrations(newRegistrations) + .status(Vehicle.Status.ABGEMELDET) + .build()); + + this.updateList(); + } catch (InvalidVehicleException | ServiceException e) { + LOG.error("Error while unregistering.", e); + Alert a = new Alert(AlertType.ERROR, e.getMessage()); + a.show(); + } + }); + + menu.getItems().add(abmelden); + return menu; + } + + @FXML + protected void createOperationClicked() { + Vehicle[] vehicles = new Vehicle[chosenVehicles.size()]; + for (int i = 0; i < chosenVehicles.size(); i++) { + vehicles[i] = chosenVehicles.get(i); + } + Operation operation = + Operation.builder() + .additionalInfo(txtNote.getText()) + .destination(txtAddress.getText()) + .opCode(txtCode.getText()) + .status(Status.ACTIVE) + .vehicles(Set.of(vehicles)) + .build(); + try { + operationService.add(operation); + } catch (ServiceException | InvalidOperationException e) { + Alert alert = new Alert(Alert.AlertType.ERROR); + alert.setTitle("Fehler"); + alert.setHeaderText("Fehler!"); + alert.setContentText(e.getMessage()); + alert.showAndWait(); + return; + } + Alert alert = new Alert(AlertType.CONFIRMATION); + alert.setTitle("Erfolg"); + alert.setHeaderText("Erfolgreich gespeichert"); + alert.setContentText("Der Einsatz wurde erfolgreich gespeichert."); + alert.showAndWait(); + updateList(); + lblChosenVehicles.setText("keine ausgewählt"); + txtAddress.setText(""); + txtCode.setText(""); + txtNote.setText(""); + chosenVehicles = new LinkedList<>(); + } + + public void onRegistrationLinkClicked(ActionEvent actionEvent) { + openNewWindow("RegistrationWindow.fxml"); + } + + public void onEmployeeLinkClicked(ActionEvent actionEvent) { + openNewWindow("listEmployees.fxml"); + } + + public void onVehicleLinkClicked(ActionEvent actionEvent) { + openNewWindow("createCar.fxml"); + } + + public void onArchivLinkClicked() { + openNewArchivWindow(); + } + + private void openNewArchivWindow() { + Stage stage = new Stage(); + try { + stage.setScene( + new Scene( + (Parent) + fxmlLoader.load( + getClass() + .getResourceAsStream( + "/fxml/ArchiveOperation.fxml")))); + } catch (IOException e) { + LOG.error("Could not open new window: {}", e); + } + stage.setTitle("Einsatz erstellen"); + stage.centerOnScreen(); + stage.show(); + updateList(); + } + + private void openNewWindow(String fxmlFileName) { + + Stage stage = new Stage(); + try { + stage.setScene( + new Scene( + (Parent) + fxmlLoader.load( + getClass() + .getResourceAsStream( + "/fxml/" + fxmlFileName)))); + } catch (IOException e) { + LOG.error("Could not open new window: {}", e); + } + + stage.setTitle("Ressourcenverwaltung"); + stage.centerOnScreen(); + stage.showAndWait(); // important to call wait so that updateList is executed afterwards + + updateList(); + } + + void setVisible(boolean b) { + apInvisible.setVisible(!b); + } + + private void openDetailsWindow(Operation operation) { + operationDetailsController.initOperation(operation); + this.setVisible(false); + } + + @FXML + public void onOperationCodeChanged(KeyEvent keyEvent) { + if (keyEvent.getCode() == KeyCode.ENTER) { + updateList(); + } + } +} diff --git a/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/controller/OperationDetailsController.java b/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/controller/OperationDetailsController.java new file mode 100644 index 0000000..dc7e969 --- /dev/null +++ b/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/controller/OperationDetailsController.java @@ -0,0 +1,162 @@ +package at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.controller; + +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Operation; +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Operation.Status; +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Vehicle; +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.service.OperationService; +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.service.VehicleService; +import at.ac.tuwien.sepm.assignment.groupphase.exception.InvalidOperationException; +import at.ac.tuwien.sepm.assignment.groupphase.exception.ServiceException; +import java.util.Collection; +import java.util.EnumSet; +import java.util.stream.Collectors; +import javafx.collections.FXCollections; +import javafx.fxml.FXML; +import javafx.scene.control.Alert; +import javafx.scene.control.Alert.AlertType; +import javafx.scene.control.Button; +import javafx.scene.control.Label; +import javafx.scene.control.ListCell; +import javafx.scene.control.ListView; +import javafx.scene.layout.AnchorPane; +import org.springframework.stereotype.Controller; + +@Controller +public class OperationDetailsController { + + public Operation operation; + private final OperationService operationService; + private final VehicleService vehicleService; + private final CreateOperationController createOperationController; + @FXML private ListView lvVehicles; + @FXML private ListView lvActiveOperations; + @FXML private Label lblChosenVehicles; + @FXML private Button btnCloseOperation; + @FXML private Button btnCancelOperation; + @FXML private Label lblCode, lblAdditionalInfo, lblAddress; + @FXML private AnchorPane operationDetailsAP; + + public OperationDetailsController( + OperationService operationService, + VehicleService vehicleService, + CreateOperationController createOperationController) { + this.operationService = operationService; + this.vehicleService = vehicleService; + this.createOperationController = createOperationController; + } + + @FXML + private void initialize() { + lvVehicles.setCellFactory( + param -> + new ListCell<>() { + @Override + protected void updateItem(Vehicle item, boolean empty) { + super.updateItem(item, empty); + + if (empty || item == null || item.name() == null) { + setText(null); + } else { + setText(item.name()); + } + } + }); + lvActiveOperations.setCellFactory( + param -> + new ListCell<>() { + @Override + protected void updateItem(Operation item, boolean empty) { + super.updateItem(item, empty); + + if (empty || item == null || item.opCode() == null) { + setText(null); + } else { + setText(item.opCode()); + } + } + }); + lvActiveOperations.setOnMouseClicked( + event -> { + if (event.getClickCount() == 2) { + if (lvActiveOperations.getSelectionModel().getSelectedItem() == null) { + return; + } + initOperation(lvActiveOperations.getSelectionModel().getSelectedItem()); + } + }); + } + + void initOperation(Operation operation) { + fillActiveList(); + this.operation = operation; + lblCode.setText(operation.opCode()); + Collection vehicleNames = + operation.vehicles().stream().map(Vehicle::name).collect(Collectors.toList()); + String result = String.join(", ", vehicleNames); + lblChosenVehicles.setText(result.toString()); + lblAdditionalInfo.setText(operation.additionalInfo()); + lblAddress.setText(operation.destination()); + lvVehicles.setItems(FXCollections.observableArrayList(operation.vehicles())); + operationDetailsAP.setVisible(true); + } + + private void fillActiveList() { + try { + lvActiveOperations.setItems( + FXCollections.observableArrayList( + operationService.list(EnumSet.of(Status.ACTIVE)))); + } catch (ServiceException e) { + Alert alert = new Alert(AlertType.ERROR); + alert.setTitle("Fehler"); + alert.setHeaderText("Fehler!"); + alert.setContentText(e.getMessage()); + alert.showAndWait(); + } + } + + @FXML + public void closeOperationClicked() { + try { + operationService.complete(operation.id(), Status.COMPLETED); + } catch (InvalidOperationException | ServiceException e) { + Alert alert = new Alert(AlertType.ERROR); + alert.setTitle("Fehler"); + alert.setHeaderText("Fehler!"); + alert.setContentText(e.getMessage()); + alert.showAndWait(); + return; + } + Alert alert = new Alert(AlertType.CONFIRMATION); + alert.setTitle("Erfolg"); + alert.setHeaderText("Erfolgreich aktualisiert"); + alert.setContentText("Der Einsatz wurde erfolgreich aktualisiert."); + alert.showAndWait(); + closeWindow(); + createOperationController.updateList(); + } + + public void cancelOperationClicked() { + try { + operationService.complete(operation.id(), Status.CANCELLED); + } catch (InvalidOperationException | ServiceException e) { + Alert alert = new Alert(AlertType.ERROR); + alert.setTitle("Fehler"); + alert.setHeaderText("Fehler!"); + alert.setContentText(e.getMessage()); + alert.showAndWait(); + return; + } + Alert alert = new Alert(AlertType.CONFIRMATION); + alert.setTitle("Erfolg"); + alert.setHeaderText("Erfolgreich aktualisiert"); + alert.setContentText("Der Einsatz wurde erfolgreich aktualisiert."); + alert.showAndWait(); + closeWindow(); + createOperationController.updateList(); + } + + public void closeWindow() { + operationDetailsAP.setVisible(false); + this.createOperationController.setVisible(true); + } +} diff --git a/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/controller/VehiclePaneController.java b/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/controller/VehiclePaneController.java new file mode 100644 index 0000000..6c0932b --- /dev/null +++ b/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/controller/VehiclePaneController.java @@ -0,0 +1,113 @@ +package at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.controller; + +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Employee.EducationLevel; +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Registration; +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Vehicle; +import java.io.IOException; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import javafx.fxml.FXML; +import javafx.fxml.FXMLLoader; +import javafx.scene.Node; +import javafx.scene.image.Image; +import javafx.scene.image.ImageView; +import javafx.scene.text.Text; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class VehiclePaneController { + + private static Logger LOG = LoggerFactory.getLogger(VehiclePaneController.class); + + public static VehiclePaneController createVehiclePane() throws IOException { + FXMLLoader fxmlLoader = + new FXMLLoader(VehiclePaneController.class.getResource("/fxml/vehiclePane.fxml")); + Node root = fxmlLoader.load(); + VehiclePaneController result = fxmlLoader.getController(); + result.rootElement = root; + + return result; + } + + @FXML private Text txtType; + @FXML private Text txtNumber; + @FXML private ImageView ivNEF; + @FXML private Text txtNEF; + @FXML private ImageView ivQualification; + @FXML private Text txtQualification; + @FXML private Text txtRooftype; + + private Node rootElement; + private Vehicle data; + + public Node getRootElement() { + return rootElement; + } + + public Vehicle getData() { + return data; + } + + /** + * * Set the displayed data of this VehiclePane. + * + * @param vehicle The data to display. + * @param showQualification If true, the most recent registration of vehicle will be searched + * for the highest qualification. + */ + public void setData(Vehicle vehicle, boolean showQualification) { + txtType.setText(vehicle.type().name()); + String constrType = vehicle.constructionType().name(); + txtRooftype.setText( + constrType.substring(0, 1).toUpperCase() + constrType.substring(1).toLowerCase()); + txtNumber.setText("-" + vehicle.id()); + if (vehicle.hasNef()) { + ivNEF.setImage(new Image("images/NEF.png")); + txtNEF.setText("hat NEF-Halterung"); + } else { + ivNEF.setImage(new Image("images/NotNEF.png")); + txtNEF.setText("keine NEF-Halterung"); + } + if (showQualification) { + + Instant now = Instant.now(); + List regs = vehicle.registrations(); + + if (regs == null) { + return; + } + + Optional edu = + regs.stream() + .filter(reg -> reg.start().isBefore(now) && reg.end().isAfter(now)) + .map(reg -> reg.employee().educationLevel()) + .max(EducationLevel::compareTo); + + if (!edu.isPresent()) { + return; + } + + txtQualification.setText(edu.get().name()); + } else { + txtQualification.setVisible(false); + txtQualification.setManaged(false); + ivQualification.setVisible(false); + ivQualification.setManaged(false); + } + + this.data = vehicle; + } + + public void setSelected(boolean selected) { + rootElement.getStyleClass().clear(); + + if (selected) { + rootElement.getStyleClass().add("bg-yellow"); + rootElement.getStyleClass().add("shadowed"); + } else { + rootElement.getStyleClass().add("bg-white"); + rootElement.getStyleClass().add("shadowed"); + } + } +} diff --git a/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/DBOperationDAO.java b/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/DBOperationDAO.java deleted file mode 100644 index 0bb25b8..0000000 --- a/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/DBOperationDAO.java +++ /dev/null @@ -1,217 +0,0 @@ -package at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dao; - -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Operation; -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Operation.Severity; -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Operation.Status; -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Vehicle; -import at.ac.tuwien.sepm.assignment.groupphase.exception.ElementNotFoundException; -import at.ac.tuwien.sepm.assignment.groupphase.exception.PersistenceException; -import at.ac.tuwien.sepm.assignment.groupphase.util.JDBCConnectionManager; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Timestamp; -import java.util.EnumSet; -import java.util.HashSet; -import java.util.Objects; -import java.util.Set; -import java.util.stream.Collectors; -import org.springframework.lang.NonNull; -import org.springframework.stereotype.Repository; - -@Repository -public class DBOperationDAO implements OperationDAO { - - private JDBCConnectionManager jdbcConnectionManager; - private VehicleDAO vehicleDAO; - - public DBOperationDAO(JDBCConnectionManager jdbcConnectionManager, VehicleDAO vehicleDAO) { - this.jdbcConnectionManager = jdbcConnectionManager; - this.vehicleDAO = vehicleDAO; - } - - @Override - public long add(@NonNull Operation o) throws PersistenceException { - String sql = - "INSERT INTO Operation(opCode, severity, created, destination, additionalInfo," - + " status) VALUES (?, ?, ?, ?, ?, ?)"; - String sql2 = "INSERT INTO VehicleOperation(vehicleId, operationId) VALUES (?, ?)"; - long operationId; - - try { - Connection con = jdbcConnectionManager.getConnection(); - con.setAutoCommit(false); - try (PreparedStatement pstmt = con.prepareStatement(sql)) { - pstmt.setString(1, o.opCode()); - pstmt.setInt(2, o.severity().ordinal()); - pstmt.setTimestamp(3, Timestamp.from(Objects.requireNonNull(o.created()))); - pstmt.setString(4, o.destination()); - pstmt.setString(5, o.additionalInfo()); - pstmt.setInt(6, o.status().ordinal()); - pstmt.executeUpdate(); - - try (ResultSet rs = pstmt.getGeneratedKeys()) { - if (!rs.next()) throw new PersistenceException("Failed to persist operation"); - - operationId = rs.getLong(1); - } - } - - try (PreparedStatement pstmt = con.prepareStatement(sql2)) { - pstmt.setLong(2, operationId); - - for (long id : (Iterable) o.vehicles().stream().map(Vehicle::id)::iterator) { - pstmt.setLong(1, id); - pstmt.addBatch(); - } - - pstmt.executeBatch(); - } - con.commit(); - con.setAutoCommit(true); - return operationId; - } catch (SQLException e) { - throw new PersistenceException(e); - } - } - - @Override - public void update(@NonNull Operation o) throws ElementNotFoundException, PersistenceException { - // Note this will, by design, not update created - String sql = - "UPDATE Operation SET opCode = ?, severity = ?, destination = ?," - + " additionalInfo = ?, status = ? WHERE id = ?"; - String sql2 = "DELETE FROM VehicleOperation WHERE operationId = ?"; - String sql3 = "INSERT INTO VehicleOperation(vehicleId, operationId) VALUES (?, ?)"; - - try { - Connection con = jdbcConnectionManager.getConnection(); - con.setAutoCommit(false); - try (PreparedStatement pstmt = con.prepareStatement(sql)) { - pstmt.setString(1, o.opCode()); - pstmt.setInt(2, o.severity().ordinal()); - pstmt.setString(3, o.destination()); - pstmt.setString(4, o.additionalInfo()); - pstmt.setInt(5, o.status().ordinal()); - pstmt.setLong(6, o.id()); - - if (pstmt.executeUpdate() != 1) - throw new ElementNotFoundException("No such operationId exists"); - } - - try (PreparedStatement pstmt = con.prepareStatement(sql2)) { - pstmt.setLong(1, o.id()); - pstmt.executeUpdate(); - } - - try (PreparedStatement pstmt = con.prepareStatement(sql3)) { - pstmt.setLong(2, o.id()); - - for (long id : (Iterable) o.vehicles().stream().map(Vehicle::id)::iterator) { - pstmt.setLong(1, id); - pstmt.addBatch(); - } - - pstmt.executeBatch(); - } - con.commit(); - con.setAutoCommit(true); - } catch (SQLException e) { - throw new PersistenceException(e); - } - } - - @Override - public Operation get(long operationId) throws ElementNotFoundException, PersistenceException { - String sql = "Select * from operation where id = ?"; - - try { - Connection con = jdbcConnectionManager.getConnection(); - try (PreparedStatement pstmt = con.prepareStatement(sql)) { - pstmt.setLong(1, operationId); - pstmt.execute(); - - try (ResultSet rs = pstmt.getResultSet()) { - if (!rs.next()) - throw new ElementNotFoundException("No such element could be found"); - - return operationFromRS(rs); - } - } - } catch (SQLException e) { - throw new PersistenceException(e); - } - } - - @Override - public Set list(EnumSet statuses) throws PersistenceException { - // This hack exists because H2 currently has a bug that prevents IN (?) with an array of - // ids, i.e. pstmt.setArray(1, con.createArrayOf("INT", intarray) from working. See - // commented code below. - String str = - statuses.stream() - .map(Enum::name) - .map(s -> "'" + s + "'") - .collect(Collectors.joining(",")); - String sql = "SELECT * FROM Operation WHERE status IN (" + str + ")"; - Set operations = new HashSet<>(); - - try { - Connection con = jdbcConnectionManager.getConnection(); - - try (PreparedStatement pstmt = con.prepareStatement(sql)) { - // Object[] arr = statuses.stream().map(Enum::ordinal).toArray(); - // pstmt.setArray(1, con.createArrayOf("INT", arr)); - - try (ResultSet rs = pstmt.executeQuery()) { - while (rs.next()) operations.add(operationFromRS(rs)); - } - } - - return operations; - } catch (SQLException e) { - throw new PersistenceException(e); - } - } - - private Operation operationFromRS(ResultSet rs) throws PersistenceException, SQLException { - Long operationId = rs.getLong("id"); - - return Operation.builder() - .id(operationId) - .opCode(rs.getString("opCode")) - .severity(Severity.valueOf(rs.getString("severity"))) - .status(Status.valueOf(rs.getString("status"))) - .vehicles(getVehiclesFromOperationId(operationId)) - .created(rs.getTimestamp("created").toInstant()) - .destination(rs.getString("destination")) - .additionalInfo(rs.getString("additionalInfo")) - .build(); - } - - private Set getVehiclesFromOperationId(long operationId) throws PersistenceException { - String sql = "SELECT vehicleId FROM VehicleOperation WHERE operationId = ?"; - Set vehicles = new HashSet<>(); - - try { - Connection con = jdbcConnectionManager.getConnection(); - try (PreparedStatement pstmt = con.prepareStatement(sql)) { - pstmt.setLong(1, operationId); - pstmt.execute(); - - try (ResultSet rs = pstmt.getResultSet()) { - while (rs.next()) { - vehicles.add(vehicleDAO.get(rs.getLong("vehicleId"))); - } - } - } - } catch (SQLException e) { - throw new PersistenceException(e); - } catch (ElementNotFoundException e) { - throw new PersistenceException("VehicleOperation contained nonexistent vehicle", e); - } - - return vehicles; - } -} diff --git a/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/EmployeeDatabaseDAO.java b/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/EmployeeDatabaseDAO.java new file mode 100644 index 0000000..fd0add7 --- /dev/null +++ b/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/EmployeeDatabaseDAO.java @@ -0,0 +1,196 @@ +package at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dao; + +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Employee; +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Employee.EducationLevel; +import at.ac.tuwien.sepm.assignment.groupphase.exception.ElementNotFoundException; +import at.ac.tuwien.sepm.assignment.groupphase.exception.PersistenceException; +import at.ac.tuwien.sepm.assignment.groupphase.util.JDBCConnectionManager; +import java.lang.invoke.MethodHandles; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Savepoint; +import java.sql.Statement; +import java.sql.Timestamp; +import java.util.HashSet; +import java.util.Set; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Repository; + +@Repository +public class EmployeeDatabaseDAO implements EmployeeDAO { + + private static final Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); + private static final String INSERT_EMPLOYEE_VERSION = + "INSERT INTO EmployeeVersion(name, birthday, educationLevel, isDriver, isPilot) " + + "VALUES(?, ?, ?, ?, ?)"; + private static final String INSERT_EMPLOYEE = "INSERT INTO Employee(version) VALUES(?)"; + private static final String LIST_EMPLOYEE = + "SELECT emp.id, v.name, v.birthday, v.educationLevel, v.isDriver, v.isPilot " + + "FROM employee emp " + + "JOIN EmployeeVersion v ON v.id = emp.version"; + private static final String UPDATE_EMPLOYEE = "UPDATE Employee SET version = ? WHERE id = ?"; + + private final PreparedStatement insertEmployeeVersion, + insertEmployee, + listEmployee, + updateEmployee; + + private final Connection connection; + + public EmployeeDatabaseDAO(JDBCConnectionManager connectionManager) + throws PersistenceException { + + try { + + connection = connectionManager.getConnection(); + insertEmployeeVersion = + connection.prepareStatement( + INSERT_EMPLOYEE_VERSION, Statement.RETURN_GENERATED_KEYS); + insertEmployee = + connection.prepareStatement(INSERT_EMPLOYEE, Statement.RETURN_GENERATED_KEYS); + + listEmployee = connection.prepareStatement(LIST_EMPLOYEE); + + updateEmployee = connection.prepareStatement(UPDATE_EMPLOYEE); + + } catch (SQLException e) { + throw new PersistenceException(e); + } + } + + @Override + public long add(Employee employee) throws PersistenceException { + + // Assumption: the given employee is already validated (from service) + Savepoint savepoint = null; + try { + savepoint = connection.setSavepoint(); + connection.setAutoCommit(false); + insertEmployeeVersion.setString(1, employee.name()); + insertEmployeeVersion.setTimestamp( + 2, Timestamp.valueOf(employee.birthday().atStartOfDay())); + insertEmployeeVersion.setString(3, employee.educationLevel().toString()); + insertEmployeeVersion.setBoolean(4, employee.isDriver()); + insertEmployeeVersion.setBoolean(5, employee.isPilot()); + insertEmployeeVersion.executeUpdate(); + ResultSet resultSetEmployeeVersion = insertEmployeeVersion.getGeneratedKeys(); + if (resultSetEmployeeVersion.next()) { + long versionId = resultSetEmployeeVersion.getLong(1); + + insertEmployee.setLong(1, versionId); + insertEmployee.executeUpdate(); + + ResultSet resultSetEmployee = insertEmployee.getGeneratedKeys(); + if (resultSetEmployee.next()) { + connection.commit(); + return resultSetEmployee.getLong(1); + } + } + + throw new PersistenceException("Employee was not updated"); + + } catch (SQLException e) { + try { + if (savepoint != null) { + connection.rollback(savepoint); + } + } catch (SQLException e1) { + throw new PersistenceException(e); + } + throw new PersistenceException(e); + } finally { + try { + connection.setAutoCommit(true); + } catch (SQLException e) { + throw new PersistenceException(e); + } + } + } + + @Override + public void update(Employee employee) throws ElementNotFoundException, PersistenceException { + + Savepoint savepoint = null; + try { + savepoint = connection.setSavepoint(); + connection.setAutoCommit(false); + + insertEmployeeVersion.setString(1, employee.name()); + insertEmployeeVersion.setTimestamp( + 2, Timestamp.valueOf(employee.birthday().atStartOfDay())); + insertEmployeeVersion.setString(3, employee.educationLevel().toString()); + insertEmployeeVersion.setBoolean(4, employee.isDriver()); + insertEmployeeVersion.setBoolean(5, employee.isPilot()); + insertEmployeeVersion.executeUpdate(); + ResultSet resultSetEmployeeVersion = insertEmployeeVersion.getGeneratedKeys(); + + if (resultSetEmployeeVersion.next()) { + long versionId = resultSetEmployeeVersion.getLong(1); + + updateEmployee.setLong(1, versionId); + updateEmployee.setLong(2, employee.id()); + int affectedRows = updateEmployee.executeUpdate(); + + if (affectedRows == 1) { + connection.commit(); + } else { + throw new ElementNotFoundException( + "element not found with id: " + employee.id()); + } + } + + } catch (SQLException e) { + try { + if (savepoint != null) { + connection.rollback(savepoint); + } + } catch (SQLException e1) { + throw new PersistenceException(e); + } + throw new PersistenceException(e); + } finally { + try { + connection.setAutoCommit(true); + } catch (SQLException e) { + throw new PersistenceException(e); + } + } + } + + @Override + public Set list() throws PersistenceException { + + try { + ResultSet rs = listEmployee.executeQuery(); + + Set employees = new HashSet<>(); + while (rs.next()) { + + Employee employee = + Employee.builder() + .id(rs.getLong(1)) + .name(rs.getString(2)) + .birthday(rs.getTimestamp(3).toLocalDateTime().toLocalDate()) + .educationLevel(EducationLevel.valueOf(rs.getString(4))) + .isDriver(rs.getBoolean(5)) + .isPilot(rs.getBoolean(6)) + .build(); + + employees.add(employee); + } + + return employees; + + } catch (SQLException e) { + throw new PersistenceException(e); + } + } + + @Override + public void remove(long id) throws ElementNotFoundException, PersistenceException { + throw new UnsupportedOperationException(); + } +} diff --git a/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/EmployeeDatabaseDao.java b/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/EmployeeDatabaseDao.java deleted file mode 100644 index 40a9134..0000000 --- a/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/EmployeeDatabaseDao.java +++ /dev/null @@ -1,196 +0,0 @@ -package at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dao; - -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Employee; -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Employee.EducationLevel; -import at.ac.tuwien.sepm.assignment.groupphase.exception.ElementNotFoundException; -import at.ac.tuwien.sepm.assignment.groupphase.exception.PersistenceException; -import at.ac.tuwien.sepm.assignment.groupphase.util.JDBCConnectionManager; -import java.lang.invoke.MethodHandles; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Savepoint; -import java.sql.Statement; -import java.sql.Timestamp; -import java.util.HashSet; -import java.util.Set; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Repository; - -@Repository -public class EmployeeDatabaseDao implements EmployeeDAO { - - private static final Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); - private static final String INSERT_EMPLOYEE_VERSION = - "INSERT INTO EmployeeVersion(name, birthday, educationLevel, isDriver, isPilot) " - + "VALUES(?, ?, ?, ?, ?)"; - private static final String INSERT_EMPLOYEE = "INSERT INTO Employee(version) VALUES(?)"; - private static final String LIST_EMPLOYEE = - "SELECT emp.id, v.name, v.birthday, v.educationLevel, v.isDriver, v.isPilot " - + "FROM employee emp " - + "JOIN EmployeeVersion v ON v.id = emp.version"; - private static final String UPDATE_EMPLOYEE = "UPDATE Employee SET version = ? WHERE id = ?"; - - private final PreparedStatement insertEmployeeVersion, - insertEmployee, - listEmployee, - updateEmployee; - - private final Connection connection; - - public EmployeeDatabaseDao(JDBCConnectionManager connectionManager) - throws PersistenceException { - - try { - - connection = connectionManager.getConnection(); - insertEmployeeVersion = - connection.prepareStatement( - INSERT_EMPLOYEE_VERSION, Statement.RETURN_GENERATED_KEYS); - insertEmployee = - connection.prepareStatement(INSERT_EMPLOYEE, Statement.RETURN_GENERATED_KEYS); - - listEmployee = connection.prepareStatement(LIST_EMPLOYEE); - - updateEmployee = connection.prepareStatement(UPDATE_EMPLOYEE); - - } catch (SQLException e) { - throw new PersistenceException(e); - } - } - - @Override - public long add(Employee employee) throws PersistenceException { - - // Assumption: the given employee is already validated (from service) - Savepoint savepoint = null; - try { - savepoint = connection.setSavepoint(); - connection.setAutoCommit(false); - insertEmployeeVersion.setString(1, employee.name()); - insertEmployeeVersion.setTimestamp( - 2, Timestamp.valueOf(employee.birthday().atStartOfDay())); - insertEmployeeVersion.setString(3, employee.educationLevel().toString()); - insertEmployeeVersion.setBoolean(4, employee.isDriver()); - insertEmployeeVersion.setBoolean(5, employee.isPilot()); - insertEmployeeVersion.executeUpdate(); - ResultSet resultSetEmployeeVersion = insertEmployeeVersion.getGeneratedKeys(); - if (resultSetEmployeeVersion.next()) { - long versionId = resultSetEmployeeVersion.getLong(1); - - insertEmployee.setLong(1, versionId); - insertEmployee.executeUpdate(); - - ResultSet resultSetEmployee = insertEmployee.getGeneratedKeys(); - if (resultSetEmployee.next()) { - connection.commit(); - return resultSetEmployee.getLong(1); - } - } - - throw new PersistenceException("Employee was not updated"); - - } catch (SQLException e) { - try { - if (savepoint != null) { - connection.rollback(savepoint); - } - } catch (SQLException e1) { - throw new PersistenceException(e); - } - throw new PersistenceException(e); - } finally { - try { - connection.setAutoCommit(true); - } catch (SQLException e) { - throw new PersistenceException(e); - } - } - } - - @Override - public void update(Employee employee) throws ElementNotFoundException, PersistenceException { - - Savepoint savepoint = null; - try { - savepoint = connection.setSavepoint(); - connection.setAutoCommit(false); - - insertEmployeeVersion.setString(1, employee.name()); - insertEmployeeVersion.setTimestamp( - 2, Timestamp.valueOf(employee.birthday().atStartOfDay())); - insertEmployeeVersion.setString(3, employee.educationLevel().toString()); - insertEmployeeVersion.setBoolean(4, employee.isDriver()); - insertEmployeeVersion.setBoolean(5, employee.isPilot()); - insertEmployeeVersion.executeUpdate(); - ResultSet resultSetEmployeeVersion = insertEmployeeVersion.getGeneratedKeys(); - - if (resultSetEmployeeVersion.next()) { - long versionId = resultSetEmployeeVersion.getLong(1); - - updateEmployee.setLong(1, versionId); - updateEmployee.setLong(2, employee.id()); - int affectedRows = updateEmployee.executeUpdate(); - - if (affectedRows == 1) { - connection.commit(); - } else { - throw new ElementNotFoundException( - "element not found with id: " + employee.id()); - } - } - - } catch (SQLException e) { - try { - if (savepoint != null) { - connection.rollback(savepoint); - } - } catch (SQLException e1) { - throw new PersistenceException(e); - } - throw new PersistenceException(e); - } finally { - try { - connection.setAutoCommit(true); - } catch (SQLException e) { - throw new PersistenceException(e); - } - } - } - - @Override - public Set list() throws PersistenceException { - - try { - ResultSet rs = listEmployee.executeQuery(); - - Set employees = new HashSet<>(); - while (rs.next()) { - - Employee employee = - Employee.builder() - .id(rs.getLong(1)) - .name(rs.getString(2)) - .birthday(rs.getTimestamp(3).toLocalDateTime().toLocalDate()) - .educationLevel(EducationLevel.valueOf(rs.getString(4))) - .isDriver(rs.getBoolean(5)) - .isPilot(rs.getBoolean(6)) - .build(); - - employees.add(employee); - } - - return employees; - - } catch (SQLException e) { - throw new PersistenceException(e); - } - } - - @Override - public void remove(long id) throws ElementNotFoundException, PersistenceException { - throw new UnsupportedOperationException(); - } -} diff --git a/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/OperationDatabaseDAO.java b/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/OperationDatabaseDAO.java new file mode 100644 index 0000000..0a465f2 --- /dev/null +++ b/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/OperationDatabaseDAO.java @@ -0,0 +1,218 @@ +package at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dao; + +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Operation; +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Operation.Severity; +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Operation.Status; +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Vehicle; +import at.ac.tuwien.sepm.assignment.groupphase.exception.ElementNotFoundException; +import at.ac.tuwien.sepm.assignment.groupphase.exception.PersistenceException; +import at.ac.tuwien.sepm.assignment.groupphase.util.JDBCConnectionManager; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.util.EnumSet; +import java.util.HashSet; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; +import org.springframework.lang.NonNull; +import org.springframework.stereotype.Repository; + +@Repository +public class OperationDatabaseDAO implements OperationDAO { + + private JDBCConnectionManager jdbcConnectionManager; + private VehicleDAO vehicleDAO; + + public OperationDatabaseDAO( + JDBCConnectionManager jdbcConnectionManager, VehicleDAO vehicleDAO) { + this.jdbcConnectionManager = jdbcConnectionManager; + this.vehicleDAO = vehicleDAO; + } + + @Override + public long add(@NonNull Operation o) throws PersistenceException { + String sql = + "INSERT INTO Operation(opCode, severity, created, destination, additionalInfo," + + " status) VALUES (?, ?, ?, ?, ?, ?)"; + String sql2 = "INSERT INTO VehicleOperation(vehicleId, operationId) VALUES (?, ?)"; + long operationId; + + try { + Connection con = jdbcConnectionManager.getConnection(); + con.setAutoCommit(false); + try (PreparedStatement pstmt = con.prepareStatement(sql)) { + pstmt.setString(1, o.opCode()); + pstmt.setInt(2, o.severity().ordinal()); + pstmt.setTimestamp(3, Timestamp.from(Objects.requireNonNull(o.created()))); + pstmt.setString(4, o.destination()); + pstmt.setString(5, o.additionalInfo()); + pstmt.setInt(6, o.status().ordinal()); + pstmt.executeUpdate(); + + try (ResultSet rs = pstmt.getGeneratedKeys()) { + if (!rs.next()) throw new PersistenceException("Failed to persist operation"); + + operationId = rs.getLong(1); + } + } + + try (PreparedStatement pstmt = con.prepareStatement(sql2)) { + pstmt.setLong(2, operationId); + + for (long id : (Iterable) o.vehicles().stream().map(Vehicle::id)::iterator) { + pstmt.setLong(1, id); + pstmt.addBatch(); + } + + pstmt.executeBatch(); + } + con.commit(); + con.setAutoCommit(true); + return operationId; + } catch (SQLException e) { + throw new PersistenceException(e); + } + } + + @Override + public void update(@NonNull Operation o) throws ElementNotFoundException, PersistenceException { + // Note this will, by design, not update created + String sql = + "UPDATE Operation SET opCode = ?, severity = ?, destination = ?," + + " additionalInfo = ?, status = ? WHERE id = ?"; + String sql2 = "DELETE FROM VehicleOperation WHERE operationId = ?"; + String sql3 = "INSERT INTO VehicleOperation(vehicleId, operationId) VALUES (?, ?)"; + + try { + Connection con = jdbcConnectionManager.getConnection(); + con.setAutoCommit(false); + try (PreparedStatement pstmt = con.prepareStatement(sql)) { + pstmt.setString(1, o.opCode()); + pstmt.setInt(2, o.severity().ordinal()); + pstmt.setString(3, o.destination()); + pstmt.setString(4, o.additionalInfo()); + pstmt.setInt(5, o.status().ordinal()); + pstmt.setLong(6, o.id()); + + if (pstmt.executeUpdate() != 1) + throw new ElementNotFoundException("No such operationId exists"); + } + + try (PreparedStatement pstmt = con.prepareStatement(sql2)) { + pstmt.setLong(1, o.id()); + pstmt.executeUpdate(); + } + + try (PreparedStatement pstmt = con.prepareStatement(sql3)) { + pstmt.setLong(2, o.id()); + + for (long id : (Iterable) o.vehicles().stream().map(Vehicle::id)::iterator) { + pstmt.setLong(1, id); + pstmt.addBatch(); + } + + pstmt.executeBatch(); + } + con.commit(); + con.setAutoCommit(true); + } catch (SQLException e) { + throw new PersistenceException(e); + } + } + + @Override + public Operation get(long operationId) throws ElementNotFoundException, PersistenceException { + String sql = "Select * from operation where id = ?"; + + try { + Connection con = jdbcConnectionManager.getConnection(); + try (PreparedStatement pstmt = con.prepareStatement(sql)) { + pstmt.setLong(1, operationId); + pstmt.execute(); + + try (ResultSet rs = pstmt.getResultSet()) { + if (!rs.next()) + throw new ElementNotFoundException("No such element could be found"); + + return operationFromRS(rs); + } + } + } catch (SQLException e) { + throw new PersistenceException(e); + } + } + + @Override + public Set list(EnumSet statuses) throws PersistenceException { + // This hack exists because H2 currently has a bug that prevents IN (?) with an array of + // ids, i.e. pstmt.setArray(1, con.createArrayOf("INT", intarray) from working. See + // commented code below. + String str = + statuses.stream() + .map(Enum::name) + .map(s -> "'" + s + "'") + .collect(Collectors.joining(",")); + String sql = "SELECT * FROM Operation WHERE status IN (" + str + ")"; + Set operations = new HashSet<>(); + + try { + Connection con = jdbcConnectionManager.getConnection(); + + try (PreparedStatement pstmt = con.prepareStatement(sql)) { + // Object[] arr = statuses.stream().map(Enum::ordinal).toArray(); + // pstmt.setArray(1, con.createArrayOf("INT", arr)); + + try (ResultSet rs = pstmt.executeQuery()) { + while (rs.next()) operations.add(operationFromRS(rs)); + } + } + + return operations; + } catch (SQLException e) { + throw new PersistenceException(e); + } + } + + private Operation operationFromRS(ResultSet rs) throws PersistenceException, SQLException { + Long operationId = rs.getLong("id"); + + return Operation.builder() + .id(operationId) + .opCode(rs.getString("opCode")) + .severity(Severity.valueOf(rs.getString("severity"))) + .status(Status.valueOf(rs.getString("status"))) + .vehicles(getVehiclesFromOperationId(operationId)) + .created(rs.getTimestamp("created").toInstant()) + .destination(rs.getString("destination")) + .additionalInfo(rs.getString("additionalInfo")) + .build(); + } + + private Set getVehiclesFromOperationId(long operationId) throws PersistenceException { + String sql = "SELECT vehicleId FROM VehicleOperation WHERE operationId = ?"; + Set vehicles = new HashSet<>(); + + try { + Connection con = jdbcConnectionManager.getConnection(); + try (PreparedStatement pstmt = con.prepareStatement(sql)) { + pstmt.setLong(1, operationId); + pstmt.execute(); + + try (ResultSet rs = pstmt.getResultSet()) { + while (rs.next()) { + vehicles.add(vehicleDAO.get(rs.getLong("vehicleId"))); + } + } + } + } catch (SQLException e) { + throw new PersistenceException(e); + } catch (ElementNotFoundException e) { + throw new PersistenceException("VehicleOperation contained nonexistent vehicle", e); + } + + return vehicles; + } +} diff --git a/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/VehicleDatabaseDAO.java b/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/VehicleDatabaseDAO.java new file mode 100644 index 0000000..6d50588 --- /dev/null +++ b/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/VehicleDatabaseDAO.java @@ -0,0 +1,220 @@ +package at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dao; + +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Vehicle; +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Vehicle.ConstructionType; +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Vehicle.Status; +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Vehicle.VehicleType; +import at.ac.tuwien.sepm.assignment.groupphase.exception.ElementNotFoundException; +import at.ac.tuwien.sepm.assignment.groupphase.exception.PersistenceException; +import at.ac.tuwien.sepm.assignment.groupphase.util.JDBCConnectionManager; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.HashSet; +import java.util.Set; +import org.springframework.stereotype.Repository; + +@Repository +public class VehicleDatabaseDAO implements VehicleDAO { + + private final JDBCConnectionManager jdbcConnectionManager; + private RegistrationDatabaseDAO registrationDatabaseDao; + + public VehicleDatabaseDAO( + JDBCConnectionManager j, RegistrationDatabaseDAO registrationDatabaseDao) { + jdbcConnectionManager = j; + this.registrationDatabaseDao = registrationDatabaseDao; + } + + public long add(Vehicle vehicle) throws PersistenceException { + String query1 = + "INSERT INTO VehicleVersion (name,hasNef,constructionType,type) VALUES (?,?,?,?)"; + String query2 = "INSERT INTO Vehicle (version,status) VALUES (?,?)"; + + String status = "ABGEMELDET"; + String name = ""; + int id = -1; + int version = -1; + try { + Connection connection = jdbcConnectionManager.getConnection(); + connection.setAutoCommit(false); + try (PreparedStatement p1 = + connection.prepareStatement(query1, PreparedStatement.RETURN_GENERATED_KEYS)) { + + p1.setString(1, name); + p1.setBoolean(2, vehicle.hasNef()); + p1.setString(3, vehicle.constructionType().name()); + + p1.setString(4, vehicle.type().name()); + + p1.executeUpdate(); + try (ResultSet keyResultSet = p1.getGeneratedKeys()) { + + if (keyResultSet.next()) { + version = keyResultSet.getInt(1); + } + } + } + try (PreparedStatement p2 = + connection.prepareStatement(query2, Statement.RETURN_GENERATED_KEYS)) { + + p2.setInt(1, version); + p2.setString(2, status); + p2.executeUpdate(); + try (ResultSet keyResultSet = p2.getGeneratedKeys()) { + + if (keyResultSet.next()) { + id = keyResultSet.getInt(1); + } + } + + name = vehicle.type().name() + "-" + id; + } + query1 = "UPDATE VehicleVersion SET name=? WHERE id=?"; + try (PreparedStatement p3 = connection.prepareStatement(query1)) { + p3.setString(1, name); + p3.setInt(2, version); + p3.executeUpdate(); + } + + connection.commit(); + connection.setAutoCommit(true); + } catch (SQLException e) { + throw new PersistenceException(e); + } + return id; + } + + @Override + public void update(Vehicle vehicle) throws ElementNotFoundException, PersistenceException { + String query = "SELECT * FROM vehicle WHERE id=?"; + + long vehicleID = -1; + long vehicleVersion = -1; + try { + Connection connection = jdbcConnectionManager.getConnection(); + connection.setAutoCommit(false); + try (PreparedStatement p = + connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS)) { + + p.setLong(1, vehicle.id()); + p.executeQuery(); + try (ResultSet rs = p.getResultSet()) { + while (rs.next()) { + vehicleID = rs.getLong("id"); + } + } + } + if (vehicleID == -1) { + throw new ElementNotFoundException("Vehicle don´t found"); + } + + query = + "INSERT INTO VehicleVersion (name,hasNef,constructionType,type) VALUES (?,?,?,?)"; + String name = ""; + try (PreparedStatement p = + connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS)) { + p.setString(1, name); + p.setBoolean(2, vehicle.hasNef()); + p.setString(3, vehicle.constructionType().name()); + + p.setString(4, vehicle.type().name()); + + p.executeUpdate(); + + try (ResultSet keyResultSet = p.getGeneratedKeys()) { + + if (keyResultSet.next()) { + vehicleVersion = keyResultSet.getInt(1); + } + } + if (vehicleVersion == -1) { + throw new ElementNotFoundException("Vehicle don´t found"); + } + } + name = vehicle.type().name() + "-" + vehicleID; + + query = "UPDATE VehicleVersion SET name=? WHERE id=?"; + try (PreparedStatement p = connection.prepareStatement(query)) { + + p.setString(1, name); + p.setLong(2, vehicleVersion); + p.executeUpdate(); + } + query = "UPDATE Vehicle SET version=? WHERE id=?"; + try (PreparedStatement p = connection.prepareStatement(query)) { + + p.setLong(1, vehicleVersion); + p.setLong(2, vehicleID); + p.executeUpdate(); + } + connection.commit(); + connection.setAutoCommit(true); + } catch (SQLException e) { + throw new PersistenceException(e); + } + } + + @Override + public Set list() throws PersistenceException { + Set result = new HashSet<>(); + + String sql = + "Select * from VehicleVersion, Vehicle where VehicleVersion.id=Vehicle.version"; + + try (PreparedStatement pstmt = + jdbcConnectionManager.getConnection().prepareStatement(sql)) { + pstmt.executeQuery(); + try (ResultSet rs = pstmt.getResultSet()) { + while (rs.next()) { + result.add(vehicleFromRS(rs)); + } + } + } catch (SQLException e) { + throw new PersistenceException("Die Werte konnten nicht geladen werden.", e); + } + return result; + } + + @Override + public Vehicle get(long id) throws ElementNotFoundException, PersistenceException { + String sql = + "SELECT a.id, b.name, b.constructionType, b.type, a.status, b.hasNef" + + " FROM Vehicle a" + + " INNER JOIN VehicleVersion b" + + " ON version = b.id" + + " WHERE a.id = ?"; + + try { + Connection con = jdbcConnectionManager.getConnection(); + try (PreparedStatement pstmt = con.prepareStatement(sql)) { + pstmt.setLong(1, id); + + try (ResultSet rs = pstmt.executeQuery()) { + if (!rs.first()) throw new ElementNotFoundException("No such vehicle exists"); + + return vehicleFromRS(rs); + } + } + } catch (SQLException e) { + throw new PersistenceException(e); + } + } + + @Override + public void remove(long id) throws ElementNotFoundException, PersistenceException {} + + private Vehicle vehicleFromRS(ResultSet rs) throws SQLException, PersistenceException { + return Vehicle.builder() + .id(rs.getLong("Vehicle.id")) + .name(rs.getString("name")) + .constructionType(ConstructionType.values()[rs.getInt("constructionType")]) + .type(VehicleType.valueOf(rs.getString("type"))) + .status(Status.values()[rs.getInt("status")]) + .hasNef(rs.getBoolean("hasNef")) + .registrations(registrationDatabaseDao.list(rs.getLong("id"))) + .build(); + } +} diff --git a/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/VehicleDatabaseDao.java b/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/VehicleDatabaseDao.java deleted file mode 100644 index 89a3aca..0000000 --- a/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/VehicleDatabaseDao.java +++ /dev/null @@ -1,220 +0,0 @@ -package at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dao; - -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Vehicle; -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Vehicle.ConstructionType; -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Vehicle.Status; -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Vehicle.VehicleType; -import at.ac.tuwien.sepm.assignment.groupphase.exception.ElementNotFoundException; -import at.ac.tuwien.sepm.assignment.groupphase.exception.PersistenceException; -import at.ac.tuwien.sepm.assignment.groupphase.util.JDBCConnectionManager; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.HashSet; -import java.util.Set; -import org.springframework.stereotype.Repository; - -@Repository -public class VehicleDatabaseDao implements VehicleDAO { - - private final JDBCConnectionManager jdbcConnectionManager; - private RegistrationDatabaseDAO registrationDatabaseDao; - - public VehicleDatabaseDao( - JDBCConnectionManager j, RegistrationDatabaseDAO registrationDatabaseDao) { - jdbcConnectionManager = j; - this.registrationDatabaseDao = registrationDatabaseDao; - } - - public long add(Vehicle vehicle) throws PersistenceException { - String query1 = - "INSERT INTO VehicleVersion (name,hasNef,constructionType,type) VALUES (?,?,?,?)"; - String query2 = "INSERT INTO Vehicle (version,status) VALUES (?,?)"; - - String status = "ABGEMELDET"; - String name = ""; - int id = -1; - int version = -1; - try { - Connection connection = jdbcConnectionManager.getConnection(); - connection.setAutoCommit(false); - try (PreparedStatement p1 = - connection.prepareStatement(query1, PreparedStatement.RETURN_GENERATED_KEYS)) { - - p1.setString(1, name); - p1.setBoolean(2, vehicle.hasNef()); - p1.setString(3, vehicle.constructionType().name()); - - p1.setString(4, vehicle.type().name()); - - p1.executeUpdate(); - try (ResultSet keyResultSet = p1.getGeneratedKeys()) { - - if (keyResultSet.next()) { - version = keyResultSet.getInt(1); - } - } - } - try (PreparedStatement p2 = - connection.prepareStatement(query2, Statement.RETURN_GENERATED_KEYS)) { - - p2.setInt(1, version); - p2.setString(2, status); - p2.executeUpdate(); - try (ResultSet keyResultSet = p2.getGeneratedKeys()) { - - if (keyResultSet.next()) { - id = keyResultSet.getInt(1); - } - } - - name = vehicle.type().name() + "-" + id; - } - query1 = "UPDATE VehicleVersion SET name=? WHERE id=?"; - try (PreparedStatement p3 = connection.prepareStatement(query1)) { - p3.setString(1, name); - p3.setInt(2, version); - p3.executeUpdate(); - } - - connection.commit(); - connection.setAutoCommit(true); - } catch (SQLException e) { - throw new PersistenceException(e); - } - return id; - } - - @Override - public void update(Vehicle vehicle) throws ElementNotFoundException, PersistenceException { - String query = "SELECT * FROM vehicle WHERE id=?"; - - long vehicleID = -1; - long vehicleVersion = -1; - try { - Connection connection = jdbcConnectionManager.getConnection(); - connection.setAutoCommit(false); - try (PreparedStatement p = - connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS)) { - - p.setLong(1, vehicle.id()); - p.executeQuery(); - try (ResultSet rs = p.getResultSet()) { - while (rs.next()) { - vehicleID = rs.getLong("id"); - } - } - } - if (vehicleID == -1) { - throw new ElementNotFoundException("Vehicle don´t found"); - } - - query = - "INSERT INTO VehicleVersion (name,hasNef,constructionType,type) VALUES (?,?,?,?)"; - String name = ""; - try (PreparedStatement p = - connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS)) { - p.setString(1, name); - p.setBoolean(2, vehicle.hasNef()); - p.setString(3, vehicle.constructionType().name()); - - p.setString(4, vehicle.type().name()); - - p.executeUpdate(); - - try (ResultSet keyResultSet = p.getGeneratedKeys()) { - - if (keyResultSet.next()) { - vehicleVersion = keyResultSet.getInt(1); - } - } - if (vehicleVersion == -1) { - throw new ElementNotFoundException("Vehicle don´t found"); - } - } - name = vehicle.type().name() + "-" + vehicleID; - - query = "UPDATE VehicleVersion SET name=? WHERE id=?"; - try (PreparedStatement p = connection.prepareStatement(query)) { - - p.setString(1, name); - p.setLong(2, vehicleVersion); - p.executeUpdate(); - } - query = "UPDATE Vehicle SET version=? WHERE id=?"; - try (PreparedStatement p = connection.prepareStatement(query)) { - - p.setLong(1, vehicleVersion); - p.setLong(2, vehicleID); - p.executeUpdate(); - } - connection.commit(); - connection.setAutoCommit(true); - } catch (SQLException e) { - throw new PersistenceException(e); - } - } - - @Override - public Set list() throws PersistenceException { - Set result = new HashSet<>(); - - String sql = - "Select * from VehicleVersion, Vehicle where VehicleVersion.id=Vehicle.version"; - - try (PreparedStatement pstmt = - jdbcConnectionManager.getConnection().prepareStatement(sql)) { - pstmt.executeQuery(); - try (ResultSet rs = pstmt.getResultSet()) { - while (rs.next()) { - result.add(vehicleFromRS(rs)); - } - } - } catch (SQLException e) { - throw new PersistenceException("Die Werte konnten nicht geladen werden.", e); - } - return result; - } - - @Override - public Vehicle get(long id) throws ElementNotFoundException, PersistenceException { - String sql = - "SELECT a.id, b.name, b.constructionType, b.type, a.status, b.hasNef" - + " FROM Vehicle a" - + " INNER JOIN VehicleVersion b" - + " ON version = b.id" - + " WHERE a.id = ?"; - - try { - Connection con = jdbcConnectionManager.getConnection(); - try (PreparedStatement pstmt = con.prepareStatement(sql)) { - pstmt.setLong(1, id); - - try (ResultSet rs = pstmt.executeQuery()) { - if (!rs.first()) throw new ElementNotFoundException("No such vehicle exists"); - - return vehicleFromRS(rs); - } - } - } catch (SQLException e) { - throw new PersistenceException(e); - } - } - - @Override - public void remove(long id) throws ElementNotFoundException, PersistenceException {} - - private Vehicle vehicleFromRS(ResultSet rs) throws SQLException, PersistenceException { - return Vehicle.builder() - .id(rs.getLong("Vehicle.id")) - .name(rs.getString("name")) - .constructionType(ConstructionType.values()[rs.getInt("constructionType")]) - .type(VehicleType.valueOf(rs.getString("type"))) - .status(Status.values()[rs.getInt("status")]) - .hasNef(rs.getBoolean("hasNef")) - .registrations(registrationDatabaseDao.list(rs.getLong("id"))) - .build(); - } -} diff --git a/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/ui/vehiclepane/VehiclePaneController.java b/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/ui/vehiclepane/VehiclePaneController.java deleted file mode 100644 index e7a1cc0..0000000 --- a/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/ui/vehiclepane/VehiclePaneController.java +++ /dev/null @@ -1,113 +0,0 @@ -package at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.ui.vehiclepane; - -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Employee.EducationLevel; -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Registration; -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Vehicle; -import java.io.IOException; -import java.time.Instant; -import java.util.List; -import java.util.Optional; -import javafx.fxml.FXML; -import javafx.fxml.FXMLLoader; -import javafx.scene.Node; -import javafx.scene.image.Image; -import javafx.scene.image.ImageView; -import javafx.scene.text.Text; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class VehiclePaneController { - - private static Logger LOG = LoggerFactory.getLogger(VehiclePaneController.class); - - public static VehiclePaneController createVehiclePane() throws IOException { - FXMLLoader fxmlLoader = - new FXMLLoader(VehiclePaneController.class.getResource("/fxml/vehiclePane.fxml")); - Node root = fxmlLoader.load(); - VehiclePaneController result = fxmlLoader.getController(); - result.rootElement = root; - - return result; - } - - @FXML private Text txtType; - @FXML private Text txtNumber; - @FXML private ImageView ivNEF; - @FXML private Text txtNEF; - @FXML private ImageView ivQualification; - @FXML private Text txtQualification; - @FXML private Text txtRooftype; - - private Node rootElement; - private Vehicle data; - - public Node getRootElement() { - return rootElement; - } - - public Vehicle getData() { - return data; - } - - /** - * * Set the displayed data of this VehiclePane. - * - * @param vehicle The data to display. - * @param showQualification If true, the most recent registration of vehicle will be searched - * for the highest qualification. - */ - public void setData(Vehicle vehicle, boolean showQualification) { - txtType.setText(vehicle.type().name()); - String constrType = vehicle.constructionType().name(); - txtRooftype.setText( - constrType.substring(0, 1).toUpperCase() + constrType.substring(1).toLowerCase()); - txtNumber.setText("-" + vehicle.id()); - if (vehicle.hasNef()) { - ivNEF.setImage(new Image("images/NEF.png")); - txtNEF.setText("hat NEF-Halterung"); - } else { - ivNEF.setImage(new Image("images/NotNEF.png")); - txtNEF.setText("keine NEF-Halterung"); - } - if (showQualification) { - - Instant now = Instant.now(); - List regs = vehicle.registrations(); - - if (regs == null) { - return; - } - - Optional edu = - regs.stream() - .filter(reg -> reg.start().isBefore(now) && reg.end().isAfter(now)) - .map(reg -> reg.employee().educationLevel()) - .max(EducationLevel::compareTo); - - if (!edu.isPresent()) { - return; - } - - txtQualification.setText(edu.get().name()); - } else { - txtQualification.setVisible(false); - txtQualification.setManaged(false); - ivQualification.setVisible(false); - ivQualification.setManaged(false); - } - - this.data = vehicle; - } - - public void setSelected(boolean selected) { - rootElement.getStyleClass().clear(); - - if (selected) { - rootElement.getStyleClass().add("bg-yellow"); - rootElement.getStyleClass().add("shadowed"); - } else { - rootElement.getStyleClass().add("bg-white"); - rootElement.getStyleClass().add("shadowed"); - } - } -} diff --git a/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/userInterface/ArchiveOperationController.java b/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/userInterface/ArchiveOperationController.java deleted file mode 100644 index 53e7067..0000000 --- a/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/userInterface/ArchiveOperationController.java +++ /dev/null @@ -1,127 +0,0 @@ -package at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.userInterface; - -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Operation; -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Operation.Status; -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Vehicle; -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.service.OperationService; -import at.ac.tuwien.sepm.assignment.groupphase.exception.ServiceException; -import java.time.LocalDateTime; -import java.time.ZoneOffset; -import java.util.Collection; -import java.util.EnumSet; -import java.util.LinkedList; -import java.util.Objects; -import java.util.stream.Collectors; -import javafx.fxml.FXML; -import javafx.scene.control.Alert; -import javafx.scene.control.Alert.AlertType; -import javafx.scene.control.Button; -import javafx.scene.control.Hyperlink; -import javafx.scene.control.Label; -import javafx.scene.layout.AnchorPane; -import javafx.scene.layout.FlowPane; -import org.springframework.stereotype.Controller; - -@Controller -public class ArchiveOperationController { - @FXML private AnchorPane apDetails; - @FXML private Label lblCodeHeader; - @FXML private Hyperlink hypBack; - @FXML private Label lblOpCode; - @FXML private Label lblVehicles; - @FXML private Label lblDate; - @FXML private Label lblAddress; - @FXML private FlowPane fpVehicles; - private final OperationService operationService; - @FXML private FlowPane archiveOperationFlowPane; - private LinkedList list = new LinkedList<>(); - - public ArchiveOperationController(OperationService operationService) { - this.operationService = operationService; - } - - @FXML - private void initialize() { - try { - list.addAll(operationService.list(EnumSet.of(Status.CANCELLED, Status.COMPLETED))); - } catch (ServiceException e) { - Alert alert = new Alert(AlertType.ERROR); - alert.setTitle("Fehler"); - alert.setHeaderText("Fehler!"); - alert.setContentText("Die Einsätze konnten nicht geladen werden!"); - alert.showAndWait(); - } - for (Operation operation : list) { - Button b = new Button(); - b.setPrefHeight(200); - b.setPrefWidth(750 / 2); - b.setText(operation.opCode()); - b.setOnAction(event -> buttonClicked(b)); - archiveOperationFlowPane.getChildren().add(b); - } - } - - private Operation detailOperation; - - private void buttonClicked(Button button) { - int size = archiveOperationFlowPane.getChildren().size(); - int index = 0; - for (int i = 0; i < size; i++) { - if (archiveOperationFlowPane.getChildren().get(i) == button) { - index = i; - break; - } - } - detailOperation = list.get(index); - setOperation(); - setDetailsVisible(true); - } - - private void setOperation() { - lblCodeHeader.setText(detailOperation.opCode()); - String date = "am "; - if (detailOperation.created() != null) { - LocalDateTime myDateTime = - LocalDateTime.ofInstant( - Objects.requireNonNull(detailOperation.created()), ZoneOffset.UTC); - date += - myDateTime.getDayOfMonth() - + "." - + myDateTime.getMonth().getValue() - + "." - + myDateTime.getYear(); - lblDate.setText(date); - } else { - lblDate.setText("---"); - } - - lblOpCode.setText(detailOperation.opCode()); - Collection elements = - detailOperation.vehicles().stream().map(Vehicle::name).collect(Collectors.toList()); - String result = String.join(", ", elements); - - lblVehicles.setText(result); - lblAddress.setText(detailOperation.destination()); - - for (Vehicle vehicle : detailOperation.vehicles()) { - Button b = new Button(); - b.setPrefHeight(200); - b.setPrefWidth(600 / 2); - b.setText(vehicle.name()); - fpVehicles.getChildren().add(b); - } - } - - public void setListVisible(boolean b) { - archiveOperationFlowPane.setVisible(b); - } - - private void setDetailsVisible(boolean b) { - apDetails.setVisible(b); - } - - public void backClicked() { - fpVehicles.getChildren().clear(); - setDetailsVisible(false); - } -} diff --git a/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/userInterface/CreateOperationController.java b/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/userInterface/CreateOperationController.java deleted file mode 100644 index 67c8807..0000000 --- a/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/userInterface/CreateOperationController.java +++ /dev/null @@ -1,366 +0,0 @@ -package at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.userInterface; - -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Operation; -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Operation.Status; -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Registration; -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Vehicle; -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.service.OperationService; -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.service.VehicleService; -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.ui.vehiclepane.VehiclePaneController; -import at.ac.tuwien.sepm.assignment.groupphase.exception.InvalidOperationException; -import at.ac.tuwien.sepm.assignment.groupphase.exception.InvalidVehicleException; -import at.ac.tuwien.sepm.assignment.groupphase.exception.ServiceException; -import at.ac.tuwien.sepm.assignment.groupphase.util.SpringFXMLLoader; -import java.io.IOException; -import java.lang.invoke.MethodHandles; -import java.time.Instant; -import java.time.temporal.ChronoUnit; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; -import javafx.collections.FXCollections; -import javafx.event.ActionEvent; -import javafx.fxml.FXML; -import javafx.scene.Parent; -import javafx.scene.Scene; -import javafx.scene.control.Alert; -import javafx.scene.control.Alert.AlertType; -import javafx.scene.control.Button; -import javafx.scene.control.ContextMenu; -import javafx.scene.control.Label; -import javafx.scene.control.ListCell; -import javafx.scene.control.ListView; -import javafx.scene.control.MenuItem; -import javafx.scene.control.TextField; -import javafx.scene.input.KeyCode; -import javafx.scene.input.KeyEvent; -import javafx.scene.input.MouseButton; -import javafx.scene.layout.AnchorPane; -import javafx.scene.layout.FlowPane; -import javafx.stage.Stage; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Controller; - -@Controller -public class CreateOperationController { - - private static final Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); - - public AnchorPane apCreateOperation; - @FXML private TextField txtCode; - @FXML private TextField txtAddress; - @FXML private TextField txtNote; - @FXML private Button btnCreateOperation; - @FXML private ListView lvVehicles; - @FXML private ListView lvActiveOperations; - @FXML private Label lblChosenVehicles; - @FXML private AnchorPane apInvisible; - @FXML private OperationDetailsController operationDetailsController; - @FXML private FlowPane fpVehicles; - - private LinkedList chosenVehicles = new LinkedList<>(); - - private final OperationService operationService; - private final VehicleService vehicleService; - private final SpringFXMLLoader fxmlLoader; - - public CreateOperationController( - OperationService operationService, - VehicleService vehicleService, - SpringFXMLLoader fxmlLoader) { - this.operationService = operationService; - this.vehicleService = vehicleService; - this.fxmlLoader = fxmlLoader; - } - - @FXML - private void initialize() { - lblChosenVehicles.setText("keine ausgewählt"); - lvActiveOperations.setCellFactory( - param -> - new ListCell<>() { - @Override - protected void updateItem(Operation item, boolean empty) { - super.updateItem(item, empty); - - if (empty || item == null || item.opCode() == null) { - setText(null); - } else { - setText(item.opCode()); - } - } - }); - lvActiveOperations.setOnMouseClicked( - event -> { - if (event.getClickCount() == 2) { - if (lvActiveOperations.getSelectionModel().getSelectedItem() == null) { - return; - } - openDetailsWindow(lvActiveOperations.getSelectionModel().getSelectedItem()); - } - }); - } - - public void updateList() { - try { - fpVehicles.getChildren().clear(); - - // TODO: this should probably be handled differently - Set vehicles; - if (txtCode.getText().isEmpty()) { - vehicles = - vehicleService.list( - EnumSet.complementOf(EnumSet.of(Vehicle.Status.ABGEMELDET))); - } else { - vehicles = operationService.rankVehicles(txtCode.getText()); - } - - for (Vehicle vehicle : vehicles) { - VehiclePaneController controller = VehiclePaneController.createVehiclePane(); - - controller.setData(vehicle, true); - controller - .getRootElement() - .setOnMouseClicked( - event -> { - if (event.getButton().equals(MouseButton.SECONDARY)) { - createContextMenu(vehicle, vehicleService) - .show( - controller.getRootElement(), - event.getScreenX(), - event.getScreenY()); - } else { - if (chosenVehicles.contains(vehicle)) { - chosenVehicles.remove(vehicle); - controller.setSelected(false); - } else { - chosenVehicles.add(vehicle); - controller.setSelected(true); - } - - StringBuilder result = new StringBuilder(); - for (int i = 0; i < chosenVehicles.size(); i++) { - if (i == chosenVehicles.size() - 1) { - result.append(chosenVehicles.get(i).name()); - } else { - result.append(chosenVehicles.get(i).name()) - .append(", "); - } - } - if (result.toString().equals("")) { - lblChosenVehicles.setText("keine ausgewählt"); - } else { - lblChosenVehicles.setText(result.toString()); - } - } - }); - - fpVehicles.getChildren().add(controller.getRootElement()); - } - } catch (ServiceException | IOException | InvalidOperationException e) { - LOG.error("Error while updating list.", e); - - Alert alert = new Alert(Alert.AlertType.ERROR); - alert.setTitle("Fehler"); - alert.setHeaderText("Fehler!"); - alert.setContentText(e.getMessage()); - alert.showAndWait(); - } - try { - lvActiveOperations.setItems( - FXCollections.observableArrayList( - operationService.list(EnumSet.of(Status.ACTIVE)))); - } catch (ServiceException e) { - Alert alert = new Alert(Alert.AlertType.ERROR); - alert.setTitle("Fehler - Einsätze"); - alert.setHeaderText("Beim Holen der aktiven Einsätze ist ein Fehler aufgetreten."); - alert.setContentText(e.getMessage()); - alert.showAndWait(); - } - } - - private ContextMenu createContextMenu(Vehicle data, VehicleService vehicleService) { - ContextMenu menu = new ContextMenu(); - - for (Vehicle.Status status : Vehicle.Status.values()) { - if (status == Vehicle.Status.ABGEMELDET) { - continue; - } - - MenuItem mi = new MenuItem(status.name()); - - if (status == Vehicle.Status.FREI_FUNK || status == Vehicle.Status.FREI_WACHE) { - mi.getStyleClass().add("mi-free"); - } else { - mi.getStyleClass().add("mi-other"); - } - - mi.setOnAction( - event -> { - try { - vehicleService.update(data.toBuilder().status(status).build()); - this.updateList(); - } catch (InvalidVehicleException | ServiceException e) { - LOG.error("Error while setting status.", e); - Alert a = new Alert(AlertType.ERROR, e.getMessage()); - a.show(); - } - }); - - menu.getItems().add(mi); - } - - MenuItem abmelden = new MenuItem("abmelden"); - - abmelden.setOnAction( - event -> { - try { - List registrations = data.registrations(); - assert registrations - != null; // Otherwise the element shouldn't be in the list. - - List newRegistrations = new ArrayList<>(); - Instant now = Instant.now(); - - for (Registration registration : registrations) { - if (registration.start().isBefore(now) - && registration.end().isAfter(now)) { - newRegistrations.add( - registration - .toBuilder() - .end(Instant.now().minus(1, ChronoUnit.SECONDS)) - .build()); - } else newRegistrations.add(registration); - } - - vehicleService.update( - data.toBuilder() - .registrations(newRegistrations) - .status(Vehicle.Status.ABGEMELDET) - .build()); - - this.updateList(); - } catch (InvalidVehicleException | ServiceException e) { - LOG.error("Error while unregistering.", e); - Alert a = new Alert(AlertType.ERROR, e.getMessage()); - a.show(); - } - }); - - menu.getItems().add(abmelden); - return menu; - } - - @FXML - protected void createOperationClicked() { - Vehicle[] vehicles = new Vehicle[chosenVehicles.size()]; - for (int i = 0; i < chosenVehicles.size(); i++) { - vehicles[i] = chosenVehicles.get(i); - } - Operation operation = - Operation.builder() - .additionalInfo(txtNote.getText()) - .destination(txtAddress.getText()) - .opCode(txtCode.getText()) - .status(Status.ACTIVE) - .vehicles(Set.of(vehicles)) - .build(); - try { - operationService.add(operation); - } catch (ServiceException | InvalidOperationException e) { - Alert alert = new Alert(Alert.AlertType.ERROR); - alert.setTitle("Fehler"); - alert.setHeaderText("Fehler!"); - alert.setContentText(e.getMessage()); - alert.showAndWait(); - return; - } - Alert alert = new Alert(AlertType.CONFIRMATION); - alert.setTitle("Erfolg"); - alert.setHeaderText("Erfolgreich gespeichert"); - alert.setContentText("Der Einsatz wurde erfolgreich gespeichert."); - alert.showAndWait(); - updateList(); - lblChosenVehicles.setText("keine ausgewählt"); - txtAddress.setText(""); - txtCode.setText(""); - txtNote.setText(""); - chosenVehicles = new LinkedList<>(); - } - - public void onRegistrationLinkClicked(ActionEvent actionEvent) { - openNewWindow("RegistrationWindow.fxml"); - } - - public void onEmployeeLinkClicked(ActionEvent actionEvent) { - openNewWindow("listEmployees.fxml"); - } - - public void onVehicleLinkClicked(ActionEvent actionEvent) { - openNewWindow("createCar.fxml"); - } - - public void onArchivLinkClicked() { - openNewArchivWindow(); - } - - private void openNewArchivWindow() { - Stage stage = new Stage(); - try { - stage.setScene( - new Scene( - (Parent) - fxmlLoader.load( - getClass() - .getResourceAsStream( - "/fxml/ArchiveOperation.fxml")))); - } catch (IOException e) { - LOG.error("Could not open new window: {}", e); - } - stage.setTitle("Einsatz erstellen"); - stage.centerOnScreen(); - stage.show(); - updateList(); - } - - private void openNewWindow(String fxmlFileName) { - - Stage stage = new Stage(); - try { - stage.setScene( - new Scene( - (Parent) - fxmlLoader.load( - getClass() - .getResourceAsStream( - "/fxml/" + fxmlFileName)))); - } catch (IOException e) { - LOG.error("Could not open new window: {}", e); - } - - stage.setTitle("Einsatz erstellen"); - stage.centerOnScreen(); - stage.showAndWait(); // important to call wait so that updateList is executed afterwards - - updateList(); - } - - void setVisible(boolean b) { - apInvisible.setVisible(!b); - } - - private void openDetailsWindow(Operation operation) { - operationDetailsController.initOperation(operation); - this.setVisible(false); - } - - @FXML - public void onOperationCodeChanged(KeyEvent keyEvent) { - if (keyEvent.getCode() == KeyCode.ENTER) { - updateList(); - } - } -} diff --git a/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/userInterface/OperationDetailsController.java b/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/userInterface/OperationDetailsController.java deleted file mode 100644 index 9c9eb28..0000000 --- a/src/main/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/userInterface/OperationDetailsController.java +++ /dev/null @@ -1,162 +0,0 @@ -package at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.userInterface; - -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Operation; -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Operation.Status; -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Vehicle; -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.service.OperationService; -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.service.VehicleService; -import at.ac.tuwien.sepm.assignment.groupphase.exception.InvalidOperationException; -import at.ac.tuwien.sepm.assignment.groupphase.exception.ServiceException; -import java.util.Collection; -import java.util.EnumSet; -import java.util.stream.Collectors; -import javafx.collections.FXCollections; -import javafx.fxml.FXML; -import javafx.scene.control.Alert; -import javafx.scene.control.Alert.AlertType; -import javafx.scene.control.Button; -import javafx.scene.control.Label; -import javafx.scene.control.ListCell; -import javafx.scene.control.ListView; -import javafx.scene.layout.AnchorPane; -import org.springframework.stereotype.Controller; - -@Controller -public class OperationDetailsController { - - public Operation operation; - private final OperationService operationService; - private final VehicleService vehicleService; - private final CreateOperationController createOperationController; - @FXML private ListView lvVehicles; - @FXML private ListView lvActiveOperations; - @FXML private Label lblChosenVehicles; - @FXML private Button btnCloseOperation; - @FXML private Button btnCancelOperation; - @FXML private Label lblCode, lblAdditionalInfo, lblAddress; - @FXML private AnchorPane operationDetailsAP; - - public OperationDetailsController( - OperationService operationService, - VehicleService vehicleService, - CreateOperationController createOperationController) { - this.operationService = operationService; - this.vehicleService = vehicleService; - this.createOperationController = createOperationController; - } - - @FXML - private void initialize() { - lvVehicles.setCellFactory( - param -> - new ListCell<>() { - @Override - protected void updateItem(Vehicle item, boolean empty) { - super.updateItem(item, empty); - - if (empty || item == null || item.name() == null) { - setText(null); - } else { - setText(item.name()); - } - } - }); - lvActiveOperations.setCellFactory( - param -> - new ListCell<>() { - @Override - protected void updateItem(Operation item, boolean empty) { - super.updateItem(item, empty); - - if (empty || item == null || item.opCode() == null) { - setText(null); - } else { - setText(item.opCode()); - } - } - }); - lvActiveOperations.setOnMouseClicked( - event -> { - if (event.getClickCount() == 2) { - if (lvActiveOperations.getSelectionModel().getSelectedItem() == null) { - return; - } - initOperation(lvActiveOperations.getSelectionModel().getSelectedItem()); - } - }); - } - - void initOperation(Operation operation) { - fillActiveList(); - this.operation = operation; - lblCode.setText(operation.opCode()); - Collection vehicleNames = - operation.vehicles().stream().map(Vehicle::name).collect(Collectors.toList()); - String result = String.join(", ", vehicleNames); - lblChosenVehicles.setText(result.toString()); - lblAdditionalInfo.setText(operation.additionalInfo()); - lblAddress.setText(operation.destination()); - lvVehicles.setItems(FXCollections.observableArrayList(operation.vehicles())); - operationDetailsAP.setVisible(true); - } - - private void fillActiveList() { - try { - lvActiveOperations.setItems( - FXCollections.observableArrayList( - operationService.list(EnumSet.of(Status.ACTIVE)))); - } catch (ServiceException e) { - Alert alert = new Alert(AlertType.ERROR); - alert.setTitle("Fehler"); - alert.setHeaderText("Fehler!"); - alert.setContentText(e.getMessage()); - alert.showAndWait(); - } - } - - @FXML - public void closeOperationClicked() { - try { - operationService.complete(operation.id(), Status.COMPLETED); - } catch (InvalidOperationException | ServiceException e) { - Alert alert = new Alert(AlertType.ERROR); - alert.setTitle("Fehler"); - alert.setHeaderText("Fehler!"); - alert.setContentText(e.getMessage()); - alert.showAndWait(); - return; - } - Alert alert = new Alert(AlertType.CONFIRMATION); - alert.setTitle("Erfolg"); - alert.setHeaderText("Erfolgreich aktualisiert"); - alert.setContentText("Der Einsatz wurde erfolgreich aktualisiert."); - alert.showAndWait(); - closeWindow(); - createOperationController.updateList(); - } - - public void cancelOperationClicked() { - try { - operationService.complete(operation.id(), Status.CANCELLED); - } catch (InvalidOperationException | ServiceException e) { - Alert alert = new Alert(AlertType.ERROR); - alert.setTitle("Fehler"); - alert.setHeaderText("Fehler!"); - alert.setContentText(e.getMessage()); - alert.showAndWait(); - return; - } - Alert alert = new Alert(AlertType.CONFIRMATION); - alert.setTitle("Erfolg"); - alert.setHeaderText("Erfolgreich aktualisiert"); - alert.setContentText("Der Einsatz wurde erfolgreich aktualisiert."); - alert.showAndWait(); - closeWindow(); - createOperationController.updateList(); - } - - public void closeWindow() { - operationDetailsAP.setVisible(false); - this.createOperationController.setVisible(true); - } -} diff --git a/src/main/resources/fxml/ArchiveOperation.fxml b/src/main/resources/fxml/ArchiveOperation.fxml index 45d128c..88b5b39 100644 --- a/src/main/resources/fxml/ArchiveOperation.fxml +++ b/src/main/resources/fxml/ArchiveOperation.fxml @@ -7,7 +7,7 @@ - + diff --git a/src/main/resources/fxml/CreateOperationController.fxml b/src/main/resources/fxml/CreateOperationController.fxml index 9b063e3..8a8f5d7 100644 --- a/src/main/resources/fxml/CreateOperationController.fxml +++ b/src/main/resources/fxml/CreateOperationController.fxml @@ -11,7 +11,7 @@ diff --git a/src/main/resources/fxml/OperationDetails.fxml b/src/main/resources/fxml/OperationDetails.fxml index f4d2a17..3ac7d93 100644 --- a/src/main/resources/fxml/OperationDetails.fxml +++ b/src/main/resources/fxml/OperationDetails.fxml @@ -7,7 +7,7 @@ - + diff --git a/src/main/resources/fxml/vehiclePane.fxml b/src/main/resources/fxml/vehiclePane.fxml index a9efaa6..f2030f6 100644 --- a/src/main/resources/fxml/vehiclePane.fxml +++ b/src/main/resources/fxml/vehiclePane.fxml @@ -10,7 +10,7 @@ - + diff --git a/src/test/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/EmployeeDAOTest.java b/src/test/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/EmployeeDAOTest.java new file mode 100644 index 0000000..585e5ea --- /dev/null +++ b/src/test/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/EmployeeDAOTest.java @@ -0,0 +1,254 @@ +package at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dao; + +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Employee; +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Employee.EducationLevel; +import at.ac.tuwien.sepm.assignment.groupphase.exception.ElementNotFoundException; +import at.ac.tuwien.sepm.assignment.groupphase.exception.PersistenceException; +import at.ac.tuwien.sepm.assignment.groupphase.util.Helper; +import at.ac.tuwien.sepm.assignment.groupphase.util.JdbcTestCase; +import java.io.InputStream; +import java.time.LocalDate; +import java.util.Set; +import org.dbunit.Assertion; +import org.dbunit.dataset.DataSetException; +import org.dbunit.dataset.IDataSet; +import org.dbunit.dataset.ITable; +import org.dbunit.dataset.filter.DefaultColumnFilter; +import org.dbunit.dataset.xml.FlatXmlDataSetBuilder; +import org.dbunit.util.fileloader.FlatXmlDataFileLoader; +import org.junit.Assert; +import org.junit.Test; + +public class EmployeeDAOTest extends JdbcTestCase { + + private EmployeeDAO employeePersistence; + + public EmployeeDAOTest() throws PersistenceException { + employeePersistence = new EmployeeDatabaseDAO(getJdbcConnectionManager()); + } + + @Override + protected IDataSet getDataSet() throws DataSetException { + InputStream res = + getClass() + .getClassLoader() + .getResourceAsStream("EmployeePersistenceTestBaseData.xml"); + return new FlatXmlDataSetBuilder().build(res); + } + + @Test + public void testListEmployees() throws PersistenceException { + Set employees = employeePersistence.list(); + + System.out.println(LocalDate.parse("2010-10-10")); + Employee empOne = + Employee.builder() + .id(1) + .name("Adam") + .birthday(LocalDate.parse("2010-10-10")) + .educationLevel(EducationLevel.RS) + .isDriver(true) + .isPilot(false) + .build(); + + Employee empTwo = + Employee.builder() + .id(2) + .name("Max") + .birthday(LocalDate.parse("1990-11-11")) + .educationLevel(EducationLevel.NFS) + .isDriver(false) + .isPilot(false) + .build(); + + Employee empThree = + Employee.builder() + .id(3) + .name("Lisa") + .birthday(LocalDate.parse("1999-10-16")) + .educationLevel(EducationLevel.NKI) + .isDriver(true) + .isPilot(false) + .build(); + + Assert.assertTrue(employees.contains(empOne)); + Assert.assertTrue(employees.contains(empTwo)); + Assert.assertTrue(employees.contains(empThree)); + Assert.assertEquals(3, employees.size()); + } + + @Test + public void testEmployeeListNoElement() throws PersistenceException { + Set employees = employeePersistence.list(); + + Employee empOne = + Employee.builder() + .id(10) + .name("Adam") + .birthday(LocalDate.parse("2010-10-10")) + .educationLevel(EducationLevel.RS) + .isDriver(true) + .isPilot(false) + .build(); + + Assert.assertFalse(employees.contains(empOne)); + } + + Employee validEmployee = + Employee.builder() + .name("Testperson") + .birthday(LocalDate.parse("2010-11-11")) + .educationLevel(EducationLevel.NA) + .isDriver(true) + .isPilot(false) + .build(); + + @Test + public void testAddValidEmployee_EmployeeVersion() throws Exception { + + employeePersistence.add(validEmployee); + + String[] excludedColumnsEmployeeVersion = new String[] {"ID"}; + String tableEmployeeVersion = "EMPLOYEEVERSION"; + + // load actual and expected data set + IDataSet actualDataSet = getConnection().createDataSet(); + IDataSet expectedDataSet = + new FlatXmlDataFileLoader().load("/testAddValidEmployee_expected.xml"); + + // extract employeeVersion table + ITable actualEmployeeVersionTable = actualDataSet.getTable(tableEmployeeVersion); + ITable expectedEmployeeVersionTable = expectedDataSet.getTable(tableEmployeeVersion); + + // exclude 'id' column as it is an autogenerated value + ITable actualFilteredTable = + DefaultColumnFilter.excludedColumnsTable( + actualEmployeeVersionTable, excludedColumnsEmployeeVersion); + ITable expectedFilteredTable = + DefaultColumnFilter.excludedColumnsTable( + expectedEmployeeVersionTable, excludedColumnsEmployeeVersion); + + Assertion.assertEquals(expectedFilteredTable, actualFilteredTable); + } + + @Test + public void testAddValidEmployee_Employee() throws Exception { + + employeePersistence.add(validEmployee); + + String[] excludedColumnsEmployee = new String[] {"VERSION", "ID"}; + String tableEmployee = "EMPLOYEE"; + + // load actual and expected data set + IDataSet actualDataSet = getConnection().createDataSet(); + IDataSet expectedDataSet = + new FlatXmlDataFileLoader().load("/testAddValidEmployee_expected.xml"); + + // extract employee table + ITable actualEmployeeTable = actualDataSet.getTable(tableEmployee); + ITable expectedEmployeeTable = expectedDataSet.getTable(tableEmployee); + + // exclude 'version' as it is an autogenerated value + ITable actualFilteredEmpTable = + DefaultColumnFilter.excludedColumnsTable( + actualEmployeeTable, excludedColumnsEmployee); + ITable expectedFilteredEmpTable = + DefaultColumnFilter.excludedColumnsTable( + expectedEmployeeTable, excludedColumnsEmployee); + + Assertion.assertEquals(expectedFilteredEmpTable, actualFilteredEmpTable); + } + + @Test + public void testAddValidEmployee_Join() throws Exception { + + employeePersistence.add(validEmployee); + + String[] excludedColumns = new String[] {"E_VERSION", "V_ID", "E_ID"}; + String table = "EMP_JOIN"; + String expectedXmlDataFileName = "testAddValidEmployeeJoin_expected.xml"; + + String sqlJoinEmployeeVersion = + "SELECT e.id AS E_ID, v.name AS V_NAME, v.birthday AS V_BIRTHDAY, " + + "v.educationLevel as V_EDUCATIONLEVEL, " + + "v.isDriver AS V_ISDRIVER, v.isPilot AS V_ISPILOT " + + "FROM Employee e " + + "JOIN EmployeeVersion v ON e.version = v.id"; + + ITable actualFilteredJoinData = + Helper.getActualFilteredQueryTableData( + getConnection(), table, sqlJoinEmployeeVersion, excludedColumns); + + ITable expectedFilteredJoinData = + Helper.getExpectedFilteredTableData( + table, excludedColumns, expectedXmlDataFileName); + + Assertion.assertEquals(expectedFilteredJoinData, actualFilteredJoinData); + } + + Employee validUpdateEmployee = + Employee.builder() + .id(3) + .name("Lisa") + .birthday(LocalDate.parse("1999-10-16")) + .educationLevel(EducationLevel.NKA) + .isDriver(true) + .isPilot(true) + .build(); + + @Test + public void testUpdateValidEmployee_EmployeeVersion() throws Exception { + + employeePersistence.update(validUpdateEmployee); + + String[] excludedColumnsEmployeeVersion = new String[] {"ID"}; + String tableEmployeeVersion = "EMPLOYEEVERSION"; + + ITable actualTableData = + Helper.getActualFilteredTableData( + getConnection(), tableEmployeeVersion, excludedColumnsEmployeeVersion); + ITable expedtedTableData = + Helper.getExpectedFilteredTableData( + tableEmployeeVersion, + excludedColumnsEmployeeVersion, + "testUpdateValidEmployee_expected.xml"); + + Assertion.assertEquals(expedtedTableData, actualTableData); + } + + @Test + public void testUpdateValidEmployee_Employee() throws Exception { + + employeePersistence.update(validUpdateEmployee); + + String[] excludedColumns = new String[] {"VERSION"}; + String tableName = "EMPLOYEE"; + String expectedXmlDataFileName = "testUpdateValidEmployee_expected.xml"; + + ITable actualTableData = + Helper.getActualFilteredTableData(getConnection(), tableName, excludedColumns); + + ITable expectedTableData = + Helper.getExpectedFilteredTableData( + tableName, excludedColumns, expectedXmlDataFileName); + + Assertion.assertEquals(expectedTableData, actualTableData); + } + + @Test(expected = ElementNotFoundException.class) + public void testUpdateNonExistingEmployee() + throws PersistenceException, ElementNotFoundException { + + Employee nonExistentEmployee = + Employee.builder() + .id(1000) + .name("Lisa") + .birthday(LocalDate.parse("1999-10-16")) + .educationLevel(EducationLevel.NKA) + .isDriver(true) + .isPilot(true) + .build(); + + employeePersistence.update(nonExistentEmployee); + } +} diff --git a/src/test/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/EmployeePersistenceTest.java b/src/test/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/EmployeePersistenceTest.java deleted file mode 100644 index 5536c1c..0000000 --- a/src/test/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/EmployeePersistenceTest.java +++ /dev/null @@ -1,254 +0,0 @@ -package at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dao; - -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Employee; -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Employee.EducationLevel; -import at.ac.tuwien.sepm.assignment.groupphase.exception.ElementNotFoundException; -import at.ac.tuwien.sepm.assignment.groupphase.exception.PersistenceException; -import at.ac.tuwien.sepm.assignment.groupphase.util.Helper; -import at.ac.tuwien.sepm.assignment.groupphase.util.JdbcTestCase; -import java.io.InputStream; -import java.time.LocalDate; -import java.util.Set; -import org.dbunit.Assertion; -import org.dbunit.dataset.DataSetException; -import org.dbunit.dataset.IDataSet; -import org.dbunit.dataset.ITable; -import org.dbunit.dataset.filter.DefaultColumnFilter; -import org.dbunit.dataset.xml.FlatXmlDataSetBuilder; -import org.dbunit.util.fileloader.FlatXmlDataFileLoader; -import org.junit.Assert; -import org.junit.Test; - -public class EmployeePersistenceTest extends JdbcTestCase { - - private EmployeeDAO employeePersistence; - - public EmployeePersistenceTest() throws PersistenceException { - employeePersistence = new EmployeeDatabaseDao(getJdbcConnectionManager()); - } - - @Override - protected IDataSet getDataSet() throws DataSetException { - InputStream res = - getClass() - .getClassLoader() - .getResourceAsStream("EmployeePersistenceTestBaseData.xml"); - return new FlatXmlDataSetBuilder().build(res); - } - - @Test - public void testListEmployees() throws PersistenceException { - Set employees = employeePersistence.list(); - - System.out.println(LocalDate.parse("2010-10-10")); - Employee empOne = - Employee.builder() - .id(1) - .name("Adam") - .birthday(LocalDate.parse("2010-10-10")) - .educationLevel(EducationLevel.RS) - .isDriver(true) - .isPilot(false) - .build(); - - Employee empTwo = - Employee.builder() - .id(2) - .name("Max") - .birthday(LocalDate.parse("1990-11-11")) - .educationLevel(EducationLevel.NFS) - .isDriver(false) - .isPilot(false) - .build(); - - Employee empThree = - Employee.builder() - .id(3) - .name("Lisa") - .birthday(LocalDate.parse("1999-10-16")) - .educationLevel(EducationLevel.NKI) - .isDriver(true) - .isPilot(false) - .build(); - - Assert.assertTrue(employees.contains(empOne)); - Assert.assertTrue(employees.contains(empTwo)); - Assert.assertTrue(employees.contains(empThree)); - Assert.assertEquals(3, employees.size()); - } - - @Test - public void testEmployeeListNoElement() throws PersistenceException { - Set employees = employeePersistence.list(); - - Employee empOne = - Employee.builder() - .id(10) - .name("Adam") - .birthday(LocalDate.parse("2010-10-10")) - .educationLevel(EducationLevel.RS) - .isDriver(true) - .isPilot(false) - .build(); - - Assert.assertFalse(employees.contains(empOne)); - } - - Employee validEmployee = - Employee.builder() - .name("Testperson") - .birthday(LocalDate.parse("2010-11-11")) - .educationLevel(EducationLevel.NA) - .isDriver(true) - .isPilot(false) - .build(); - - @Test - public void testAddValidEmployee_EmployeeVersion() throws Exception { - - employeePersistence.add(validEmployee); - - String[] excludedColumnsEmployeeVersion = new String[] {"ID"}; - String tableEmployeeVersion = "EMPLOYEEVERSION"; - - // load actual and expected data set - IDataSet actualDataSet = getConnection().createDataSet(); - IDataSet expectedDataSet = - new FlatXmlDataFileLoader().load("/testAddValidEmployee_expected.xml"); - - // extract employeeVersion table - ITable actualEmployeeVersionTable = actualDataSet.getTable(tableEmployeeVersion); - ITable expectedEmployeeVersionTable = expectedDataSet.getTable(tableEmployeeVersion); - - // exclude 'id' column as it is an autogenerated value - ITable actualFilteredTable = - DefaultColumnFilter.excludedColumnsTable( - actualEmployeeVersionTable, excludedColumnsEmployeeVersion); - ITable expectedFilteredTable = - DefaultColumnFilter.excludedColumnsTable( - expectedEmployeeVersionTable, excludedColumnsEmployeeVersion); - - Assertion.assertEquals(expectedFilteredTable, actualFilteredTable); - } - - @Test - public void testAddValidEmployee_Employee() throws Exception { - - employeePersistence.add(validEmployee); - - String[] excludedColumnsEmployee = new String[] {"VERSION", "ID"}; - String tableEmployee = "EMPLOYEE"; - - // load actual and expected data set - IDataSet actualDataSet = getConnection().createDataSet(); - IDataSet expectedDataSet = - new FlatXmlDataFileLoader().load("/testAddValidEmployee_expected.xml"); - - // extract employee table - ITable actualEmployeeTable = actualDataSet.getTable(tableEmployee); - ITable expectedEmployeeTable = expectedDataSet.getTable(tableEmployee); - - // exclude 'version' as it is an autogenerated value - ITable actualFilteredEmpTable = - DefaultColumnFilter.excludedColumnsTable( - actualEmployeeTable, excludedColumnsEmployee); - ITable expectedFilteredEmpTable = - DefaultColumnFilter.excludedColumnsTable( - expectedEmployeeTable, excludedColumnsEmployee); - - Assertion.assertEquals(expectedFilteredEmpTable, actualFilteredEmpTable); - } - - @Test - public void testAddValidEmployee_Join() throws Exception { - - employeePersistence.add(validEmployee); - - String[] excludedColumns = new String[] {"E_VERSION", "V_ID", "E_ID"}; - String table = "EMP_JOIN"; - String expectedXmlDataFileName = "testAddValidEmployeeJoin_expected.xml"; - - String sqlJoinEmployeeVersion = - "SELECT e.id AS E_ID, v.name AS V_NAME, v.birthday AS V_BIRTHDAY, " - + "v.educationLevel as V_EDUCATIONLEVEL, " - + "v.isDriver AS V_ISDRIVER, v.isPilot AS V_ISPILOT " - + "FROM Employee e " - + "JOIN EmployeeVersion v ON e.version = v.id"; - - ITable actualFilteredJoinData = - Helper.getActualFilteredQueryTableData( - getConnection(), table, sqlJoinEmployeeVersion, excludedColumns); - - ITable expectedFilteredJoinData = - Helper.getExpectedFilteredTableData( - table, excludedColumns, expectedXmlDataFileName); - - Assertion.assertEquals(expectedFilteredJoinData, actualFilteredJoinData); - } - - Employee validUpdateEmployee = - Employee.builder() - .id(3) - .name("Lisa") - .birthday(LocalDate.parse("1999-10-16")) - .educationLevel(EducationLevel.NKA) - .isDriver(true) - .isPilot(true) - .build(); - - @Test - public void testUpdateValidEmployee_EmployeeVersion() throws Exception { - - employeePersistence.update(validUpdateEmployee); - - String[] excludedColumnsEmployeeVersion = new String[] {"ID"}; - String tableEmployeeVersion = "EMPLOYEEVERSION"; - - ITable actualTableData = - Helper.getActualFilteredTableData( - getConnection(), tableEmployeeVersion, excludedColumnsEmployeeVersion); - ITable expedtedTableData = - Helper.getExpectedFilteredTableData( - tableEmployeeVersion, - excludedColumnsEmployeeVersion, - "testUpdateValidEmployee_expected.xml"); - - Assertion.assertEquals(expedtedTableData, actualTableData); - } - - @Test - public void testUpdateValidEmployee_Employee() throws Exception { - - employeePersistence.update(validUpdateEmployee); - - String[] excludedColumns = new String[] {"VERSION"}; - String tableName = "EMPLOYEE"; - String expectedXmlDataFileName = "testUpdateValidEmployee_expected.xml"; - - ITable actualTableData = - Helper.getActualFilteredTableData(getConnection(), tableName, excludedColumns); - - ITable expectedTableData = - Helper.getExpectedFilteredTableData( - tableName, excludedColumns, expectedXmlDataFileName); - - Assertion.assertEquals(expectedTableData, actualTableData); - } - - @Test(expected = ElementNotFoundException.class) - public void testUpdateNonExistingEmployee() - throws PersistenceException, ElementNotFoundException { - - Employee nonExistentEmployee = - Employee.builder() - .id(1000) - .name("Lisa") - .birthday(LocalDate.parse("1999-10-16")) - .educationLevel(EducationLevel.NKA) - .isDriver(true) - .isPilot(true) - .build(); - - employeePersistence.update(nonExistentEmployee); - } -} diff --git a/src/test/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/OperationDAOTest.java b/src/test/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/OperationDAOTest.java index d2a6b7e..f173376 100644 --- a/src/test/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/OperationDAOTest.java +++ b/src/test/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/OperationDAOTest.java @@ -29,12 +29,12 @@ public class OperationDAOTest extends JdbcTestCase { public OperationDAOTest() throws PersistenceException { // TODO: fix once everything properly uses dependency injection - EmployeeDAO employeeDAO = new EmployeeDatabaseDao(getJdbcConnectionManager()); + EmployeeDAO employeeDAO = new EmployeeDatabaseDAO(getJdbcConnectionManager()); RegistrationDatabaseDAO registrationDatabaseDAO = new RegistrationDatabaseDAO(getJdbcConnectionManager(), employeeDAO); VehicleDAO vehicleDAO = - new VehicleDatabaseDao(getJdbcConnectionManager(), registrationDatabaseDAO); - this.operationDAO = new DBOperationDAO(getJdbcConnectionManager(), vehicleDAO); + new VehicleDatabaseDAO(getJdbcConnectionManager(), registrationDatabaseDAO); + this.operationDAO = new OperationDatabaseDAO(getJdbcConnectionManager(), vehicleDAO); Vehicle v1 = Vehicle.builder() diff --git a/src/test/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/RegistrationDAOTest.java b/src/test/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/RegistrationDAOTest.java new file mode 100644 index 0000000..e8ea809 --- /dev/null +++ b/src/test/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/RegistrationDAOTest.java @@ -0,0 +1,172 @@ +package at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dao; + +import static org.junit.Assert.*; + +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Employee; +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Employee.EducationLevel; +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Registration; +import at.ac.tuwien.sepm.assignment.groupphase.exception.PersistenceException; +import at.ac.tuwien.sepm.assignment.groupphase.util.JDBCConnectionManager; +import java.nio.charset.Charset; +import java.sql.SQLException; +import java.time.Instant; +import java.time.LocalDate; +import java.util.HashSet; +import java.util.Set; +import org.h2.tools.RunScript; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +public class RegistrationDAOTest { + + // Base taken from EmployeeDAOTest + + private static final String JDBC_DRIVER = org.h2.Driver.class.getName(); + private static final String JDBC_URL = "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1"; + private static final String USER = ""; + private static final String PASSWORD = ""; + + private RegistrationDAO registrationDAO; + + public RegistrationDAOTest() throws PersistenceException { + JDBCConnectionManager jdbcConnectionManager = new JDBCConnectionManager(JDBC_URL); + this.registrationDAO = + new RegistrationDatabaseDAO( + jdbcConnectionManager, new EmployeeDatabaseDAO(jdbcConnectionManager)); + // TODO: Use Spring Dependency Injection here! + } + + @BeforeClass + public static void setupDatabase() throws SQLException { + RunScript.execute( + JDBC_URL, + USER, + PASSWORD, + "classpath:sql/database.sql", + Charset.forName("UTF8"), + false); + RunScript.execute( + JDBC_URL, + USER, + PASSWORD, + "classpath:sql/H2RegistrationDAOTest_populate.sql", + Charset.forName("UTF8"), + false); + } + /* + @Before + public void setUp() throws SQLException { + RunScript.execute( + JDBC_URL, + USER, + PASSWORD, + "classpath:sql/H2RegistrationDAOTest_populate.sql", + Charset.forName("UTF8"), + false); + } + */ + @AfterClass + public static void tearDown() throws SQLException { + RunScript.execute( + JDBC_URL, + USER, + PASSWORD, + "classpath:sql/H2RegistrationDAOTest_depopulate.sql", + Charset.forName("UTF8"), + false); + } + + @Rule public ExpectedException thrown = ExpectedException.none(); + + @Test + public void addRegistrationsShouldSucceed() throws PersistenceException { + Set registrations = new HashSet<>(); + /* + Vehicle vehicle = Vehicle.builder() + .id(1) + .name("RTW-1") + .constructionType(ConstructionType.HOCHDACH) + .type(VehicleType.RTW) + .status(Status.ABGEMELDET) + .hasNef(true) + .build(); + */ + Employee employee1 = + Employee.builder() + .id(1) + .name("John Doe") + .birthday(LocalDate.now()) // incorrect, but should be irrelevant + .educationLevel(EducationLevel.RS) + .isDriver(true) + .isPilot(true) + .build(); + Employee employee2 = + Employee.builder() + .id(2) + .name("Nick \"Kage\" Verily") + .birthday(LocalDate.now()) // incorrect, but should be irrelevant + .educationLevel(EducationLevel.NKV) + .isDriver(true) + .isPilot(false) + .build(); + Employee employee3 = + Employee.builder() + .id(3) + .name("Nicht Arzt") + .birthday(LocalDate.now()) // incorrect, but should be irrelevant + .educationLevel(EducationLevel.NA) + .isDriver(false) + .isPilot(false) + .build(); + Registration registration1 = + Registration.builder() + .start(Instant.now()) // incorrect, but should be irrelevant to outcome + .end(Instant.now()) // same + .employee(employee1) + .build(); + Registration registration2 = + Registration.builder() + .start(Instant.now()) // incorrect, but should be irrelevant to outcome + .end(Instant.now()) // same + .employee(employee2) + .build(); + Registration registration3 = + Registration.builder() + .start(Instant.now()) // incorrect, but should be irrelevant to outcome + .end(Instant.now()) // same + .employee(employee3) + .build(); + registrations.add(registration1); + registrations.add(registration2); + registrations.add(registration3); + + Set returnvalues = registrationDAO.add(1, registrations); + assertFalse(returnvalues.isEmpty()); // can be improved... + } + + @Test + public void addRegistrationToInexistentVehicleShouldFail() throws PersistenceException { + thrown.expect(PersistenceException.class); + Set registrations = new HashSet<>(); + Employee employee = + Employee.builder() + .id(1) + .name("John Doe") + .birthday(LocalDate.now()) // incorrect, but should be irrelevant + .educationLevel(EducationLevel.RS) + .isDriver(true) + .isPilot(true) + .build(); + Registration registration = + Registration.builder() + .start(Instant.MIN) + .end(Instant.MAX) + .employee(employee) + .build(); + registrations.add(registration); + registrationDAO.add(200, registrations); + } +} diff --git a/src/test/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/RegistrationDatabaseDAOTest.java b/src/test/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/RegistrationDatabaseDAOTest.java deleted file mode 100644 index bdc16fb..0000000 --- a/src/test/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/RegistrationDatabaseDAOTest.java +++ /dev/null @@ -1,172 +0,0 @@ -package at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dao; - -import static org.junit.Assert.*; - -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Employee; -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Employee.EducationLevel; -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Registration; -import at.ac.tuwien.sepm.assignment.groupphase.exception.PersistenceException; -import at.ac.tuwien.sepm.assignment.groupphase.util.JDBCConnectionManager; -import java.nio.charset.Charset; -import java.sql.SQLException; -import java.time.Instant; -import java.time.LocalDate; -import java.util.HashSet; -import java.util.Set; -import org.h2.tools.RunScript; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - -public class RegistrationDatabaseDAOTest { - - // Base taken from EmployeePersistenceTest - - private static final String JDBC_DRIVER = org.h2.Driver.class.getName(); - private static final String JDBC_URL = "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1"; - private static final String USER = ""; - private static final String PASSWORD = ""; - - private RegistrationDAO registrationDAO; - - public RegistrationDatabaseDAOTest() throws PersistenceException { - JDBCConnectionManager jdbcConnectionManager = new JDBCConnectionManager(JDBC_URL); - this.registrationDAO = - new RegistrationDatabaseDAO( - jdbcConnectionManager, new EmployeeDatabaseDao(jdbcConnectionManager)); - // TODO: Use Spring Dependency Injection here! - } - - @BeforeClass - public static void setupDatabase() throws SQLException { - RunScript.execute( - JDBC_URL, - USER, - PASSWORD, - "classpath:sql/database.sql", - Charset.forName("UTF8"), - false); - RunScript.execute( - JDBC_URL, - USER, - PASSWORD, - "classpath:sql/H2RegistrationDAOTest_populate.sql", - Charset.forName("UTF8"), - false); - } - /* - @Before - public void setUp() throws SQLException { - RunScript.execute( - JDBC_URL, - USER, - PASSWORD, - "classpath:sql/H2RegistrationDAOTest_populate.sql", - Charset.forName("UTF8"), - false); - } - */ - @AfterClass - public static void tearDown() throws SQLException { - RunScript.execute( - JDBC_URL, - USER, - PASSWORD, - "classpath:sql/H2RegistrationDAOTest_depopulate.sql", - Charset.forName("UTF8"), - false); - } - - @Rule public ExpectedException thrown = ExpectedException.none(); - - @Test - public void addRegistrationsShouldSucceed() throws PersistenceException { - Set registrations = new HashSet<>(); - /* - Vehicle vehicle = Vehicle.builder() - .id(1) - .name("RTW-1") - .constructionType(ConstructionType.HOCHDACH) - .type(VehicleType.RTW) - .status(Status.ABGEMELDET) - .hasNef(true) - .build(); - */ - Employee employee1 = - Employee.builder() - .id(1) - .name("John Doe") - .birthday(LocalDate.now()) // incorrect, but should be irrelevant - .educationLevel(EducationLevel.RS) - .isDriver(true) - .isPilot(true) - .build(); - Employee employee2 = - Employee.builder() - .id(2) - .name("Nick \"Kage\" Verily") - .birthday(LocalDate.now()) // incorrect, but should be irrelevant - .educationLevel(EducationLevel.NKV) - .isDriver(true) - .isPilot(false) - .build(); - Employee employee3 = - Employee.builder() - .id(3) - .name("Nicht Arzt") - .birthday(LocalDate.now()) // incorrect, but should be irrelevant - .educationLevel(EducationLevel.NA) - .isDriver(false) - .isPilot(false) - .build(); - Registration registration1 = - Registration.builder() - .start(Instant.now()) // incorrect, but should be irrelevant to outcome - .end(Instant.now()) // same - .employee(employee1) - .build(); - Registration registration2 = - Registration.builder() - .start(Instant.now()) // incorrect, but should be irrelevant to outcome - .end(Instant.now()) // same - .employee(employee2) - .build(); - Registration registration3 = - Registration.builder() - .start(Instant.now()) // incorrect, but should be irrelevant to outcome - .end(Instant.now()) // same - .employee(employee3) - .build(); - registrations.add(registration1); - registrations.add(registration2); - registrations.add(registration3); - - Set returnvalues = registrationDAO.add(1, registrations); - assertFalse(returnvalues.isEmpty()); // can be improved... - } - - @Test - public void addRegistrationToInexistentVehicleShouldFail() throws PersistenceException { - thrown.expect(PersistenceException.class); - Set registrations = new HashSet<>(); - Employee employee = - Employee.builder() - .id(1) - .name("John Doe") - .birthday(LocalDate.now()) // incorrect, but should be irrelevant - .educationLevel(EducationLevel.RS) - .isDriver(true) - .isPilot(true) - .build(); - Registration registration = - Registration.builder() - .start(Instant.MIN) - .end(Instant.MAX) - .employee(employee) - .build(); - registrations.add(registration); - registrationDAO.add(200, registrations); - } -} diff --git a/src/test/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/VehicleDAOTest.java b/src/test/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/VehicleDAOTest.java new file mode 100644 index 0000000..1862214 --- /dev/null +++ b/src/test/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/VehicleDAOTest.java @@ -0,0 +1,161 @@ +package at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dao; + +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Vehicle; +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Vehicle.ConstructionType; +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Vehicle.Status; +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Vehicle.VehicleType; +import at.ac.tuwien.sepm.assignment.groupphase.exception.ElementNotFoundException; +import at.ac.tuwien.sepm.assignment.groupphase.exception.PersistenceException; +import at.ac.tuwien.sepm.assignment.groupphase.util.Helper; +import at.ac.tuwien.sepm.assignment.groupphase.util.JdbcTestCase; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Set; +import org.dbunit.Assertion; +import org.dbunit.dataset.IDataSet; +import org.dbunit.dataset.ITable; +import org.dbunit.dataset.xml.FlatXmlDataSetBuilder; +import org.junit.Assert; +import org.junit.Test; + +public class VehicleDAOTest extends JdbcTestCase { + + private VehicleDAO vehicleDAO; + + private Vehicle validUpdateVehicle = + Vehicle.builder() + .hasNef(true) + .constructionType(ConstructionType.HOCHDACH) + .type(VehicleType.RTW) + .id(2) + .name("RTW-2") + .status(Status.ABGEMELDET) + .build(); + + public VehicleDAOTest() throws PersistenceException { + vehicleDAO = + new VehicleDatabaseDAO( + getJdbcConnectionManager(), + new RegistrationDatabaseDAO( + getJdbcConnectionManager(), + new EmployeeDatabaseDAO(getJdbcConnectionManager()))); + // TODO: use Spring Dependency Injection! + } + + @Override + protected IDataSet getDataSet() throws Exception { + InputStream res = getClass().getClassLoader().getResourceAsStream("vehicleTestData.xml"); + return new FlatXmlDataSetBuilder().build(res); + } + + @Test + public void testListVehicle() throws PersistenceException { + Set vehicles = vehicleDAO.list(); + + Vehicle v1 = + Vehicle.builder() + .id(1) + .constructionType(ConstructionType.HOCHDACH) + .name("RTW-1") + .hasNef(true) + .status(Status.ABGEMELDET) + .type(VehicleType.RTW) + .registrations(new ArrayList<>()) + .build(); + Vehicle v2 = + Vehicle.builder() + .id(2) + .constructionType(ConstructionType.MITTELHOCHDACH) + .name("KTW-2") + .hasNef(false) + .status(Status.FREI_WACHE) + .type(VehicleType.KTW) + .registrations(new ArrayList<>()) + .build(); + Vehicle v3 = + Vehicle.builder() + .id(3) + .constructionType(ConstructionType.NORMAL) + .name("NEF-3") + .hasNef(false) + .status(Status.FREI_FUNK) + .type(VehicleType.NEF) + .registrations(new ArrayList<>()) + .build(); + + Assert.assertTrue(vehicles.contains(v1)); + Assert.assertTrue(vehicles.contains(v2)); + Assert.assertTrue(vehicles.contains(v3)); + Assert.assertEquals(3, vehicles.size()); + } + + @Test + public void testVehicleListNoElement() throws PersistenceException { + Set vehicles = vehicleDAO.list(); + + Vehicle v1 = + Vehicle.builder() + .id(30) + .constructionType(ConstructionType.NORMAL) + .name("NEF-3") + .hasNef(false) + .status(Status.FREI_FUNK) + .type(VehicleType.NEF) + .build(); + + Assert.assertFalse(vehicles.contains(v1)); + } + + @Test + public void testUpdateValid_VehicleVersion() throws Exception { + vehicleDAO.update(validUpdateVehicle); + + String[] excludedColumnsVehicleVersion = new String[] {"ID", "NAME"}; + String tableVehicleVersion = "VEHICLEVERSION"; + + ITable actualTableData = + Helper.getActualFilteredTableData( + getConnection(), tableVehicleVersion, excludedColumnsVehicleVersion); + + ITable expectedTableData = + Helper.getExpectedFilteredTableData( + tableVehicleVersion, + excludedColumnsVehicleVersion, + "vehicleTestUpdateExpectedData.xml"); + Assertion.assertEquals(expectedTableData, actualTableData); + } + + @Test + public void testUpdateValid_Vehicle() throws Exception { + vehicleDAO.update(validUpdateVehicle); + + String[] excludedColumnsVehicleVersion = new String[] {"VERSION", "STATUS"}; + String tableVehicleVersion = "VEHICLE"; + + ITable actualTableData = + Helper.getActualFilteredTableData( + getConnection(), tableVehicleVersion, excludedColumnsVehicleVersion); + + ITable expectedTableData = + Helper.getExpectedFilteredTableData( + tableVehicleVersion, + excludedColumnsVehicleVersion, + "vehicleTestUpdateExpectedData.xml"); + Assertion.assertEquals(expectedTableData, actualTableData); + } + + @Test(expected = ElementNotFoundException.class) + public void testUpdateNonExistingVehicle() + throws PersistenceException, ElementNotFoundException { + Vehicle nonExistentVehicle = + Vehicle.builder() + .id(35) + .constructionType(ConstructionType.NORMAL) + .name("NEF-3") + .hasNef(false) + .status(Status.FREI_FUNK) + .type(VehicleType.NEF) + .build(); + vehicleDAO.update(nonExistentVehicle); + } +} diff --git a/src/test/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/VehiclePersistenceTest.java b/src/test/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/VehiclePersistenceTest.java deleted file mode 100644 index 0beb5c1..0000000 --- a/src/test/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/dao/VehiclePersistenceTest.java +++ /dev/null @@ -1,161 +0,0 @@ -package at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dao; - -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Vehicle; -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Vehicle.ConstructionType; -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Vehicle.Status; -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Vehicle.VehicleType; -import at.ac.tuwien.sepm.assignment.groupphase.exception.ElementNotFoundException; -import at.ac.tuwien.sepm.assignment.groupphase.exception.PersistenceException; -import at.ac.tuwien.sepm.assignment.groupphase.util.Helper; -import at.ac.tuwien.sepm.assignment.groupphase.util.JdbcTestCase; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Set; -import org.dbunit.Assertion; -import org.dbunit.dataset.IDataSet; -import org.dbunit.dataset.ITable; -import org.dbunit.dataset.xml.FlatXmlDataSetBuilder; -import org.junit.Assert; -import org.junit.Test; - -public class VehiclePersistenceTest extends JdbcTestCase { - - private VehicleDAO vehicleDAO; - - private Vehicle validUpdateVehicle = - Vehicle.builder() - .hasNef(true) - .constructionType(ConstructionType.HOCHDACH) - .type(VehicleType.RTW) - .id(2) - .name("RTW-2") - .status(Status.ABGEMELDET) - .build(); - - public VehiclePersistenceTest() throws PersistenceException { - vehicleDAO = - new VehicleDatabaseDao( - getJdbcConnectionManager(), - new RegistrationDatabaseDAO( - getJdbcConnectionManager(), - new EmployeeDatabaseDao(getJdbcConnectionManager()))); - // TODO: use Spring Dependency Injection! - } - - @Override - protected IDataSet getDataSet() throws Exception { - InputStream res = getClass().getClassLoader().getResourceAsStream("vehicleTestData.xml"); - return new FlatXmlDataSetBuilder().build(res); - } - - @Test - public void testListVehicle() throws PersistenceException { - Set vehicles = vehicleDAO.list(); - - Vehicle v1 = - Vehicle.builder() - .id(1) - .constructionType(ConstructionType.HOCHDACH) - .name("RTW-1") - .hasNef(true) - .status(Status.ABGEMELDET) - .type(VehicleType.RTW) - .registrations(new ArrayList<>()) - .build(); - Vehicle v2 = - Vehicle.builder() - .id(2) - .constructionType(ConstructionType.MITTELHOCHDACH) - .name("KTW-2") - .hasNef(false) - .status(Status.FREI_WACHE) - .type(VehicleType.KTW) - .registrations(new ArrayList<>()) - .build(); - Vehicle v3 = - Vehicle.builder() - .id(3) - .constructionType(ConstructionType.NORMAL) - .name("NEF-3") - .hasNef(false) - .status(Status.FREI_FUNK) - .type(VehicleType.NEF) - .registrations(new ArrayList<>()) - .build(); - - Assert.assertTrue(vehicles.contains(v1)); - Assert.assertTrue(vehicles.contains(v2)); - Assert.assertTrue(vehicles.contains(v3)); - Assert.assertEquals(3, vehicles.size()); - } - - @Test - public void testVehicleListNoElement() throws PersistenceException { - Set vehicles = vehicleDAO.list(); - - Vehicle v1 = - Vehicle.builder() - .id(30) - .constructionType(ConstructionType.NORMAL) - .name("NEF-3") - .hasNef(false) - .status(Status.FREI_FUNK) - .type(VehicleType.NEF) - .build(); - - Assert.assertFalse(vehicles.contains(v1)); - } - - @Test - public void testUpdateValid_VehicleVersion() throws Exception { - vehicleDAO.update(validUpdateVehicle); - - String[] excludedColumnsVehicleVersion = new String[] {"ID", "NAME"}; - String tableVehicleVersion = "VEHICLEVERSION"; - - ITable actualTableData = - Helper.getActualFilteredTableData( - getConnection(), tableVehicleVersion, excludedColumnsVehicleVersion); - - ITable expectedTableData = - Helper.getExpectedFilteredTableData( - tableVehicleVersion, - excludedColumnsVehicleVersion, - "vehicleTestUpdateExpectedData.xml"); - Assertion.assertEquals(expectedTableData, actualTableData); - } - - @Test - public void testUpdateValid_Vehicle() throws Exception { - vehicleDAO.update(validUpdateVehicle); - - String[] excludedColumnsVehicleVersion = new String[] {"VERSION", "STATUS"}; - String tableVehicleVersion = "VEHICLE"; - - ITable actualTableData = - Helper.getActualFilteredTableData( - getConnection(), tableVehicleVersion, excludedColumnsVehicleVersion); - - ITable expectedTableData = - Helper.getExpectedFilteredTableData( - tableVehicleVersion, - excludedColumnsVehicleVersion, - "vehicleTestUpdateExpectedData.xml"); - Assertion.assertEquals(expectedTableData, actualTableData); - } - - @Test(expected = ElementNotFoundException.class) - public void testUpdateNonExistingVehicle() - throws PersistenceException, ElementNotFoundException { - Vehicle nonExistentVehicle = - Vehicle.builder() - .id(35) - .constructionType(ConstructionType.NORMAL) - .name("NEF-3") - .hasNef(false) - .status(Status.FREI_FUNK) - .type(VehicleType.NEF) - .build(); - vehicleDAO.update(nonExistentVehicle); - } -} diff --git a/src/test/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/service/EmployeeServiceTest.java b/src/test/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/service/EmployeeServiceTest.java index c49cd9d..90f0a44 100644 --- a/src/test/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/service/EmployeeServiceTest.java +++ b/src/test/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/service/EmployeeServiceTest.java @@ -7,7 +7,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dao.EmployeeDAO; -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dao.EmployeeDatabaseDao; +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dao.EmployeeDatabaseDAO; import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Employee; import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Employee.EducationLevel; import at.ac.tuwien.sepm.assignment.groupphase.exception.ElementNotFoundException; @@ -20,7 +20,7 @@ import org.junit.Test; public class EmployeeServiceTest { - private final EmployeeDAO employeePersistence = mock(EmployeeDatabaseDao.class); + private final EmployeeDAO employeePersistence = mock(EmployeeDatabaseDAO.class); private final EmployeeService employeeService = new EmployeeServiceImpl(employeePersistence); private final Employee.Builder employeeBuilder = diff --git a/src/test/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/service/RegistrationServiceImplTest.java b/src/test/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/service/RegistrationServiceImplTest.java deleted file mode 100644 index 95d8d77..0000000 --- a/src/test/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/service/RegistrationServiceImplTest.java +++ /dev/null @@ -1,148 +0,0 @@ -package at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.service; - -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.Mockito.when; - -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dao.RegistrationDAO; -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dao.VehicleDAO; -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Employee; -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Employee.EducationLevel; -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Registration; -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Vehicle; -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Vehicle.Builder; -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Vehicle.ConstructionType; -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Vehicle.Status; -import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Vehicle.VehicleType; -import at.ac.tuwien.sepm.assignment.groupphase.exception.ElementNotFoundException; -import at.ac.tuwien.sepm.assignment.groupphase.exception.InvalidRegistrationException; -import at.ac.tuwien.sepm.assignment.groupphase.exception.InvalidVehicleException; -import at.ac.tuwien.sepm.assignment.groupphase.exception.PersistenceException; -import at.ac.tuwien.sepm.assignment.groupphase.exception.ServiceException; -import java.time.Instant; -import java.time.LocalDate; -import java.time.temporal.ChronoUnit; -import java.util.HashSet; -import java.util.Set; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; - -public class RegistrationServiceImplTest { - - @Mock private RegistrationDAO registrationDAO; - - @Mock private VehicleDAO vehicleDAO; - - @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Rule public ExpectedException thrown = ExpectedException.none(); - - @Before - public void setUp() throws ElementNotFoundException, PersistenceException { - MockitoAnnotations.initMocks(this); - Builder b = - Vehicle.builder() - .name("RTW-1") - .constructionType(ConstructionType.HOCHDACH) - .status(Status.ABGEMELDET) - .type(VehicleType.RTW) - .hasNef(true); - when(vehicleDAO.get(anyLong())).thenAnswer(ans -> b.id(ans.getArgument(0)).build()); - } - - @Test - public void addValidRegistrationsShouldSucceed() - throws InvalidRegistrationException, ServiceException, InvalidVehicleException { - RegistrationService registrationService = - new RegistrationServiceImpl(registrationDAO, vehicleDAO); - Set registrations = new HashSet<>(); - Vehicle vehicle = - Vehicle.builder() - .id(1) - .name("RTW-1") - .constructionType(ConstructionType.HOCHDACH) - .type(VehicleType.RTW) - .status(Status.ABGEMELDET) - .hasNef(true) - .build(); - Employee employee1 = - Employee.builder() - .id(1) - .name("John Doe") - .birthday(LocalDate.now()) // incorrect, but should be irrelevant - .educationLevel(EducationLevel.RS) - .isDriver(true) - .isPilot(true) - .build(); - Employee employee2 = - Employee.builder() - .id(2) - .name("Nick \"Kage\" Verily") - .birthday(LocalDate.now()) // incorrect, but should be irrelevant - .educationLevel(EducationLevel.NKV) - .isDriver(true) - .isPilot(false) - .build(); - Employee employee3 = - Employee.builder() - .id(3) - .name("Nicht Arzt") - .birthday(LocalDate.now()) // incorrect, but should be irrelevant - .educationLevel(EducationLevel.NA) - .isDriver(false) - .isPilot(false) - .build(); - Instant start = Instant.now(); - Instant end = start.plus(8, ChronoUnit.HOURS); - Registration registration1 = - Registration.builder().start(start).end(end).employee(employee1).build(); - Registration registration2 = - Registration.builder().start(start).end(end).employee(employee2).build(); - Registration registration3 = - Registration.builder().start(start).end(end).employee(employee3).build(); - registrations.add(registration1); - registrations.add(registration2); - registrations.add(registration3); - registrationService.add(vehicle.id(), registrations); - } - - @Test - public void addOnlyOnePersonToRTWShouldFail() - throws InvalidRegistrationException, ServiceException, InvalidVehicleException { - thrown.expect(InvalidRegistrationException.class); - RegistrationService registrationService = - new RegistrationServiceImpl(registrationDAO, vehicleDAO); - Set registrations = new HashSet<>(); - Vehicle vehicle = - Vehicle.builder() - .id(1) - .name("RTW-1") - .constructionType(ConstructionType.HOCHDACH) - .type(VehicleType.RTW) - .status(Status.ABGEMELDET) - .hasNef(true) - .build(); - Employee employee = - Employee.builder() - .id(1) - .name("John Doe") - .birthday(LocalDate.now()) // incorrect, but should be irrelevant - .educationLevel(EducationLevel.RS) - .isDriver(true) - .isPilot(true) - .build(); - Registration registration = - Registration.builder() - .start(Instant.MIN) - .end(Instant.MAX) - .employee(employee) - .build(); - registrations.add(registration); - registrationService.add(vehicle.id(), registrations); - } -} diff --git a/src/test/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/service/RegistrationServiceTest.java b/src/test/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/service/RegistrationServiceTest.java new file mode 100644 index 0000000..4d3a251 --- /dev/null +++ b/src/test/java/at/ac/tuwien/sepm/assignment/groupphase/einsatzverwaltung/service/RegistrationServiceTest.java @@ -0,0 +1,148 @@ +package at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.service; + +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.when; + +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dao.RegistrationDAO; +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dao.VehicleDAO; +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Employee; +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Employee.EducationLevel; +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Registration; +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Vehicle; +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Vehicle.Builder; +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Vehicle.ConstructionType; +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Vehicle.Status; +import at.ac.tuwien.sepm.assignment.groupphase.einsatzverwaltung.dto.Vehicle.VehicleType; +import at.ac.tuwien.sepm.assignment.groupphase.exception.ElementNotFoundException; +import at.ac.tuwien.sepm.assignment.groupphase.exception.InvalidRegistrationException; +import at.ac.tuwien.sepm.assignment.groupphase.exception.InvalidVehicleException; +import at.ac.tuwien.sepm.assignment.groupphase.exception.PersistenceException; +import at.ac.tuwien.sepm.assignment.groupphase.exception.ServiceException; +import java.time.Instant; +import java.time.LocalDate; +import java.time.temporal.ChronoUnit; +import java.util.HashSet; +import java.util.Set; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.junit.MockitoJUnit; +import org.mockito.junit.MockitoRule; + +public class RegistrationServiceTest { + + @Mock private RegistrationDAO registrationDAO; + + @Mock private VehicleDAO vehicleDAO; + + @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); + + @Rule public ExpectedException thrown = ExpectedException.none(); + + @Before + public void setUp() throws ElementNotFoundException, PersistenceException { + MockitoAnnotations.initMocks(this); + Builder b = + Vehicle.builder() + .name("RTW-1") + .constructionType(ConstructionType.HOCHDACH) + .status(Status.ABGEMELDET) + .type(VehicleType.RTW) + .hasNef(true); + when(vehicleDAO.get(anyLong())).thenAnswer(ans -> b.id(ans.getArgument(0)).build()); + } + + @Test + public void addValidRegistrationsShouldSucceed() + throws InvalidRegistrationException, ServiceException, InvalidVehicleException { + RegistrationService registrationService = + new RegistrationServiceImpl(registrationDAO, vehicleDAO); + Set registrations = new HashSet<>(); + Vehicle vehicle = + Vehicle.builder() + .id(1) + .name("RTW-1") + .constructionType(ConstructionType.HOCHDACH) + .type(VehicleType.RTW) + .status(Status.ABGEMELDET) + .hasNef(true) + .build(); + Employee employee1 = + Employee.builder() + .id(1) + .name("John Doe") + .birthday(LocalDate.now()) // incorrect, but should be irrelevant + .educationLevel(EducationLevel.RS) + .isDriver(true) + .isPilot(true) + .build(); + Employee employee2 = + Employee.builder() + .id(2) + .name("Nick \"Kage\" Verily") + .birthday(LocalDate.now()) // incorrect, but should be irrelevant + .educationLevel(EducationLevel.NKV) + .isDriver(true) + .isPilot(false) + .build(); + Employee employee3 = + Employee.builder() + .id(3) + .name("Nicht Arzt") + .birthday(LocalDate.now()) // incorrect, but should be irrelevant + .educationLevel(EducationLevel.NA) + .isDriver(false) + .isPilot(false) + .build(); + Instant start = Instant.now(); + Instant end = start.plus(8, ChronoUnit.HOURS); + Registration registration1 = + Registration.builder().start(start).end(end).employee(employee1).build(); + Registration registration2 = + Registration.builder().start(start).end(end).employee(employee2).build(); + Registration registration3 = + Registration.builder().start(start).end(end).employee(employee3).build(); + registrations.add(registration1); + registrations.add(registration2); + registrations.add(registration3); + registrationService.add(vehicle.id(), registrations); + } + + @Test + public void addOnlyOnePersonToRTWShouldFail() + throws InvalidRegistrationException, ServiceException, InvalidVehicleException { + thrown.expect(InvalidRegistrationException.class); + RegistrationService registrationService = + new RegistrationServiceImpl(registrationDAO, vehicleDAO); + Set registrations = new HashSet<>(); + Vehicle vehicle = + Vehicle.builder() + .id(1) + .name("RTW-1") + .constructionType(ConstructionType.HOCHDACH) + .type(VehicleType.RTW) + .status(Status.ABGEMELDET) + .hasNef(true) + .build(); + Employee employee = + Employee.builder() + .id(1) + .name("John Doe") + .birthday(LocalDate.now()) // incorrect, but should be irrelevant + .educationLevel(EducationLevel.RS) + .isDriver(true) + .isPilot(true) + .build(); + Registration registration = + Registration.builder() + .start(Instant.MIN) + .end(Instant.MAX) + .employee(employee) + .build(); + registrations.add(registration); + registrationService.add(vehicle.id(), registrations); + } +} -- cgit v1.2.3-70-g09d2