From 0d98d36b6fd64c4eb8210c44cb67cbfac4c9ad47 Mon Sep 17 00:00:00 2001 From: AdrianBalunan Date: Fri, 24 Apr 2026 10:41:22 +0200 Subject: [PATCH 1/4] Feat: Mvn testing, formating, lifecycles and etc changes --- helpmehelpapplication/.gitignore | 1 - helpmehelpapplication/pom.xml | 19 + .../systemutvikling/team6/HmHApplication.java | 22 +- .../team6/controller/AboutPageController.java | 14 +- .../AvailableOrganizationController.java | 15 +- .../controller/CharityPageController.java | 24 +- .../controller/CreateUserPageController.java | 123 +- .../controller/DonationPageController.java | 37 +- .../team6/controller/FrontpageController.java | 41 +- .../controller/GiveFeedbackController.java | 156 +-- .../team6/controller/LoginPageController.java | 101 +- .../controller/components/BaseController.java | 95 +- .../components/CategoryTagController.java | 73 +- .../components/DonationCardController.java | 37 +- .../components/FeedbackCardController.java | 30 +- .../components/FooterController.java | 29 +- .../components/InboxCardController.java | 35 +- .../components/InterestCardController.java | 65 +- .../controller/components/LoaderScene.java | 46 +- .../components/NavbarController.java | 112 +- .../components/OrgDonationCardController.java | 33 +- .../OrganizationCardController.java | 6 +- .../profileOrgEditController.java | 175 +-- .../profileOrgInboxController.java | 200 ++-- .../profileOrgPaymentsController.java | 143 ++- .../profileOrgSettingsController.java | 226 ++-- .../profileUserHistoryController.java | 167 ++- .../profileUserInboxController.java | 156 ++- .../profileUserInterestController.java | 162 ++- .../profileUserSettingsController.java | 389 ++++--- .../team6/database/DAO/CategoryDAO.java | 22 +- .../team6/database/DAO/CharityDAO.java | 23 +- .../team6/database/DAO/CharityUserDAO.java | 246 ++-- .../team6/database/DAO/DonationDAO.java | 175 ++- .../team6/database/DAO/FavouritesDAO.java | 319 +++--- .../team6/database/DAO/FeedbackDAO.java | 190 ++-- .../team6/database/DAO/MessageDAO.java | 149 ++- .../team6/database/DAO/UserDAO.java | 183 ++- .../team6/database/DatabaseSetup.java | 2 +- .../team6/models/user/Message.java | 3 +- .../team6/models/user/User.java | 4 +- .../team6/service/AuthenticationService.java | 206 ++-- .../team6/database/DAO/CategoryDAOTest.java | 97 +- .../team6/database/DAO/CharityDAOTest.java | 639 ++++++----- .../database/DAO/CharityUserDAOTest.java | 521 +++++---- .../team6/database/DAO/DonationDAOTest.java | 144 ++- .../team6/database/DAO/FavouritesDAOTest.java | 621 +++++----- .../team6/database/DAO/FeedbackDAOTest.java | 449 ++++---- .../team6/database/DAO/MessageDAOTest.java | 267 +++-- .../team6/database/DAO/UserDAOTest.java | 1003 ++++++++--------- .../team6/models/CharityTest.java | 182 ++- .../team6/models/DonationTest.java | 26 +- .../team6/models/FeedbackTest.java | 31 +- .../models/registry/CharityRegistryTest.java | 20 +- .../models/registry/DonationRegistryTest.java | 1 - .../models/registry/UserRegistryTest.java | 173 ++- .../team6/models/user/InboxTest.java | 7 +- .../team6/models/user/MessageTest.java | 200 ++-- .../team6/models/user/UserTest.java | 800 +++++-------- 59 files changed, 4511 insertions(+), 4924 deletions(-) diff --git a/helpmehelpapplication/.gitignore b/helpmehelpapplication/.gitignore index 3fbc17a8..75408f0c 100644 --- a/helpmehelpapplication/.gitignore +++ b/helpmehelpapplication/.gitignore @@ -1,4 +1,3 @@ .idea/ -target/ helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DatabaseConnection.java helpmehelpapplication/src/main/resources/fxml/test/ diff --git a/helpmehelpapplication/pom.xml b/helpmehelpapplication/pom.xml index ec74b68b..c1f5d381 100644 --- a/helpmehelpapplication/pom.xml +++ b/helpmehelpapplication/pom.xml @@ -116,6 +116,25 @@ + + org.jacoco + jacoco-maven-plugin + 0.8.13 + + + + prepare-agent + + + + report + test + + report + + + + \ No newline at end of file diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/HmHApplication.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/HmHApplication.java index ba6064b6..92c37b29 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/HmHApplication.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/HmHApplication.java @@ -27,7 +27,6 @@ public void start(Stage stage) throws Exception { new FXMLLoader(HmHApplication.class.getResource("/fxml/frontPage.fxml")); Scene scene = new Scene(fxmlLoader.load()); - BaseController controller = fxmlLoader.getController(); controller.setAuthToken(authToken); @@ -43,11 +42,14 @@ public void start(Stage stage) throws Exception { stage.show(); // Re-enter fullscreen when restored from taskbar - stage.iconifiedProperty().addListener((obs, wasIconified, isNowIconified) -> { - if (!isNowIconified) { - stage.setFullScreen(true); - } - }); + stage + .iconifiedProperty() + .addListener( + (obs, wasIconified, isNowIconified) -> { + if (!isNowIconified) { + stage.setFullScreen(true); + } + }); } @Override @@ -71,7 +73,7 @@ public void init() { APIToDatabaseService db = new APIToDatabaseService(conn); if (scraper.getAPIScraper().checkConnection()) { - /* + /* if (scraper.checkConnection()) { CharityRegistry charityRegistry = scraper.parseJSON(scraper.getJSONData()); for (Charity charity : charityRegistry.getAllCharities()) { @@ -80,15 +82,13 @@ public void init() { */ // Comment out the two below to use already generated database. - //CharityRegistry charityRegistry = scraper.getAPIAndURLCharityData(); - //db.addAPIDataToTable(charityRegistry.getAllCharities()); + // CharityRegistry charityRegistry = scraper.getAPIAndURLCharityData(); + // db.addAPIDataToTable(charityRegistry.getAllCharities()); } } catch (Exception e) { e.printStackTrace(); } System.out.println("-- \n Init complete \n --"); - - } public static void main(String[] args) { diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/AboutPageController.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/AboutPageController.java index 46366db6..395466ce 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/AboutPageController.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/AboutPageController.java @@ -6,12 +6,12 @@ import ntnu.systemutvikling.team6.controller.components.NavbarController; public class AboutPageController extends BaseController { - @FXML private NavbarController navbarController; - @FXML private FooterController footerController; + @FXML private NavbarController navbarController; + @FXML private FooterController footerController; - @Override - protected void authTokenisSet() { - navbarController.setAuthToken(authToken); - footerController.setAuthToken(authToken); - } + @Override + protected void authTokenisSet() { + navbarController.setAuthToken(authToken); + footerController.setAuthToken(authToken); + } } diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/AvailableOrganizationController.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/AvailableOrganizationController.java index 1621d8d8..230ef931 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/AvailableOrganizationController.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/AvailableOrganizationController.java @@ -10,8 +10,8 @@ import javafx.scene.control.TextField; import javafx.scene.layout.FlowPane; import ntnu.systemutvikling.team6.controller.components.*; -import ntnu.systemutvikling.team6.database.DatabaseConnection; import ntnu.systemutvikling.team6.database.DAO.CharityDAO; +import ntnu.systemutvikling.team6.database.DatabaseConnection; import ntnu.systemutvikling.team6.models.Charity; import ntnu.systemutvikling.team6.models.registry.CharityRegistry; @@ -34,7 +34,7 @@ public class AvailableOrganizationController extends BaseController { private List allCharities; @Override - protected void authTokenisSet(){ + protected void authTokenisSet() { navbarController.setAuthToken(authToken); footerController.setAuthToken(authToken); } @@ -53,8 +53,6 @@ public void initialize() { CharityRegistry charities = db.getCharitiesFromDB(); allCharities = charities.getAllCharities(); - - cardsContainer.getChildren().clear(); searchField @@ -82,18 +80,17 @@ private List filterCharities(String query) { String name = charity.getName(); String description = charity.getDescription(); - if (name == null || name.isBlank()){ + if (name == null || name.isBlank()) { name = "This one has no name"; } else { name = name.toLowerCase(); } - if (description == null || description.isBlank()){ + if (description == null || description.isBlank()) { description = "This one has no description"; } else { description = description.toLowerCase(); } - if (name.contains(query) || description.contains(query)) { matches.add(charity); } @@ -111,7 +108,8 @@ private void displayCharities(List charities) { for (Charity charity : charities) { try { - FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/components/organizationCard.fxml")); + FXMLLoader loader = + new FXMLLoader(getClass().getResource("/fxml/components/organizationCard.fxml")); Parent card = loader.load(); OrganizationCardController cardController = loader.getController(); @@ -138,7 +136,6 @@ public void setInitialSearch(String query) { searchField.setText(query); } - /** * This method is used to switch to the charity page for the selected charity. * diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/CharityPageController.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/CharityPageController.java index 363afbcb..40a09f97 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/CharityPageController.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/CharityPageController.java @@ -1,10 +1,10 @@ package ntnu.systemutvikling.team6.controller; -import javafx.event.ActionEvent; import java.io.ByteArrayInputStream; import java.util.ArrayList; import java.util.List; import java.util.Objects; +import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Hyperlink; import javafx.scene.control.Label; @@ -57,12 +57,11 @@ public class CharityPageController extends BaseController { public void initialize() {} @Override - protected void authTokenisSet(){ + protected void authTokenisSet() { navbarController.setAuthToken(authToken); footerController.setAuthToken(authToken); } - private Charity charity; /** @@ -79,11 +78,9 @@ protected void authTokenisSet(){ public void setCharity(Charity charity) { this.charity = charity; - CharityDescription.setText(charity.getDescription()); CharityName.setText(charity.getName()); - if (this.charity.getLogoBlob() != null) { ByteArrayInputStream logoByteStream = new ByteArrayInputStream(this.charity.getLogoBlob()); Image CharityLogoImage = new Image(logoByteStream); @@ -117,8 +114,8 @@ public void setCharity(Charity charity) { keyValueFormaalLabel.setText(String.format("%.1f%%", numbers.getLast())); } - // Sets the categories - setCategories(charity.getCategory()); + // Sets the categories + setCategories(charity.getCategory()); } /** @@ -144,16 +141,15 @@ public void switchToFrontPage(ActionEvent event) { * @param event is the event that triggered the search. */ @FXML - private void switchToFeedbackPage(ActionEvent event){ + private void switchToFeedbackPage(ActionEvent event) { LoaderScene.LoadScene("giveFeedback", event, charity, null, authToken); - } - /** - * Opens OS default webbrowser and loads the url of the charity on click. - * - * @param event the onclick event - */ + /** + * Opens OS default webbrowser and loads the url of the charity on click. + * + * @param event the onclick event + */ @FXML public void handleHomepageClick(ActionEvent event) { try { diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/CreateUserPageController.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/CreateUserPageController.java index 75dd33c5..ba29af77 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/CreateUserPageController.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/CreateUserPageController.java @@ -10,76 +10,77 @@ import ntnu.systemutvikling.team6.controller.components.LoaderScene; import ntnu.systemutvikling.team6.controller.components.NavbarController; - - public class CreateUserPageController extends BaseController { - @FXML - private NavbarController navbarController; - @FXML - private FooterController footerController; - - @FXML private TextField firstNameField; - @FXML private TextField emailField; - @FXML private PasswordField passwordField; - @FXML private PasswordField confirmPasswordField; + @FXML private NavbarController navbarController; + @FXML private FooterController footerController; + @FXML private TextField firstNameField; + @FXML private TextField emailField; + @FXML private PasswordField passwordField; + @FXML private PasswordField confirmPasswordField; - @Override - protected void authTokenisSet() { - if (isLoggedin()){ - LoaderScene.LoadScene("frontPage", new ActionEvent(), null, null, authToken); - } - navbarController.setAuthToken(authToken); - footerController.setAuthToken(authToken); + @Override + protected void authTokenisSet() { + if (isLoggedin()) { + LoaderScene.LoadScene("frontPage", new ActionEvent(), null, null, authToken); } + navbarController.setAuthToken(authToken); + footerController.setAuthToken(authToken); + } - @FXML - private void handleCreateAccount(ActionEvent event){ - String nameText = firstNameField.getText(); - String emailText = emailField.getText(); - String password = passwordField.getText(); - String confirmPassword = confirmPasswordField.getText(); - - if (nameText.isBlank() || emailText.isBlank() || password.isBlank() || confirmPassword.isBlank()) { - showAlert(Alert.AlertType.ERROR, "Empty input", "Please fill out all fields"); - return; - } - - if (emailText == null || emailText.isBlank() || !emailText.contains("@") || !emailText.contains(".")) { - showAlert(Alert.AlertType.ERROR, "Invalid Email", "Please enter a valid email"); - return; - } + @FXML + private void handleCreateAccount(ActionEvent event) { + String nameText = firstNameField.getText(); + String emailText = emailField.getText(); + String password = passwordField.getText(); + String confirmPassword = confirmPasswordField.getText(); - if (!password.equals(confirmPassword)) { - showAlert(Alert.AlertType.ERROR, "Mismatch of password", "Password do not match"); - return; - } + if (nameText.isBlank() + || emailText.isBlank() + || password.isBlank() + || confirmPassword.isBlank()) { + showAlert(Alert.AlertType.ERROR, "Empty input", "Please fill out all fields"); + return; + } - // login - boolean registerSuccess; - try { - registerSuccess = authToken.register(nameText,emailText, confirmPassword); - } catch (IllegalArgumentException e) { - showAlert(Alert.AlertType.ERROR, "Email already taken", "Email already taken by another user."); - return; - } catch (Exception e) { - e.printStackTrace(); - showAlert(Alert.AlertType.ERROR, "Unexpected Error", "Unexpected error ocurred"); - return; + if (emailText == null + || emailText.isBlank() + || !emailText.contains("@") + || !emailText.contains(".")) { + showAlert(Alert.AlertType.ERROR, "Invalid Email", "Please enter a valid email"); + return; + } - } - if (registerSuccess) { - showAlert( - Alert.AlertType.INFORMATION, - "Sign up sucsess", - "You have registered a new account! Please login with same credentials"); - LoaderScene.LoadScene("loginSite", event, null, null, authToken); - } + if (!password.equals(confirmPassword)) { + showAlert(Alert.AlertType.ERROR, "Mismatch of password", "Password do not match"); + return; } - @FXML - private void switchToLoginPage(ActionEvent event){ - System.out.println("Click!"); - LoaderScene.LoadScene("loginSite", event, null, null, authToken); + // login + boolean registerSuccess; + try { + registerSuccess = authToken.register(nameText, emailText, confirmPassword); + } catch (IllegalArgumentException e) { + showAlert( + Alert.AlertType.ERROR, "Email already taken", "Email already taken by another user."); + return; + } catch (Exception e) { + e.printStackTrace(); + showAlert(Alert.AlertType.ERROR, "Unexpected Error", "Unexpected error ocurred"); + return; } + if (registerSuccess) { + showAlert( + Alert.AlertType.INFORMATION, + "Sign up sucsess", + "You have registered a new account! Please login with same credentials"); + LoaderScene.LoadScene("loginSite", event, null, null, authToken); + } + } + + @FXML + private void switchToLoginPage(ActionEvent event) { + System.out.println("Click!"); + LoaderScene.LoadScene("loginSite", event, null, null, authToken); + } } diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/DonationPageController.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/DonationPageController.java index 2e8b09c8..12c6e0b3 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/DonationPageController.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/DonationPageController.java @@ -1,9 +1,7 @@ package ntnu.systemutvikling.team6.controller; -import java.sql.Date; import java.time.LocalDate; import java.util.Optional; - import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.fxml.FXML; @@ -42,17 +40,17 @@ public class DonationPageController extends BaseController { @Override protected void authTokenisSet() { - if (!isLoggedin()){ + if (!isLoggedin()) { showAlert(Alert.AlertType.ERROR, "Not logged inn", "You need to be logged inn to donate."); - Platform.runLater(() -> { - Stage stage = (Stage) Stage.getWindows().stream() - .filter(w -> w.isShowing()) - .findFirst() - .orElse(null); - if (stage != null) { - LoaderScene.LoadScene("loginSite", stage, null, null, authToken); - } - }); + Platform.runLater( + () -> { + Stage stage = + (Stage) + Stage.getWindows().stream().filter(w -> w.isShowing()).findFirst().orElse(null); + if (stage != null) { + LoaderScene.LoadScene("loginSite", stage, null, null, authToken); + } + }); } navbarController.setAuthToken(authToken); footerController.setAuthToken(authToken); @@ -73,7 +71,7 @@ public void setCharity(Charity charity) { CharityName.setText(charity.getName()); } - private void populateFields(){ + private void populateFields() { boolean isFavourite = favouritesDAO.isFavourite(authToken.getCurrentUser(), charity); heartButton.setSelected(isFavourite); updateHeartIcon(isFavourite); @@ -95,13 +93,14 @@ private void onHeartToggle() { private void updateHeartIcon(boolean selected) { heartButton.setText(selected ? "♥" : "♡"); } + /** * This method is used to switch back to the Donation page when the user clicks the back button. * * @param event */ public void switchToCharityPage(ActionEvent event) { - LoaderScene.LoadScene("charityPage", event, charity, null,authToken); + LoaderScene.LoadScene("charityPage", event, charity, null, authToken); } /** @@ -139,13 +138,14 @@ public void Donate(ActionEvent event) { } Optional resultAnonymous = Optional.empty(); - if (authToken.getCurrentUser().getSettings().isAnonymous()){ + if (authToken.getCurrentUser().getSettings().isAnonymous()) { Alert confirmAnonymous = new Alert(Alert.AlertType.CONFIRMATION); confirmAnonymous.setTitle("You're going to donate Anonymously"); - confirmAnonymous.setHeaderText("You're about to make an anonymous donation. The charity and other donors will not be able to see your name amd email assosiated with the donation"); + confirmAnonymous.setHeaderText( + "You're about to make an anonymous donation. The charity and other donors will not be able to see your name amd email assosiated with the donation"); confirmAnonymous.setContentText("Are you sure?"); resultAnonymous = confirmAnonymous.showAndWait(); - if (resultAnonymous.isPresent() && resultAnonymous.get() == ButtonType.CANCEL){ + if (resultAnonymous.isPresent() && resultAnonymous.get() == ButtonType.CANCEL) { return; } } @@ -157,7 +157,8 @@ public void Donate(ActionEvent event) { Optional result = confirm.showAndWait(); if (result.isPresent() && result.get() == ButtonType.OK) { - Donation donation = new Donation(amount, LocalDate.now(), charity, authToken.getCurrentUser()); + Donation donation = + new Donation(amount, LocalDate.now(), charity, authToken.getCurrentUser()); donationSender.addDonation(donation); showAlert( Alert.AlertType.INFORMATION, diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/FrontpageController.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/FrontpageController.java index 0bcef6db..aa7fa05d 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/FrontpageController.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/FrontpageController.java @@ -5,7 +5,6 @@ import java.util.List; import java.util.Objects; import java.util.Random; - import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; @@ -14,10 +13,10 @@ import javafx.scene.control.Label; import javafx.scene.layout.FlowPane; import ntnu.systemutvikling.team6.controller.components.*; -import ntnu.systemutvikling.team6.database.DAO.DonationDAO; -import ntnu.systemutvikling.team6.database.DatabaseConnection; import ntnu.systemutvikling.team6.database.DAO.CategoryDAO; import ntnu.systemutvikling.team6.database.DAO.CharityDAO; +import ntnu.systemutvikling.team6.database.DAO.DonationDAO; +import ntnu.systemutvikling.team6.database.DatabaseConnection; import ntnu.systemutvikling.team6.models.Charity; import ntnu.systemutvikling.team6.models.Donation; import ntnu.systemutvikling.team6.models.registry.CharityRegistry; @@ -30,7 +29,7 @@ * it, or click on the featured charity to see more details about it. It also has buttons to switch * to the charity page and the donation page for the featured charity */ -public class FrontpageController extends BaseController{ +public class FrontpageController extends BaseController { @FXML private Charity featuredCharity; @FXML private FlowPane cardsContainer; @FXML private Label Carosel_Organisasjon; @@ -48,10 +47,8 @@ public class FrontpageController extends BaseController{ private List allCharities = new ArrayList<>(); - - @Override - protected void authTokenisSet(){ + protected void authTokenisSet() { navbarController.setAuthToken(authToken); footerController.setAuthToken(authToken); loadPage(); @@ -66,11 +63,9 @@ protected void authTokenisSet(){ * amount of donations, and percentage of pre-approved charities are also displayed on the page. */ @FXML - public void initialize() { - - } + public void initialize() {} - private void loadPage(){ + private void loadPage() { try { DatabaseConnection conn = new DatabaseConnection(); CharityDAO cdb = new CharityDAO(conn); @@ -83,7 +78,7 @@ private void loadPage(){ for (String category : categories) { CheckBox cb = new CheckBox(category); - cb.setStyle("-fx-font-size: 12; -fx-padding: 10 0 0 20; -fx-text-fill: black" ); + cb.setStyle("-fx-font-size: 12; -fx-padding: 10 0 0 20; -fx-text-fill: black"); cb.setOnAction( e -> { @@ -112,15 +107,15 @@ private void loadPage(){ Total_Orgnisasjon.setText(Integer.toString(charitiesSize)); Total_Donations.setText( - Double.toString( - donations.getAllDonations().stream().mapToDouble(Donation::getAmount).sum())); + Double.toString( + donations.getAllDonations().stream().mapToDouble(Donation::getAmount).sum())); PreApproved_Percentage.setText( - String.format( - "%.2f", - charities.getAllCharities().stream().filter(Charity::getPreApproved).count() - * 100.0 - / charitiesSize) - + "%"); + String.format( + "%.2f", + charities.getAllCharities().stream().filter(Charity::getPreApproved).count() + * 100.0 + / charitiesSize) + + "%"); } catch (Exception e) { e.printStackTrace(); } @@ -158,10 +153,10 @@ public void handleCategoryFilterChange(ActionEvent event) { * This method is used to filter the charities based on the selected filters. * *

The filters are whether the charity was pre-verified, or if it falls under one (or more) of - * the given categories.

+ * the given categories. * - *

The check checks whether the given charity has ALL filters. If one does not apply, - * the charity is rejected.

+ *

The check checks whether the given charity has ALL filters. If one does not apply, the + * charity is rejected. * * @return a list of filtered charities. */ diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/GiveFeedbackController.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/GiveFeedbackController.java index e6d599f1..32a05ce4 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/GiveFeedbackController.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/GiveFeedbackController.java @@ -1,5 +1,7 @@ package ntnu.systemutvikling.team6.controller; +import java.io.IOException; +import java.util.ArrayList; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.fxml.FXML; @@ -13,98 +15,96 @@ import ntnu.systemutvikling.team6.controller.components.*; import ntnu.systemutvikling.team6.database.DAO.FeedbackDAO; import ntnu.systemutvikling.team6.database.DatabaseConnection; -import ntnu.systemutvikling.team6.database.DAO.CharityDAO; import ntnu.systemutvikling.team6.models.Charity; import ntnu.systemutvikling.team6.models.Feedback; -import java.io.IOException; -import java.util.ArrayList; - public class GiveFeedbackController extends BaseController { - private Charity charity; - @FXML private NavbarController navbarController; - @FXML private FooterController footerController; - - @FXML private FlowPane feedbackContainer; - @FXML private Label charityNameLabel; - @FXML private TextArea feedbackCommentArea; + private Charity charity; + @FXML private NavbarController navbarController; + @FXML private FooterController footerController; + @FXML private FlowPane feedbackContainer; + @FXML private Label charityNameLabel; + @FXML private TextArea feedbackCommentArea; + @FXML + public void setCharity(Charity charity) { + this.charity = charity; - @FXML - public void setCharity(Charity charity) { - this.charity = charity; + charityNameLabel.setText(charity.getName()); + } - charityNameLabel.setText(charity.getName()); + @Override + protected void authTokenisSet() { + if (!isLoggedin()) { + showAlert(Alert.AlertType.ERROR, "Not logged inn", "You need to be logged inn to donate."); + Platform.runLater( + () -> { + Stage stage = + (Stage) + Stage.getWindows().stream().filter(w -> w.isShowing()).findFirst().orElse(null); + if (stage != null) { + LoaderScene.LoadScene("loginSite", stage, null, null, authToken); + } + }); } + navbarController.setAuthToken(authToken); + footerController.setAuthToken(authToken); + populateFields(); + } - @Override - protected void authTokenisSet() { - if (!isLoggedin()){ - showAlert(Alert.AlertType.ERROR, "Not logged inn", "You need to be logged inn to donate."); - Platform.runLater(() -> { - Stage stage = (Stage) Stage.getWindows().stream() - .filter(w -> w.isShowing()) - .findFirst() - .orElse(null); - if (stage != null) { - LoaderScene.LoadScene("loginSite", stage, null, null, authToken); - } - }); - } - navbarController.setAuthToken(authToken); - footerController.setAuthToken(authToken); - populateFields(); - } - private void populateFields(){ - DatabaseConnection conn = new DatabaseConnection(); - FeedbackDAO feedbackDAO = new FeedbackDAO(conn); - ArrayList feedbacks = feedbackDAO.getFeedbackforCharityUUID(charity.getUUID().toString()); - displayFeedbacks(feedbacks); + private void populateFields() { + DatabaseConnection conn = new DatabaseConnection(); + FeedbackDAO feedbackDAO = new FeedbackDAO(conn); + ArrayList feedbacks = + feedbackDAO.getFeedbackforCharityUUID(charity.getUUID().toString()); + displayFeedbacks(feedbacks); + } + + private void displayFeedbacks(ArrayList feedbacks) { + feedbackContainer.getChildren().clear(); + if (feedbacks.isEmpty()) { + javafx.scene.control.Label empty = new javafx.scene.control.Label("You have no Feedbacks"); + empty.setStyle("-fx-text-fill: #777777; -fx-font-size: 14;"); + feedbackContainer.getChildren().add(empty); } - private void displayFeedbacks(ArrayList feedbacks){ - feedbackContainer.getChildren().clear(); - if (feedbacks.isEmpty()) { - javafx.scene.control.Label empty = new javafx.scene.control.Label("You have no Feedbacks"); - empty.setStyle("-fx-text-fill: #777777; -fx-font-size: 14;"); - feedbackContainer.getChildren().add(empty); - } - for (Feedback feedback : feedbacks) { - try { - FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/components/feedbackCard.fxml")); - Parent card = loader.load(); - FeedbackCardController cardController = loader.getController(); - cardController.setMessage(feedback); - cardController.setAuthToken(authToken); - feedbackContainer.getChildren().add(card); - } catch (IOException e) { - throw new RuntimeException("Could not load organization card.", e); - } - } + for (Feedback feedback : feedbacks) { + try { + FXMLLoader loader = + new FXMLLoader(getClass().getResource("/fxml/components/feedbackCard.fxml")); + Parent card = loader.load(); + FeedbackCardController cardController = loader.getController(); + cardController.setMessage(feedback); + cardController.setAuthToken(authToken); + feedbackContainer.getChildren().add(card); + } catch (IOException e) { + throw new RuntimeException("Could not load organization card.", e); + } } + } - @FXML - private void handleSubmitFeedback(ActionEvent event){ - String feedbackCommentAreaText = feedbackCommentArea.getText(); - Feedback newFeedback = new Feedback(authToken.getCurrentUser(), feedbackCommentAreaText); + @FXML + private void handleSubmitFeedback(ActionEvent event) { + String feedbackCommentAreaText = feedbackCommentArea.getText(); + Feedback newFeedback = new Feedback(authToken.getCurrentUser(), feedbackCommentAreaText); - DatabaseConnection conn = new DatabaseConnection(); - FeedbackDAO feedbackDAO = new FeedbackDAO(conn); - boolean submitSuccess; - try { - submitSuccess = feedbackDAO.addFeedbackToCharity(newFeedback, charity); - } catch (Exception e) { - e.printStackTrace(); - showAlert(Alert.AlertType.ERROR, "Unexpected Error", "Unexpected error ocurred"); - return; - } - if (submitSuccess) { - showAlert( - Alert.AlertType.INFORMATION, - "Feedback received", - charity.getName() + " has gotten your feedback"); - LoaderScene.LoadScene("charityPage", event, charity, null, authToken); - } + DatabaseConnection conn = new DatabaseConnection(); + FeedbackDAO feedbackDAO = new FeedbackDAO(conn); + boolean submitSuccess; + try { + submitSuccess = feedbackDAO.addFeedbackToCharity(newFeedback, charity); + } catch (Exception e) { + e.printStackTrace(); + showAlert(Alert.AlertType.ERROR, "Unexpected Error", "Unexpected error ocurred"); + return; + } + if (submitSuccess) { + showAlert( + Alert.AlertType.INFORMATION, + "Feedback received", + charity.getName() + " has gotten your feedback"); + LoaderScene.LoadScene("charityPage", event, charity, null, authToken); } + } } diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/LoginPageController.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/LoginPageController.java index 3e13f25a..99633dac 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/LoginPageController.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/LoginPageController.java @@ -1,5 +1,6 @@ package ntnu.systemutvikling.team6.controller; +import java.awt.*; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Alert; @@ -10,67 +11,61 @@ import ntnu.systemutvikling.team6.controller.components.LoaderScene; import ntnu.systemutvikling.team6.controller.components.NavbarController; -import java.awt.*; - - public class LoginPageController extends BaseController { - @FXML private NavbarController navbarController; - @FXML private FooterController footerController; + @FXML private NavbarController navbarController; + @FXML private FooterController footerController; - @FXML private TextField emailField; - @FXML private PasswordField passwordField; + @FXML private TextField emailField; + @FXML private PasswordField passwordField; - @Override - protected void authTokenisSet() { - if (isLoggedin()){ - LoaderScene.LoadScene("frontPage", new ActionEvent(), null, null, authToken); - } - navbarController.setAuthToken(authToken); - footerController.setAuthToken(authToken); + @Override + protected void authTokenisSet() { + if (isLoggedin()) { + LoaderScene.LoadScene("frontPage", new ActionEvent(), null, null, authToken); } + navbarController.setAuthToken(authToken); + footerController.setAuthToken(authToken); + } - @FXML - private void handleLogin(ActionEvent event){ - String emailText = emailField.getText(); - String password = passwordField.getText(); + @FXML + private void handleLogin(ActionEvent event) { + String emailText = emailField.getText(); + String password = passwordField.getText(); - if (emailText.isBlank() || password.isBlank()){ - showAlert(Alert.AlertType.ERROR, "Empty input", "Please fill out all fields"); - return; - } - - if (!emailText.contains("@") || !emailText.contains(".")) { - showAlert(Alert.AlertType.ERROR, "Invalid Email", "Please enter a valid email"); - return; - } + if (emailText.isBlank() || password.isBlank()) { + showAlert(Alert.AlertType.ERROR, "Empty input", "Please fill out all fields"); + return; + } - boolean loginSuccess; - try { - loginSuccess = authToken.login(emailText, password); - } catch (Exception e) { - e.printStackTrace(); - showAlert(Alert.AlertType.ERROR, "Unexpected Error", "Unexpected error ocurred"); - return; - } - if (loginSuccess) { - showAlert( - Alert.AlertType.INFORMATION, - "Login Success", - "Login Successful!"); - LoaderScene.LoadScene("profile_user_Settings", event, null, null, authToken); - } else { - showAlert( - Alert.AlertType.ERROR, - "Account not found", - "User logg inn failed. Either email is wrong or password"); - emailField.setText(""); - passwordField.setText(""); - } + if (!emailText.contains("@") || !emailText.contains(".")) { + showAlert(Alert.AlertType.ERROR, "Invalid Email", "Please enter a valid email"); + return; } - @FXML - private void switchToSignupPage(ActionEvent event){ - System.out.println("Click!"); - LoaderScene.LoadScene("creater_user_site", event, null, null, authToken); + boolean loginSuccess; + try { + loginSuccess = authToken.login(emailText, password); + } catch (Exception e) { + e.printStackTrace(); + showAlert(Alert.AlertType.ERROR, "Unexpected Error", "Unexpected error ocurred"); + return; } + if (loginSuccess) { + showAlert(Alert.AlertType.INFORMATION, "Login Success", "Login Successful!"); + LoaderScene.LoadScene("profile_user_Settings", event, null, null, authToken); + } else { + showAlert( + Alert.AlertType.ERROR, + "Account not found", + "User logg inn failed. Either email is wrong or password"); + emailField.setText(""); + passwordField.setText(""); + } + } + + @FXML + private void switchToSignupPage(ActionEvent event) { + System.out.println("Click!"); + LoaderScene.LoadScene("creater_user_site", event, null, null, authToken); + } } diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/BaseController.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/BaseController.java index 48ceb2ec..2b9a8121 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/BaseController.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/BaseController.java @@ -1,55 +1,56 @@ package ntnu.systemutvikling.team6.controller.components; - import javafx.scene.control.Alert; import ntnu.systemutvikling.team6.service.AuthenticationService; - public abstract class BaseController { - protected AuthenticationService authToken; - - public void setAuthToken(AuthenticationService authToken){ - this.authToken = authToken; - authTokenisSet(); - }; - protected abstract void authTokenisSet(); - // Update ui (login button or profile circle) after authtoken is set: - // Make sure to invoke navbarController.setAuthtoken AND FooterController on controller that have @FXML private navbarController as an attribute. - // If footerController and NavbarController on the same file overwrite one of the controllers switchtofrontpage. - - - - protected boolean isLoggedin(){ - return authToken != null && authToken.isLoggedin(); - } - - - /** - * Show an JavaFx alert dialog with the specified type, title, and message. - * - * @param type - * @param title - * @param message - */ - protected void showAlert(Alert.AlertType type, String title, String message) { - Alert alert = new Alert(type); - alert.setTitle(title); - alert.setHeaderText(null); - alert.setContentText(message); - alert.showAndWait(); - } - - // Example on the minimum inside of a controller that extends the baseControlle and inserts footer and navbar fxml: - /* - @FXML - private NavbarController navbarController; - @FXML private FooterController footerController; - - @Override - protected void authTokenisSet() { - navbarController.setAuthToken(authToken); - footerController.setAuthToken(authToken); - } - */ + protected AuthenticationService authToken; + + public void setAuthToken(AuthenticationService authToken) { + this.authToken = authToken; + authTokenisSet(); + } + ; + + protected abstract void authTokenisSet(); + + // Update ui (login button or profile circle) after authtoken is set: + // Make sure to invoke navbarController.setAuthtoken AND FooterController on controller that have + // @FXML private navbarController as an attribute. + // If footerController and NavbarController on the same file overwrite one of the controllers + // switchtofrontpage. + + protected boolean isLoggedin() { + return authToken != null && authToken.isLoggedin(); + } + + /** + * Show an JavaFx alert dialog with the specified type, title, and message. + * + * @param type + * @param title + * @param message + */ + protected void showAlert(Alert.AlertType type, String title, String message) { + Alert alert = new Alert(type); + alert.setTitle(title); + alert.setHeaderText(null); + alert.setContentText(message); + alert.showAndWait(); + } + + // Example on the minimum inside of a controller that extends the baseControlle and inserts footer + // and navbar fxml: + /* + @FXML + private NavbarController navbarController; + @FXML private FooterController footerController; + + @Override + protected void authTokenisSet() { + navbarController.setAuthToken(authToken); + footerController.setAuthToken(authToken); + } + */ } diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/CategoryTagController.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/CategoryTagController.java index 5fecbbc8..1a4540a0 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/CategoryTagController.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/CategoryTagController.java @@ -3,40 +3,41 @@ import javafx.fxml.FXML; import javafx.scene.control.Button; -public class CategoryTagController extends BaseController{ - @FXML private Button button; - private static final String[][] TAG_COLORS = { - {"#E5F0D7", "#6E8A5C"}, // green - {"#D7E8F0", "#5C7A8A"}, // blue - {"#F0E5D7", "#8A6E5C"}, // orange - {"#EFD7F0", "#8A5C8A"}, // purple - {"#F0D7D7", "#8A5C5C"}, // red - {"#D7F0EE", "#5C8A87"}, // teal - {"#F0EDD7", "#8A845C"}, // yellow - }; - - private String[] getRandomTagColor() { - return TAG_COLORS[(int) (Math.random() * TAG_COLORS.length)]; - } - - private String category; - - @Override - protected void authTokenisSet() { - - } - - public void setCategory(String category) { - this.category = category; - - button.setText(category); - String[] colors = getRandomTagColor(); - button.setStyle( - "-fx-background-color: " + colors[0] + ";" + - "-fx-text-fill: " + colors[1] + ";" + - "-fx-background-radius: 20;" + - "-fx-font-size: 11px;" + - "-fx-padding: 4 10 4 10;" - ); - } +public class CategoryTagController extends BaseController { + @FXML private Button button; + private static final String[][] TAG_COLORS = { + {"#E5F0D7", "#6E8A5C"}, // green + {"#D7E8F0", "#5C7A8A"}, // blue + {"#F0E5D7", "#8A6E5C"}, // orange + {"#EFD7F0", "#8A5C8A"}, // purple + {"#F0D7D7", "#8A5C5C"}, // red + {"#D7F0EE", "#5C8A87"}, // teal + {"#F0EDD7", "#8A845C"}, // yellow + }; + + private String[] getRandomTagColor() { + return TAG_COLORS[(int) (Math.random() * TAG_COLORS.length)]; + } + + private String category; + + @Override + protected void authTokenisSet() {} + + public void setCategory(String category) { + this.category = category; + + button.setText(category); + String[] colors = getRandomTagColor(); + button.setStyle( + "-fx-background-color: " + + colors[0] + + ";" + + "-fx-text-fill: " + + colors[1] + + ";" + + "-fx-background-radius: 20;" + + "-fx-font-size: 11px;" + + "-fx-padding: 4 10 4 10;"); + } } diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/DonationCardController.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/DonationCardController.java index 596f18d8..34caf904 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/DonationCardController.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/DonationCardController.java @@ -3,29 +3,26 @@ import javafx.fxml.FXML; import javafx.scene.control.Label; import ntnu.systemutvikling.team6.models.Donation; -import ntnu.systemutvikling.team6.models.user.Message; -public class DonationCardController extends BaseController{ - @FXML private Label charityNameLabel; - @FXML private Label purchaseIDLabel; - @FXML private Label dateLabel; - @FXML private Label AnonymousLabel; - @FXML private Label totalLabel; +public class DonationCardController extends BaseController { + @FXML private Label charityNameLabel; + @FXML private Label purchaseIDLabel; + @FXML private Label dateLabel; + @FXML private Label AnonymousLabel; + @FXML private Label totalLabel; - private Donation donation; + private Donation donation; - @Override - protected void authTokenisSet() { + @Override + protected void authTokenisSet() {} - } + public void setDonation(Donation donation) { + this.donation = donation; - public void setDonation(Donation donation) { - this.donation = donation; - - charityNameLabel.setText(donation.getCharity().getName()); - purchaseIDLabel.setText(donation.getDonationID().toString()); - dateLabel.setText(donation.getDate().toString()); - AnonymousLabel.setText(donation.isAnonymous() ? "Yes" : "No"); - totalLabel.setText(String.valueOf(donation.getAmount())); - } + charityNameLabel.setText(donation.getCharity().getName()); + purchaseIDLabel.setText(donation.getDonationID().toString()); + dateLabel.setText(donation.getDate().toString()); + AnonymousLabel.setText(donation.isAnonymous() ? "Yes" : "No"); + totalLabel.setText(String.valueOf(donation.getAmount())); + } } diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/FeedbackCardController.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/FeedbackCardController.java index 987c7311..17bb8f31 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/FeedbackCardController.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/FeedbackCardController.java @@ -3,26 +3,24 @@ import javafx.fxml.FXML; import javafx.scene.control.Label; import ntnu.systemutvikling.team6.models.Feedback; -import ntnu.systemutvikling.team6.models.user.Message; public class FeedbackCardController extends BaseController { - @FXML private Label usernameLabel; - @FXML private Label dateLabel; - @FXML private Label commentLabel; + @FXML private Label usernameLabel; + @FXML private Label dateLabel; + @FXML private Label commentLabel; - private Feedback feedback; + private Feedback feedback; - @Override - protected void authTokenisSet() { + @Override + protected void authTokenisSet() {} - } + public void setMessage(Feedback feedback) { + this.feedback = feedback; - public void setMessage(Feedback feedback) { - this.feedback = feedback; - - System.out.println(feedback.isAnonymous()); - usernameLabel.setText(feedback.isAnonymous() ? "Anonymous Doner" : feedback.getUser().getUsername()); - dateLabel.setText(feedback.getDate().toString()); - commentLabel.setText(feedback.getComment()); - } + System.out.println(feedback.isAnonymous()); + usernameLabel.setText( + feedback.isAnonymous() ? "Anonymous Doner" : feedback.getUser().getUsername()); + dateLabel.setText(feedback.getDate().toString()); + commentLabel.setText(feedback.getComment()); + } } diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/FooterController.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/FooterController.java index 05e25d19..c6e800b8 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/FooterController.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/FooterController.java @@ -2,25 +2,20 @@ import javafx.event.ActionEvent; import javafx.fxml.FXML; -import javafx.scene.control.Button; -import javafx.scene.control.Label; -import ntnu.systemutvikling.team6.service.AuthenticationService; public class FooterController extends BaseController { - @FXML - private void switchToAboutPage(ActionEvent event) { - System.out.println("Click!"); - LoaderScene.LoadScene("aboutPage", event, null, null, authToken); - } - @FXML - private void switchToFrontPage(ActionEvent event) { - System.out.println("Click!"); - LoaderScene.LoadScene("frontPage", event, null, null, authToken); - } + @FXML + private void switchToAboutPage(ActionEvent event) { + System.out.println("Click!"); + LoaderScene.LoadScene("aboutPage", event, null, null, authToken); + } - @Override - protected void authTokenisSet() { + @FXML + private void switchToFrontPage(ActionEvent event) { + System.out.println("Click!"); + LoaderScene.LoadScene("frontPage", event, null, null, authToken); + } - - } + @Override + protected void authTokenisSet() {} } diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/InboxCardController.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/InboxCardController.java index be0b2b06..d26e9d77 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/InboxCardController.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/InboxCardController.java @@ -1,31 +1,26 @@ package ntnu.systemutvikling.team6.controller.components; -import javafx.event.ActionEvent; import javafx.fxml.FXML; -import javafx.scene.control.Button; import javafx.scene.control.Label; -import ntnu.systemutvikling.team6.models.Charity; import ntnu.systemutvikling.team6.models.user.Message; -public class InboxCardController extends BaseController{ - @FXML private Label messageFrom; - @FXML private Label messageTitle; - @FXML private Label messageContent; - @FXML private Label messageDate; +public class InboxCardController extends BaseController { + @FXML private Label messageFrom; + @FXML private Label messageTitle; + @FXML private Label messageContent; + @FXML private Label messageDate; - private Message message; + private Message message; - @Override - protected void authTokenisSet() { + @Override + protected void authTokenisSet() {} - } + public void setMessage(Message message) { + this.message = message; - public void setMessage(Message message) { - this.message = message; - - messageFrom.setText(message.getFrom().getName()); - messageTitle.setText(message.getTitle()); - messageContent.setText(message.getContent()); - messageDate.setText(message.getTimeAndDate().toString()); - } + messageFrom.setText(message.getFrom().getName()); + messageTitle.setText(message.getTitle()); + messageContent.setText(message.getContent()); + messageDate.setText(message.getTimeAndDate().toString()); + } } diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/InterestCardController.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/InterestCardController.java index e7aec6f1..73dc1e5b 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/InterestCardController.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/InterestCardController.java @@ -6,43 +6,44 @@ import javafx.scene.control.Label; import ntnu.systemutvikling.team6.models.Charity; -public class InterestCardController extends BaseController{ - @FXML private Label charityDescription; - @FXML private Label verifyLabel; - @FXML private Label charityNameLabel; +public class InterestCardController extends BaseController { + @FXML private Label charityDescription; + @FXML private Label verifyLabel; + @FXML private Label charityNameLabel; - @FXML private Button detailsButton; - @FXML private Button donateButton; + @FXML private Button detailsButton; + @FXML private Button donateButton; - private Charity charity; + private Charity charity; - @Override - protected void authTokenisSet() { + @Override + protected void authTokenisSet() {} - } - - public void setOrganization(Charity charity) { - this.charity = charity; - - charityNameLabel.setText(charity.getName()); - verifyLabel.setText(charity.getPreApproved() ? "Verify" : "Unverified"); - verifyLabel.setStyle(charity.getPreApproved() ? "-fx-background-color: #2f8f3a; -fx-alignment: CENTER_LEFT; -fx-text-fill: white;" : "-fx-alignment: CENTER_LEFT; -fx-background-color: #D11D27; -fx-text-fill: white;"); - charityDescription.setText(charity.getDescription()); + public void setOrganization(Charity charity) { + this.charity = charity; - if(charity.getName().equals("You have no Favourites")){ - detailsButton.setVisible(false); - donateButton.setVisible(false); - } - } - - /* EVENTS */ - @FXML - private void switchToCharity(ActionEvent event){ - LoaderScene.LoadScene("CharityPage", event, charity, null, authToken); - } + charityNameLabel.setText(charity.getName()); + verifyLabel.setText(charity.getPreApproved() ? "Verify" : "Unverified"); + verifyLabel.setStyle( + charity.getPreApproved() + ? "-fx-background-color: #2f8f3a; -fx-alignment: CENTER_LEFT; -fx-text-fill: white;" + : "-fx-alignment: CENTER_LEFT; -fx-background-color: #D11D27; -fx-text-fill: white;"); + charityDescription.setText(charity.getDescription()); - @FXML - private void switchToDonate(ActionEvent event){ - LoaderScene.LoadScene("DonationPage", event, charity, null, authToken); + if (charity.getName().equals("You have no Favourites")) { + detailsButton.setVisible(false); + donateButton.setVisible(false); } + } + + /* EVENTS */ + @FXML + private void switchToCharity(ActionEvent event) { + LoaderScene.LoadScene("CharityPage", event, charity, null, authToken); + } + + @FXML + private void switchToDonate(ActionEvent event) { + LoaderScene.LoadScene("DonationPage", event, charity, null, authToken); + } } diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/LoaderScene.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/LoaderScene.java index 5adc1c0e..173c394b 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/LoaderScene.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/LoaderScene.java @@ -21,14 +21,19 @@ */ public class LoaderScene { /** - * When going to a new scene, this method and another called to load the new scene. - * It loads the FXML file for the new scene, sets the controller, and switches the scene. + * When going to a new scene, this method and another called to load the new scene. It loads the + * FXML file for the new scene, sets the controller, and switches the scene. * * @param sceneName * @param event * @param charity */ - public static void LoadScene(String sceneName, Stage stage, Charity charity, String query, AuthenticationService authtoken) { + public static void LoadScene( + String sceneName, + Stage stage, + Charity charity, + String query, + AuthenticationService authtoken) { try { System.out.println(HmHApplication.class.getResource("/fxml/" + sceneName + ".fxml")); FXMLLoader fxmlLoader = @@ -40,7 +45,7 @@ public static void LoadScene(String sceneName, Stage stage, Charity charity, Str // Needs to be expanded when more pages get implemented. // Controllers that need charities: - if (charity != null){ + if (charity != null) { if (controller instanceof CharityPageController charityController) { charityController.setCharity(charity); } @@ -53,14 +58,14 @@ public static void LoadScene(String sceneName, Stage stage, Charity charity, Str } // Controllers that need query - if (query != null){ + if (query != null) { if (controller instanceof AvailableOrganizationController availableOrganizationController) { availableOrganizationController.setInitialSearch(query); } } // All controllers need to set authtoken - if (controller instanceof BaseController baseController){ + if (controller instanceof BaseController baseController) { baseController.setAuthToken(authtoken); } @@ -73,23 +78,30 @@ public static void LoadScene(String sceneName, Stage stage, Charity charity, Str stage.setScene(scene); stage.setFullScreen(true); stage.show(); - stage.iconifiedProperty().addListener((obs, wasIconified, isNowIconified) -> { - if (!isNowIconified) { - stage.setFullScreen(true); - } - }); + stage + .iconifiedProperty() + .addListener( + (obs, wasIconified, isNowIconified) -> { + if (!isNowIconified) { + stage.setFullScreen(true); + } + }); } catch (IOException e) { throw new RuntimeException(e); } } + /** - * This method is the same as above, but tailored for Action Events, say through clicking a button. - * It takes the name of - * * the scene to load, the event that triggered the scene change, and the charity that is being - * * passed to the new scene (if applicable). + * This method is the same as above, but tailored for Action Events, say through clicking a + * button. It takes the name of * the scene to load, the event that triggered the scene change, + * and the charity that is being * passed to the new scene (if applicable). */ - - public static void LoadScene(String sceneName, ActionEvent event, Charity charity, String query, AuthenticationService authtoken) { + public static void LoadScene( + String sceneName, + ActionEvent event, + Charity charity, + String query, + AuthenticationService authtoken) { Stage stage = (Stage) ((Node) event.getSource()).getScene().getWindow(); LoadScene(sceneName, stage, charity, query, authtoken); } diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/NavbarController.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/NavbarController.java index 8052ef19..ceca5890 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/NavbarController.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/NavbarController.java @@ -1,75 +1,73 @@ package ntnu.systemutvikling.team6.controller.components; +import java.awt.*; import javafx.event.ActionEvent; -import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.TextField; -import java.awt.*; -import java.awt.event.MouseEvent; - public class NavbarController extends BaseController { - @FXML protected TextField frontSearchField; - @FXML private Button loginButton; - @FXML private Button profileButton; - @FXML private Button toCharityUserButton; - - @Override - protected void authTokenisSet() { - boolean loggedIn = super.isLoggedin(); - if (loggedIn){ - if (authToken.isCharityUser() != null){ - toCharityUserButton.setVisible(true); - toCharityUserButton.setManaged(true); - } - loginButton.setVisible(false); - loginButton.setManaged(false); - profileButton.setVisible(true); - profileButton.setManaged(true); - profileButton.setText(authToken.getCurrentUser().getUsername().substring(0,2).toUpperCase().trim()); - } else { - loginButton.setVisible(true); - loginButton.setManaged(true); - profileButton.setVisible(false); - profileButton.setManaged(false); - toCharityUserButton.setVisible(false); - toCharityUserButton.setManaged(false); - } + @FXML protected TextField frontSearchField; + @FXML private Button loginButton; + @FXML private Button profileButton; + @FXML private Button toCharityUserButton; + @Override + protected void authTokenisSet() { + boolean loggedIn = super.isLoggedin(); + if (loggedIn) { + if (authToken.isCharityUser() != null) { + toCharityUserButton.setVisible(true); + toCharityUserButton.setManaged(true); + } + loginButton.setVisible(false); + loginButton.setManaged(false); + profileButton.setVisible(true); + profileButton.setManaged(true); + profileButton.setText( + authToken.getCurrentUser().getUsername().substring(0, 2).toUpperCase().trim()); + } else { + loginButton.setVisible(true); + loginButton.setManaged(true); + profileButton.setVisible(false); + profileButton.setManaged(false); + toCharityUserButton.setVisible(false); + toCharityUserButton.setManaged(false); } - @FXML - private void handleFrontSearch(ActionEvent event){ - String query = frontSearchField.getText().trim(); + } - if (query.isEmpty()) { - return; - } + @FXML + private void handleFrontSearch(ActionEvent event) { + String query = frontSearchField.getText().trim(); - LoaderScene.LoadScene("available_organizations", event, null, query, authToken); + if (query.isEmpty()) { + return; } - @FXML - private void switchToFrontPage(ActionEvent event) { - System.out.println("Click!"); - LoaderScene.LoadScene("frontPage", event, null, null, authToken); - } + LoaderScene.LoadScene("available_organizations", event, null, query, authToken); + } - @FXML - private void switchToProfilePage(ActionEvent event) { - System.out.println("Click!"); - LoaderScene.LoadScene("profile_user_settings", event, null, null, authToken); - } + @FXML + private void switchToFrontPage(ActionEvent event) { + System.out.println("Click!"); + LoaderScene.LoadScene("frontPage", event, null, null, authToken); + } - @FXML - private void switchToLoginPage(ActionEvent event) { - System.out.println("Click!"); - LoaderScene.LoadScene("loginSite", event, null, null, authToken); - } + @FXML + private void switchToProfilePage(ActionEvent event) { + System.out.println("Click!"); + LoaderScene.LoadScene("profile_user_settings", event, null, null, authToken); + } - @FXML - private void switchToCharityUserPage(ActionEvent event) { - System.out.println("Click!"); - LoaderScene.LoadScene("profile_org_settings", event, null, null, authToken); - } + @FXML + private void switchToLoginPage(ActionEvent event) { + System.out.println("Click!"); + LoaderScene.LoadScene("loginSite", event, null, null, authToken); + } + + @FXML + private void switchToCharityUserPage(ActionEvent event) { + System.out.println("Click!"); + LoaderScene.LoadScene("profile_org_settings", event, null, null, authToken); + } } diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/OrgDonationCardController.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/OrgDonationCardController.java index 5fcbe69e..00b144bb 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/OrgDonationCardController.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/OrgDonationCardController.java @@ -4,25 +4,24 @@ import javafx.scene.control.Label; import ntnu.systemutvikling.team6.models.Donation; -public class OrgDonationCardController extends BaseController{ - @FXML private Label donerNameLabel; - @FXML private Label purchaseIDLabel; - @FXML private Label dateLabel; - @FXML private Label totalLabel; +public class OrgDonationCardController extends BaseController { + @FXML private Label donerNameLabel; + @FXML private Label purchaseIDLabel; + @FXML private Label dateLabel; + @FXML private Label totalLabel; - private Donation donation; + private Donation donation; - @Override - protected void authTokenisSet() { + @Override + protected void authTokenisSet() {} - } + public void setDonation(Donation donation) { + this.donation = donation; - public void setDonation(Donation donation) { - this.donation = donation; - - donerNameLabel.setText(donation.isAnonymous() ? "Anonymous Doner" : donation.getCharity().getName()); - purchaseIDLabel.setText(donation.getDonationID().toString()); - dateLabel.setText(donation.getDate().toString()); - totalLabel.setText(String.valueOf(donation.getAmount())); - } + donerNameLabel.setText( + donation.isAnonymous() ? "Anonymous Doner" : donation.getCharity().getName()); + purchaseIDLabel.setText(donation.getDonationID().toString()); + dateLabel.setText(donation.getDate().toString()); + totalLabel.setText(String.valueOf(donation.getAmount())); + } } diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/OrganizationCardController.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/OrganizationCardController.java index 3d7c53ef..24a7c520 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/OrganizationCardController.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/components/OrganizationCardController.java @@ -19,9 +19,7 @@ public class OrganizationCardController extends BaseController { private Charity charity; @Override - protected void authTokenisSet() { - - } + protected void authTokenisSet() {} public void setOrganization(Charity charity) { this.charity = charity; @@ -39,6 +37,4 @@ public void switchToDonationPage(ActionEvent event) { System.out.println(authToken.getCurrentUser().getId().toString()); LoaderScene.LoadScene("DonationPage", event, charity, null, authToken); } - - } diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/profileCharity/profileOrgEditController.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/profileCharity/profileOrgEditController.java index 12c0094f..1828c3c6 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/profileCharity/profileOrgEditController.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/profileCharity/profileOrgEditController.java @@ -3,113 +3,120 @@ import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.fxml.FXML; -import javafx.fxml.FXMLLoader; -import javafx.scene.Parent; import javafx.scene.control.Alert; import javafx.scene.control.Label; import javafx.scene.control.TextArea; -import javafx.scene.control.TextField; -import javafx.scene.layout.HBox; import javafx.stage.Stage; import ntnu.systemutvikling.team6.controller.components.BaseController; -import ntnu.systemutvikling.team6.controller.components.CategoryTagController; import ntnu.systemutvikling.team6.controller.components.LoaderScene; import ntnu.systemutvikling.team6.controller.components.NavbarController; import ntnu.systemutvikling.team6.database.DAO.CharityUserDAO; import ntnu.systemutvikling.team6.database.DatabaseConnection; import ntnu.systemutvikling.team6.models.Charity; -import java.io.IOException; -import java.util.List; - public class profileOrgEditController extends BaseController { - @FXML - private NavbarController navbarController; - - @FXML private Label charityNameLabel; - @FXML private Label charityNameLabel2; - @FXML private TextArea descriptionField; + @FXML private NavbarController navbarController; - @Override - protected void authTokenisSet() { - if (!isLoggedin() || authToken.isCharityUser() == null){ - showAlert(Alert.AlertType.ERROR, "Not logged inn or dont have privileges", "You need to be logged inn an account with Charity User priviliges."); - Platform.runLater(() -> { - Stage stage = (Stage) Stage.getWindows().stream() - .filter(w -> w.isShowing()) - .findFirst() - .orElse(null); - if (stage != null) { - LoaderScene.LoadScene("loginSite", stage, null, null, authToken); - } - }); - return; - } - navbarController.setAuthToken(authToken); - populateFields(); - } + @FXML private Label charityNameLabel; + @FXML private Label charityNameLabel2; + @FXML private TextArea descriptionField; - private void populateFields(){ - Charity usersCharity = authToken.isCharityUser(); - charityNameLabel.setText(usersCharity.getName()); - charityNameLabel2.setText(usersCharity.getName()); - descriptionField.setText(usersCharity.getDescription()); + @Override + protected void authTokenisSet() { + if (!isLoggedin() || authToken.isCharityUser() == null) { + showAlert( + Alert.AlertType.ERROR, + "Not logged inn or dont have privileges", + "You need to be logged inn an account with Charity User priviliges."); + Platform.runLater( + () -> { + Stage stage = + (Stage) + Stage.getWindows().stream().filter(w -> w.isShowing()).findFirst().orElse(null); + if (stage != null) { + LoaderScene.LoadScene("loginSite", stage, null, null, authToken); + } + }); + return; } + navbarController.setAuthToken(authToken); + populateFields(); + } - @FXML - private void handleSaveDescription(ActionEvent event){ - String descriptionFieldText = descriptionField.getText(); - + private void populateFields() { + Charity usersCharity = authToken.isCharityUser(); + charityNameLabel.setText(usersCharity.getName()); + charityNameLabel2.setText(usersCharity.getName()); + descriptionField.setText(usersCharity.getDescription()); + } - if (descriptionFieldText.isBlank()) { - showAlert(Alert.AlertType.ERROR, "Empty input", "Yeah, maybe it was empty before but now it need one"); - return; - } + @FXML + private void handleSaveDescription(ActionEvent event) { + String descriptionFieldText = descriptionField.getText(); - boolean updateSuccess; - DatabaseConnection conn = new DatabaseConnection(); - CharityUserDAO userDataObject = new CharityUserDAO(conn); - Charity savedCharity = authToken.isCharityUser(); - Charity minimalCharityWithJustNewDescription = new Charity(savedCharity.getUUID().toString(), savedCharity.getOrg_number(), savedCharity.getName(), null, savedCharity.getStatus(), savedCharity.getPreApproved(),descriptionFieldText, null, null, null); - try { - updateSuccess = userDataObject.updateCharityVanityDescription(minimalCharityWithJustNewDescription); - } catch (Exception e) { - e.printStackTrace(); - showAlert(Alert.AlertType.ERROR, "Unexpected Error", "Unexpected error ocurred"); - return; - } - if (updateSuccess) { - showAlert( - Alert.AlertType.INFORMATION, - "Settings updated", - "You have successfully changed your settings"); - authToken.isCharityUser().setDescription(descriptionFieldText); - LoaderScene.LoadScene("profile_user_settings", event, null, null, authToken); - } else { - System.out.println("Something went wrong when updating Settings"); - } + if (descriptionFieldText.isBlank()) { + showAlert( + Alert.AlertType.ERROR, + "Empty input", + "Yeah, maybe it was empty before but now it need one"); + return; } - @FXML - private void switchToPaymentsPage(ActionEvent event){ - LoaderScene.LoadScene("profile_org_Payments", event, null, null, authToken); + boolean updateSuccess; + DatabaseConnection conn = new DatabaseConnection(); + CharityUserDAO userDataObject = new CharityUserDAO(conn); + Charity savedCharity = authToken.isCharityUser(); + Charity minimalCharityWithJustNewDescription = + new Charity( + savedCharity.getUUID().toString(), + savedCharity.getOrg_number(), + savedCharity.getName(), + null, + savedCharity.getStatus(), + savedCharity.getPreApproved(), + descriptionFieldText, + null, + null, + null); + try { + updateSuccess = + userDataObject.updateCharityVanityDescription(minimalCharityWithJustNewDescription); + } catch (Exception e) { + e.printStackTrace(); + showAlert(Alert.AlertType.ERROR, "Unexpected Error", "Unexpected error ocurred"); + return; } - - @FXML - private void switchToFeedbackPage(ActionEvent event){ - LoaderScene.LoadScene("profile_org_Inbox", event, null, null, authToken); + if (updateSuccess) { + showAlert( + Alert.AlertType.INFORMATION, + "Settings updated", + "You have successfully changed your settings"); + authToken.isCharityUser().setDescription(descriptionFieldText); + LoaderScene.LoadScene("profile_user_settings", event, null, null, authToken); + } else { + System.out.println("Something went wrong when updating Settings"); } + } - @FXML - private void switchToSettingsPage(ActionEvent event){ - LoaderScene.LoadScene("profile_org_Settings", event, null, null, authToken); - } + @FXML + private void switchToPaymentsPage(ActionEvent event) { + LoaderScene.LoadScene("profile_org_Payments", event, null, null, authToken); + } + @FXML + private void switchToFeedbackPage(ActionEvent event) { + LoaderScene.LoadScene("profile_org_Inbox", event, null, null, authToken); + } - @FXML - private void handleLogout(ActionEvent event){ - authToken.logout(); - showAlert(Alert.AlertType.INFORMATION, "Logging out", "Logging out..."); - LoaderScene.LoadScene("FrontPage", event, null, null, authToken); - } + @FXML + private void switchToSettingsPage(ActionEvent event) { + LoaderScene.LoadScene("profile_org_Settings", event, null, null, authToken); + } + + @FXML + private void handleLogout(ActionEvent event) { + authToken.logout(); + showAlert(Alert.AlertType.INFORMATION, "Logging out", "Logging out..."); + LoaderScene.LoadScene("FrontPage", event, null, null, authToken); + } } diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/profileCharity/profileOrgInboxController.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/profileCharity/profileOrgInboxController.java index 335e9441..c0dd5db6 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/profileCharity/profileOrgInboxController.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/profileCharity/profileOrgInboxController.java @@ -1,5 +1,7 @@ package ntnu.systemutvikling.team6.controller.profileCharity; +import java.io.IOException; +import java.util.ArrayList; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.fxml.FXML; @@ -15,121 +17,115 @@ import ntnu.systemutvikling.team6.database.DAO.FeedbackDAO; import ntnu.systemutvikling.team6.database.DAO.MessageDAO; import ntnu.systemutvikling.team6.database.DatabaseConnection; -import ntnu.systemutvikling.team6.database.DAO.CharityDAO; import ntnu.systemutvikling.team6.models.Charity; import ntnu.systemutvikling.team6.models.Feedback; import ntnu.systemutvikling.team6.models.user.Message; -import java.io.IOException; -import java.util.ArrayList; - public class profileOrgInboxController extends BaseController { - @FXML - private NavbarController navbarController; - @FXML - private FlowPane cardsContainer; - @FXML private Label charityNameLabel; - @FXML private TextField messageTitleField; - @FXML private TextArea messageContentField; - - - @Override - protected void authTokenisSet() { - if (!isLoggedin() || authToken.isCharityUser() == null) { - showAlert(Alert.AlertType.ERROR, "Not logged inn", "You need to be logged inn to donate."); - Platform.runLater(() -> { - Stage stage = (Stage) Stage.getWindows().stream() - .filter(w -> w.isShowing()) - .findFirst() - .orElse(null); - if (stage != null) { - LoaderScene.LoadScene("loginSite", stage, null, null, authToken); - } - }); - } - navbarController.setAuthToken(authToken); - populateFields(); - } - - public void populateFields() { - Charity usersCharity = authToken.isCharityUser(); - charityNameLabel.setText(usersCharity.getName()); - - // Messages - DatabaseConnection conn = new DatabaseConnection(); - FeedbackDAO feedbackDAO = new FeedbackDAO(conn); - ArrayList feedbacks = feedbackDAO.getFeedbackforCharityUUID(authToken.isCharityUser().getUUID().toString()); - displayFeedbacks(feedbacks); - } - - private void displayFeedbacks(ArrayList feedbacks){ - cardsContainer.getChildren().clear(); - if (feedbacks.isEmpty()) { - Label empty = new Label("You have no Feedbacks"); - empty.setStyle("-fx-text-fill: #777777; -fx-font-size: 14;"); - cardsContainer.getChildren().add(empty); - } - - for (Feedback feedback : feedbacks) { - try { - FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/components/feedbackCard.fxml")); - Parent card = loader.load(); - FeedbackCardController cardController = loader.getController(); - cardController.setMessage(feedback); - cardController.setAuthToken(authToken); - cardsContainer.getChildren().add(card); - } catch (IOException e) { - throw new RuntimeException("Could not load organization card.", e); + @FXML private NavbarController navbarController; + @FXML private FlowPane cardsContainer; + @FXML private Label charityNameLabel; + @FXML private TextField messageTitleField; + @FXML private TextArea messageContentField; + + @Override + protected void authTokenisSet() { + if (!isLoggedin() || authToken.isCharityUser() == null) { + showAlert(Alert.AlertType.ERROR, "Not logged inn", "You need to be logged inn to donate."); + Platform.runLater( + () -> { + Stage stage = + (Stage) + Stage.getWindows().stream().filter(w -> w.isShowing()).findFirst().orElse(null); + if (stage != null) { + LoaderScene.LoadScene("loginSite", stage, null, null, authToken); } - } + }); } - - @FXML - private void handleSendMessage(ActionEvent event) { - String title = messageTitleField.getText().trim(); - String content = messageContentField.getText().trim(); - - if (title.isBlank() || content.isBlank()) { - showAlert(Alert.AlertType.ERROR, "Empty fields", "Please fill in both title and message."); - return; - } - - try { - DatabaseConnection conn = new DatabaseConnection(); - MessageDAO messageDAO = new MessageDAO(conn); - Charity charity = authToken.isCharityUser(); - Message messageStaticId = new Message(title, authToken.isCharityUser(), content); - messageDAO.addMessage(messageStaticId); - showAlert(Alert.AlertType.INFORMATION, "Sent!", "Your message has been sent to all donors."); - messageTitleField.clear(); - messageContentField.clear(); - } catch (Exception e) { - e.printStackTrace(); - showAlert(Alert.AlertType.ERROR, "Error", "Something went wrong sending the message."); - } + navbarController.setAuthToken(authToken); + populateFields(); + } + + public void populateFields() { + Charity usersCharity = authToken.isCharityUser(); + charityNameLabel.setText(usersCharity.getName()); + + // Messages + DatabaseConnection conn = new DatabaseConnection(); + FeedbackDAO feedbackDAO = new FeedbackDAO(conn); + ArrayList feedbacks = + feedbackDAO.getFeedbackforCharityUUID(authToken.isCharityUser().getUUID().toString()); + displayFeedbacks(feedbacks); + } + + private void displayFeedbacks(ArrayList feedbacks) { + cardsContainer.getChildren().clear(); + if (feedbacks.isEmpty()) { + Label empty = new Label("You have no Feedbacks"); + empty.setStyle("-fx-text-fill: #777777; -fx-font-size: 14;"); + cardsContainer.getChildren().add(empty); } - // Sidebar Methods - @FXML - private void switchToPaymentsPage(ActionEvent event) { - LoaderScene.LoadScene("profile_org_Payments", event, null, null, authToken); + for (Feedback feedback : feedbacks) { + try { + FXMLLoader loader = + new FXMLLoader(getClass().getResource("/fxml/components/feedbackCard.fxml")); + Parent card = loader.load(); + FeedbackCardController cardController = loader.getController(); + cardController.setMessage(feedback); + cardController.setAuthToken(authToken); + cardsContainer.getChildren().add(card); + } catch (IOException e) { + throw new RuntimeException("Could not load organization card.", e); + } } + } - @FXML - private void switchToEditPage(ActionEvent event) { - LoaderScene.LoadScene("profile_org_edit", event, null, null, authToken); - } + @FXML + private void handleSendMessage(ActionEvent event) { + String title = messageTitleField.getText().trim(); + String content = messageContentField.getText().trim(); - @FXML - private void switchToSettingsPage(ActionEvent event) { - LoaderScene.LoadScene("profile_org_Settings", event, null, null, authToken); + if (title.isBlank() || content.isBlank()) { + showAlert(Alert.AlertType.ERROR, "Empty fields", "Please fill in both title and message."); + return; } - - @FXML - private void handleLogout(ActionEvent event) { - authToken.logout(); - showAlert(Alert.AlertType.INFORMATION, "Logging out", "Logging out..."); - LoaderScene.LoadScene("FrontPage", event, null, null, authToken); + try { + DatabaseConnection conn = new DatabaseConnection(); + MessageDAO messageDAO = new MessageDAO(conn); + Charity charity = authToken.isCharityUser(); + Message messageStaticId = new Message(title, authToken.isCharityUser(), content); + messageDAO.addMessage(messageStaticId); + showAlert(Alert.AlertType.INFORMATION, "Sent!", "Your message has been sent to all donors."); + messageTitleField.clear(); + messageContentField.clear(); + } catch (Exception e) { + e.printStackTrace(); + showAlert(Alert.AlertType.ERROR, "Error", "Something went wrong sending the message."); } + } + + // Sidebar Methods + @FXML + private void switchToPaymentsPage(ActionEvent event) { + LoaderScene.LoadScene("profile_org_Payments", event, null, null, authToken); + } + + @FXML + private void switchToEditPage(ActionEvent event) { + LoaderScene.LoadScene("profile_org_edit", event, null, null, authToken); + } + + @FXML + private void switchToSettingsPage(ActionEvent event) { + LoaderScene.LoadScene("profile_org_Settings", event, null, null, authToken); + } + + @FXML + private void handleLogout(ActionEvent event) { + authToken.logout(); + showAlert(Alert.AlertType.INFORMATION, "Logging out", "Logging out..."); + LoaderScene.LoadScene("FrontPage", event, null, null, authToken); + } } diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/profileCharity/profileOrgPaymentsController.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/profileCharity/profileOrgPaymentsController.java index 5d505e33..32c2b26d 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/profileCharity/profileOrgPaymentsController.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/profileCharity/profileOrgPaymentsController.java @@ -1,5 +1,7 @@ package ntnu.systemutvikling.team6.controller.profileCharity; +import java.io.IOException; +import java.util.List; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.fxml.FXML; @@ -15,91 +17,86 @@ import ntnu.systemutvikling.team6.models.Charity; import ntnu.systemutvikling.team6.models.Donation; import ntnu.systemutvikling.team6.models.registry.DonationRegistry; -import ntnu.systemutvikling.team6.models.user.User; - -import java.io.IOException; -import java.util.List; public class profileOrgPaymentsController extends BaseController { - @FXML - private NavbarController navbarController; - @FXML private VBox cardsContainer; - @FXML private Label charityNameLabel; - + @FXML private NavbarController navbarController; + @FXML private VBox cardsContainer; + @FXML private Label charityNameLabel; - @Override - protected void authTokenisSet() { - if (!isLoggedin() || authToken.isCharityUser() == null){ - showAlert(Alert.AlertType.ERROR, "Not logged inn", "You need to be logged inn to donate."); - Platform.runLater(() -> { - Stage stage = (Stage) Stage.getWindows().stream() - .filter(w -> w.isShowing()) - .findFirst() - .orElse(null); - if (stage != null) { - LoaderScene.LoadScene("loginSite", stage, null, null, authToken); - } - }); - } - navbarController.setAuthToken(authToken); - populateFields(); + @Override + protected void authTokenisSet() { + if (!isLoggedin() || authToken.isCharityUser() == null) { + showAlert(Alert.AlertType.ERROR, "Not logged inn", "You need to be logged inn to donate."); + Platform.runLater( + () -> { + Stage stage = + (Stage) + Stage.getWindows().stream().filter(w -> w.isShowing()).findFirst().orElse(null); + if (stage != null) { + LoaderScene.LoadScene("loginSite", stage, null, null, authToken); + } + }); } + navbarController.setAuthToken(authToken); + populateFields(); + } - public void populateFields() { - Charity usersCharity = authToken.isCharityUser(); - charityNameLabel.setText(usersCharity.getName()); + public void populateFields() { + Charity usersCharity = authToken.isCharityUser(); + charityNameLabel.setText(usersCharity.getName()); - // DonationHistory - DatabaseConnection conn = new DatabaseConnection(); - DonationDAO donationDAO = new DonationDAO(conn); - DonationRegistry donationRegistry = donationDAO.getDonationForCharity(authToken.isCharityUser().getUUID().toString()); - displayDonations(donationRegistry); - } - - private void displayDonations(DonationRegistry donationRegistry) { - cardsContainer.getChildren().clear(); - List donations = donationRegistry.getAllDonations(); - if(donations.isEmpty()){ - Label empty = new Label("You have no Donations"); - empty.setStyle("-fx-text-fill: #777777; -fx-font-size: 14;"); - cardsContainer.getChildren().add(empty); - } + // DonationHistory + DatabaseConnection conn = new DatabaseConnection(); + DonationDAO donationDAO = new DonationDAO(conn); + DonationRegistry donationRegistry = + donationDAO.getDonationForCharity(authToken.isCharityUser().getUUID().toString()); + displayDonations(donationRegistry); + } - for (Donation donation : donations) { - try { - FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/components/profileOrgDonationCard.fxml")); - Parent card = loader.load(); - OrgDonationCardController cardController = loader.getController(); - cardController.setDonation(donation); - cardController.setAuthToken(authToken); - cardsContainer.getChildren().add(card); - } catch (IOException e) { - throw new RuntimeException("Could not load organization card.", e); - } - } + private void displayDonations(DonationRegistry donationRegistry) { + cardsContainer.getChildren().clear(); + List donations = donationRegistry.getAllDonations(); + if (donations.isEmpty()) { + Label empty = new Label("You have no Donations"); + empty.setStyle("-fx-text-fill: #777777; -fx-font-size: 14;"); + cardsContainer.getChildren().add(empty); } - // Sidebar Methods - @FXML - private void switchToEditPage(ActionEvent event){ - LoaderScene.LoadScene("profile_org_edit", event, null, null, authToken); + for (Donation donation : donations) { + try { + FXMLLoader loader = + new FXMLLoader(getClass().getResource("/fxml/components/profileOrgDonationCard.fxml")); + Parent card = loader.load(); + OrgDonationCardController cardController = loader.getController(); + cardController.setDonation(donation); + cardController.setAuthToken(authToken); + cardsContainer.getChildren().add(card); + } catch (IOException e) { + throw new RuntimeException("Could not load organization card.", e); + } } + } - @FXML - private void switchToFeedbackPage(ActionEvent event){ - LoaderScene.LoadScene("profile_org_Inbox", event, null, null, authToken); - } + // Sidebar Methods + @FXML + private void switchToEditPage(ActionEvent event) { + LoaderScene.LoadScene("profile_org_edit", event, null, null, authToken); + } - @FXML - private void switchToSettingsPage(ActionEvent event){ - LoaderScene.LoadScene("profile_org_Settings", event, null, null, authToken); - } + @FXML + private void switchToFeedbackPage(ActionEvent event) { + LoaderScene.LoadScene("profile_org_Inbox", event, null, null, authToken); + } + @FXML + private void switchToSettingsPage(ActionEvent event) { + LoaderScene.LoadScene("profile_org_Settings", event, null, null, authToken); + } - @FXML - private void handleLogout(ActionEvent event){ - authToken.logout(); - showAlert(Alert.AlertType.INFORMATION, "Logging out", "Logging out..."); - LoaderScene.LoadScene("FrontPage", event, null, null, authToken); - } + @FXML + private void handleLogout(ActionEvent event) { + authToken.logout(); + showAlert(Alert.AlertType.INFORMATION, "Logging out", "Logging out..."); + LoaderScene.LoadScene("FrontPage", event, null, null, authToken); + } } diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/profileCharity/profileOrgSettingsController.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/profileCharity/profileOrgSettingsController.java index f9d3acce..c8c3824c 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/profileCharity/profileOrgSettingsController.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/profileCharity/profileOrgSettingsController.java @@ -1,5 +1,7 @@ package ntnu.systemutvikling.team6.controller.profileCharity; +import java.io.IOException; +import java.util.List; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.fxml.FXML; @@ -15,123 +17,131 @@ import ntnu.systemutvikling.team6.database.DatabaseConnection; import ntnu.systemutvikling.team6.models.Charity; -import java.io.IOException; -import java.util.List; - public class profileOrgSettingsController extends BaseController { - @FXML private NavbarController navbarController; - @FXML private Label charityNameLabel; - @FXML private TextField organizationNameField; - @FXML private HBox tagContainer; - - @Override - protected void authTokenisSet() { - if (!isLoggedin() || authToken.isCharityUser() == null){ - showAlert(Alert.AlertType.ERROR, "Not logged inn or dont have privileges", "You need to be logged inn an account with Charity User priviliges."); - Platform.runLater(() -> { - Stage stage = (Stage) Stage.getWindows().stream() - .filter(w -> w.isShowing()) - .findFirst() - .orElse(null); - if (stage != null) { - LoaderScene.LoadScene("loginSite", stage, null, null, authToken); - } - }); - return; - } - navbarController.setAuthToken(authToken); - populateFields(); - } - - private void populateFields(){ - Charity usersCharity = authToken.isCharityUser(); - charityNameLabel.setText(usersCharity.getName()); - organizationNameField.setText(usersCharity.getName()); - - // Tags - List categories = usersCharity.getCategory(); - displayCategories(categories); - - } - - private void displayCategories(List categories) { - tagContainer.getChildren().clear(); - if(categories.isEmpty()){ - Label empty = new Label("No categories"); - empty.setStyle("-fx-text-fill: #777777; -fx-font-size: 14;"); - tagContainer.getChildren().add(empty); - return; - } - - for (String category : categories) { - try { - FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/components/categoryTag.fxml")); - Parent card = loader.load(); - CategoryTagController cardController = loader.getController(); - cardController.setCategory(category); - cardController.setAuthToken(authToken); - tagContainer.getChildren().add(card); - } catch (IOException e) { - throw new RuntimeException("Could not load organization card.", e); + @FXML private NavbarController navbarController; + @FXML private Label charityNameLabel; + @FXML private TextField organizationNameField; + @FXML private HBox tagContainer; + + @Override + protected void authTokenisSet() { + if (!isLoggedin() || authToken.isCharityUser() == null) { + showAlert( + Alert.AlertType.ERROR, + "Not logged inn or dont have privileges", + "You need to be logged inn an account with Charity User priviliges."); + Platform.runLater( + () -> { + Stage stage = + (Stage) + Stage.getWindows().stream().filter(w -> w.isShowing()).findFirst().orElse(null); + if (stage != null) { + LoaderScene.LoadScene("loginSite", stage, null, null, authToken); } - } + }); + return; } - - @FXML - private void handleNewName(ActionEvent event){ - String organizationNameFieldText = organizationNameField.getText(); - - - if (organizationNameFieldText.isBlank()) { - showAlert(Alert.AlertType.ERROR, "Empty input", "Please fill out all fields"); - return; - } - - boolean updateSuccess; - DatabaseConnection conn = new DatabaseConnection(); - CharityUserDAO userDataObject = new CharityUserDAO(conn); - Charity savedCharity = authToken.isCharityUser(); - Charity minimalCharityWithJustNewName = new Charity(savedCharity.getUUID().toString(), savedCharity.getOrg_number(), organizationNameFieldText, null, savedCharity.getStatus(), savedCharity.getPreApproved(),null, null, null, null); - try { - updateSuccess = userDataObject.updateCharityVanityName(minimalCharityWithJustNewName); - } catch (Exception e) { - e.printStackTrace(); - showAlert(Alert.AlertType.ERROR, "Unexpected Error", "Unexpected error ocurred"); - return; - } - if (updateSuccess) { - showAlert( - Alert.AlertType.INFORMATION, - "Settings updated", - "You have successfully changed your settings"); - authToken.isCharityUser().setName(organizationNameFieldText); - LoaderScene.LoadScene("profile_user_settings", event, null, null, authToken); - } else { - System.out.println("Something went wrong when updating Settings"); - } - + navbarController.setAuthToken(authToken); + populateFields(); + } + + private void populateFields() { + Charity usersCharity = authToken.isCharityUser(); + charityNameLabel.setText(usersCharity.getName()); + organizationNameField.setText(usersCharity.getName()); + + // Tags + List categories = usersCharity.getCategory(); + displayCategories(categories); + } + + private void displayCategories(List categories) { + tagContainer.getChildren().clear(); + if (categories.isEmpty()) { + Label empty = new Label("No categories"); + empty.setStyle("-fx-text-fill: #777777; -fx-font-size: 14;"); + tagContainer.getChildren().add(empty); + return; } - @FXML - private void switchToPaymentsPage(ActionEvent event){ - LoaderScene.LoadScene("profile_org_Payments", event, null, null, authToken); + for (String category : categories) { + try { + FXMLLoader loader = + new FXMLLoader(getClass().getResource("/fxml/components/categoryTag.fxml")); + Parent card = loader.load(); + CategoryTagController cardController = loader.getController(); + cardController.setCategory(category); + cardController.setAuthToken(authToken); + tagContainer.getChildren().add(card); + } catch (IOException e) { + throw new RuntimeException("Could not load organization card.", e); + } } + } - @FXML - private void switchToFeedbackPage(ActionEvent event){ - LoaderScene.LoadScene("profile_org_Inbox", event, null, null, authToken); - } + @FXML + private void handleNewName(ActionEvent event) { + String organizationNameFieldText = organizationNameField.getText(); - @FXML - private void switchToEditPage(ActionEvent event){ - LoaderScene.LoadScene("profile_org_edit", event, null, null, authToken); + if (organizationNameFieldText.isBlank()) { + showAlert(Alert.AlertType.ERROR, "Empty input", "Please fill out all fields"); + return; } - - @FXML - private void handleLogout(ActionEvent event){ - authToken.logout(); - showAlert(Alert.AlertType.INFORMATION, "Logging out", "Logging out..."); - LoaderScene.LoadScene("FrontPage", event, null, null, authToken); + boolean updateSuccess; + DatabaseConnection conn = new DatabaseConnection(); + CharityUserDAO userDataObject = new CharityUserDAO(conn); + Charity savedCharity = authToken.isCharityUser(); + Charity minimalCharityWithJustNewName = + new Charity( + savedCharity.getUUID().toString(), + savedCharity.getOrg_number(), + organizationNameFieldText, + null, + savedCharity.getStatus(), + savedCharity.getPreApproved(), + null, + null, + null, + null); + try { + updateSuccess = userDataObject.updateCharityVanityName(minimalCharityWithJustNewName); + } catch (Exception e) { + e.printStackTrace(); + showAlert(Alert.AlertType.ERROR, "Unexpected Error", "Unexpected error ocurred"); + return; + } + if (updateSuccess) { + showAlert( + Alert.AlertType.INFORMATION, + "Settings updated", + "You have successfully changed your settings"); + authToken.isCharityUser().setName(organizationNameFieldText); + LoaderScene.LoadScene("profile_user_settings", event, null, null, authToken); + } else { + System.out.println("Something went wrong when updating Settings"); } + } + + @FXML + private void switchToPaymentsPage(ActionEvent event) { + LoaderScene.LoadScene("profile_org_Payments", event, null, null, authToken); + } + + @FXML + private void switchToFeedbackPage(ActionEvent event) { + LoaderScene.LoadScene("profile_org_Inbox", event, null, null, authToken); + } + + @FXML + private void switchToEditPage(ActionEvent event) { + LoaderScene.LoadScene("profile_org_edit", event, null, null, authToken); + } + + @FXML + private void handleLogout(ActionEvent event) { + authToken.logout(); + showAlert(Alert.AlertType.INFORMATION, "Logging out", "Logging out..."); + LoaderScene.LoadScene("FrontPage", event, null, null, authToken); + } } diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/profileUser/profileUserHistoryController.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/profileUser/profileUserHistoryController.java index 28810585..9756867d 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/profileUser/profileUserHistoryController.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/profileUser/profileUserHistoryController.java @@ -1,5 +1,7 @@ package ntnu.systemutvikling.team6.controller.profileUser; +import java.io.IOException; +import java.util.List; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.fxml.FXML; @@ -7,7 +9,6 @@ import javafx.scene.Parent; import javafx.scene.control.Alert; import javafx.scene.control.Label; -import javafx.scene.layout.FlowPane; import javafx.scene.layout.VBox; import javafx.stage.Stage; import ntnu.systemutvikling.team6.controller.components.*; @@ -15,103 +16,99 @@ import ntnu.systemutvikling.team6.database.DatabaseConnection; import ntnu.systemutvikling.team6.models.Donation; import ntnu.systemutvikling.team6.models.registry.DonationRegistry; -import ntnu.systemutvikling.team6.models.user.Inbox; -import ntnu.systemutvikling.team6.models.user.Message; import ntnu.systemutvikling.team6.models.user.User; -import java.io.IOException; -import java.util.List; -import java.util.stream.Collectors; - public class profileUserHistoryController extends BaseController { - @FXML - private NavbarController navbarController; - @FXML private VBox cardsContainer; - @FXML private Label nameLabel; - @FXML private Label shortNameLabel; - @FXML private Label totalAmmount; + @FXML private NavbarController navbarController; + @FXML private VBox cardsContainer; + @FXML private Label nameLabel; + @FXML private Label shortNameLabel; + @FXML private Label totalAmmount; - @Override - protected void authTokenisSet() { - if (!isLoggedin()){ - showAlert(Alert.AlertType.ERROR, "Not logged inn", "You need to be logged inn to donate."); - Platform.runLater(() -> { - Stage stage = (Stage) Stage.getWindows().stream() - .filter(w -> w.isShowing()) - .findFirst() - .orElse(null); - if (stage != null) { - LoaderScene.LoadScene("loginSite", stage, null, null, authToken); - } - }); - } - navbarController.setAuthToken(authToken); - populateFields(); + @Override + protected void authTokenisSet() { + if (!isLoggedin()) { + showAlert(Alert.AlertType.ERROR, "Not logged inn", "You need to be logged inn to donate."); + Platform.runLater( + () -> { + Stage stage = + (Stage) + Stage.getWindows().stream().filter(w -> w.isShowing()).findFirst().orElse(null); + if (stage != null) { + LoaderScene.LoadScene("loginSite", stage, null, null, authToken); + } + }); } + navbarController.setAuthToken(authToken); + populateFields(); + } - public void populateFields() { - User user = authToken.getCurrentUser(); - // Names - nameLabel.setText(user.getUsername()); - shortNameLabel.setText(user.getUsername().substring(0, 2).toUpperCase().trim()); - - // DonationHistory - DatabaseConnection conn = new DatabaseConnection(); - DonationDAO donationDAO = new DonationDAO(conn); - DonationRegistry donationRegistry = donationDAO.getDonationForUser(authToken.getCurrentUser().getId().toString()); - double ammount = donationRegistry.getAllDonations().stream().mapToDouble(d->d.getAmount()).sum(); - totalAmmount.setText(String.valueOf(ammount)); - displayDonations(donationRegistry); - } + public void populateFields() { + User user = authToken.getCurrentUser(); + // Names + nameLabel.setText(user.getUsername()); + shortNameLabel.setText(user.getUsername().substring(0, 2).toUpperCase().trim()); - private void displayDonations(DonationRegistry donationRegistry) { - cardsContainer.getChildren().clear(); - List donations = donationRegistry.getAllDonations(); - if(donations.isEmpty()){ - Label empty = new Label("You have no Donations"); - empty.setStyle("-fx-text-fill: #777777; -fx-font-size: 14;"); - cardsContainer.getChildren().add(empty); - } + // DonationHistory + DatabaseConnection conn = new DatabaseConnection(); + DonationDAO donationDAO = new DonationDAO(conn); + DonationRegistry donationRegistry = + donationDAO.getDonationForUser(authToken.getCurrentUser().getId().toString()); + double ammount = + donationRegistry.getAllDonations().stream().mapToDouble(d -> d.getAmount()).sum(); + totalAmmount.setText(String.valueOf(ammount)); + displayDonations(donationRegistry); + } - for (Donation donation : donations) { - try { - FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/components/profileDonationCard.fxml")); - Parent card = loader.load(); - DonationCardController cardController = loader.getController(); - cardController.setDonation(donation); - cardController.setAuthToken(authToken); - cardsContainer.getChildren().add(card); - } catch (IOException e) { - throw new RuntimeException("Could not load organization card.", e); - } - } + private void displayDonations(DonationRegistry donationRegistry) { + cardsContainer.getChildren().clear(); + List donations = donationRegistry.getAllDonations(); + if (donations.isEmpty()) { + Label empty = new Label("You have no Donations"); + empty.setStyle("-fx-text-fill: #777777; -fx-font-size: 14;"); + cardsContainer.getChildren().add(empty); } - // Sidebar Methods - @FXML - private void handleLogout(ActionEvent event){ - authToken.logout(); - showAlert(Alert.AlertType.INFORMATION, "Logging out", "Logging out..."); - LoaderScene.LoadScene("FrontPage", event, null, null, authToken); + for (Donation donation : donations) { + try { + FXMLLoader loader = + new FXMLLoader(getClass().getResource("/fxml/components/profileDonationCard.fxml")); + Parent card = loader.load(); + DonationCardController cardController = loader.getController(); + cardController.setDonation(donation); + cardController.setAuthToken(authToken); + cardsContainer.getChildren().add(card); + } catch (IOException e) { + throw new RuntimeException("Could not load organization card.", e); + } } + } - @FXML - private void switchToFrontPage(ActionEvent event){ - LoaderScene.LoadScene("FrontPage", event, null, null, authToken); - } + // Sidebar Methods + @FXML + private void handleLogout(ActionEvent event) { + authToken.logout(); + showAlert(Alert.AlertType.INFORMATION, "Logging out", "Logging out..."); + LoaderScene.LoadScene("FrontPage", event, null, null, authToken); + } - @FXML - private void switchToInterestPage(ActionEvent event){ - LoaderScene.LoadScene("profile_user_interests", event, null, null, authToken); - } + @FXML + private void switchToFrontPage(ActionEvent event) { + LoaderScene.LoadScene("FrontPage", event, null, null, authToken); + } - @FXML - private void switchToInboxPage(ActionEvent event){ - LoaderScene.LoadScene("profile_user_inbox", event, null, null, authToken); - } + @FXML + private void switchToInterestPage(ActionEvent event) { + LoaderScene.LoadScene("profile_user_interests", event, null, null, authToken); + } - @FXML - private void switchToSettingsPage(ActionEvent event){ - LoaderScene.LoadScene("profile_user_settings", event, null, null, authToken); - } + @FXML + private void switchToInboxPage(ActionEvent event) { + LoaderScene.LoadScene("profile_user_inbox", event, null, null, authToken); + } + + @FXML + private void switchToSettingsPage(ActionEvent event) { + LoaderScene.LoadScene("profile_user_settings", event, null, null, authToken); + } } diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/profileUser/profileUserInboxController.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/profileUser/profileUserInboxController.java index 39352704..0292d387 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/profileUser/profileUserInboxController.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/profileUser/profileUserInboxController.java @@ -1,5 +1,7 @@ package ntnu.systemutvikling.team6.controller.profileUser; +import java.io.IOException; +import java.util.List; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.fxml.FXML; @@ -10,102 +12,94 @@ import javafx.scene.layout.FlowPane; import javafx.stage.Stage; import ntnu.systemutvikling.team6.controller.components.*; -import ntnu.systemutvikling.team6.database.DAO.FavouritesDAO; -import ntnu.systemutvikling.team6.database.DatabaseConnection; -import ntnu.systemutvikling.team6.models.Charity; import ntnu.systemutvikling.team6.models.user.Inbox; import ntnu.systemutvikling.team6.models.user.Message; -import ntnu.systemutvikling.team6.models.user.Settings; import ntnu.systemutvikling.team6.models.user.User; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - public class profileUserInboxController extends BaseController { - @FXML private NavbarController navbarController; - @FXML private FlowPane cardsContainer; - @FXML private Label nameLabel; - @FXML private Label shortNameLabel; + @FXML private NavbarController navbarController; + @FXML private FlowPane cardsContainer; + @FXML private Label nameLabel; + @FXML private Label shortNameLabel; - @Override - protected void authTokenisSet() { - if (!isLoggedin()){ - showAlert(Alert.AlertType.ERROR, "Not logged inn", "You need to be logged inn to donate."); - Platform.runLater(() -> { - Stage stage = (Stage) Stage.getWindows().stream() - .filter(w -> w.isShowing()) - .findFirst() - .orElse(null); - if (stage != null) { - LoaderScene.LoadScene("loginSite", stage, null, null, authToken); - } - }); - } - navbarController.setAuthToken(authToken); - populateFields(); + @Override + protected void authTokenisSet() { + if (!isLoggedin()) { + showAlert(Alert.AlertType.ERROR, "Not logged inn", "You need to be logged inn to donate."); + Platform.runLater( + () -> { + Stage stage = + (Stage) + Stage.getWindows().stream().filter(w -> w.isShowing()).findFirst().orElse(null); + if (stage != null) { + LoaderScene.LoadScene("loginSite", stage, null, null, authToken); + } + }); } + navbarController.setAuthToken(authToken); + populateFields(); + } - public void populateFields() { - User user = authToken.getCurrentUser(); - // Names - nameLabel.setText(user.getUsername()); - shortNameLabel.setText(user.getUsername().substring(0, 2).toUpperCase().trim()); - - // Messages - Inbox inbox = authToken.getCurrentUser().getInbox(); - displayInbox(inbox); - } + public void populateFields() { + User user = authToken.getCurrentUser(); + // Names + nameLabel.setText(user.getUsername()); + shortNameLabel.setText(user.getUsername().substring(0, 2).toUpperCase().trim()); - private void displayInbox(Inbox inbox) { - cardsContainer.getChildren().clear(); - List messages = inbox.getMessages(); - if(messages.isEmpty()){ - Label empty = new Label("You have no messages"); - empty.setStyle("-fx-text-fill: #777777; -fx-font-size: 14;"); - cardsContainer.getChildren().add(empty); - } + // Messages + Inbox inbox = authToken.getCurrentUser().getInbox(); + displayInbox(inbox); + } - for (Message message : messages) { - try { - FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/components/inboxCard.fxml")); - Parent card = loader.load(); - InboxCardController cardController = loader.getController(); - cardController.setMessage(message); - cardController.setAuthToken(authToken); - cardsContainer.getChildren().add(card); - } catch (IOException e) { - throw new RuntimeException("Could not load organization card.", e); - } - } + private void displayInbox(Inbox inbox) { + cardsContainer.getChildren().clear(); + List messages = inbox.getMessages(); + if (messages.isEmpty()) { + Label empty = new Label("You have no messages"); + empty.setStyle("-fx-text-fill: #777777; -fx-font-size: 14;"); + cardsContainer.getChildren().add(empty); } - // Sidebar Methods - @FXML - private void handleLogout(ActionEvent event){ - authToken.logout(); - showAlert(Alert.AlertType.INFORMATION, "Logging out", "Logging out..."); - LoaderScene.LoadScene("FrontPage", event, null, null, authToken); + for (Message message : messages) { + try { + FXMLLoader loader = + new FXMLLoader(getClass().getResource("/fxml/components/inboxCard.fxml")); + Parent card = loader.load(); + InboxCardController cardController = loader.getController(); + cardController.setMessage(message); + cardController.setAuthToken(authToken); + cardsContainer.getChildren().add(card); + } catch (IOException e) { + throw new RuntimeException("Could not load organization card.", e); + } } + } - @FXML - private void switchToFrontPage(ActionEvent event){ - LoaderScene.LoadScene("FrontPage", event, null, null, authToken); - } + // Sidebar Methods + @FXML + private void handleLogout(ActionEvent event) { + authToken.logout(); + showAlert(Alert.AlertType.INFORMATION, "Logging out", "Logging out..."); + LoaderScene.LoadScene("FrontPage", event, null, null, authToken); + } - @FXML - private void switchToInterestPage(ActionEvent event){ - LoaderScene.LoadScene("profile_user_interests", event, null, null, authToken); - } + @FXML + private void switchToFrontPage(ActionEvent event) { + LoaderScene.LoadScene("FrontPage", event, null, null, authToken); + } - @FXML - private void switchToHistoryPage(ActionEvent event){ - LoaderScene.LoadScene("profile_user_history", event, null, null, authToken); - } + @FXML + private void switchToInterestPage(ActionEvent event) { + LoaderScene.LoadScene("profile_user_interests", event, null, null, authToken); + } - @FXML - private void switchToSettingsPage(ActionEvent event){ - LoaderScene.LoadScene("profile_user_settings", event, null, null, authToken); - } + @FXML + private void switchToHistoryPage(ActionEvent event) { + LoaderScene.LoadScene("profile_user_history", event, null, null, authToken); + } + + @FXML + private void switchToSettingsPage(ActionEvent event) { + LoaderScene.LoadScene("profile_user_settings", event, null, null, authToken); + } } diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/profileUser/profileUserInterestController.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/profileUser/profileUserInterestController.java index 7ebffcf6..00c1f131 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/profileUser/profileUserInterestController.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/profileUser/profileUserInterestController.java @@ -1,5 +1,7 @@ package ntnu.systemutvikling.team6.controller.profileUser; +import java.io.IOException; +import java.util.ArrayList; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.fxml.FXML; @@ -7,109 +9,103 @@ import javafx.scene.Parent; import javafx.scene.control.Alert; import javafx.scene.control.Label; -import javafx.scene.control.ScrollPane; import javafx.scene.layout.FlowPane; -import javafx.scene.layout.VBox; import javafx.stage.Stage; import ntnu.systemutvikling.team6.controller.components.*; import ntnu.systemutvikling.team6.database.DAO.FavouritesDAO; import ntnu.systemutvikling.team6.database.DatabaseConnection; import ntnu.systemutvikling.team6.models.Charity; -import ntnu.systemutvikling.team6.models.registry.CharityRegistry; -import ntnu.systemutvikling.team6.models.user.Language; import ntnu.systemutvikling.team6.models.user.Settings; import ntnu.systemutvikling.team6.models.user.User; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - public class profileUserInterestController extends BaseController { - @FXML private NavbarController navbarController; - @FXML private FlowPane cardsContainer; - @FXML private Label nameLabel; - @FXML private Label shortNameLabel; + @FXML private NavbarController navbarController; + @FXML private FlowPane cardsContainer; + @FXML private Label nameLabel; + @FXML private Label shortNameLabel; - @Override - protected void authTokenisSet() { - if (!isLoggedin()){ - showAlert(Alert.AlertType.ERROR, "Not logged inn", "You need to be logged inn to donate."); - Platform.runLater(() -> { - Stage stage = (Stage) Stage.getWindows().stream() - .filter(w -> w.isShowing()) - .findFirst() - .orElse(null); - if (stage != null) { - LoaderScene.LoadScene("loginSite", stage, null, null, authToken); - } - }); - } - navbarController.setAuthToken(authToken); - populateFields(); + @Override + protected void authTokenisSet() { + if (!isLoggedin()) { + showAlert(Alert.AlertType.ERROR, "Not logged inn", "You need to be logged inn to donate."); + Platform.runLater( + () -> { + Stage stage = + (Stage) + Stage.getWindows().stream().filter(w -> w.isShowing()).findFirst().orElse(null); + if (stage != null) { + LoaderScene.LoadScene("loginSite", stage, null, null, authToken); + } + }); } + navbarController.setAuthToken(authToken); + populateFields(); + } - public void populateFields() { - User user = authToken.getCurrentUser(); - Settings settings = user.getSettings(); - // Names - nameLabel.setText(user.getUsername()); - shortNameLabel.setText(user.getUsername().substring(0, 2).toUpperCase().trim()); - - // Favourites - DatabaseConnection conn = new DatabaseConnection(); - FavouritesDAO favouritesDAO = new FavouritesDAO(conn); - ArrayList favourites = new ArrayList<>(favouritesDAO.getFavouritesForUser(authToken.getCurrentUser().getId().toString())); - displayFavourites(favourites); - } + public void populateFields() { + User user = authToken.getCurrentUser(); + Settings settings = user.getSettings(); + // Names + nameLabel.setText(user.getUsername()); + shortNameLabel.setText(user.getUsername().substring(0, 2).toUpperCase().trim()); - private void displayFavourites(ArrayList favourites) { - cardsContainer.getChildren().clear(); - if(favourites.isEmpty()){ - Label empty = new Label("You have no favourited Charities"); - empty.setStyle("-fx-text-fill: #777777; -fx-font-size: 14;"); - cardsContainer.getChildren().add(empty); - } + // Favourites + DatabaseConnection conn = new DatabaseConnection(); + FavouritesDAO favouritesDAO = new FavouritesDAO(conn); + ArrayList favourites = + new ArrayList<>( + favouritesDAO.getFavouritesForUser(authToken.getCurrentUser().getId().toString())); + displayFavourites(favourites); + } - for (Charity charity : favourites) { - try { - FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/components/interestCard.fxml")); - Parent card = loader.load(); - InterestCardController cardController = loader.getController(); - cardController.setOrganization(charity); - cardController.setAuthToken(authToken); - cardsContainer.getChildren().add(card); - } catch (IOException e) { - throw new RuntimeException("Could not load organization card.", e); - } - } + private void displayFavourites(ArrayList favourites) { + cardsContainer.getChildren().clear(); + if (favourites.isEmpty()) { + Label empty = new Label("You have no favourited Charities"); + empty.setStyle("-fx-text-fill: #777777; -fx-font-size: 14;"); + cardsContainer.getChildren().add(empty); } - // Sidebar Methods - @FXML - private void handleLogout(ActionEvent event){ - authToken.logout(); - showAlert(Alert.AlertType.INFORMATION, "Logging out", "Logging out..."); - LoaderScene.LoadScene("FrontPage", event, null, null, authToken); + for (Charity charity : favourites) { + try { + FXMLLoader loader = + new FXMLLoader(getClass().getResource("/fxml/components/interestCard.fxml")); + Parent card = loader.load(); + InterestCardController cardController = loader.getController(); + cardController.setOrganization(charity); + cardController.setAuthToken(authToken); + cardsContainer.getChildren().add(card); + } catch (IOException e) { + throw new RuntimeException("Could not load organization card.", e); + } } + } - @FXML - private void switchToFrontPage(ActionEvent event){ - LoaderScene.LoadScene("FrontPage", event, null, null, authToken); - } + // Sidebar Methods + @FXML + private void handleLogout(ActionEvent event) { + authToken.logout(); + showAlert(Alert.AlertType.INFORMATION, "Logging out", "Logging out..."); + LoaderScene.LoadScene("FrontPage", event, null, null, authToken); + } - @FXML - private void switchToInboxPage(ActionEvent event){ - LoaderScene.LoadScene("profile_user_inbox", event, null, null, authToken); - } + @FXML + private void switchToFrontPage(ActionEvent event) { + LoaderScene.LoadScene("FrontPage", event, null, null, authToken); + } - @FXML - private void switchToHistoryPage(ActionEvent event){ - LoaderScene.LoadScene("profile_user_history", event, null, null, authToken); - } + @FXML + private void switchToInboxPage(ActionEvent event) { + LoaderScene.LoadScene("profile_user_inbox", event, null, null, authToken); + } - @FXML - private void switchToSettingsPage(ActionEvent event){ - LoaderScene.LoadScene("profile_user_settings", event, null, null, authToken); - } + @FXML + private void switchToHistoryPage(ActionEvent event) { + LoaderScene.LoadScene("profile_user_history", event, null, null, authToken); + } + + @FXML + private void switchToSettingsPage(ActionEvent event) { + LoaderScene.LoadScene("profile_user_settings", event, null, null, authToken); + } } diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/profileUser/profileUserSettingsController.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/profileUser/profileUserSettingsController.java index 8e0ef078..7e92fea7 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/profileUser/profileUserSettingsController.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/profileUser/profileUserSettingsController.java @@ -14,203 +14,216 @@ import ntnu.systemutvikling.team6.security.PasswordHasher; public class profileUserSettingsController extends BaseController { - @FXML private NavbarController navbarController; - @FXML private ComboBox languageComboBox; - @FXML private ComboBox themeComboBox; - @FXML private ToggleButton anonymousToggle; - @FXML private Label anonymousLabel; - - @FXML private TextField NameField; - @FXML private TextField EmailField; - @FXML private PasswordField PassWordField; - @FXML private TextField ConfirmPasswordField; - @FXML private Button ConfirmChangeSettings; - @FXML private Button ConfirmChangeSettings1; - - // Sidebar FXML variables - @FXML private Label nameLabel; - @FXML private Label shortNameLabel; - @FXML private Label shortNameLabel2; - @FXML private Button logoutButton; - - - - @Override - protected void authTokenisSet() { - if (!isLoggedin()){ - showAlert(Alert.AlertType.ERROR, "Not logged inn", "You need to be logged inn to donate."); - Platform.runLater(() -> { - Stage stage = (Stage) Stage.getWindows().stream() - .filter(w -> w.isShowing()) - .findFirst() - .orElse(null); - if (stage != null) { - LoaderScene.LoadScene("loginSite", stage, null, null, authToken); - } - }); - } - navbarController.setAuthToken(authToken); - populateFields(); + @FXML private NavbarController navbarController; + @FXML private ComboBox languageComboBox; + @FXML private ComboBox themeComboBox; + @FXML private ToggleButton anonymousToggle; + @FXML private Label anonymousLabel; + + @FXML private TextField NameField; + @FXML private TextField EmailField; + @FXML private PasswordField PassWordField; + @FXML private TextField ConfirmPasswordField; + @FXML private Button ConfirmChangeSettings; + @FXML private Button ConfirmChangeSettings1; + + // Sidebar FXML variables + @FXML private Label nameLabel; + @FXML private Label shortNameLabel; + @FXML private Label shortNameLabel2; + @FXML private Button logoutButton; + + @Override + protected void authTokenisSet() { + if (!isLoggedin()) { + showAlert(Alert.AlertType.ERROR, "Not logged inn", "You need to be logged inn to donate."); + Platform.runLater( + () -> { + Stage stage = + (Stage) + Stage.getWindows().stream().filter(w -> w.isShowing()).findFirst().orElse(null); + if (stage != null) { + LoaderScene.LoadScene("loginSite", stage, null, null, authToken); + } + }); } - public void populateFields(){ - languageComboBox.getItems().addAll("English", "Norwegian"); - themeComboBox.getItems().addAll("Light mode", "Dark mode"); - - User user = authToken.getCurrentUser(); - Settings settings = user.getSettings(); - // Names - nameLabel.setText(user.getUsername()); - shortNameLabel.setText(user.getUsername().substring(0,2).toUpperCase().trim()); - shortNameLabel2.setText(user.getUsername().substring(0,2).toUpperCase().trim()); - - NameField.setText(user.getUsername()); - EmailField.setText(user.getEmail()); - - // SettingsPage Spesefic: - languageComboBox.setValue(settings.getLanguage() == Language.NORWEGIAN ? "Norwegian" : "English"); - themeComboBox.setValue(settings.isLightMode() ? "Light mode" : "Dark mode"); - anonymousToggle.setSelected(settings.isAnonymous()); - - boolean on = settings.isAnonymous(); - anonymousLabel.setText(on ? "On" : "Off"); - anonymousToggle.setStyle( - "-fx-background-color: " + (on ? "#2f8f8b" : "#ccc") + ";" + - "-fx-background-radius: 14; -fx-min-width: 32; -fx-min-height: 28;" + - "-fx-max-width: 52; -fx-max-height: 28;" - ); + navbarController.setAuthToken(authToken); + populateFields(); + } + + public void populateFields() { + languageComboBox.getItems().addAll("English", "Norwegian"); + themeComboBox.getItems().addAll("Light mode", "Dark mode"); + + User user = authToken.getCurrentUser(); + Settings settings = user.getSettings(); + // Names + nameLabel.setText(user.getUsername()); + shortNameLabel.setText(user.getUsername().substring(0, 2).toUpperCase().trim()); + shortNameLabel2.setText(user.getUsername().substring(0, 2).toUpperCase().trim()); + + NameField.setText(user.getUsername()); + EmailField.setText(user.getEmail()); + + // SettingsPage Spesefic: + languageComboBox.setValue( + settings.getLanguage() == Language.NORWEGIAN ? "Norwegian" : "English"); + themeComboBox.setValue(settings.isLightMode() ? "Light mode" : "Dark mode"); + anonymousToggle.setSelected(settings.isAnonymous()); + + boolean on = settings.isAnonymous(); + anonymousLabel.setText(on ? "On" : "Off"); + anonymousToggle.setStyle( + "-fx-background-color: " + + (on ? "#2f8f8b" : "#ccc") + + ";" + + "-fx-background-radius: 14; -fx-min-width: 32; -fx-min-height: 28;" + + "-fx-max-width: 52; -fx-max-height: 28;"); + } + + @FXML + private void handleAnonymousToggle(ActionEvent event) { + boolean on = anonymousToggle.isSelected(); + anonymousLabel.setText(on ? "On" : "Off"); + anonymousToggle.setStyle( + "-fx-background-color: " + + (on ? "#2f8f8b" : "#ccc") + + ";" + + "-fx-background-radius: 14; -fx-min-width: 32; -fx-min-height: 28;" + + "-fx-max-width: 52; -fx-max-height: 28;"); + } + + @FXML + private void handleNewProfile(ActionEvent event) { + String nameText = NameField.getText(); + String emailText = EmailField.getText(); + String password = PassWordField.getText(); + String confirmPassword = ConfirmPasswordField.getText(); + + if (nameText.isBlank() + || emailText.isBlank() + || password.isBlank() + || confirmPassword.isBlank()) { + showAlert(Alert.AlertType.ERROR, "Empty input", "Please fill out all fields"); + return; } - @FXML - private void handleAnonymousToggle(ActionEvent event) { - boolean on = anonymousToggle.isSelected(); - anonymousLabel.setText(on ? "On" : "Off"); - anonymousToggle.setStyle( - "-fx-background-color: " + (on ? "#2f8f8b" : "#ccc") + ";" + - "-fx-background-radius: 14; -fx-min-width: 32; -fx-min-height: 28;" + - "-fx-max-width: 52; -fx-max-height: 28;" - ); + if (emailText == null + || emailText.isBlank() + || !emailText.contains("@") + || !emailText.contains(".")) { + showAlert(Alert.AlertType.ERROR, "Invalid Email", "Please enter a valid email"); + return; } - @FXML - private void handleNewProfile(ActionEvent event){ - String nameText = NameField.getText(); - String emailText = EmailField.getText(); - String password = PassWordField.getText(); - String confirmPassword = ConfirmPasswordField.getText(); - - if (nameText.isBlank() || emailText.isBlank() || password.isBlank() || confirmPassword.isBlank()) { - showAlert(Alert.AlertType.ERROR, "Empty input", "Please fill out all fields"); - return; - } - - if (emailText == null || emailText.isBlank() || !emailText.contains("@") || !emailText.contains(".")) { - showAlert(Alert.AlertType.ERROR, "Invalid Email", "Please enter a valid email"); - return; - } - - if (!password.equals(confirmPassword)) { - showAlert(Alert.AlertType.ERROR, "Mismatch of password", "Password do not match"); - return; - } - String hashPassword = new PasswordHasher().getHashPassword(password); - User newUserOnlyCredentials= new User(authToken.getCurrentUser().getId().toString(),nameText, emailText, hashPassword,"NORMAL_USER"); - - boolean updateSuccess; - DatabaseConnection conn = new DatabaseConnection(); - UserDAO userDataObject = new UserDAO(conn); - try { - if (!emailText.equals(authToken.getCurrentUser().getEmail())) { - boolean isEmailTaken = userDataObject.isEmailTaken(emailText); - if (!isEmailTaken) { - updateSuccess = userDataObject.updateUserDetails(newUserOnlyCredentials); - } else { - throw new IllegalArgumentException("Email Alreay taken"); - } - } else { - updateSuccess = userDataObject.updateUserDetails(newUserOnlyCredentials); - } - } catch (IllegalArgumentException e) { - showAlert(Alert.AlertType.ERROR, "Email already taken", "Email already taken by another user."); - return; - } catch (Exception e) { - e.printStackTrace(); - showAlert(Alert.AlertType.ERROR, "Unexpected Error", "Unexpected error ocurred"); - return; - } - if (updateSuccess) { - showAlert( - Alert.AlertType.INFORMATION, - "Settings updated", - "You have successfully changed your settings"); - authToken.getCurrentUser().setUsername(nameText); - authToken.getCurrentUser().setPassword(password); - authToken.getCurrentUser().setEmail(emailText); - LoaderScene.LoadScene("profile_user_settings", event, null, null, authToken); - } else { - System.out.println("Something went wrong when updating Settings"); - } - + if (!password.equals(confirmPassword)) { + showAlert(Alert.AlertType.ERROR, "Mismatch of password", "Password do not match"); + return; } - - @FXML - private void handleNewPreferences(ActionEvent event) { - String selectedLanguage = languageComboBox.getValue(); - String selectedTheme = themeComboBox.getValue(); - boolean isAnonymous = anonymousToggle.isSelected(); - - Settings updatedSettings = new Settings( - isAnonymous, - selectedLanguage.equals("Norwegian") ? Language.NORWEGIAN : Language.ENGLISH, - selectedTheme.equals("Light mode") - ); - - DatabaseConnection conn = new DatabaseConnection(); - UserDAO userDataObject = new UserDAO(conn); - boolean updateSettingsSuccess; - try { - updateSettingsSuccess = userDataObject.updateUserSettings(authToken.getCurrentUser(), updatedSettings); - } catch (Exception e) { - e.printStackTrace(); - showAlert(Alert.AlertType.ERROR, "Unexpected Error", "Unexpected error ocurred"); - return; - } - if (updateSettingsSuccess) { - showAlert( - Alert.AlertType.INFORMATION, - "Settings updated", - "You have successfully changed your settings"); - authToken.getCurrentUser().setSettings(updatedSettings); - LoaderScene.LoadScene("profile_user_settings", event, null, null, authToken); + String hashPassword = new PasswordHasher().getHashPassword(password); + User newUserOnlyCredentials = + new User( + authToken.getCurrentUser().getId().toString(), + nameText, + emailText, + hashPassword, + "NORMAL_USER"); + + boolean updateSuccess; + DatabaseConnection conn = new DatabaseConnection(); + UserDAO userDataObject = new UserDAO(conn); + try { + if (!emailText.equals(authToken.getCurrentUser().getEmail())) { + boolean isEmailTaken = userDataObject.isEmailTaken(emailText); + if (!isEmailTaken) { + updateSuccess = userDataObject.updateUserDetails(newUserOnlyCredentials); + } else { + throw new IllegalArgumentException("Email Alreay taken"); } + } else { + updateSuccess = userDataObject.updateUserDetails(newUserOnlyCredentials); + } + } catch (IllegalArgumentException e) { + showAlert( + Alert.AlertType.ERROR, "Email already taken", "Email already taken by another user."); + return; + } catch (Exception e) { + e.printStackTrace(); + showAlert(Alert.AlertType.ERROR, "Unexpected Error", "Unexpected error ocurred"); + return; } - - // Sidebar Methods - @FXML - private void handleLogout(ActionEvent event){ - authToken.logout(); - showAlert(Alert.AlertType.INFORMATION, "Logging out", "Logging out..."); - LoaderScene.LoadScene("FrontPage", event, null, null, authToken); - } - - @FXML - private void switchToFrontPage(ActionEvent event){ - LoaderScene.LoadScene("FrontPage", event, null, null, authToken); - } - - @FXML - private void switchToInboxPage(ActionEvent event){ - LoaderScene.LoadScene("profile_user_inbox", event, null, null, authToken); - + if (updateSuccess) { + showAlert( + Alert.AlertType.INFORMATION, + "Settings updated", + "You have successfully changed your settings"); + authToken.getCurrentUser().setUsername(nameText); + authToken.getCurrentUser().setPassword(password); + authToken.getCurrentUser().setEmail(emailText); + LoaderScene.LoadScene("profile_user_settings", event, null, null, authToken); + } else { + System.out.println("Something went wrong when updating Settings"); } - - @FXML - private void switchToHistoryPage(ActionEvent event){ - LoaderScene.LoadScene("profile_user_history", event, null, null, authToken); + } + + @FXML + private void handleNewPreferences(ActionEvent event) { + String selectedLanguage = languageComboBox.getValue(); + String selectedTheme = themeComboBox.getValue(); + boolean isAnonymous = anonymousToggle.isSelected(); + + Settings updatedSettings = + new Settings( + isAnonymous, + selectedLanguage.equals("Norwegian") ? Language.NORWEGIAN : Language.ENGLISH, + selectedTheme.equals("Light mode")); + + DatabaseConnection conn = new DatabaseConnection(); + UserDAO userDataObject = new UserDAO(conn); + boolean updateSettingsSuccess; + try { + updateSettingsSuccess = + userDataObject.updateUserSettings(authToken.getCurrentUser(), updatedSettings); + } catch (Exception e) { + e.printStackTrace(); + showAlert(Alert.AlertType.ERROR, "Unexpected Error", "Unexpected error ocurred"); + return; } - - @FXML - private void switchToInterestPage(ActionEvent event){ - LoaderScene.LoadScene("profile_user_interests", event, null, null, authToken); + if (updateSettingsSuccess) { + showAlert( + Alert.AlertType.INFORMATION, + "Settings updated", + "You have successfully changed your settings"); + authToken.getCurrentUser().setSettings(updatedSettings); + LoaderScene.LoadScene("profile_user_settings", event, null, null, authToken); } - + } + + // Sidebar Methods + @FXML + private void handleLogout(ActionEvent event) { + authToken.logout(); + showAlert(Alert.AlertType.INFORMATION, "Logging out", "Logging out..."); + LoaderScene.LoadScene("FrontPage", event, null, null, authToken); + } + + @FXML + private void switchToFrontPage(ActionEvent event) { + LoaderScene.LoadScene("FrontPage", event, null, null, authToken); + } + + @FXML + private void switchToInboxPage(ActionEvent event) { + LoaderScene.LoadScene("profile_user_inbox", event, null, null, authToken); + } + + @FXML + private void switchToHistoryPage(ActionEvent event) { + LoaderScene.LoadScene("profile_user_history", event, null, null, authToken); + } + + @FXML + private void switchToInterestPage(ActionEvent event) { + LoaderScene.LoadScene("profile_user_interests", event, null, null, authToken); + } } diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DAO/CategoryDAO.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DAO/CategoryDAO.java index 49a0ae70..bcc16bab 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DAO/CategoryDAO.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DAO/CategoryDAO.java @@ -16,21 +16,21 @@ public class CategoryDAO { private final DatabaseConnection connection; - /** - * Constructs a new {@code CategoryDAO} with the given database connection. - * - * @param connection the {@link DatabaseConnection} to use for executing queries; must not be - * {@code null} - */ + /** + * Constructs a new {@code CategoryDAO} with the given database connection. + * + * @param connection the {@link DatabaseConnection} to use for executing queries; must not be + * {@code null} + */ public CategoryDAO(DatabaseConnection connection) { this.connection = connection; } - /** - * Retrieves all the categories listed in the Category table of the database. - * - * @return a list of strings containing the name of the categories - */ + /** + * Retrieves all the categories listed in the Category table of the database. + * + * @return a list of strings containing the name of the categories + */ public List getCategoriesFromDB() { List categories = new ArrayList<>(); diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DAO/CharityDAO.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DAO/CharityDAO.java index 85e73dc9..85393a8a 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DAO/CharityDAO.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DAO/CharityDAO.java @@ -15,11 +15,11 @@ /** * Data access class responsible for acsessing charity-related data from the database. - *

- * Primarily provides read methods to retrieve all charities (with their associated feedback and users) as well - * as feedback entries for a specific charity by UUID. - *

- * All queries are executed against a MySQL database via a {@link DatabaseConnection}. + * + *

Primarily provides read methods to retrieve all charities (with their associated feedback and + * users) as well as feedback entries for a specific charity by UUID. + * + *

All queries are executed against a MySQL database via a {@link DatabaseConnection}. */ public class CharityDAO { private final DatabaseConnection connection; @@ -38,9 +38,10 @@ public CharityDAO(DatabaseConnection connection) { * Retrieves all charities from the database, including their associated feedback and the users * who submitted each piece of feedback. * - *

The query performs a LEFT JOIN between the {@code Charities}, {@code Feedback}, {@code - * User} and {@code category(s)} tables and a INNER JOIN with {@code CharityVanity} table. Each unique charity is added once - * to the registry; any feedback rows found for that charity are appended to its feedback list. + *

The query performs a LEFT JOIN between the {@code Charities}, {@code Feedback}, {@code User} + * and {@code category(s)} tables and a INNER JOIN with {@code CharityVanity} table. Each unique + * charity is added once to the registry; any feedback rows found for that charity are appended to + * its feedback list. * *

Note: charities with no feedback and categories are still included in the result due to the * LEFT JOIN. @@ -189,11 +190,11 @@ public ArrayList getFeedbackforCharityUUID(String charity_uuid) { rs.getString("user_email"), rs.getString("user_password"), rs.getString("role")); - userWithSettingsAndNoInbox.setSettings(new Settings( + userWithSettingsAndNoInbox.setSettings( + new Settings( rs.getBoolean("isAnonymous"), Language.valueOf(rs.getString("language")), - rs.getBoolean("lightmode") - )); + rs.getBoolean("lightmode"))); Feedback feedback = new Feedback( rs.getString("UUID_feedback"), diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DAO/CharityUserDAO.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DAO/CharityUserDAO.java index ee324f77..8b7fe701 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DAO/CharityUserDAO.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DAO/CharityUserDAO.java @@ -1,165 +1,161 @@ package ntnu.systemutvikling.team6.database.DAO; -import ntnu.systemutvikling.team6.database.DatabaseConnection; -import ntnu.systemutvikling.team6.models.Charity; -import ntnu.systemutvikling.team6.models.user.Settings; -import ntnu.systemutvikling.team6.models.user.User; - import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; +import ntnu.systemutvikling.team6.database.DatabaseConnection; +import ntnu.systemutvikling.team6.models.Charity; /** - * This Data Access Object is responsible for communication to the Database for a potensial user that is also a CharityUser. + * This Data Access Object is responsible for communication to the Database for a potensial user + * that is also a CharityUser. * - *

- * CharityUsers have additional features and priviliges that regular users don't have. Methods - * specified provide the opportunity to save a new name or description. - *

- *

- * All queries are executed against a MySQL database via a {@link DatabaseConnection}. - *

+ *

CharityUsers have additional features and priviliges that regular users don't have. Methods + * specified provide the opportunity to save a new name or description. * + *

All queries are executed against a MySQL database via a {@link DatabaseConnection}. */ public class CharityUserDAO { - private DatabaseConnection connection; - - /** - * Constructs a new {@code CharityUserDAO} with the given database connection. - * - * @param connection the {@link DatabaseConnection} to use for executing queries; must not be - * {@code null} - */ - public CharityUserDAO(DatabaseConnection connection) { - this.connection = connection; - } - - /** - * Updates the Charity's name in the {@code CharityVanity} table in the database by getting the Charity object in question. - * - * @param charity Charity containing the new name for the database - * @return True or False based on if the update succeed or not - */ - public boolean updateCharityVanityName(Charity charity){ - Connection conn = null; - String sql = """ - UPDATE CharityVanity SET + private DatabaseConnection connection; + + /** + * Constructs a new {@code CharityUserDAO} with the given database connection. + * + * @param connection the {@link DatabaseConnection} to use for executing queries; must not be + * {@code null} + */ + public CharityUserDAO(DatabaseConnection connection) { + this.connection = connection; + } + + /** + * Updates the Charity's name in the {@code CharityVanity} table in the database by getting the + * Charity object in question. + * + * @param charity Charity containing the new name for the database + * @return True or False based on if the update succeed or not + */ + public boolean updateCharityVanityName(Charity charity) { + Connection conn = null; + String sql = + """ + UPDATE CharityVanity SET charity_name = ? WHERE UUID_charity = ?; """; - try { - conn = connection.getMySqlConnection(); - PreparedStatement ps = conn.prepareStatement(sql); + try { + conn = connection.getMySqlConnection(); + PreparedStatement ps = conn.prepareStatement(sql); - System.out.println(charity.getUUID().toString()); - ps.setString(1, charity.getName()); - ps.setString(2, charity.getUUID().toString()); + System.out.println(charity.getUUID().toString()); + ps.setString(1, charity.getName()); + ps.setString(2, charity.getUUID().toString()); - return ps.executeUpdate() > 0; - - } catch (SQLException e) { - e.printStackTrace(); - System.out.println("Something went wrong when updating ah"); - return false; - } + return ps.executeUpdate() > 0; + } catch (SQLException e) { + e.printStackTrace(); + System.out.println("Something went wrong when updating ah"); + return false; } - - /** - * Updates the Charity's description in the {@code CharityVanity} table in the database by getting the Charity object in question. - * - * @param charity Charity containing the new name for the database - * @return True or False based on if the update succeed or not - */ - public boolean updateCharityVanityDescription(Charity charity){ - Connection conn = null; - String sql = """ - UPDATE CharityVanity SET + } + + /** + * Updates the Charity's description in the {@code CharityVanity} table in the database by getting + * the Charity object in question. + * + * @param charity Charity containing the new name for the database + * @return True or False based on if the update succeed or not + */ + public boolean updateCharityVanityDescription(Charity charity) { + Connection conn = null; + String sql = + """ + UPDATE CharityVanity SET description = ? WHERE UUID_charity = ?; """; - try { - conn = connection.getMySqlConnection(); - PreparedStatement ps = conn.prepareStatement(sql); - - System.out.println(charity.getUUID().toString()); - ps.setString(1, charity.getDescription()); - ps.setString(2, charity.getUUID().toString()); + try { + conn = connection.getMySqlConnection(); + PreparedStatement ps = conn.prepareStatement(sql); - return ps.executeUpdate() > 0; + System.out.println(charity.getUUID().toString()); + ps.setString(1, charity.getDescription()); + ps.setString(2, charity.getUUID().toString()); - } catch (SQLException e) { - e.printStackTrace(); - System.out.println("Something went wrong when updating ah"); - return false; - } + return ps.executeUpdate() > 0; + } catch (SQLException e) { + e.printStackTrace(); + System.out.println("Something went wrong when updating ah"); + return false; } - - /** - * Gets the Charity that the User is connected to by using {@code CharityUsers} as an identifie/bridge. - * - * @param uuid Id of the User. - * @return The Charity the CharityUser is connected to. - */ - public Charity getUserCharityUser(String uuid){ - if (uuid == null || uuid.isBlank()) { - throw new IllegalArgumentException( - "UUID cannot be null or blank"); - } - Charity currentCharity = null; - Connection conn = null; - try { - conn = connection.getMySqlConnection(); - String sql_query = - """ + } + + /** + * Gets the Charity that the User is connected to by using {@code CharityUsers} as an + * identifie/bridge. + * + * @param uuid Id of the User. + * @return The Charity the CharityUser is connected to. + */ + public Charity getUserCharityUser(String uuid) { + if (uuid == null || uuid.isBlank()) { + throw new IllegalArgumentException("UUID cannot be null or blank"); + } + Charity currentCharity = null; + Connection conn = null; + try { + conn = connection.getMySqlConnection(); + String sql_query = + """ SELECT c.UUID_charities, c.org_number, c.pre_approved, c.status, cv.charity_name, cv.charity_link, cv.description, cv.logoURL, cv.key_values, cv.logoBLOB, cat.category - FROM CharityUsers cu + FROM CharityUsers cu INNER JOIN Charities c ON c.UUID_charities = cu.TheCharity INNER JOIN CharityVanity cv ON cv.UUID_charity = c.UUID_charities LEFT JOIN Charity_Categories cc ON cc.Charities_UUID_charities = c.UUID_charities LEFT JOIN Categories cat ON cat.category_id = cc.Categories_category_id WHERE CharityUserId = ? """; - PreparedStatement stmt = conn.prepareStatement(sql_query); - stmt.setString(1, uuid); - ResultSet rs = stmt.executeQuery(); - - String lastCharity = null; - - while (rs.next()) { - String currentId = rs.getString("UUID_charities"); - if (lastCharity == null || !currentId.equals(lastCharity)) { - currentCharity = - new Charity( - rs.getString("UUID_charities"), - rs.getString("org_number"), - rs.getString("charity_name"), - rs.getString("charity_link"), - rs.getString("status"), - rs.getBoolean("pre_approved"), - rs.getString("description"), - rs.getString("logoURL"), - rs.getString("key_values"), - rs.getBytes("logoBLOB")); - lastCharity = currentId; - } - - String categoryName = rs.getString("category"); - if (categoryName != null && !currentCharity.getCategory().contains(categoryName)) { - currentCharity.getCategory().add(categoryName); - } - } - - } catch (SQLException e) { - e.printStackTrace(); - throw new RuntimeException("ERROR: Something went wrong during updating charities table."); + PreparedStatement stmt = conn.prepareStatement(sql_query); + stmt.setString(1, uuid); + ResultSet rs = stmt.executeQuery(); + + String lastCharity = null; + + while (rs.next()) { + String currentId = rs.getString("UUID_charities"); + if (lastCharity == null || !currentId.equals(lastCharity)) { + currentCharity = + new Charity( + rs.getString("UUID_charities"), + rs.getString("org_number"), + rs.getString("charity_name"), + rs.getString("charity_link"), + rs.getString("status"), + rs.getBoolean("pre_approved"), + rs.getString("description"), + rs.getString("logoURL"), + rs.getString("key_values"), + rs.getBytes("logoBLOB")); + lastCharity = currentId; + } + + String categoryName = rs.getString("category"); + if (categoryName != null && !currentCharity.getCategory().contains(categoryName)) { + currentCharity.getCategory().add(categoryName); } - return currentCharity; + } + + } catch (SQLException e) { + e.printStackTrace(); + throw new RuntimeException("ERROR: Something went wrong during updating charities table."); } + return currentCharity; + } } diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DAO/DonationDAO.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DAO/DonationDAO.java index 8fd3b1a2..1e6c1cc3 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DAO/DonationDAO.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DAO/DonationDAO.java @@ -1,7 +1,6 @@ package ntnu.systemutvikling.team6.database.DAO; import java.sql.*; -import java.util.UUID; import ntnu.systemutvikling.team6.database.DatabaseConnection; import ntnu.systemutvikling.team6.models.Charity; import ntnu.systemutvikling.team6.models.Donation; @@ -9,8 +8,9 @@ import ntnu.systemutvikling.team6.models.user.User; /** - * This class is responsible for sending and receiving concurrent information about the donation to and from the Donation - * Database. Usually called from the Donation related controller, where the user is able to view their donations. + * This class is responsible for sending and receiving concurrent information about the donation to + * and from the Donation Database. Usually called from the Donation related controller, where the + * user is able to view their donations. */ public class DonationDAO { private final DatabaseConnection connection; @@ -28,9 +28,9 @@ public DonationDAO(DatabaseConnection connection) { /** * Retrieves all donations from the database, each populated with its associated {@link Charity}. * - *

The query performs an INNER JOIN between the {@code Donations}, {@code Charities} and {@code User} tables - * on the donations row Charity_id and user_id. Donations without a matching charity are excluded from the - * result. + *

The query performs an INNER JOIN between the {@code Donations}, {@code Charities} and {@code + * User} tables on the donations row Charity_id and user_id. Donations without a matching charity + * are excluded from the result. * * @return a {@link DonationRegistry} containing all matched donations; never {@code null}, but * may be empty if no rows are returned @@ -42,7 +42,7 @@ public DonationRegistry getDonationFromDB() { try { conn = connection.getMySqlConnection(); String sql_query = - """ + """ SELECT d.UUID_Donations, d.amount, d.isAnonymous, d.date, d.charity_id, d.user_id, c.UUID_charities, c.org_number, c.pre_approved, c.status, @@ -57,27 +57,27 @@ public DonationRegistry getDonationFromDB() { registry = new DonationRegistry(); while (rs.next()) { Charity charity = - new Charity( - rs.getString("UUID_charities"), - rs.getString("org_number"), - rs.getBoolean("pre_approved"), - rs.getString("status")); + new Charity( + rs.getString("UUID_charities"), + rs.getString("org_number"), + rs.getBoolean("pre_approved"), + rs.getString("status")); User user = - new User( - rs.getString("UUID_User"), - rs.getString("user_name"), - rs.getString("user_email"), - rs.getString("user_password"), - rs.getString("role")); + new User( + rs.getString("UUID_User"), + rs.getString("user_name"), + rs.getString("user_email"), + rs.getString("user_password"), + rs.getString("role")); Donation donation = - new Donation( - rs.getString("UUID_Donations"), - rs.getDouble("amount"), - rs.getDate("date").toLocalDate(), - charity, - user, - rs.getBoolean("isAnonymous")); + new Donation( + rs.getString("UUID_Donations"), + rs.getDouble("amount"), + rs.getDate("date").toLocalDate(), + charity, + user, + rs.getBoolean("isAnonymous")); registry.addDonation(donation); } } catch (SQLException e) { @@ -90,11 +90,9 @@ public DonationRegistry getDonationFromDB() { /** * Retrieves all donation data from the {@code Donations} table for a spesific user using its ID. * - *

- * Query selects from {@code Donations}, then INNER JOINS with {@code Charities} and {@code CharityVanity} - * to get names among other thing, and {@code User} table to get the donor. At the end uses a WHERE-clause to - * get the specified User. - *

+ *

Query selects from {@code Donations}, then INNER JOINS with {@code Charities} and {@code + * CharityVanity} to get names among other thing, and {@code User} table to get the donor. At the + * end uses a WHERE-clause to get the specified User. * * @param uuid the java.UUID for the user but in string. * @return Returns a DOnationRegistry with all donations. @@ -105,7 +103,7 @@ public DonationRegistry getDonationForUser(String uuid) { try { conn = connection.getMySqlConnection(); String sql_query = - """ + """ SELECT d.UUID_Donations, d.amount, d.isAnonymous, d.date, d.charity_id, d.user_id, c.UUID_charities, c.org_number, c.pre_approved, c.status, @@ -113,7 +111,7 @@ public DonationRegistry getDonationForUser(String uuid) { u.UUID_User, u.user_name, u.user_email, u.user_password, u.role FROM Donations d INNER JOIN Charities c ON d.charity_id = c.UUID_charities - INNER JOIN CharityVanity cv ON cv.UUID_charity = c.UUID_charities + INNER JOIN CharityVanity cv ON cv.UUID_charity = c.UUID_charities INNER JOIN User u ON d.user_id = u.UUID_user WHERE d.user_id = ? """; @@ -124,32 +122,32 @@ public DonationRegistry getDonationForUser(String uuid) { registry = new DonationRegistry(); while (rs.next()) { Charity charity = - new Charity( - rs.getString("UUID_charities"), - rs.getString("org_number"), - rs.getString("charity_name"), - rs.getString("charity_link"), - rs.getString("status"), - rs.getBoolean("pre_approved"), - rs.getString("description"), - rs.getString("logoURL"), - rs.getString("key_values"), - rs.getBytes("logoBLOB")); + new Charity( + rs.getString("UUID_charities"), + rs.getString("org_number"), + rs.getString("charity_name"), + rs.getString("charity_link"), + rs.getString("status"), + rs.getBoolean("pre_approved"), + rs.getString("description"), + rs.getString("logoURL"), + rs.getString("key_values"), + rs.getBytes("logoBLOB")); User user = - new User( - rs.getString("UUID_User"), - rs.getString("user_name"), - rs.getString("user_email"), - rs.getString("user_password"), - rs.getString("role")); + new User( + rs.getString("UUID_User"), + rs.getString("user_name"), + rs.getString("user_email"), + rs.getString("user_password"), + rs.getString("role")); Donation donation = - new Donation( - rs.getString("UUID_Donations"), - rs.getDouble("amount"), - rs.getDate("date").toLocalDate(), - charity, - user, - rs.getBoolean("isAnonymous")); + new Donation( + rs.getString("UUID_Donations"), + rs.getDouble("amount"), + rs.getDate("date").toLocalDate(), + charity, + user, + rs.getBoolean("isAnonymous")); registry.addDonation(donation); } } catch (SQLException e) { @@ -160,14 +158,13 @@ public DonationRegistry getDonationForUser(String uuid) { } /** - * Retrieves all donation data from the {@code Donations} table for a specific Charity using its ID. + * Retrieves all donation data from the {@code Donations} table for a specific Charity using its + * ID. * - *

- * Mostly used by Charity Users to view how much money they have. - * Query selects from {@code Donations}, then INNER JOINS with {@code Charities} and {@code CharityVanity} - * to get names among other thing, and {@code User} table to get the donor. At the end uses a WHERE - clause - * to get the Charity in question. - *

+ *

Mostly used by Charity Users to view how much money they have. Query selects from {@code + * Donations}, then INNER JOINS with {@code Charities} and {@code CharityVanity} to get names + * among other thing, and {@code User} table to get the donor. At the end uses a WHERE - clause to + * get the Charity in question. * * @param uuid the java.UUID for the user but in string. * @return Returns a DOnationRegistry with all donations. @@ -178,7 +175,7 @@ public DonationRegistry getDonationForCharity(String uuid) { try { conn = connection.getMySqlConnection(); String sql_query = - """ + """ SELECT d.UUID_Donations, d.amount, d.isAnonymous, d.date, d.charity_id, d.user_id, c.UUID_charities, c.org_number, c.pre_approved, c.status, @@ -186,7 +183,7 @@ public DonationRegistry getDonationForCharity(String uuid) { u.UUID_User, u.user_name, u.user_email, u.user_password, u.role FROM Donations d INNER JOIN Charities c ON d.charity_id = c.UUID_charities - INNER JOIN CharityVanity cv ON cv.UUID_charity = c.UUID_charities + INNER JOIN CharityVanity cv ON cv.UUID_charity = c.UUID_charities INNER JOIN User u ON d.user_id = u.UUID_user WHERE c.UUID_charities = ? """; @@ -197,32 +194,32 @@ public DonationRegistry getDonationForCharity(String uuid) { registry = new DonationRegistry(); while (rs.next()) { Charity charity = - new Charity( - rs.getString("UUID_charities"), - rs.getString("org_number"), - rs.getString("charity_name"), - rs.getString("charity_link"), - rs.getString("status"), - rs.getBoolean("pre_approved"), - rs.getString("description"), - rs.getString("logoURL"), - rs.getString("key_values"), - rs.getBytes("logoBLOB")); + new Charity( + rs.getString("UUID_charities"), + rs.getString("org_number"), + rs.getString("charity_name"), + rs.getString("charity_link"), + rs.getString("status"), + rs.getBoolean("pre_approved"), + rs.getString("description"), + rs.getString("logoURL"), + rs.getString("key_values"), + rs.getBytes("logoBLOB")); User user = - new User( - rs.getString("UUID_User"), - rs.getString("user_name"), - rs.getString("user_email"), - rs.getString("user_password"), - rs.getString("role")); + new User( + rs.getString("UUID_User"), + rs.getString("user_name"), + rs.getString("user_email"), + rs.getString("user_password"), + rs.getString("role")); Donation donation = - new Donation( - rs.getString("UUID_Donations"), - rs.getDouble("amount"), - rs.getDate("date").toLocalDate(), - charity, - user, - rs.getBoolean("isAnonymous")); + new Donation( + rs.getString("UUID_Donations"), + rs.getDouble("amount"), + rs.getDate("date").toLocalDate(), + charity, + user, + rs.getBoolean("isAnonymous")); registry.addDonation(donation); } } catch (SQLException e) { diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DAO/FavouritesDAO.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DAO/FavouritesDAO.java index 2c15d9dc..f9450288 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DAO/FavouritesDAO.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DAO/FavouritesDAO.java @@ -1,193 +1,184 @@ package ntnu.systemutvikling.team6.database.DAO; -import ntnu.systemutvikling.team6.database.DatabaseConnection; -import ntnu.systemutvikling.team6.models.Charity; -import ntnu.systemutvikling.team6.models.Feedback; -import ntnu.systemutvikling.team6.models.registry.CharityRegistry; -import ntnu.systemutvikling.team6.models.user.Language; -import ntnu.systemutvikling.team6.models.user.Settings; -import ntnu.systemutvikling.team6.models.user.User; - import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; -import java.time.LocalDate; -import java.util.ArrayList; import java.util.List; +import ntnu.systemutvikling.team6.database.DatabaseConnection; +import ntnu.systemutvikling.team6.models.Charity; +import ntnu.systemutvikling.team6.models.registry.CharityRegistry; +import ntnu.systemutvikling.team6.models.user.User; /** - * Data access class responsible for getting managing favourites for a logged inn user in the application. - *

- * Methods include gettng users favourites, adding a favourite and checking if the charity was favourited. - *

+ * Data access class responsible for getting managing favourites for a logged inn user in the + * application. + * + *

Methods include gettng users favourites, adding a favourite and checking if the charity was + * favourited. * *

All queries are executed against a MySQL database via a {@link DatabaseConnection}. */ public class FavouritesDAO { - private final DatabaseConnection connection; - - /** - * Constructs a new {@code FavouritesDAO} with the given database connection. - * - * @param connection the {@link DatabaseConnection} to use for executing queries; must not be - * {@code null} - */ - public FavouritesDAO(DatabaseConnection connection) { - this.connection = connection; + private final DatabaseConnection connection; + + /** + * Constructs a new {@code FavouritesDAO} with the given database connection. + * + * @param connection the {@link DatabaseConnection} to use for executing queries; must not be + * {@code null} + */ + public FavouritesDAO(DatabaseConnection connection) { + this.connection = connection; + } + + /** + * Checks if both {@code User} and {@code Charity} are in the same row in the {@code + * User_has_favourites } table. If it is, the charity is considered a favourite by the User + * + *

Uses a Select query with a WHERE-clause that searches for a row with both ids, which + * considered a favourite. + * + * @param user User in question + * @param charity Charity in question of being favourite by User. + * @return + */ + public boolean isFavourite(User user, Charity charity) { + String sql = "SELECT * FROM User_has_favourites WHERE Favourer = ? AND Favourite_Charity = ?"; + + try (Connection conn = connection.getMySqlConnection(); + PreparedStatement ps = conn.prepareStatement(sql)) { + + ps.setString(1, user.getId().toString()); + ps.setString(2, charity.getUUID().toString()); + + ResultSet rs = ps.executeQuery(); + return rs.next(); + + } catch (SQLException e) { + e.printStackTrace(); + return false; } - - /** - * Checks if both {@code User} and {@code Charity} are in the same row in the {@code User_has_favourites } table. - * If it is, the charity is considered a favourite by the User - * - *

- * Uses a Select query with a WHERE-clause that searches for a row with both ids, which considered a favourite. - *

- * @param user User in question - * @param charity Charity in question of being favourite by User. - * @return - */ - public boolean isFavourite(User user, Charity charity) { - String sql = "SELECT * FROM User_has_favourites WHERE Favourer = ? AND Favourite_Charity = ?"; - - try (Connection conn = connection.getMySqlConnection(); - PreparedStatement ps = conn.prepareStatement(sql)) { - - ps.setString(1, user.getId().toString()); - ps.setString(2, charity.getUUID().toString()); - - ResultSet rs = ps.executeQuery(); - return rs.next(); - - } catch (SQLException e) { - e.printStackTrace(); - return false; - } - } - - /** - * Send a quick insert query to the {@code User_has_favourites} table, adding a row with favourer and the - * favourite Charity - * - * @param user User or the Favourer in the database - * @param charity Favourite charity in question. - * @return True or False based on if it succeeded or not - */ - public boolean addFavourite(User user, Charity charity) { - String sql = "INSERT INTO User_has_favourites (Favourer, Favourite_charity) VALUES (?, ?)"; - - try (Connection conn = connection.getMySqlConnection(); - PreparedStatement ps = conn.prepareStatement(sql)) { - - ps.setString(1, user.getId().toString()); - ps.setString(2, charity.getUUID().toString()); - return ps.executeUpdate() > 0; - - } catch (SQLException e) { - e.printStackTrace(); - return false; - } + } + + /** + * Send a quick insert query to the {@code User_has_favourites} table, adding a row with favourer + * and the favourite Charity + * + * @param user User or the Favourer in the database + * @param charity Favourite charity in question. + * @return True or False based on if it succeeded or not + */ + public boolean addFavourite(User user, Charity charity) { + String sql = "INSERT INTO User_has_favourites (Favourer, Favourite_charity) VALUES (?, ?)"; + + try (Connection conn = connection.getMySqlConnection(); + PreparedStatement ps = conn.prepareStatement(sql)) { + + ps.setString(1, user.getId().toString()); + ps.setString(2, charity.getUUID().toString()); + return ps.executeUpdate() > 0; + + } catch (SQLException e) { + e.printStackTrace(); + return false; } - - /** - * Does a quick remove query to delete a previous favourite charity. - * - *

- * This will not invoke and Argument-Exception because the remove query is avabile only after being added - * throught {@code addFavourite} - *

- * @param user user in question of having a favourite - * @param charity Charity about to be removed a favourite - * @return - */ - - public boolean removeFavourite(User user, Charity charity) { - String sql = "DELETE FROM User_has_favourites WHERE Favourer = ? AND Favourite_charity = ?"; - - try (Connection conn = connection.getMySqlConnection(); - PreparedStatement ps = conn.prepareStatement(sql)) { - - ps.setString(1, user.getId().toString()); - ps.setString(2, charity.getUUID().toString()); - return ps.executeUpdate() > 0; - - } catch (SQLException e) { - e.printStackTrace(); - return false; - } + } + + /** + * Does a quick remove query to delete a previous favourite charity. + * + *

This will not invoke and Argument-Exception because the remove query is avabile only after + * being added throught {@code addFavourite} + * + * @param user user in question of having a favourite + * @param charity Charity about to be removed a favourite + * @return + */ + public boolean removeFavourite(User user, Charity charity) { + String sql = "DELETE FROM User_has_favourites WHERE Favourer = ? AND Favourite_charity = ?"; + + try (Connection conn = connection.getMySqlConnection(); + PreparedStatement ps = conn.prepareStatement(sql)) { + + ps.setString(1, user.getId().toString()); + ps.setString(2, charity.getUUID().toString()); + return ps.executeUpdate() > 0; + + } catch (SQLException e) { + e.printStackTrace(); + return false; } - - /** - * Get all detailts about the users favourites. - * - *

- * Uses a Select-query, INNER JOIN between {@code Charities} and {@code CharityVanity} tables, and LEFT JOIN - * {@code Charity_Categories} and {@code Categries} tables to get fill all attributes in the {@code Charity} - * object. At the end, uses a WHERE-clause to grab the right favourer. - *

- * @param user_id UUID in String for the Favourer - * @return An empty or non-empty List of Charities that have been favourited by User - */ - public List getFavouritesForUser(String user_id) { - CharityRegistry registry = null; - Connection conn = null; - try { - conn = connection.getMySqlConnection(); - String sql_query = - """ - SELECT + } + + /** + * Get all detailts about the users favourites. + * + *

Uses a Select-query, INNER JOIN between {@code Charities} and {@code CharityVanity} tables, + * and LEFT JOIN {@code Charity_Categories} and {@code Categries} tables to get fill all + * attributes in the {@code Charity} object. At the end, uses a WHERE-clause to grab the right + * favourer. + * + * @param user_id UUID in String for the Favourer + * @return An empty or non-empty List of Charities that have been favourited by User + */ + public List getFavouritesForUser(String user_id) { + CharityRegistry registry = null; + Connection conn = null; + try { + conn = connection.getMySqlConnection(); + String sql_query = + """ + SELECT uf.Favourite_Charity, c.UUID_charities, c.org_number, c.pre_approved, c.status, cv.charity_name, cv.charity_link, cv.description, cv.logoURL, cv.key_values, cv.logoBLOB, cat.category FROM User_has_favourites uf - INNER JOIN Charities c ON uf.Favourite_Charity = c.UUID_charities + INNER JOIN Charities c ON uf.Favourite_Charity = c.UUID_charities INNER JOIN CharityVanity cv ON uf.Favourite_Charity = cv.UUID_charity LEFT JOIN Charity_Categories cc ON cc.Charities_UUID_charities = c.UUID_charities LEFT JOIN Categories cat ON cat.category_id = cc.Categories_category_id WHERE Favourer = ?; """; - PreparedStatement stmt = conn.prepareStatement(sql_query); - stmt.setString(1, user_id); - ResultSet rs = stmt.executeQuery(); - - - Charity currentCharity = null; - - registry = new CharityRegistry(); - while (rs.next()) { - String currentId = rs.getString("UUID_charities"); - if (currentCharity == null || !currentId.equals(currentCharity.getUUID().toString())) { - System.out.println("Adding Charities"); - currentCharity = - new Charity( - rs.getString("UUID_charities"), - rs.getString("org_number"), - rs.getString("charity_name"), - rs.getString("charity_link"), - rs.getString("status"), - rs.getBoolean("pre_approved"), - rs.getString("description"), - rs.getString("logoURL"), - rs.getString("key_values"), - rs.getBytes("logoBLOB")); - registry.addCharity(currentCharity); - } - - String categoryName = rs.getString("category"); - if (categoryName != null & !currentCharity.getCategory().contains(categoryName)) { - currentCharity.getCategory().add(categoryName); - } - - } - } catch (SQLException e) { - e.printStackTrace(); - throw new RuntimeException("ERROR: Something went wrong during updating."); - } finally { - conn = null; + PreparedStatement stmt = conn.prepareStatement(sql_query); + stmt.setString(1, user_id); + ResultSet rs = stmt.executeQuery(); + + Charity currentCharity = null; + + registry = new CharityRegistry(); + while (rs.next()) { + String currentId = rs.getString("UUID_charities"); + if (currentCharity == null || !currentId.equals(currentCharity.getUUID().toString())) { + System.out.println("Adding Charities"); + currentCharity = + new Charity( + rs.getString("UUID_charities"), + rs.getString("org_number"), + rs.getString("charity_name"), + rs.getString("charity_link"), + rs.getString("status"), + rs.getBoolean("pre_approved"), + rs.getString("description"), + rs.getString("logoURL"), + rs.getString("key_values"), + rs.getBytes("logoBLOB")); + registry.addCharity(currentCharity); + } + + String categoryName = rs.getString("category"); + if (categoryName != null & !currentCharity.getCategory().contains(categoryName)) { + currentCharity.getCategory().add(categoryName); } - return registry.getAllCharities(); + } + } catch (SQLException e) { + e.printStackTrace(); + throw new RuntimeException("ERROR: Something went wrong during updating."); + } finally { + conn = null; } -} \ No newline at end of file + return registry.getAllCharities(); + } +} diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DAO/FeedbackDAO.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DAO/FeedbackDAO.java index 4b7a5a32..e546e87b 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DAO/FeedbackDAO.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DAO/FeedbackDAO.java @@ -1,5 +1,8 @@ package ntnu.systemutvikling.team6.database.DAO; +import java.sql.*; +import java.time.LocalDate; +import java.util.ArrayList; import ntnu.systemutvikling.team6.database.DatabaseConnection; import ntnu.systemutvikling.team6.models.Charity; import ntnu.systemutvikling.team6.models.Feedback; @@ -7,82 +10,79 @@ import ntnu.systemutvikling.team6.models.user.Settings; import ntnu.systemutvikling.team6.models.user.User; -import java.sql.*; -import java.time.LocalDate; -import java.util.ArrayList; - /** - * This Data Access Object is mainly responsible for handling Feedbacks and communitcating with the DataBase. - * Primarily interacting with the {@code Feedback} table. + * This Data Access Object is mainly responsible for handling Feedbacks and communitcating with the + * DataBase. Primarily interacting with the {@code Feedback} table. */ public class FeedbackDAO { - private final DatabaseConnection connection; + private final DatabaseConnection connection; - /** - * Constructs a new {@code FeedbackDAO} with the given database connection. - * - * @param connection the {@link DatabaseConnection} to use for executing queries; must not be - * {@code null} - */ - public FeedbackDAO(DatabaseConnection connection){ - this.connection = connection; - } + /** + * Constructs a new {@code FeedbackDAO} with the given database connection. + * + * @param connection the {@link DatabaseConnection} to use for executing queries; must not be + * {@code null} + */ + public FeedbackDAO(DatabaseConnection connection) { + this.connection = connection; + } - /** - * Send a simple insert query to the {@code Feedback} table. Containing the comment, date, if its an Anonymous - * Feedback and recipients. - * - * @param feedback Feedback object contain all relevant info, as said above. - * @param toCharity Dedicated Charity object, the recipient. - * @return - */ - public boolean addFeedbackToCharity(Feedback feedback, Charity toCharity){ - String sql = """ - INSERT INTO Feedback + /** + * Send a simple insert query to the {@code Feedback} table. Containing the comment, date, if its + * an Anonymous Feedback and recipients. + * + * @param feedback Feedback object contain all relevant info, as said above. + * @param toCharity Dedicated Charity object, the recipient. + * @return + */ + public boolean addFeedbackToCharity(Feedback feedback, Charity toCharity) { + String sql = + """ + INSERT INTO Feedback (UUID_feedback, feedback_comment, feedback_date, isAnonymous, charity_id, user_id) VALUES (?, ?, ?, ?, ?, ?); - - """; - try (Connection conn = connection.getMySqlConnection(); - PreparedStatement ps = conn.prepareStatement(sql)) { + """; - ps.setString(1, feedback.getFeedbackId().toString()); - ps.setString(2, feedback.getComment()); - ps.setDate(3, Date.valueOf(feedback.getDate())); - ps.setBoolean(4, feedback.getUser().getSettings().isAnonymous()); - ps.setString(5, toCharity.getUUID().toString()); - ps.setString(6, feedback.getUser().getId().toString()); - return ps.executeUpdate() > 0; + try (Connection conn = connection.getMySqlConnection(); + PreparedStatement ps = conn.prepareStatement(sql)) { - } catch (SQLException e) { - e.printStackTrace(); - return false; - } + ps.setString(1, feedback.getFeedbackId().toString()); + ps.setString(2, feedback.getComment()); + ps.setDate(3, Date.valueOf(feedback.getDate())); + ps.setBoolean(4, feedback.getUser().getSettings().isAnonymous()); + ps.setString(5, toCharity.getUUID().toString()); + ps.setString(6, feedback.getUser().getId().toString()); + return ps.executeUpdate() > 0; + } catch (SQLException e) { + e.printStackTrace(); + return false; } - /** - * A helper function that retrieves all feedback entries associated with a specific charity, - * identified by its UUID. Currently, has no use. - * - *

Each {@link Feedback} object is populated with the associated {@link User} (without settings - * or inbox data). The query uses a LEFT JOIN between the {@code Feedback} and {@code User} - * tables, filtered by {@code charity_id}. - * - * @param charity_uuid the UUID of the charity whose feedback should be retrieved; must not be - * {@code null} - * @return an {@link ArrayList} of {@link Feedback} objects for the given charity; returns an - * empty list if no feedback exists for that charity - * @throws RuntimeException if any exception occurs while executing the query, wrapping the - * original cause - */ - public ArrayList getFeedbackforCharityUUID(String charity_uuid) { - ArrayList Feedbacks = new ArrayList<>(); - Connection conn = null; - try { - conn = connection.getMySqlConnection(); - String sql_query = - """ + } + + /** + * A helper function that retrieves all feedback entries associated with a specific charity, + * identified by its UUID. Currently, has no use. + * + *

Each {@link Feedback} object is populated with the associated {@link User} (without settings + * or inbox data). The query uses a LEFT JOIN between the {@code Feedback} and {@code User} + * tables, filtered by {@code charity_id}. + * + * @param charity_uuid the UUID of the charity whose feedback should be retrieved; must not be + * {@code null} + * @return an {@link ArrayList} of {@link Feedback} objects for the given charity; returns an + * empty list if no feedback exists for that charity + * @throws RuntimeException if any exception occurs while executing the query, wrapping the + * original cause + */ + public ArrayList getFeedbackforCharityUUID(String charity_uuid) { + ArrayList Feedbacks = new ArrayList<>(); + Connection conn = null; + try { + conn = connection.getMySqlConnection(); + String sql_query = + """ SELECT f.UUID_feedback, f.feedback_comment, f.feedback_date, f.isAnonymous, f.charity_id, f.user_id, u.UUID_user, u.user_name, u.user_email, u.user_password, u.role, @@ -92,37 +92,37 @@ public ArrayList getFeedbackforCharityUUID(String charity_uuid) { RIGHT JOIN Settings s ON u.UUID_user = s.UUID_user WHERE f.charity_id = ?; """; - PreparedStatement stmt = conn.prepareStatement(sql_query); - stmt.setString(1, charity_uuid); - ResultSet rs = stmt.executeQuery(); + PreparedStatement stmt = conn.prepareStatement(sql_query); + stmt.setString(1, charity_uuid); + ResultSet rs = stmt.executeQuery(); - while (rs.next()) { - User userWithSettingsAndNoInbox = - new User( - rs.getString("UUID_User"), - rs.getString("user_name"), - rs.getString("user_email"), - rs.getString("user_password"), - rs.getString("role")); - userWithSettingsAndNoInbox.setSettings(new Settings( - rs.getBoolean("isAnonymous"), - Language.valueOf(rs.getString("language")), - rs.getBoolean("lightmode") - )); - Feedback feedback = - new Feedback( - rs.getString("UUID_feedback"), - userWithSettingsAndNoInbox, - rs.getString("feedback_comment"), - LocalDate.parse(rs.getString("feedback_date"))); - Feedbacks.add(feedback); - } - } catch (Exception e) { - e.printStackTrace(); - throw new RuntimeException(e); - } finally { - conn = null; - } - return Feedbacks; + while (rs.next()) { + User userWithSettingsAndNoInbox = + new User( + rs.getString("UUID_User"), + rs.getString("user_name"), + rs.getString("user_email"), + rs.getString("user_password"), + rs.getString("role")); + userWithSettingsAndNoInbox.setSettings( + new Settings( + rs.getBoolean("isAnonymous"), + Language.valueOf(rs.getString("language")), + rs.getBoolean("lightmode"))); + Feedback feedback = + new Feedback( + rs.getString("UUID_feedback"), + userWithSettingsAndNoInbox, + rs.getString("feedback_comment"), + LocalDate.parse(rs.getString("feedback_date"))); + Feedbacks.add(feedback); + } + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException(e); + } finally { + conn = null; } + return Feedbacks; + } } diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DAO/MessageDAO.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DAO/MessageDAO.java index 0ad6b9ac..3d141d84 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DAO/MessageDAO.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DAO/MessageDAO.java @@ -1,8 +1,5 @@ package ntnu.systemutvikling.team6.database.DAO; -import ntnu.systemutvikling.team6.database.DatabaseConnection; -import ntnu.systemutvikling.team6.models.user.Message; - import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; @@ -11,101 +8,101 @@ import java.util.ArrayList; import java.util.List; import java.util.UUID; +import ntnu.systemutvikling.team6.database.DatabaseConnection; +import ntnu.systemutvikling.team6.models.user.Message; /** - * This Data Access Object is mainly responsible for handling Messages and Message object to communitcate correctly - * with the DataBase. - * Primarily interacting with the {@code Messages} table. + * This Data Access Object is mainly responsible for handling Messages and Message object to + * communitcate correctly with the DataBase. Primarily interacting with the {@code Messages} table. */ public class MessageDAO { - private final DatabaseConnection connection; + private final DatabaseConnection connection; - /** - * Constructs a new {@code FeedbackDAO} with the given database connection. - * - * @param connection the {@link DatabaseConnection} to use for executing queries; must not be - * {@code null} - */ - public MessageDAO(DatabaseConnection connection){ - this.connection = connection; - } + /** + * Constructs a new {@code FeedbackDAO} with the given database connection. + * + * @param connection the {@link DatabaseConnection} to use for executing queries; must not be + * {@code null} + */ + public MessageDAO(DatabaseConnection connection) { + this.connection = connection; + } - /** - * Uses a repeated INSERT-query to send a message to all donor (as in Users that have donated). - * - *

- * First grabs all donors (all Users that have donated to the charity) ids by getting - * the Charity_id throught the attribute. - *

- * @param message Message object contain all relevant info, including the Charity id. - * @return True or False based on if it succeeded or not - */ - public boolean addMessage(Message message){ - // First fetch all unique donors for this charity - List donorIds = getDonorIdsForCharity(message.getFrom().getUUID().toString()); + /** + * Uses a repeated INSERT-query to send a message to all donor (as in Users that have donated). + * + *

First grabs all donors (all Users that have donated to the charity) ids by getting the + * Charity_id throught the attribute. + * + * @param message Message object contain all relevant info, including the Charity id. + * @return True or False based on if it succeeded or not + */ + public boolean addMessage(Message message) { + // First fetch all unique donors for this charity + List donorIds = getDonorIdsForCharity(message.getFrom().getUUID().toString()); - if (donorIds.isEmpty()) return false; - String sql = """ - INSERT INTO Messages + if (donorIds.isEmpty()) return false; + String sql = + """ + INSERT INTO Messages (UUID_message, message_title, message_content, message_date, sender_charity_id, user_id) VALUES (?, ?, ?, ?, ?, ?) """; - try (Connection conn = connection.getMySqlConnection(); - PreparedStatement stmt = conn.prepareStatement(sql)) { + try (Connection conn = connection.getMySqlConnection(); + PreparedStatement stmt = conn.prepareStatement(sql)) { - for (String donorId : donorIds) { - stmt.setString(1, UUID.randomUUID().toString()); - stmt.setString(2, message.getTitle()); - stmt.setString(3, message.getContent()); - stmt.setDate(4, Date.valueOf(message.getTimeAndDate())); - stmt.setString(5, message.getFrom().getUUID().toString()); - stmt.setString(6, donorId); - stmt.addBatch(); - } + for (String donorId : donorIds) { + stmt.setString(1, UUID.randomUUID().toString()); + stmt.setString(2, message.getTitle()); + stmt.setString(3, message.getContent()); + stmt.setDate(4, Date.valueOf(message.getTimeAndDate())); + stmt.setString(5, message.getFrom().getUUID().toString()); + stmt.setString(6, donorId); + stmt.addBatch(); + } - int[] results = stmt.executeBatch(); - return results.length > 0; + int[] results = stmt.executeBatch(); + return results.length > 0; - } catch (SQLException e) { - e.printStackTrace(); - throw new RuntimeException("ERROR: Failed to send messages to donors."); - } + } catch (SQLException e) { + e.printStackTrace(); + throw new RuntimeException("ERROR: Failed to send messages to donors."); } + } - /** - * Private helper function used in {@code addMessage} method, which finds all distinct User Ids that have donated - * to given Charity. - * - *

- * Uses a Select query with a distinct modifier to not get duplicate user_id. At the end uses an WHERE-clause - * to get the spesified charity. - *

- * - * @param charityId Charity's I'd to search for. - * @return An empty or non-empty list of Ids as String. - */ - private List getDonorIdsForCharity(String charityId) { - List donorIds = new ArrayList<>(); - String sql = """ + /** + * Private helper function used in {@code addMessage} method, which finds all distinct User Ids + * that have donated to given Charity. + * + *

Uses a Select query with a distinct modifier to not get duplicate user_id. At the end uses + * an WHERE-clause to get the spesified charity. + * + * @param charityId Charity's I'd to search for. + * @return An empty or non-empty list of Ids as String. + */ + private List getDonorIdsForCharity(String charityId) { + List donorIds = new ArrayList<>(); + String sql = + """ SELECT DISTINCT user_id FROM Donations WHERE charity_id = ? """; - try (Connection conn = connection.getMySqlConnection(); - PreparedStatement stmt = conn.prepareStatement(sql)) { + try (Connection conn = connection.getMySqlConnection(); + PreparedStatement stmt = conn.prepareStatement(sql)) { - stmt.setString(1, charityId); - try (ResultSet rs = stmt.executeQuery()) { - while (rs.next()) { - donorIds.add(rs.getString("user_id")); - } - } - } catch (SQLException e) { - e.printStackTrace(); - throw new RuntimeException("ERROR: Failed to fetch donor IDs."); + stmt.setString(1, charityId); + try (ResultSet rs = stmt.executeQuery()) { + while (rs.next()) { + donorIds.add(rs.getString("user_id")); } - return donorIds; + } + } catch (SQLException e) { + e.printStackTrace(); + throw new RuntimeException("ERROR: Failed to fetch donor IDs."); } + return donorIds; + } } diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DAO/UserDAO.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DAO/UserDAO.java index b570d8b9..c3627149 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DAO/UserDAO.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DAO/UserDAO.java @@ -3,7 +3,6 @@ import java.sql.*; import java.time.LocalDate; import java.util.HashSet; - import ntnu.systemutvikling.team6.database.DatabaseConnection; import ntnu.systemutvikling.team6.models.Charity; import ntnu.systemutvikling.team6.models.registry.UserRegistry; @@ -32,27 +31,25 @@ public UserDAO(DatabaseConnection connection) { } /** - * Uses a select query to check if the provided Email already exists in {@code User} table. Return value is based on if finds a row or not. + * Uses a select query to check if the provided Email already exists in {@code User} table. Return + * value is based on if finds a row or not. + * + *

Check if email is a valid email. Uses a Select query to get a row containing the provided + * email. If it exists, return true. If not, return false Used in tandem with {@code + * LoginPageController} prevent duplicate Emails appearing on database. * - *

- * Check if email is a valid email. - * Uses a Select query to get a row containing the provided email. - * If it exists, return true. - * If not, return false - * Used in tandem with {@code LoginPageController} prevent duplicate Emails appearing on database. - *

* @param email Email in question. Check * @return */ - public boolean isEmailTaken(String email){ + public boolean isEmailTaken(String email) { if (email == null || email.isBlank() || !email.contains("@") || !email.contains(".")) { throw new IllegalArgumentException( - "Email cannot be null or blank," + " and must contain '@' and '.'"); + "Email cannot be null or blank," + " and must contain '@' and '.'"); } try (Connection conn = connection.getMySqlConnection()) { String mysql = - """ + """ SELECT UUID_User FROM User WHERE user_email = ? """; PreparedStatement statement = conn.prepareStatement(mysql); @@ -70,7 +67,6 @@ public boolean isEmailTaken(String email){ return false; } - /** * Retrieves a single {@link User} from the database by their UUID. * @@ -89,7 +85,7 @@ public User getUserFromDBUuid(String user_id) { try { conn = connection.getMySqlConnection(); String sql_query = - """ + """ SELECT u.UUID_User, u.user_name, u.user_email, u.user_password, u.role, s.UUID_user, s.isAnonymous, s.language, s.lightmode, @@ -113,18 +109,18 @@ public User getUserFromDBUuid(String user_id) { String userId = rs.getString("UUID_User"); if (lastUserid == null || !userId.equals(lastUserid)) { user = - new User( - userId, - rs.getString("user_name"), - rs.getString("user_email"), - rs.getString("user_password"), - rs.getString("role")); + new User( + userId, + rs.getString("user_name"), + rs.getString("user_email"), + rs.getString("user_password"), + rs.getString("role")); if (rs.getString("isAnonymous") != null) { Settings settings = - new Settings( - rs.getBoolean("isAnonymous"), - Language.valueOf(rs.getString("language").toUpperCase()), - rs.getBoolean("lightmode")); + new Settings( + rs.getBoolean("isAnonymous"), + Language.valueOf(rs.getString("language").toUpperCase()), + rs.getBoolean("lightmode")); user.setSettings(settings); } user.setInbox(new Inbox()); @@ -136,7 +132,8 @@ public User getUserFromDBUuid(String user_id) { Charity fromCharity = null; String charityId = rs.getString("UUID_charities"); if (charityId != null) { - fromCharity = new Charity( + fromCharity = + new Charity( charityId, rs.getString("org_number"), rs.getString("charity_name"), @@ -146,17 +143,16 @@ public User getUserFromDBUuid(String user_id) { rs.getString("description"), rs.getString("logoURL"), rs.getString("key_values"), - rs.getBytes("logoBLOB") - ); + rs.getBytes("logoBLOB")); } if (fromCharity != null) { - Message message = new Message( + Message message = + new Message( rs.getString("message_title"), fromCharity, rs.getString("message_content"), - LocalDate.parse(rs.getString("message_date")) - ); + LocalDate.parse(rs.getString("message_date"))); user.getInbox().addMessage(message); } } @@ -169,6 +165,7 @@ public User getUserFromDBUuid(String user_id) { } return user; } + /** * Retrieves a single {@link User} from the database matching the given username and password. * @@ -196,7 +193,7 @@ public User getUserFromDBEmailAndPassword(String email, String password) { try { conn = connection.getMySqlConnection(); String sql_query = - """ + """ SELECT u.UUID_User, u.user_name, u.user_email, u.user_password, u.role, s.UUID_user, s.isAnonymous, s.language, s.lightmode, @@ -213,8 +210,6 @@ public User getUserFromDBEmailAndPassword(String email, String password) { PreparedStatement stmt = conn.prepareStatement(sql_query); stmt.setString(1, email); - - ResultSet rs = stmt.executeQuery(); HashSet addedMessageIds = new HashSet<>(); while (rs.next()) { @@ -224,22 +219,22 @@ public User getUserFromDBEmailAndPassword(String email, String password) { if (user == null) { String storedHash = rs.getString("user_password"); - if (!new PasswordHasher().isValidPassword(password, storedHash)){ + if (!new PasswordHasher().isValidPassword(password, storedHash)) { return null; } user = - new User( - userId, - rs.getString("user_name"), - rs.getString("user_email"), - rs.getString("user_password"), - rs.getString("role")); + new User( + userId, + rs.getString("user_name"), + rs.getString("user_email"), + rs.getString("user_password"), + rs.getString("role")); if (rs.getString("isAnonymous") != null) { Settings settings = - new Settings( - rs.getBoolean("isAnonymous"), - Language.valueOf(rs.getString("language").toUpperCase()), - rs.getBoolean("lightmode")); + new Settings( + rs.getBoolean("isAnonymous"), + Language.valueOf(rs.getString("language").toUpperCase()), + rs.getBoolean("lightmode")); user.setSettings(settings); } user.setInbox(new Inbox()); @@ -250,7 +245,8 @@ public User getUserFromDBEmailAndPassword(String email, String password) { Charity fromCharity = null; String charityId = rs.getString("UUID_charities"); if (charityId != null) { - fromCharity = new Charity( + fromCharity = + new Charity( charityId, rs.getString("org_number"), rs.getString("charity_name"), @@ -260,17 +256,16 @@ public User getUserFromDBEmailAndPassword(String email, String password) { rs.getString("description"), rs.getString("logoURL"), rs.getString("key_values"), - rs.getBytes("logoBLOB") - ); + rs.getBytes("logoBLOB")); } if (fromCharity != null) { - Message message = new Message( + Message message = + new Message( rs.getString("message_title"), fromCharity, rs.getString("message_content"), - LocalDate.parse(rs.getString("message_date")) - ); + LocalDate.parse(rs.getString("message_date"))); user.getInbox().addMessage(message); } } @@ -302,7 +297,7 @@ public UserRegistry getUsersFromDB() { try { conn = connection.getMySqlConnection(); String sql_query = - """ + """ SELECT u.UUID_User, u.user_name, u.user_email, u.user_password, u.role, s.UUID_user, s.isAnonymous, s.language, s.lightmode, @@ -327,18 +322,18 @@ public UserRegistry getUsersFromDB() { if (lastUserid == null || !userId.equals(lastUserid)) { currentUser = - new User( - userId, - rs.getString("user_name"), - rs.getString("user_email"), - rs.getString("user_password"), - rs.getString("role")); + new User( + userId, + rs.getString("user_name"), + rs.getString("user_email"), + rs.getString("user_password"), + rs.getString("role")); if (rs.getString("isAnonymous") != null) { Settings settings = - new Settings( - rs.getBoolean("isAnonymous"), - Language.valueOf(rs.getString("language").toUpperCase()), - rs.getBoolean("lightmode")); + new Settings( + rs.getBoolean("isAnonymous"), + Language.valueOf(rs.getString("language").toUpperCase()), + rs.getBoolean("lightmode")); currentUser.setSettings(settings); } currentUser.setInbox(new Inbox()); @@ -351,7 +346,8 @@ public UserRegistry getUsersFromDB() { Charity fromCharity = null; String charityId = rs.getString("UUID_charities"); if (charityId != null) { - fromCharity = new Charity( + fromCharity = + new Charity( charityId, rs.getString("org_number"), rs.getString("charity_name"), @@ -361,17 +357,16 @@ public UserRegistry getUsersFromDB() { rs.getString("description"), rs.getString("logoURL"), rs.getString("key_values"), - rs.getBytes("logoBLOB") - ); + rs.getBytes("logoBLOB")); } if (fromCharity != null) { - Message message = new Message( + Message message = + new Message( rs.getString("message_title"), fromCharity, rs.getString("message_content"), - LocalDate.parse(rs.getString("message_date")) - ); + LocalDate.parse(rs.getString("message_date"))); currentUser.getInbox().addMessage(message); } } @@ -402,7 +397,7 @@ public Inbox getInboxForUser(String user_id) { try { conn = connection.getMySqlConnection(); String sql_query = - """ + """ SELECT m.UUID_message, m.message_title, m.message_content, m.message_date, m.sender_user_id, m.sender_charity_id, m.user_id, cv.charity_name, cv.charity_link, cv.description, cv.logoURL, cv.key_values, cv.logoBLOB, @@ -420,7 +415,8 @@ public Inbox getInboxForUser(String user_id) { Charity fromCharity = null; String charityId = rs.getString("UUID_charities"); if (charityId != null) { - fromCharity = new Charity( + fromCharity = + new Charity( charityId, rs.getString("org_number"), rs.getString("charity_name"), @@ -430,17 +426,16 @@ public Inbox getInboxForUser(String user_id) { rs.getString("description"), rs.getString("logoURL"), rs.getString("key_values"), - rs.getBytes("logoBLOB") - ); + rs.getBytes("logoBLOB")); } if (fromCharity != null) { - Message message = new Message( + Message message = + new Message( rs.getString("message_title"), fromCharity, rs.getString("message_content"), - LocalDate.parse(rs.getString("message_date")) - ); + LocalDate.parse(rs.getString("message_date"))); inbox.addMessage(message); } } @@ -470,7 +465,7 @@ public Settings getSettingsForUser(String user_id) { try { conn = connection.getMySqlConnection(); String sql_query = - """ + """ SELECT UUID_user, isAnonymous, language, lightmode FROM Settings WHERE UUID_user = ?; """; @@ -481,10 +476,10 @@ public Settings getSettingsForUser(String user_id) { while (rs.next()) { settings = - new Settings( - rs.getBoolean("isAnonymous"), - Language.valueOf(rs.getString("language").toUpperCase()), - rs.getBoolean("lightmode")); + new Settings( + rs.getBoolean("isAnonymous"), + Language.valueOf(rs.getString("language").toUpperCase()), + rs.getBoolean("lightmode")); } } catch (SQLException e) { e.printStackTrace(); @@ -495,6 +490,7 @@ public Settings getSettingsForUser(String user_id) { return settings; } + /** * Gets the user and settings information and sends it to the database through MySQL. * @@ -564,17 +560,18 @@ INSERT INTO Settings ( } /** - * Updates the Users settings in the {@code Settings} table. New values are stored in the Settings object. + * Updates the Users settings in the {@code Settings} table. New values are stored in the Settings + * object. * * @param user User that is going to recieve changes * @param settings Settings object containing new attributes * @return True or False based on if the update succeed or not */ - - public boolean updateUserSettings(User user, Settings settings){ + public boolean updateUserSettings(User user, Settings settings) { Connection conn = null; - String sql = """ - UPDATE Settings SET + String sql = + """ + UPDATE Settings SET isAnonymous = ?, language = ?, lightmode = ? @@ -592,23 +589,24 @@ public boolean updateUserSettings(User user, Settings settings){ return ps.executeUpdate() > 0; } catch (SQLException e) { - e.printStackTrace(); - System.out.println("Something went wrong when updating Settings"); - return false; + e.printStackTrace(); + System.out.println("Something went wrong when updating Settings"); + return false; } - } /** - * Updates the Users name, email and password in the {@code User} table. New values are stored in oncoming User param. + * Updates the Users name, email and password in the {@code User} table. New values are stored in + * oncoming User param. * * @param user User that is going to recieve changes * @return True or False based on if the update succeed or not */ - public boolean updateUserDetails(User user){ + public boolean updateUserDetails(User user) { Connection conn = null; - String sql = """ - UPDATE User SET + String sql = + """ + UPDATE User SET user_name = ?, user_email = ?, user_password = ? @@ -630,6 +628,5 @@ public boolean updateUserDetails(User user){ System.out.println("Something went wrong when updating Settings"); return false; } - } } diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DatabaseSetup.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DatabaseSetup.java index 4b138de5..8d8d69bb 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DatabaseSetup.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DatabaseSetup.java @@ -271,7 +271,7 @@ FOREIGN KEY (`UUID_charity`) """; String userHasFavourites = - """ + """ -- ----------------------------------------------------- -- Table `apbaluna`.`User_has_favourites` -- ----------------------------------------------------- diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/models/user/Message.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/models/user/Message.java index 9a2e07c3..ad2370c2 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/models/user/Message.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/models/user/Message.java @@ -1,9 +1,8 @@ package ntnu.systemutvikling.team6.models.user; -import ntnu.systemutvikling.team6.models.Charity; - import java.time.LocalDate; import java.util.UUID; +import ntnu.systemutvikling.team6.models.Charity; // Enhetstester mangler diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/models/user/User.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/models/user/User.java index fde91f9e..2e03c72e 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/models/user/User.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/models/user/User.java @@ -35,7 +35,8 @@ public class User { * @param inbox the user´s inbox * @throws IllegalArgumentException if any required argument is invalid. */ - public User(String username, String email, String password, Role role, Settings settings, Inbox inbox) { + public User( + String username, String email, String password, Role role, Settings settings, Inbox inbox) { if (username == null || username.isBlank()) { throw new IllegalArgumentException("Name cannot be null or blank."); } @@ -208,4 +209,3 @@ public void setRole(Role role) { this.role = role; } } - diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/service/AuthenticationService.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/service/AuthenticationService.java index 0d96d149..639e0862 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/service/AuthenticationService.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/service/AuthenticationService.java @@ -9,118 +9,114 @@ import ntnu.systemutvikling.team6.models.user.Settings; import ntnu.systemutvikling.team6.models.user.User; - /** - * Service class responsible for handling user authentication operations, - * including login, registration, and logout functionality. - *

- * Maintains the state of the currently authenticated user throughout the session. - *

+ * Service class responsible for handling user authentication operations, including login, + * registration, and logout functionality. + * + *

Maintains the state of the currently authenticated user throughout the session. */ public class AuthenticationService { - /** Handles read operations for user data from the database. */ - private final UserDAO userDataAcsessObject; - /** Handles write operations for user data to the database. */ - - /** The currently authenticated user, or {@code null} if no user is logged in. */ - private User currentUser; - - private Charity isCharityUser; - - /** - * Constructs an {@code AuthenticationService} with the specified data access objects. - * - * @param userDAO the data reader used to query user information from the database - */ - public AuthenticationService(UserDAO userDAO) { - this.userDataAcsessObject = userDAO; - } - - /** - * Attempts to authenticate a user with the given credentials. - *

- * If a matching user is found in the database, they are set as the current user - * and the method returns {@code true}. - *

- * - * @param email the username of the user attempting to log in - * @param password the password of the user attempting to log in - * @return {@code true} if authentication was successful; {@code false} otherwise - */ - public boolean login(String email, String password){ - User user = userDataAcsessObject.getUserFromDBEmailAndPassword(email, password); - - if (user != null){ - currentUser = user; - CharityUserDAO charityUserDAO = new CharityUserDAO(new DatabaseConnection()); - isCharityUser = charityUserDAO.getUserCharityUser(currentUser.getId().toString()); - if (isCharityUser != null){ - currentUser.setRole(Role.CHARITY_USER); - } - System.out.println("User gotten"); - return true; - } - - return false; - } - - /** - * Registers a new user account with the provided details. - *

- * The new user is assigned the {@link Role#NORMAL_USER} role and default - * {@link Settings} and {@link Inbox}. Registration will fail if the - * username is already taken or if the database operation is unsuccessful. - * On success, the new user is set as the current user. - *

- * - * @param username the unique username for the new account - * @param email the email address associated with the new account - * @param password the password for the new account - * @return {@code true} if registration was successful; {@code false} if the - * username is already taken or the database operation failed - */ - public boolean register(String username, String email, String password ){ - User newUser = new User(username, email, password, Role.NORMAL_USER, new Settings(), new Inbox()); - - if(userDataAcsessObject.isEmailTaken(email)){ - throw new IllegalArgumentException("Email already taken"); - } - - boolean success = userDataAcsessObject.registerUser(newUser); - - if (success){ - // currentUser = newUser; - // Proceed to login first - return true; - } - return false; + /** Handles read operations for user data from the database. */ + private final UserDAO userDataAcsessObject; + + /** Handles write operations for user data to the database. */ + + /** The currently authenticated user, or {@code null} if no user is logged in. */ + private User currentUser; + + private Charity isCharityUser; + + /** + * Constructs an {@code AuthenticationService} with the specified data access objects. + * + * @param userDAO the data reader used to query user information from the database + */ + public AuthenticationService(UserDAO userDAO) { + this.userDataAcsessObject = userDAO; + } + + /** + * Attempts to authenticate a user with the given credentials. + * + *

If a matching user is found in the database, they are set as the current user and the method + * returns {@code true}. + * + * @param email the username of the user attempting to log in + * @param password the password of the user attempting to log in + * @return {@code true} if authentication was successful; {@code false} otherwise + */ + public boolean login(String email, String password) { + User user = userDataAcsessObject.getUserFromDBEmailAndPassword(email, password); + + if (user != null) { + currentUser = user; + CharityUserDAO charityUserDAO = new CharityUserDAO(new DatabaseConnection()); + isCharityUser = charityUserDAO.getUserCharityUser(currentUser.getId().toString()); + if (isCharityUser != null) { + currentUser.setRole(Role.CHARITY_USER); + } + System.out.println("User gotten"); + return true; } - /** - * Logs out the currently authenticated user by clearing the current user state. - */ - public void logout (){ - currentUser = null; + return false; + } + + /** + * Registers a new user account with the provided details. + * + *

The new user is assigned the {@link Role#NORMAL_USER} role and default {@link Settings} and + * {@link Inbox}. Registration will fail if the username is already taken or if the database + * operation is unsuccessful. On success, the new user is set as the current user. + * + * @param username the unique username for the new account + * @param email the email address associated with the new account + * @param password the password for the new account + * @return {@code true} if registration was successful; {@code false} if the username is already + * taken or the database operation failed + */ + public boolean register(String username, String email, String password) { + User newUser = + new User(username, email, password, Role.NORMAL_USER, new Settings(), new Inbox()); + + if (userDataAcsessObject.isEmailTaken(email)) { + throw new IllegalArgumentException("Email already taken"); } + boolean success = userDataAcsessObject.registerUser(newUser); - /** - * Returns the currently authenticated user. - * - * @return the current {@link User}, or {@code null} if no user is logged in - */ - public User getCurrentUser(){ - return currentUser; - } - - /** - * Checks whether a user is currently logged in. - * - * @return {@code true} if a user is authenticated; {@code false} otherwise - */ - public boolean isLoggedin(){ - return currentUser != null; + if (success) { + // currentUser = newUser; + // Proceed to login first + return true; } - - public Charity isCharityUser(){return isCharityUser;} + return false; + } + + /** Logs out the currently authenticated user by clearing the current user state. */ + public void logout() { + currentUser = null; + } + + /** + * Returns the currently authenticated user. + * + * @return the current {@link User}, or {@code null} if no user is logged in + */ + public User getCurrentUser() { + return currentUser; + } + + /** + * Checks whether a user is currently logged in. + * + * @return {@code true} if a user is authenticated; {@code false} otherwise + */ + public boolean isLoggedin() { + return currentUser != null; + } + + public Charity isCharityUser() { + return isCharityUser; + } } diff --git a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/database/DAO/CategoryDAOTest.java b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/database/DAO/CategoryDAOTest.java index 1b93019f..ef07c9ef 100644 --- a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/database/DAO/CategoryDAOTest.java +++ b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/database/DAO/CategoryDAOTest.java @@ -1,68 +1,67 @@ package ntnu.systemutvikling.team6.database.DAO; -import ntnu.systemutvikling.team6.database.DatabaseConnection; -import org.junit.jupiter.api.*; -import java.sql.*; -import java.util.List; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; -/** - * Tests made by Claude AI: Sonnet 4.6, on 24.04.206 - */ +import java.sql.*; +import java.util.List; +import ntnu.systemutvikling.team6.database.DatabaseConnection; +import org.junit.jupiter.api.*; + +/** Tests made by Claude AI: Sonnet 4.6, on 24.04.206 */ public class CategoryDAOTest { - // --- Mocks --- - private DatabaseConnection mockDbConnection; - private Connection mockConn; - private Statement mockStmt; - private ResultSet mockRs; + // --- Mocks --- + private DatabaseConnection mockDbConnection; + private Connection mockConn; + private Statement mockStmt; + private ResultSet mockRs; - private CategoryDAO categoryDAO; + private CategoryDAO categoryDAO; - @BeforeEach - void setUp() throws SQLException { - mockDbConnection = mock(DatabaseConnection.class); - mockConn = mock(Connection.class); - mockStmt = mock(Statement.class); - mockRs = mock(ResultSet.class); + @BeforeEach + void setUp() throws SQLException { + mockDbConnection = mock(DatabaseConnection.class); + mockConn = mock(Connection.class); + mockStmt = mock(Statement.class); + mockRs = mock(ResultSet.class); - when(mockDbConnection.getMySqlConnection()).thenReturn(mockConn); - when(mockConn.createStatement()).thenReturn(mockStmt); - when(mockStmt.executeQuery(anyString())).thenReturn(mockRs); + when(mockDbConnection.getMySqlConnection()).thenReturn(mockConn); + when(mockConn.createStatement()).thenReturn(mockStmt); + when(mockStmt.executeQuery(anyString())).thenReturn(mockRs); - categoryDAO = new CategoryDAO(mockDbConnection); - } + categoryDAO = new CategoryDAO(mockDbConnection); + } - @Test - void getCategoriesFromDB_returnsAllCategories() throws SQLException { - when(mockRs.next()).thenReturn(true, true, true, false); - when(mockRs.getString("category")).thenReturn("Education", "Health", "Youth"); + @Test + void getCategoriesFromDB_returnsAllCategories() throws SQLException { + when(mockRs.next()).thenReturn(true, true, true, false); + when(mockRs.getString("category")).thenReturn("Education", "Health", "Youth"); - List result = categoryDAO.getCategoriesFromDB(); + List result = categoryDAO.getCategoriesFromDB(); - assertNotNull(result); - assertEquals(3, result.size()); - assertTrue(result.contains("Education")); - assertTrue(result.contains("Health")); - assertTrue(result.contains("Youth")); - } + assertNotNull(result); + assertEquals(3, result.size()); + assertTrue(result.contains("Education")); + assertTrue(result.contains("Health")); + assertTrue(result.contains("Youth")); + } - @Test - void getCategoriesFromDB_returnsSingleCategory() throws SQLException { - when(mockRs.next()).thenReturn(true, false); - when(mockRs.getString("category")).thenReturn("Environment"); + @Test + void getCategoriesFromDB_returnsSingleCategory() throws SQLException { + when(mockRs.next()).thenReturn(true, false); + when(mockRs.getString("category")).thenReturn("Environment"); - List result = categoryDAO.getCategoriesFromDB(); + List result = categoryDAO.getCategoriesFromDB(); - assertEquals(1, result.size()); - assertEquals("Environment", result.getFirst()); - } + assertEquals(1, result.size()); + assertEquals("Environment", result.getFirst()); + } - @Test - void getCategoriesFromDB_throwsRuntimeExceptionOnSQLException() throws SQLException { - when(mockConn.createStatement()).thenThrow(new SQLException("DB down")); + @Test + void getCategoriesFromDB_throwsRuntimeExceptionOnSQLException() throws SQLException { + when(mockConn.createStatement()).thenThrow(new SQLException("DB down")); - assertThrows(RuntimeException.class, () -> categoryDAO.getCategoriesFromDB()); - } -} \ No newline at end of file + assertThrows(RuntimeException.class, () -> categoryDAO.getCategoriesFromDB()); + } +} diff --git a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/database/DAO/CharityDAOTest.java b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/database/DAO/CharityDAOTest.java index 857a2072..7215aa1f 100644 --- a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/database/DAO/CharityDAOTest.java +++ b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/database/DAO/CharityDAOTest.java @@ -1,5 +1,12 @@ package ntnu.systemutvikling.team6.database.DAO; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +import java.sql.*; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.UUID; import ntnu.systemutvikling.team6.database.DatabaseConnection; import ntnu.systemutvikling.team6.models.Charity; import ntnu.systemutvikling.team6.models.Feedback; @@ -7,326 +14,318 @@ import ntnu.systemutvikling.team6.models.user.Language; import ntnu.systemutvikling.team6.models.user.Role; import org.junit.jupiter.api.*; -import java.sql.*; -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.UUID; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; -/** - * Tests made by Claude AI: Sonnet 4.6, on 24.04.206 - */ +/** Tests made by Claude AI: Sonnet 4.6, on 24.04.206 */ public class CharityDAOTest { - // --- Mocks --- - private DatabaseConnection mockDbConnection; - private Connection mockConn; - private Statement mockRawStmt; // getCharitiesFromDB() uses createStatement() - private PreparedStatement mockStmt; // getFeedbackForCharityUUID() uses prepareStatement() - private ResultSet mockRs; - - private CharityDAO charityDAO; - - @BeforeEach - void setUp() throws SQLException { - mockDbConnection = mock(DatabaseConnection.class); - mockConn = mock(Connection.class); - mockRawStmt = mock(Statement.class); - mockStmt = mock(PreparedStatement.class); - mockRs = mock(ResultSet.class); - - when(mockDbConnection.getMySqlConnection()).thenReturn(mockConn); - when(mockConn.createStatement()).thenReturn(mockRawStmt); - when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); - - charityDAO = new CharityDAO(mockDbConnection); - } - - // ---------------------------------------------------------------- - // Helpers - // ---------------------------------------------------------------- - - /** Stubs the full set of charity columns for a single row. */ - private void stubCharityRow(String charityId) throws SQLException { - when(mockRs.getString("UUID_charities")).thenReturn(charityId); - when(mockRs.getString("org_number")).thenReturn("123456789"); - when(mockRs.getString("charity_name")).thenReturn("HelpOrg"); - when(mockRs.getString("charity_link")).thenReturn("helporg.com"); - when(mockRs.getString("status")).thenReturn("active"); - when(mockRs.getBoolean("pre_approved")).thenReturn(true); - when(mockRs.getString("description")).thenReturn("We help people"); - when(mockRs.getString("logoURL")).thenReturn(null); - when(mockRs.getString("key_values")).thenReturn(null); - when(mockRs.getBytes("logoBLOB")).thenReturn(null); - when(mockRs.getString("category")).thenReturn(null); - when(mockRs.getString("UUID_feedback")).thenReturn(null); // no feedback by default - } - - /** Stubs a feedback + user block on top of an already-stubbed charity row. */ - private void stubFeedbackRow(String feedbackId, String userId) throws SQLException { - when(mockRs.getString("UUID_feedback")).thenReturn(feedbackId); - when(mockRs.getString("feedback_comment")).thenReturn("Great charity!"); - when(mockRs.getString("feedback_date")).thenReturn(LocalDate.now().toString()); - when(mockRs.getString("UUID_User")).thenReturn(userId); - when(mockRs.getString("user_name")).thenReturn("Alice"); - when(mockRs.getString("user_email")).thenReturn("alice@example.com"); - when(mockRs.getString("user_password")).thenReturn("hashedpw"); - when(mockRs.getString("role")).thenReturn(Role.NORMAL_USER.toString()); - } - - // ---------------------------------------------------------------- - // getCharitiesFromDB() — uses createStatement() - // ---------------------------------------------------------------- - - @Test - void getCharitiesFromDB_returnsRegistryWithOneCharity() throws SQLException { - when(mockRawStmt.executeQuery(anyString())).thenReturn(mockRs); - when(mockRs.next()).thenReturn(true, false); - - String charityId = UUID.randomUUID().toString(); - stubCharityRow(charityId); - - CharityRegistry registry = charityDAO.getCharitiesFromDB(); - - assertNotNull(registry); - assertEquals(1, registry.getAllCharities().size()); - assertEquals(charityId, registry.getAllCharities().getFirst().getUUID().toString()); - assertEquals("HelpOrg", registry.getAllCharities().getFirst().getName()); - } - - @Test - void getCharitiesFromDB_returnsEmptyRegistryWhenNoRows() throws SQLException { - when(mockRawStmt.executeQuery(anyString())).thenReturn(mockRs); - when(mockRs.next()).thenReturn(false); - - CharityRegistry registry = charityDAO.getCharitiesFromDB(); - - assertNotNull(registry); - assertTrue(registry.getAllCharities().isEmpty()); - } - - @Test - void getCharitiesFromDB_doesNotDuplicateCharityAcrossMultipleRows() throws SQLException { - // Same charity appearing in two rows (e.g. two categories) → only one Charity object - when(mockRawStmt.executeQuery(anyString())).thenReturn(mockRs); - when(mockRs.next()).thenReturn(true, true, false); - - String charityId = UUID.randomUUID().toString(); - when(mockRs.getString("UUID_charities")).thenReturn(charityId); - when(mockRs.getString("org_number")).thenReturn("111"); - when(mockRs.getString("charity_name")).thenReturn("EduOrg"); - when(mockRs.getString("charity_link")).thenReturn("eduorg.com"); - when(mockRs.getString("status")).thenReturn("active"); - when(mockRs.getBoolean("pre_approved")).thenReturn(false); - when(mockRs.getString("description")).thenReturn("Education"); - when(mockRs.getString("logoURL")).thenReturn(null); - when(mockRs.getString("key_values")).thenReturn(null); - when(mockRs.getBytes("logoBLOB")).thenReturn(null); - when(mockRs.getString("category")).thenReturn("Education", "Youth"); - when(mockRs.getString("UUID_feedback")).thenReturn(null); - - CharityRegistry registry = charityDAO.getCharitiesFromDB(); - - assertEquals(1, registry.getAllCharities().size()); - assertEquals(2, registry.getAllCharities().getFirst().getCategory().size()); - assertTrue(registry.getAllCharities().getFirst().getCategory().contains("Education")); - assertTrue(registry.getAllCharities().getFirst().getCategory().contains("Youth")); - } - - @Test - void getCharitiesFromDB_returnsMultipleDistinctCharities() throws SQLException { - when(mockRawStmt.executeQuery(anyString())).thenReturn(mockRs); - when(mockRs.next()).thenReturn(true, true, false); - - String charityId1 = UUID.randomUUID().toString(); - String charityId2 = UUID.randomUUID().toString(); - - when(mockRs.getString("UUID_charities")).thenReturn(charityId1, charityId2); - when(mockRs.getString("org_number")).thenReturn("111", "222"); - when(mockRs.getString("charity_name")).thenReturn("OrgA", "OrgB"); - when(mockRs.getString("charity_link")).thenReturn("orga.com", "orgb.com"); - when(mockRs.getString("status")).thenReturn("active"); - when(mockRs.getBoolean("pre_approved")).thenReturn(true); - when(mockRs.getString("description")).thenReturn("Desc"); - when(mockRs.getString("logoURL")).thenReturn(null); - when(mockRs.getString("key_values")).thenReturn(null); - when(mockRs.getBytes("logoBLOB")).thenReturn(null); - when(mockRs.getString("category")).thenReturn(null); - when(mockRs.getString("UUID_feedback")).thenReturn(null); - - CharityRegistry registry = charityDAO.getCharitiesFromDB(); - - assertEquals(2, registry.getAllCharities().size()); - } - - @Test - void getCharitiesFromDB_appendsFeedbackToCharity() throws SQLException { - when(mockRawStmt.executeQuery(anyString())).thenReturn(mockRs); - when(mockRs.next()).thenReturn(true, false); - - String charityId = UUID.randomUUID().toString(); - String feedbackId = UUID.randomUUID().toString(); - String userId = UUID.randomUUID().toString(); - - stubCharityRow(charityId); - stubFeedbackRow(feedbackId, userId); - - CharityRegistry registry = charityDAO.getCharitiesFromDB(); - - Charity charity = registry.getAllCharities().getFirst(); - assertEquals(1, charity.getFeedbacks().size()); - assertEquals(feedbackId, charity.getFeedbacks().getFirst().getFeedbackId().toString()); - assertEquals("Great charity!", charity.getFeedbacks().getFirst().getComment()); - assertEquals(userId, charity.getFeedbacks().getFirst().getUser().getId().toString()); - } - - @Test - void getCharitiesFromDB_doesNotDuplicateFeedbackAcrossRows() throws SQLException { - // Same feedbackId appearing in two rows (e.g. two categories) → only one Feedback added - when(mockRawStmt.executeQuery(anyString())).thenReturn(mockRs); - when(mockRs.next()).thenReturn(true, true, false); - - String charityId = UUID.randomUUID().toString(); - String feedbackId = UUID.randomUUID().toString(); - String userId = UUID.randomUUID().toString(); - - when(mockRs.getString("UUID_charities")).thenReturn(charityId); - when(mockRs.getString("org_number")).thenReturn("111"); - when(mockRs.getString("charity_name")).thenReturn("Org"); - when(mockRs.getString("charity_link")).thenReturn("org.com"); - when(mockRs.getString("status")).thenReturn("active"); - when(mockRs.getBoolean("pre_approved")).thenReturn(false); - when(mockRs.getString("description")).thenReturn("desc"); - when(mockRs.getString("logoURL")).thenReturn(null); - when(mockRs.getString("key_values")).thenReturn(null); - when(mockRs.getBytes("logoBLOB")).thenReturn(null); - when(mockRs.getString("category")).thenReturn("Health", "Health"); - stubFeedbackRow(feedbackId, userId); // same feedbackId both rows - - CharityRegistry registry = charityDAO.getCharitiesFromDB(); - - assertEquals(1, registry.getAllCharities().getFirst().getFeedbacks().size()); - } - - @Test - void getCharitiesFromDB_clearsSeenFeedbackIdsWhenNewCharityStarts() throws SQLException { - // feedbackId seen on charity1 must NOT be deduplicated against charity2 - when(mockRawStmt.executeQuery(anyString())).thenReturn(mockRs); - when(mockRs.next()).thenReturn(true, true, false); - - String charityId1 = UUID.randomUUID().toString(); - String charityId2 = UUID.randomUUID().toString(); - String feedbackId = UUID.randomUUID().toString(); // same UUID reused on both charities - String userId = UUID.randomUUID().toString(); - - when(mockRs.getString("UUID_charities")).thenReturn(charityId1, charityId2); - when(mockRs.getString("org_number")).thenReturn("111", "222"); - when(mockRs.getString("charity_name")).thenReturn("OrgA", "OrgB"); - when(mockRs.getString("charity_link")).thenReturn("a.com", "b.com"); - when(mockRs.getString("status")).thenReturn("active"); - when(mockRs.getBoolean("pre_approved")).thenReturn(true); - when(mockRs.getString("description")).thenReturn("desc"); - when(mockRs.getString("logoURL")).thenReturn(null); - when(mockRs.getString("key_values")).thenReturn(null); - when(mockRs.getBytes("logoBLOB")).thenReturn(null); - when(mockRs.getString("category")).thenReturn(null); - when(mockRs.getString("UUID_feedback")).thenReturn(feedbackId); - when(mockRs.getString("feedback_comment")).thenReturn("Good"); - when(mockRs.getString("feedback_date")).thenReturn(LocalDate.now().toString()); - when(mockRs.getString("UUID_User")).thenReturn(userId); - when(mockRs.getString("user_name")).thenReturn("Bob"); - when(mockRs.getString("user_email")).thenReturn("bob@example.com"); - when(mockRs.getString("user_password")).thenReturn("pw"); - when(mockRs.getString("role")).thenReturn(Role.NORMAL_USER.toString()); - - CharityRegistry registry = charityDAO.getCharitiesFromDB(); - - // Each charity should have its own feedback entry - assertEquals(1, registry.getAllCharities().get(0).getFeedbacks().size()); - assertEquals(1, registry.getAllCharities().get(1).getFeedbacks().size()); - } - - @Test - void getCharitiesFromDB_throwsRuntimeExceptionOnSQLException() throws SQLException { - when(mockConn.createStatement()).thenThrow(new SQLException("DB down")); - - assertThrows(RuntimeException.class, () -> charityDAO.getCharitiesFromDB()); - } - - // ---------------------------------------------------------------- - // getFeedbackForCharityUUID() — uses prepareStatement() - // ---------------------------------------------------------------- - - @Test - void getFeedbackForCharityUUID_returnsFeedbackList() throws SQLException { - when(mockStmt.executeQuery()).thenReturn(mockRs); - when(mockRs.next()).thenReturn(true, false); - - String feedbackId = UUID.randomUUID().toString(); - String userId = UUID.randomUUID().toString(); - - when(mockRs.getString("UUID_feedback")).thenReturn(feedbackId); - when(mockRs.getString("feedback_comment")).thenReturn("Very helpful"); - when(mockRs.getString("feedback_date")).thenReturn(LocalDate.now().toString()); - when(mockRs.getBoolean("isAnonymous")).thenReturn(false); - when(mockRs.getString("UUID_User")).thenReturn(userId); - when(mockRs.getString("user_name")).thenReturn("Carol"); - when(mockRs.getString("user_email")).thenReturn("carol@example.com"); - when(mockRs.getString("user_password")).thenReturn("pw"); - when(mockRs.getString("role")).thenReturn(Role.NORMAL_USER.toString()); - when(mockRs.getString("language")).thenReturn(Language.ENGLISH.toString()); - when(mockRs.getBoolean("lightmode")).thenReturn(false); - - ArrayList result = charityDAO.getFeedbackforCharityUUID(UUID.randomUUID().toString()); - - assertNotNull(result); - assertEquals(1, result.size()); - assertEquals(feedbackId, result.getFirst().getFeedbackId().toString()); - assertEquals("Very helpful", result.getFirst().getComment()); - assertEquals(userId, result.getFirst().getUser().getId().toString()); - } - - @Test - void getFeedbackForCharityUUID_returnsEmptyListWhenNoFeedback() throws SQLException { - when(mockStmt.executeQuery()).thenReturn(mockRs); - when(mockRs.next()).thenReturn(false); - - ArrayList result = charityDAO.getFeedbackforCharityUUID(UUID.randomUUID().toString()); - - assertNotNull(result); - assertTrue(result.isEmpty()); - } - - @Test - void getFeedbackForCharityUUID_returnsMultipleEntries() throws SQLException { - when(mockStmt.executeQuery()).thenReturn(mockRs); - when(mockRs.next()).thenReturn(true, true, false); - - when(mockRs.getString("UUID_feedback")).thenReturn( - UUID.randomUUID().toString(), UUID.randomUUID().toString()); - when(mockRs.getString("feedback_comment")).thenReturn("Good", "Excellent"); - when(mockRs.getString("feedback_date")).thenReturn(LocalDate.now().toString()); - when(mockRs.getBoolean("isAnonymous")).thenReturn(false); - when(mockRs.getString("UUID_User")).thenReturn(UUID.randomUUID().toString()); - when(mockRs.getString("user_name")).thenReturn("User"); - when(mockRs.getString("user_email")).thenReturn("u@example.com"); - when(mockRs.getString("user_password")).thenReturn("pw"); - when(mockRs.getString("role")).thenReturn(Role.NORMAL_USER.toString()); - when(mockRs.getString("language")).thenReturn(Language.ENGLISH.toString()); - when(mockRs.getBoolean("lightmode")).thenReturn(false); - - ArrayList result = charityDAO.getFeedbackforCharityUUID(UUID.randomUUID().toString()); - - assertEquals(2, result.size()); - } - - - @Test - void getFeedbackForCharityUUID_throwsRuntimeExceptionOnSQLException() throws SQLException { - when(mockStmt.executeQuery()).thenThrow(new SQLException("Query failed")); - - assertThrows(RuntimeException.class, - () -> charityDAO.getFeedbackforCharityUUID(UUID.randomUUID().toString())); - } -} \ No newline at end of file + // --- Mocks --- + private DatabaseConnection mockDbConnection; + private Connection mockConn; + private Statement mockRawStmt; // getCharitiesFromDB() uses createStatement() + private PreparedStatement mockStmt; // getFeedbackForCharityUUID() uses prepareStatement() + private ResultSet mockRs; + + private CharityDAO charityDAO; + + @BeforeEach + void setUp() throws SQLException { + mockDbConnection = mock(DatabaseConnection.class); + mockConn = mock(Connection.class); + mockRawStmt = mock(Statement.class); + mockStmt = mock(PreparedStatement.class); + mockRs = mock(ResultSet.class); + + when(mockDbConnection.getMySqlConnection()).thenReturn(mockConn); + when(mockConn.createStatement()).thenReturn(mockRawStmt); + when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); + + charityDAO = new CharityDAO(mockDbConnection); + } + + // ---------------------------------------------------------------- + // Helpers + // ---------------------------------------------------------------- + + /** Stubs the full set of charity columns for a single row. */ + private void stubCharityRow(String charityId) throws SQLException { + when(mockRs.getString("UUID_charities")).thenReturn(charityId); + when(mockRs.getString("org_number")).thenReturn("123456789"); + when(mockRs.getString("charity_name")).thenReturn("HelpOrg"); + when(mockRs.getString("charity_link")).thenReturn("helporg.com"); + when(mockRs.getString("status")).thenReturn("active"); + when(mockRs.getBoolean("pre_approved")).thenReturn(true); + when(mockRs.getString("description")).thenReturn("We help people"); + when(mockRs.getString("logoURL")).thenReturn(null); + when(mockRs.getString("key_values")).thenReturn(null); + when(mockRs.getBytes("logoBLOB")).thenReturn(null); + when(mockRs.getString("category")).thenReturn(null); + when(mockRs.getString("UUID_feedback")).thenReturn(null); // no feedback by default + } + + /** Stubs a feedback + user block on top of an already-stubbed charity row. */ + private void stubFeedbackRow(String feedbackId, String userId) throws SQLException { + when(mockRs.getString("UUID_feedback")).thenReturn(feedbackId); + when(mockRs.getString("feedback_comment")).thenReturn("Great charity!"); + when(mockRs.getString("feedback_date")).thenReturn(LocalDate.now().toString()); + when(mockRs.getString("UUID_User")).thenReturn(userId); + when(mockRs.getString("user_name")).thenReturn("Alice"); + when(mockRs.getString("user_email")).thenReturn("alice@example.com"); + when(mockRs.getString("user_password")).thenReturn("hashedpw"); + when(mockRs.getString("role")).thenReturn(Role.NORMAL_USER.toString()); + } + + // ---------------------------------------------------------------- + // getCharitiesFromDB() — uses createStatement() + // ---------------------------------------------------------------- + + @Test + void getCharitiesFromDB_returnsRegistryWithOneCharity() throws SQLException { + when(mockRawStmt.executeQuery(anyString())).thenReturn(mockRs); + when(mockRs.next()).thenReturn(true, false); + + String charityId = UUID.randomUUID().toString(); + stubCharityRow(charityId); + + CharityRegistry registry = charityDAO.getCharitiesFromDB(); + + assertNotNull(registry); + assertEquals(1, registry.getAllCharities().size()); + assertEquals(charityId, registry.getAllCharities().getFirst().getUUID().toString()); + assertEquals("HelpOrg", registry.getAllCharities().getFirst().getName()); + } + + @Test + void getCharitiesFromDB_returnsEmptyRegistryWhenNoRows() throws SQLException { + when(mockRawStmt.executeQuery(anyString())).thenReturn(mockRs); + when(mockRs.next()).thenReturn(false); + + CharityRegistry registry = charityDAO.getCharitiesFromDB(); + + assertNotNull(registry); + assertTrue(registry.getAllCharities().isEmpty()); + } + + @Test + void getCharitiesFromDB_doesNotDuplicateCharityAcrossMultipleRows() throws SQLException { + // Same charity appearing in two rows (e.g. two categories) → only one Charity object + when(mockRawStmt.executeQuery(anyString())).thenReturn(mockRs); + when(mockRs.next()).thenReturn(true, true, false); + + String charityId = UUID.randomUUID().toString(); + when(mockRs.getString("UUID_charities")).thenReturn(charityId); + when(mockRs.getString("org_number")).thenReturn("111"); + when(mockRs.getString("charity_name")).thenReturn("EduOrg"); + when(mockRs.getString("charity_link")).thenReturn("eduorg.com"); + when(mockRs.getString("status")).thenReturn("active"); + when(mockRs.getBoolean("pre_approved")).thenReturn(false); + when(mockRs.getString("description")).thenReturn("Education"); + when(mockRs.getString("logoURL")).thenReturn(null); + when(mockRs.getString("key_values")).thenReturn(null); + when(mockRs.getBytes("logoBLOB")).thenReturn(null); + when(mockRs.getString("category")).thenReturn("Education", "Youth"); + when(mockRs.getString("UUID_feedback")).thenReturn(null); + + CharityRegistry registry = charityDAO.getCharitiesFromDB(); + + assertEquals(1, registry.getAllCharities().size()); + assertEquals(2, registry.getAllCharities().getFirst().getCategory().size()); + assertTrue(registry.getAllCharities().getFirst().getCategory().contains("Education")); + assertTrue(registry.getAllCharities().getFirst().getCategory().contains("Youth")); + } + + @Test + void getCharitiesFromDB_returnsMultipleDistinctCharities() throws SQLException { + when(mockRawStmt.executeQuery(anyString())).thenReturn(mockRs); + when(mockRs.next()).thenReturn(true, true, false); + + String charityId1 = UUID.randomUUID().toString(); + String charityId2 = UUID.randomUUID().toString(); + + when(mockRs.getString("UUID_charities")).thenReturn(charityId1, charityId2); + when(mockRs.getString("org_number")).thenReturn("111", "222"); + when(mockRs.getString("charity_name")).thenReturn("OrgA", "OrgB"); + when(mockRs.getString("charity_link")).thenReturn("orga.com", "orgb.com"); + when(mockRs.getString("status")).thenReturn("active"); + when(mockRs.getBoolean("pre_approved")).thenReturn(true); + when(mockRs.getString("description")).thenReturn("Desc"); + when(mockRs.getString("logoURL")).thenReturn(null); + when(mockRs.getString("key_values")).thenReturn(null); + when(mockRs.getBytes("logoBLOB")).thenReturn(null); + when(mockRs.getString("category")).thenReturn(null); + when(mockRs.getString("UUID_feedback")).thenReturn(null); + + CharityRegistry registry = charityDAO.getCharitiesFromDB(); + + assertEquals(2, registry.getAllCharities().size()); + } + + @Test + void getCharitiesFromDB_appendsFeedbackToCharity() throws SQLException { + when(mockRawStmt.executeQuery(anyString())).thenReturn(mockRs); + when(mockRs.next()).thenReturn(true, false); + + String charityId = UUID.randomUUID().toString(); + String feedbackId = UUID.randomUUID().toString(); + String userId = UUID.randomUUID().toString(); + + stubCharityRow(charityId); + stubFeedbackRow(feedbackId, userId); + + CharityRegistry registry = charityDAO.getCharitiesFromDB(); + + Charity charity = registry.getAllCharities().getFirst(); + assertEquals(1, charity.getFeedbacks().size()); + assertEquals(feedbackId, charity.getFeedbacks().getFirst().getFeedbackId().toString()); + assertEquals("Great charity!", charity.getFeedbacks().getFirst().getComment()); + assertEquals(userId, charity.getFeedbacks().getFirst().getUser().getId().toString()); + } + + @Test + void getCharitiesFromDB_doesNotDuplicateFeedbackAcrossRows() throws SQLException { + // Same feedbackId appearing in two rows (e.g. two categories) → only one Feedback added + when(mockRawStmt.executeQuery(anyString())).thenReturn(mockRs); + when(mockRs.next()).thenReturn(true, true, false); + + String charityId = UUID.randomUUID().toString(); + String feedbackId = UUID.randomUUID().toString(); + String userId = UUID.randomUUID().toString(); + + when(mockRs.getString("UUID_charities")).thenReturn(charityId); + when(mockRs.getString("org_number")).thenReturn("111"); + when(mockRs.getString("charity_name")).thenReturn("Org"); + when(mockRs.getString("charity_link")).thenReturn("org.com"); + when(mockRs.getString("status")).thenReturn("active"); + when(mockRs.getBoolean("pre_approved")).thenReturn(false); + when(mockRs.getString("description")).thenReturn("desc"); + when(mockRs.getString("logoURL")).thenReturn(null); + when(mockRs.getString("key_values")).thenReturn(null); + when(mockRs.getBytes("logoBLOB")).thenReturn(null); + when(mockRs.getString("category")).thenReturn("Health", "Health"); + stubFeedbackRow(feedbackId, userId); // same feedbackId both rows + + CharityRegistry registry = charityDAO.getCharitiesFromDB(); + + assertEquals(1, registry.getAllCharities().getFirst().getFeedbacks().size()); + } + + @Test + void getCharitiesFromDB_clearsSeenFeedbackIdsWhenNewCharityStarts() throws SQLException { + // feedbackId seen on charity1 must NOT be deduplicated against charity2 + when(mockRawStmt.executeQuery(anyString())).thenReturn(mockRs); + when(mockRs.next()).thenReturn(true, true, false); + + String charityId1 = UUID.randomUUID().toString(); + String charityId2 = UUID.randomUUID().toString(); + String feedbackId = UUID.randomUUID().toString(); // same UUID reused on both charities + String userId = UUID.randomUUID().toString(); + + when(mockRs.getString("UUID_charities")).thenReturn(charityId1, charityId2); + when(mockRs.getString("org_number")).thenReturn("111", "222"); + when(mockRs.getString("charity_name")).thenReturn("OrgA", "OrgB"); + when(mockRs.getString("charity_link")).thenReturn("a.com", "b.com"); + when(mockRs.getString("status")).thenReturn("active"); + when(mockRs.getBoolean("pre_approved")).thenReturn(true); + when(mockRs.getString("description")).thenReturn("desc"); + when(mockRs.getString("logoURL")).thenReturn(null); + when(mockRs.getString("key_values")).thenReturn(null); + when(mockRs.getBytes("logoBLOB")).thenReturn(null); + when(mockRs.getString("category")).thenReturn(null); + when(mockRs.getString("UUID_feedback")).thenReturn(feedbackId); + when(mockRs.getString("feedback_comment")).thenReturn("Good"); + when(mockRs.getString("feedback_date")).thenReturn(LocalDate.now().toString()); + when(mockRs.getString("UUID_User")).thenReturn(userId); + when(mockRs.getString("user_name")).thenReturn("Bob"); + when(mockRs.getString("user_email")).thenReturn("bob@example.com"); + when(mockRs.getString("user_password")).thenReturn("pw"); + when(mockRs.getString("role")).thenReturn(Role.NORMAL_USER.toString()); + + CharityRegistry registry = charityDAO.getCharitiesFromDB(); + + // Each charity should have its own feedback entry + assertEquals(1, registry.getAllCharities().get(0).getFeedbacks().size()); + assertEquals(1, registry.getAllCharities().get(1).getFeedbacks().size()); + } + + @Test + void getCharitiesFromDB_throwsRuntimeExceptionOnSQLException() throws SQLException { + when(mockConn.createStatement()).thenThrow(new SQLException("DB down")); + + assertThrows(RuntimeException.class, () -> charityDAO.getCharitiesFromDB()); + } + + // ---------------------------------------------------------------- + // getFeedbackForCharityUUID() — uses prepareStatement() + // ---------------------------------------------------------------- + + @Test + void getFeedbackForCharityUUID_returnsFeedbackList() throws SQLException { + when(mockStmt.executeQuery()).thenReturn(mockRs); + when(mockRs.next()).thenReturn(true, false); + + String feedbackId = UUID.randomUUID().toString(); + String userId = UUID.randomUUID().toString(); + + when(mockRs.getString("UUID_feedback")).thenReturn(feedbackId); + when(mockRs.getString("feedback_comment")).thenReturn("Very helpful"); + when(mockRs.getString("feedback_date")).thenReturn(LocalDate.now().toString()); + when(mockRs.getBoolean("isAnonymous")).thenReturn(false); + when(mockRs.getString("UUID_User")).thenReturn(userId); + when(mockRs.getString("user_name")).thenReturn("Carol"); + when(mockRs.getString("user_email")).thenReturn("carol@example.com"); + when(mockRs.getString("user_password")).thenReturn("pw"); + when(mockRs.getString("role")).thenReturn(Role.NORMAL_USER.toString()); + when(mockRs.getString("language")).thenReturn(Language.ENGLISH.toString()); + when(mockRs.getBoolean("lightmode")).thenReturn(false); + + ArrayList result = charityDAO.getFeedbackforCharityUUID(UUID.randomUUID().toString()); + + assertNotNull(result); + assertEquals(1, result.size()); + assertEquals(feedbackId, result.getFirst().getFeedbackId().toString()); + assertEquals("Very helpful", result.getFirst().getComment()); + assertEquals(userId, result.getFirst().getUser().getId().toString()); + } + + @Test + void getFeedbackForCharityUUID_returnsEmptyListWhenNoFeedback() throws SQLException { + when(mockStmt.executeQuery()).thenReturn(mockRs); + when(mockRs.next()).thenReturn(false); + + ArrayList result = charityDAO.getFeedbackforCharityUUID(UUID.randomUUID().toString()); + + assertNotNull(result); + assertTrue(result.isEmpty()); + } + + @Test + void getFeedbackForCharityUUID_returnsMultipleEntries() throws SQLException { + when(mockStmt.executeQuery()).thenReturn(mockRs); + when(mockRs.next()).thenReturn(true, true, false); + + when(mockRs.getString("UUID_feedback")) + .thenReturn(UUID.randomUUID().toString(), UUID.randomUUID().toString()); + when(mockRs.getString("feedback_comment")).thenReturn("Good", "Excellent"); + when(mockRs.getString("feedback_date")).thenReturn(LocalDate.now().toString()); + when(mockRs.getBoolean("isAnonymous")).thenReturn(false); + when(mockRs.getString("UUID_User")).thenReturn(UUID.randomUUID().toString()); + when(mockRs.getString("user_name")).thenReturn("User"); + when(mockRs.getString("user_email")).thenReturn("u@example.com"); + when(mockRs.getString("user_password")).thenReturn("pw"); + when(mockRs.getString("role")).thenReturn(Role.NORMAL_USER.toString()); + when(mockRs.getString("language")).thenReturn(Language.ENGLISH.toString()); + when(mockRs.getBoolean("lightmode")).thenReturn(false); + + ArrayList result = charityDAO.getFeedbackforCharityUUID(UUID.randomUUID().toString()); + + assertEquals(2, result.size()); + } + + @Test + void getFeedbackForCharityUUID_throwsRuntimeExceptionOnSQLException() throws SQLException { + when(mockStmt.executeQuery()).thenThrow(new SQLException("Query failed")); + + assertThrows( + RuntimeException.class, + () -> charityDAO.getFeedbackforCharityUUID(UUID.randomUUID().toString())); + } +} diff --git a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/database/DAO/CharityUserDAOTest.java b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/database/DAO/CharityUserDAOTest.java index 3e265694..13f7f164 100644 --- a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/database/DAO/CharityUserDAOTest.java +++ b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/database/DAO/CharityUserDAOTest.java @@ -1,272 +1,265 @@ package ntnu.systemutvikling.team6.database.DAO; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +import java.sql.*; +import java.util.UUID; import ntnu.systemutvikling.team6.database.DatabaseConnection; import ntnu.systemutvikling.team6.models.Charity; import org.junit.jupiter.api.*; -import java.sql.*; -import java.util.UUID; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; -/** - * Tests made by Claude AI: Sonnet 4.6, on 24.04.206 - */ +/** Tests made by Claude AI: Sonnet 4.6, on 24.04.206 */ public class CharityUserDAOTest { - // --- Mocks --- - private DatabaseConnection mockDbConnection; - private Connection mockConn; - private PreparedStatement mockStmt; - private ResultSet mockRs; - - private CharityUserDAO charityUserDAO; - - @BeforeEach - void setUp() throws SQLException { - mockDbConnection = mock(DatabaseConnection.class); - mockConn = mock(Connection.class); - mockStmt = mock(PreparedStatement.class); - mockRs = mock(ResultSet.class); - - when(mockDbConnection.getMySqlConnection()).thenReturn(mockConn); - when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); - - charityUserDAO = new CharityUserDAO(mockDbConnection); - } - - // ---------------------------------------------------------------- - // Helpers - // ---------------------------------------------------------------- - - private Charity buildTestCharity(String charityId) { - return new Charity( - charityId, - "123456789", - "HelpOrg", - "helporg.com", - "active", - true, - "We help people", - null, - null, - null - ); - } - - private void stubFullCharityRow(String charityId) throws SQLException { - when(mockRs.getString("UUID_charities")).thenReturn(charityId); - when(mockRs.getString("org_number")).thenReturn("123456789"); - when(mockRs.getString("charity_name")).thenReturn("HelpOrg"); - when(mockRs.getString("charity_link")).thenReturn("helporg.com"); - when(mockRs.getString("status")).thenReturn("active"); - when(mockRs.getBoolean("pre_approved")).thenReturn(true); - when(mockRs.getString("description")).thenReturn("We help people"); - when(mockRs.getString("logoURL")).thenReturn(null); - when(mockRs.getString("key_values")).thenReturn(null); - when(mockRs.getBytes("logoBLOB")).thenReturn(null); - when(mockRs.getString("category")).thenReturn(null); - } - - // ---------------------------------------------------------------- - // updateCharityVanityName() - // ---------------------------------------------------------------- - - @Test - void updateCharityVanityName_returnsTrueOnSuccess() throws SQLException { - when(mockStmt.executeUpdate()).thenReturn(1); - - assertTrue(charityUserDAO.updateCharityVanityName( - buildTestCharity(UUID.randomUUID().toString()) - )); - } - - @Test - void updateCharityVanityName_returnsFalseWhenNoRowsAffected() throws SQLException { - when(mockStmt.executeUpdate()).thenReturn(0); - - assertFalse(charityUserDAO.updateCharityVanityName( - buildTestCharity(UUID.randomUUID().toString()) - )); - } - - @Test - void updateCharityVanityName_returnsFalseOnSQLException() throws SQLException { - when(mockStmt.executeUpdate()).thenThrow(new SQLException("Update failed")); - - assertFalse(charityUserDAO.updateCharityVanityName( - buildTestCharity(UUID.randomUUID().toString()) - )); - } - - - // ---------------------------------------------------------------- - // updateCharityVanityDescription() - // ---------------------------------------------------------------- - - @Test - void updateCharityVanityDescription_returnsTrueOnSuccess() throws SQLException { - when(mockStmt.executeUpdate()).thenReturn(1); - - assertTrue(charityUserDAO.updateCharityVanityDescription( - buildTestCharity(UUID.randomUUID().toString()) - )); - } - - @Test - void updateCharityVanityDescription_returnsFalseWhenNoRowsAffected() throws SQLException { - when(mockStmt.executeUpdate()).thenReturn(0); - - assertFalse(charityUserDAO.updateCharityVanityDescription( - buildTestCharity(UUID.randomUUID().toString()) - )); - } - - @Test - void updateCharityVanityDescription_returnsFalseOnSQLException() throws SQLException { - when(mockStmt.executeUpdate()).thenThrow(new SQLException("Update failed")); - - assertFalse(charityUserDAO.updateCharityVanityDescription( - buildTestCharity(UUID.randomUUID().toString()) - )); - } - - @Test - void updateCharityVanityDescription_setsCorrectParameters() throws SQLException { - when(mockStmt.executeUpdate()).thenReturn(1); - - String charityId = UUID.randomUUID().toString(); - Charity charity = buildTestCharity(charityId); - - charityUserDAO.updateCharityVanityDescription(charity); - - verify(mockStmt).setString(1, charity.getDescription()); // description - verify(mockStmt).setString(2, charityId); // UUID_charity - } - - // ---------------------------------------------------------------- - // getUserCharityUser() - // ---------------------------------------------------------------- - - @Test - void getUserCharityUser_throwsOnNullUuid() { - assertThrows(IllegalArgumentException.class, - () -> charityUserDAO.getUserCharityUser(null)); - } - - @Test - void getUserCharityUser_throwsOnBlankUuid() { - assertThrows(IllegalArgumentException.class, - () -> charityUserDAO.getUserCharityUser(" ")); - } - - @Test - void getUserCharityUser_returnsCharityWhenFound() throws SQLException { - when(mockStmt.executeQuery()).thenReturn(mockRs); - when(mockRs.next()).thenReturn(true, false); - - String charityId = UUID.randomUUID().toString(); - stubFullCharityRow(charityId); - - Charity result = charityUserDAO.getUserCharityUser(UUID.randomUUID().toString()); - - assertNotNull(result); - assertEquals(charityId, result.getUUID().toString()); - assertEquals("HelpOrg", result.getName()); - assertEquals("We help people", result.getDescription()); - } - - @Test - void getUserCharityUser_returnsNullWhenNotFound() throws SQLException { - when(mockStmt.executeQuery()).thenReturn(mockRs); - when(mockRs.next()).thenReturn(false); - - Charity result = charityUserDAO.getUserCharityUser(UUID.randomUUID().toString()); - - assertNull(result); - } - - @Test - void getUserCharityUser_accumulatesCategoriesAcrossRows() throws SQLException { - when(mockStmt.executeQuery()).thenReturn(mockRs); - when(mockRs.next()).thenReturn(true, true, true, false); - - String charityId = UUID.randomUUID().toString(); - // Same charity across all rows, different category each time - when(mockRs.getString("UUID_charities")).thenReturn(charityId); - when(mockRs.getString("org_number")).thenReturn("123456789"); - when(mockRs.getString("charity_name")).thenReturn("HelpOrg"); - when(mockRs.getString("charity_link")).thenReturn("helporg.com"); - when(mockRs.getString("status")).thenReturn("active"); - when(mockRs.getBoolean("pre_approved")).thenReturn(true); - when(mockRs.getString("description")).thenReturn("We help"); - when(mockRs.getString("logoURL")).thenReturn(null); - when(mockRs.getString("key_values")).thenReturn(null); - when(mockRs.getBytes("logoBLOB")).thenReturn(null); - when(mockRs.getString("category")).thenReturn("Education", "Youth", "Health"); - - Charity result = charityUserDAO.getUserCharityUser(UUID.randomUUID().toString()); - - assertNotNull(result); - assertEquals(3, result.getCategory().size()); - assertTrue(result.getCategory().contains("Education")); - assertTrue(result.getCategory().contains("Youth")); - assertTrue(result.getCategory().contains("Health")); - } - - @Test - void getUserCharityUser_doesNotAddDuplicateCategories() throws SQLException { - when(mockStmt.executeQuery()).thenReturn(mockRs); - when(mockRs.next()).thenReturn(true, true, false); - - String charityId = UUID.randomUUID().toString(); - when(mockRs.getString("UUID_charities")).thenReturn(charityId); - when(mockRs.getString("org_number")).thenReturn("111"); - when(mockRs.getString("charity_name")).thenReturn("Org"); - when(mockRs.getString("charity_link")).thenReturn("org.com"); - when(mockRs.getString("status")).thenReturn("active"); - when(mockRs.getBoolean("pre_approved")).thenReturn(false); - when(mockRs.getString("description")).thenReturn("desc"); - when(mockRs.getString("logoURL")).thenReturn(null); - when(mockRs.getString("key_values")).thenReturn(null); - when(mockRs.getBytes("logoBLOB")).thenReturn(null); - // Same category name twice — should only be added once - when(mockRs.getString("category")).thenReturn("Health", "Health"); - - Charity result = charityUserDAO.getUserCharityUser(UUID.randomUUID().toString()); - - assertEquals(1, result.getCategory().size()); - } - - @Test - void getUserCharityUser_ignoresNullCategory() throws SQLException { - when(mockStmt.executeQuery()).thenReturn(mockRs); - when(mockRs.next()).thenReturn(true, false); - - String charityId = UUID.randomUUID().toString(); - stubFullCharityRow(charityId); // category stubbed as null - - Charity result = charityUserDAO.getUserCharityUser(UUID.randomUUID().toString()); - - assertNotNull(result); - assertTrue(result.getCategory().isEmpty()); - } - - @Test - void getUserCharityUser_passesCorrectUuidToQuery() throws SQLException { - when(mockStmt.executeQuery()).thenReturn(mockRs); - when(mockRs.next()).thenReturn(false); - - String userId = UUID.randomUUID().toString(); - charityUserDAO.getUserCharityUser(userId); - - verify(mockStmt).setString(1, userId); - } - - @Test - void getUserCharityUser_throwsRuntimeExceptionOnSQLException() throws SQLException { - when(mockConn.prepareStatement(anyString())).thenThrow(new SQLException("DB down")); - - assertThrows(RuntimeException.class, - () -> charityUserDAO.getUserCharityUser(UUID.randomUUID().toString())); - } -} \ No newline at end of file + // --- Mocks --- + private DatabaseConnection mockDbConnection; + private Connection mockConn; + private PreparedStatement mockStmt; + private ResultSet mockRs; + + private CharityUserDAO charityUserDAO; + + @BeforeEach + void setUp() throws SQLException { + mockDbConnection = mock(DatabaseConnection.class); + mockConn = mock(Connection.class); + mockStmt = mock(PreparedStatement.class); + mockRs = mock(ResultSet.class); + + when(mockDbConnection.getMySqlConnection()).thenReturn(mockConn); + when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); + + charityUserDAO = new CharityUserDAO(mockDbConnection); + } + + // ---------------------------------------------------------------- + // Helpers + // ---------------------------------------------------------------- + + private Charity buildTestCharity(String charityId) { + return new Charity( + charityId, + "123456789", + "HelpOrg", + "helporg.com", + "active", + true, + "We help people", + null, + null, + null); + } + + private void stubFullCharityRow(String charityId) throws SQLException { + when(mockRs.getString("UUID_charities")).thenReturn(charityId); + when(mockRs.getString("org_number")).thenReturn("123456789"); + when(mockRs.getString("charity_name")).thenReturn("HelpOrg"); + when(mockRs.getString("charity_link")).thenReturn("helporg.com"); + when(mockRs.getString("status")).thenReturn("active"); + when(mockRs.getBoolean("pre_approved")).thenReturn(true); + when(mockRs.getString("description")).thenReturn("We help people"); + when(mockRs.getString("logoURL")).thenReturn(null); + when(mockRs.getString("key_values")).thenReturn(null); + when(mockRs.getBytes("logoBLOB")).thenReturn(null); + when(mockRs.getString("category")).thenReturn(null); + } + + // ---------------------------------------------------------------- + // updateCharityVanityName() + // ---------------------------------------------------------------- + + @Test + void updateCharityVanityName_returnsTrueOnSuccess() throws SQLException { + when(mockStmt.executeUpdate()).thenReturn(1); + + assertTrue( + charityUserDAO.updateCharityVanityName(buildTestCharity(UUID.randomUUID().toString()))); + } + + @Test + void updateCharityVanityName_returnsFalseWhenNoRowsAffected() throws SQLException { + when(mockStmt.executeUpdate()).thenReturn(0); + + assertFalse( + charityUserDAO.updateCharityVanityName(buildTestCharity(UUID.randomUUID().toString()))); + } + + @Test + void updateCharityVanityName_returnsFalseOnSQLException() throws SQLException { + when(mockStmt.executeUpdate()).thenThrow(new SQLException("Update failed")); + + assertFalse( + charityUserDAO.updateCharityVanityName(buildTestCharity(UUID.randomUUID().toString()))); + } + + // ---------------------------------------------------------------- + // updateCharityVanityDescription() + // ---------------------------------------------------------------- + + @Test + void updateCharityVanityDescription_returnsTrueOnSuccess() throws SQLException { + when(mockStmt.executeUpdate()).thenReturn(1); + + assertTrue( + charityUserDAO.updateCharityVanityDescription( + buildTestCharity(UUID.randomUUID().toString()))); + } + + @Test + void updateCharityVanityDescription_returnsFalseWhenNoRowsAffected() throws SQLException { + when(mockStmt.executeUpdate()).thenReturn(0); + + assertFalse( + charityUserDAO.updateCharityVanityDescription( + buildTestCharity(UUID.randomUUID().toString()))); + } + + @Test + void updateCharityVanityDescription_returnsFalseOnSQLException() throws SQLException { + when(mockStmt.executeUpdate()).thenThrow(new SQLException("Update failed")); + + assertFalse( + charityUserDAO.updateCharityVanityDescription( + buildTestCharity(UUID.randomUUID().toString()))); + } + + @Test + void updateCharityVanityDescription_setsCorrectParameters() throws SQLException { + when(mockStmt.executeUpdate()).thenReturn(1); + + String charityId = UUID.randomUUID().toString(); + Charity charity = buildTestCharity(charityId); + + charityUserDAO.updateCharityVanityDescription(charity); + + verify(mockStmt).setString(1, charity.getDescription()); // description + verify(mockStmt).setString(2, charityId); // UUID_charity + } + + // ---------------------------------------------------------------- + // getUserCharityUser() + // ---------------------------------------------------------------- + + @Test + void getUserCharityUser_throwsOnNullUuid() { + assertThrows(IllegalArgumentException.class, () -> charityUserDAO.getUserCharityUser(null)); + } + + @Test + void getUserCharityUser_throwsOnBlankUuid() { + assertThrows(IllegalArgumentException.class, () -> charityUserDAO.getUserCharityUser(" ")); + } + + @Test + void getUserCharityUser_returnsCharityWhenFound() throws SQLException { + when(mockStmt.executeQuery()).thenReturn(mockRs); + when(mockRs.next()).thenReturn(true, false); + + String charityId = UUID.randomUUID().toString(); + stubFullCharityRow(charityId); + + Charity result = charityUserDAO.getUserCharityUser(UUID.randomUUID().toString()); + + assertNotNull(result); + assertEquals(charityId, result.getUUID().toString()); + assertEquals("HelpOrg", result.getName()); + assertEquals("We help people", result.getDescription()); + } + + @Test + void getUserCharityUser_returnsNullWhenNotFound() throws SQLException { + when(mockStmt.executeQuery()).thenReturn(mockRs); + when(mockRs.next()).thenReturn(false); + + Charity result = charityUserDAO.getUserCharityUser(UUID.randomUUID().toString()); + + assertNull(result); + } + + @Test + void getUserCharityUser_accumulatesCategoriesAcrossRows() throws SQLException { + when(mockStmt.executeQuery()).thenReturn(mockRs); + when(mockRs.next()).thenReturn(true, true, true, false); + + String charityId = UUID.randomUUID().toString(); + // Same charity across all rows, different category each time + when(mockRs.getString("UUID_charities")).thenReturn(charityId); + when(mockRs.getString("org_number")).thenReturn("123456789"); + when(mockRs.getString("charity_name")).thenReturn("HelpOrg"); + when(mockRs.getString("charity_link")).thenReturn("helporg.com"); + when(mockRs.getString("status")).thenReturn("active"); + when(mockRs.getBoolean("pre_approved")).thenReturn(true); + when(mockRs.getString("description")).thenReturn("We help"); + when(mockRs.getString("logoURL")).thenReturn(null); + when(mockRs.getString("key_values")).thenReturn(null); + when(mockRs.getBytes("logoBLOB")).thenReturn(null); + when(mockRs.getString("category")).thenReturn("Education", "Youth", "Health"); + + Charity result = charityUserDAO.getUserCharityUser(UUID.randomUUID().toString()); + + assertNotNull(result); + assertEquals(3, result.getCategory().size()); + assertTrue(result.getCategory().contains("Education")); + assertTrue(result.getCategory().contains("Youth")); + assertTrue(result.getCategory().contains("Health")); + } + + @Test + void getUserCharityUser_doesNotAddDuplicateCategories() throws SQLException { + when(mockStmt.executeQuery()).thenReturn(mockRs); + when(mockRs.next()).thenReturn(true, true, false); + + String charityId = UUID.randomUUID().toString(); + when(mockRs.getString("UUID_charities")).thenReturn(charityId); + when(mockRs.getString("org_number")).thenReturn("111"); + when(mockRs.getString("charity_name")).thenReturn("Org"); + when(mockRs.getString("charity_link")).thenReturn("org.com"); + when(mockRs.getString("status")).thenReturn("active"); + when(mockRs.getBoolean("pre_approved")).thenReturn(false); + when(mockRs.getString("description")).thenReturn("desc"); + when(mockRs.getString("logoURL")).thenReturn(null); + when(mockRs.getString("key_values")).thenReturn(null); + when(mockRs.getBytes("logoBLOB")).thenReturn(null); + // Same category name twice — should only be added once + when(mockRs.getString("category")).thenReturn("Health", "Health"); + + Charity result = charityUserDAO.getUserCharityUser(UUID.randomUUID().toString()); + + assertEquals(1, result.getCategory().size()); + } + + @Test + void getUserCharityUser_ignoresNullCategory() throws SQLException { + when(mockStmt.executeQuery()).thenReturn(mockRs); + when(mockRs.next()).thenReturn(true, false); + + String charityId = UUID.randomUUID().toString(); + stubFullCharityRow(charityId); // category stubbed as null + + Charity result = charityUserDAO.getUserCharityUser(UUID.randomUUID().toString()); + + assertNotNull(result); + assertTrue(result.getCategory().isEmpty()); + } + + @Test + void getUserCharityUser_passesCorrectUuidToQuery() throws SQLException { + when(mockStmt.executeQuery()).thenReturn(mockRs); + when(mockRs.next()).thenReturn(false); + + String userId = UUID.randomUUID().toString(); + charityUserDAO.getUserCharityUser(userId); + + verify(mockStmt).setString(1, userId); + } + + @Test + void getUserCharityUser_throwsRuntimeExceptionOnSQLException() throws SQLException { + when(mockConn.prepareStatement(anyString())).thenThrow(new SQLException("DB down")); + + assertThrows( + RuntimeException.class, + () -> charityUserDAO.getUserCharityUser(UUID.randomUUID().toString())); + } +} diff --git a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/database/DAO/DonationDAOTest.java b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/database/DAO/DonationDAOTest.java index 52f11778..2fb7fc2e 100644 --- a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/database/DAO/DonationDAOTest.java +++ b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/database/DAO/DonationDAOTest.java @@ -1,38 +1,38 @@ package ntnu.systemutvikling.team6.database.DAO; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +import java.sql.*; +import java.time.LocalDate; +import java.util.UUID; import ntnu.systemutvikling.team6.database.DatabaseConnection; import ntnu.systemutvikling.team6.models.Charity; import ntnu.systemutvikling.team6.models.Donation; import ntnu.systemutvikling.team6.models.registry.DonationRegistry; import ntnu.systemutvikling.team6.models.user.*; import org.junit.jupiter.api.*; -import java.sql.*; -import java.time.LocalDate; -import java.util.UUID; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; -/** - * Tests made by Claude AI: Sonnet 4.6, on 24.04.206 - */ +/** Tests made by Claude AI: Sonnet 4.6, on 24.04.206 */ public class DonationDAOTest { // --- Mocks --- private DatabaseConnection mockDbConnection; - private Connection mockConn; - private PreparedStatement mockStmt; - private Statement mockRawStmt; // getDonationFromDB() uses createStatement(), not prepareStatement() - private ResultSet mockRs; + private Connection mockConn; + private PreparedStatement mockStmt; + private Statement + mockRawStmt; // getDonationFromDB() uses createStatement(), not prepareStatement() + private ResultSet mockRs; private DonationDAO donationDAO; @BeforeEach void setUp() throws SQLException { mockDbConnection = mock(DatabaseConnection.class); - mockConn = mock(Connection.class); - mockStmt = mock(PreparedStatement.class); - mockRawStmt = mock(Statement.class); - mockRs = mock(ResultSet.class); + mockConn = mock(Connection.class); + mockStmt = mock(PreparedStatement.class); + mockRawStmt = mock(Statement.class); + mockRs = mock(ResultSet.class); when(mockDbConnection.getMySqlConnection()).thenReturn(mockConn); when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); @@ -46,13 +46,9 @@ void setUp() throws SQLException { // ---------------------------------------------------------------- private User buildTestUser(String userId) { - User user = new User( - userId, - "TestUser", - "test@example.com", - "hashedpassword", - Role.NORMAL_USER.toString() - ); + User user = + new User( + userId, "TestUser", "test@example.com", "hashedpassword", Role.NORMAL_USER.toString()); user.setSettings(new Settings(false, Language.ENGLISH, true)); user.setInbox(new Inbox()); return user; @@ -60,32 +56,28 @@ private User buildTestUser(String userId) { private Charity buildTestCharity(String charityId) { return new Charity( - charityId, - "123456789", - "HelpOrg", - "helporg.com", - "active", - true, - "We help people", - null, - null, - null - ); + charityId, + "123456789", + "HelpOrg", + "helporg.com", + "active", + true, + "We help people", + null, + null, + null); } private Donation buildTestDonation(String donationId, User user, Charity charity) { - return new Donation( - donationId, - 100.0, - LocalDate.now(), - charity, - user, - false - ); + return new Donation(donationId, 100.0, LocalDate.now(), charity, user, false); } - /** Stubs all ResultSet columns shared by getDonationFromDB, getDonationForUser, getDonationForCharity. */ - private void stubFullDonationRow(String donationId, String charityId, String userId) throws SQLException { + /** + * Stubs all ResultSet columns shared by getDonationFromDB, getDonationForUser, + * getDonationForCharity. + */ + private void stubFullDonationRow(String donationId, String charityId, String userId) + throws SQLException { when(mockRs.getString("UUID_Donations")).thenReturn(donationId); when(mockRs.getDouble("amount")).thenReturn(250.0); when(mockRs.getBoolean("isAnonymous")).thenReturn(false); @@ -119,8 +111,8 @@ void getDonationFromDB_returnsRegistryWithDonations() throws SQLException { when(mockRs.next()).thenReturn(true, false); String donationId = UUID.randomUUID().toString(); - String charityId = UUID.randomUUID().toString(); - String userId = UUID.randomUUID().toString(); + String charityId = UUID.randomUUID().toString(); + String userId = UUID.randomUUID().toString(); stubFullDonationRow(donationId, charityId, userId); DonationRegistry registry = donationDAO.getDonationFromDB(); @@ -129,7 +121,8 @@ void getDonationFromDB_returnsRegistryWithDonations() throws SQLException { assertEquals(1, registry.getAllDonations().size()); assertEquals(donationId, registry.getAllDonations().getFirst().getDonationID().toString()); assertEquals(250.0, registry.getAllDonations().getFirst().getAmount()); - assertEquals(charityId, registry.getAllDonations().getFirst().getCharity().getUUID().toString()); + assertEquals( + charityId, registry.getAllDonations().getFirst().getCharity().getUUID().toString()); assertEquals(userId, registry.getAllDonations().getFirst().getDonor().getId().toString()); } @@ -149,8 +142,8 @@ void getDonationFromDB_returnsMultipleDonations() throws SQLException { when(mockRawStmt.executeQuery(anyString())).thenReturn(mockRs); when(mockRs.next()).thenReturn(true, true, false); - when(mockRs.getString("UUID_Donations")).thenReturn( - UUID.randomUUID().toString(), UUID.randomUUID().toString()); + when(mockRs.getString("UUID_Donations")) + .thenReturn(UUID.randomUUID().toString(), UUID.randomUUID().toString()); when(mockRs.getDouble("amount")).thenReturn(100.0, 200.0); when(mockRs.getBoolean("isAnonymous")).thenReturn(false); when(mockRs.getDate("date")).thenReturn(Date.valueOf(LocalDate.now())); @@ -186,8 +179,8 @@ void getDonationForUser_returnsRegistryWithDonations() throws SQLException { when(mockRs.next()).thenReturn(true, false); String donationId = UUID.randomUUID().toString(); - String charityId = UUID.randomUUID().toString(); - String userId = UUID.randomUUID().toString(); + String charityId = UUID.randomUUID().toString(); + String userId = UUID.randomUUID().toString(); stubFullDonationRow(donationId, charityId, userId); DonationRegistry registry = donationDAO.getDonationForUser(userId); @@ -224,8 +217,8 @@ void getDonationForUser_passesCorrectUserIdToQuery() throws SQLException { void getDonationForUser_throwsRuntimeExceptionOnSQLException() throws SQLException { when(mockConn.prepareStatement(anyString())).thenThrow(new SQLException("Query failed")); - assertThrows(RuntimeException.class, - () -> donationDAO.getDonationForUser(UUID.randomUUID().toString())); + assertThrows( + RuntimeException.class, () -> donationDAO.getDonationForUser(UUID.randomUUID().toString())); } // ---------------------------------------------------------------- @@ -238,8 +231,8 @@ void getDonationForCharity_returnsRegistryWithDonations() throws SQLException { when(mockRs.next()).thenReturn(true, false); String donationId = UUID.randomUUID().toString(); - String charityId = UUID.randomUUID().toString(); - String userId = UUID.randomUUID().toString(); + String charityId = UUID.randomUUID().toString(); + String userId = UUID.randomUUID().toString(); stubFullDonationRow(donationId, charityId, userId); DonationRegistry registry = donationDAO.getDonationForCharity(charityId); @@ -247,7 +240,8 @@ void getDonationForCharity_returnsRegistryWithDonations() throws SQLException { assertNotNull(registry); assertEquals(1, registry.getAllDonations().size()); assertEquals(donationId, registry.getAllDonations().getFirst().getDonationID().toString()); - assertEquals(charityId, registry.getAllDonations().getFirst().getCharity().getUUID().toString()); + assertEquals( + charityId, registry.getAllDonations().getFirst().getCharity().getUUID().toString()); } @Test @@ -276,8 +270,9 @@ void getDonationForCharity_passesCorrectCharityIdToQuery() throws SQLException { void getDonationForCharity_throwsRuntimeExceptionOnSQLException() throws SQLException { when(mockConn.prepareStatement(anyString())).thenThrow(new SQLException("Query failed")); - assertThrows(RuntimeException.class, - () -> donationDAO.getDonationForCharity(UUID.randomUUID().toString())); + assertThrows( + RuntimeException.class, + () -> donationDAO.getDonationForCharity(UUID.randomUUID().toString())); } // ---------------------------------------------------------------- @@ -287,9 +282,9 @@ void getDonationForCharity_throwsRuntimeExceptionOnSQLException() throws SQLExce @Test void addDonation_executesSuccessfully() throws SQLException { String donationId = UUID.randomUUID().toString(); - String charityId = UUID.randomUUID().toString(); - String userId = UUID.randomUUID().toString(); - User user = buildTestUser(userId); + String charityId = UUID.randomUUID().toString(); + String userId = UUID.randomUUID().toString(); + User user = buildTestUser(userId); Donation donation = buildTestDonation(donationId, user, buildTestCharity(charityId)); donationDAO.addDonation(donation); @@ -302,19 +297,19 @@ void addDonation_executesSuccessfully() throws SQLException { @Test void addDonation_setsCorrectParameterOrder() throws SQLException { String donationId = UUID.randomUUID().toString(); - String charityId = UUID.randomUUID().toString(); - String userId = UUID.randomUUID().toString(); - User user = buildTestUser(userId); + String charityId = UUID.randomUUID().toString(); + String userId = UUID.randomUUID().toString(); + User user = buildTestUser(userId); Donation donation = buildTestDonation(donationId, user, buildTestCharity(charityId)); donationDAO.addDonation(donation); - verify(mockStmt).setString(1, donationId); // UUID_Donations - verify(mockStmt).setDouble(2, donation.getAmount()); // amount - verify(mockStmt).setBoolean(3, user.getSettings().isAnonymous()); // isAnonymous - verify(mockStmt).setDate(4, Date.valueOf(donation.getDate())); // date - verify(mockStmt).setString(5, charityId); // charity_id - verify(mockStmt).setString(6, userId); // user_id + verify(mockStmt).setString(1, donationId); // UUID_Donations + verify(mockStmt).setDouble(2, donation.getAmount()); // amount + verify(mockStmt).setBoolean(3, user.getSettings().isAnonymous()); // isAnonymous + verify(mockStmt).setDate(4, Date.valueOf(donation.getDate())); // date + verify(mockStmt).setString(5, charityId); // charity_id + verify(mockStmt).setString(6, userId); // user_id } @Test @@ -323,13 +318,12 @@ void addDonation_setsAnonymousTrueWhenUserIsAnonymous() throws SQLException { User anonymousUser = buildTestUser(userId); anonymousUser.setSettings(new Settings(true, Language.ENGLISH, false)); - donationDAO.addDonation(buildTestDonation( + donationDAO.addDonation( + buildTestDonation( UUID.randomUUID().toString(), anonymousUser, - buildTestCharity(UUID.randomUUID().toString()) - )); + buildTestCharity(UUID.randomUUID().toString()))); verify(mockStmt).setBoolean(3, true); } - -} \ No newline at end of file +} diff --git a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/database/DAO/FavouritesDAOTest.java b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/database/DAO/FavouritesDAOTest.java index b11e934b..6ae16549 100644 --- a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/database/DAO/FavouritesDAOTest.java +++ b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/database/DAO/FavouritesDAOTest.java @@ -1,323 +1,316 @@ package ntnu.systemutvikling.team6.database.DAO; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +import java.sql.*; +import java.util.List; +import java.util.UUID; import ntnu.systemutvikling.team6.database.DatabaseConnection; import ntnu.systemutvikling.team6.models.Charity; import ntnu.systemutvikling.team6.models.user.*; import org.junit.jupiter.api.*; -import java.sql.*; -import java.util.List; -import java.util.UUID; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; -/** - * Tests made by Claude AI: Sonnet 4.6, on 24.04.206 - */ +/** Tests made by Claude AI: Sonnet 4.6, on 24.04.206 */ public class FavouritesDAOTest { - // --- Mocks --- - private DatabaseConnection mockDbConnection; - private Connection mockConn; - private PreparedStatement mockStmt; - private ResultSet mockRs; - - private FavouritesDAO favouritesDAO; - - @BeforeEach - void setUp() throws SQLException { - mockDbConnection = mock(DatabaseConnection.class); - mockConn = mock(Connection.class); - mockStmt = mock(PreparedStatement.class); - mockRs = mock(ResultSet.class); - - when(mockDbConnection.getMySqlConnection()).thenReturn(mockConn); - when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); - - favouritesDAO = new FavouritesDAO(mockDbConnection); - } - - // ---------------------------------------------------------------- - // Helpers - // ---------------------------------------------------------------- - - private User buildTestUser(String userId) { - User user = new User( - userId, - "TestUser", - "test@example.com", - "hashedpassword", - Role.NORMAL_USER.toString() - ); - user.setSettings(new Settings(false, Language.ENGLISH, true)); - user.setInbox(new Inbox()); - return user; - } - - private Charity buildTestCharity(String charityId) { - return new Charity( - charityId, - "123456789", - "HelpOrg", - "helporg.com", - "active", - true, - "We help people", - null, - null, - null - ); - } - - // ---------------------------------------------------------------- - // isFavourite() - // ---------------------------------------------------------------- - - @Test - void isFavourite_returnsTrueWhenRowExists() throws SQLException { - when(mockStmt.executeQuery()).thenReturn(mockRs); - when(mockRs.next()).thenReturn(true); - - String userId = UUID.randomUUID().toString(); - String charityId = UUID.randomUUID().toString(); - - assertTrue(favouritesDAO.isFavourite(buildTestUser(userId), buildTestCharity(charityId))); - } - - @Test - void isFavourite_returnsFalseWhenNoRowExists() throws SQLException { - when(mockStmt.executeQuery()).thenReturn(mockRs); - when(mockRs.next()).thenReturn(false); - - assertFalse(favouritesDAO.isFavourite( - buildTestUser(UUID.randomUUID().toString()), - buildTestCharity(UUID.randomUUID().toString()) - )); - } - - @Test - void isFavourite_returnsFalseOnSQLException() throws SQLException { - when(mockStmt.executeQuery()).thenThrow(new SQLException("Query failed")); - - assertFalse(favouritesDAO.isFavourite( - buildTestUser(UUID.randomUUID().toString()), - buildTestCharity(UUID.randomUUID().toString()) - )); - } - - @Test - void isFavourite_setsCorrectParameters() throws SQLException { - when(mockStmt.executeQuery()).thenReturn(mockRs); - when(mockRs.next()).thenReturn(false); - - String userId = UUID.randomUUID().toString(); - String charityId = UUID.randomUUID().toString(); - - favouritesDAO.isFavourite(buildTestUser(userId), buildTestCharity(charityId)); - - verify(mockStmt).setString(1, userId); // Favourer - verify(mockStmt).setString(2, charityId); // Favourite_Charity - } - - // ---------------------------------------------------------------- - // addFavourite() - // ---------------------------------------------------------------- - - @Test - void addFavourite_returnsTrueOnSuccess() throws SQLException { - when(mockStmt.executeUpdate()).thenReturn(1); - - assertTrue(favouritesDAO.addFavourite( - buildTestUser(UUID.randomUUID().toString()), - buildTestCharity(UUID.randomUUID().toString()) - )); - } - - @Test - void addFavourite_returnsFalseWhenNoRowsAffected() throws SQLException { - when(mockStmt.executeUpdate()).thenReturn(0); - - assertFalse(favouritesDAO.addFavourite( - buildTestUser(UUID.randomUUID().toString()), - buildTestCharity(UUID.randomUUID().toString()) - )); - } - - @Test - void addFavourite_returnsFalseOnSQLException() throws SQLException { - when(mockStmt.executeUpdate()).thenThrow(new SQLException("Insert failed")); - - assertFalse(favouritesDAO.addFavourite( - buildTestUser(UUID.randomUUID().toString()), - buildTestCharity(UUID.randomUUID().toString()) - )); - } - - @Test - void addFavourite_setsCorrectParameters() throws SQLException { - when(mockStmt.executeUpdate()).thenReturn(1); - - String userId = UUID.randomUUID().toString(); - String charityId = UUID.randomUUID().toString(); - - favouritesDAO.addFavourite(buildTestUser(userId), buildTestCharity(charityId)); - - verify(mockStmt).setString(1, userId); // Favourer - verify(mockStmt).setString(2, charityId); // Favourite_charity - } - - // ---------------------------------------------------------------- - // removeFavourite() - // ---------------------------------------------------------------- - - @Test - void removeFavourite_returnsTrueOnSuccess() throws SQLException { - when(mockStmt.executeUpdate()).thenReturn(1); - - assertTrue(favouritesDAO.removeFavourite( - buildTestUser(UUID.randomUUID().toString()), - buildTestCharity(UUID.randomUUID().toString()) - )); - } - - @Test - void removeFavourite_returnsFalseWhenNoRowsAffected() throws SQLException { - when(mockStmt.executeUpdate()).thenReturn(0); - - assertFalse(favouritesDAO.removeFavourite( - buildTestUser(UUID.randomUUID().toString()), - buildTestCharity(UUID.randomUUID().toString()) - )); - } - - @Test - void removeFavourite_returnsFalseOnSQLException() throws SQLException { - when(mockStmt.executeUpdate()).thenThrow(new SQLException("Delete failed")); - - assertFalse(favouritesDAO.removeFavourite( - buildTestUser(UUID.randomUUID().toString()), - buildTestCharity(UUID.randomUUID().toString()) - )); - } - - @Test - void removeFavourite_setsCorrectParameters() throws SQLException { - when(mockStmt.executeUpdate()).thenReturn(1); - - String userId = UUID.randomUUID().toString(); - String charityId = UUID.randomUUID().toString(); - - favouritesDAO.removeFavourite(buildTestUser(userId), buildTestCharity(charityId)); - - verify(mockStmt).setString(1, userId); // Favourer - verify(mockStmt).setString(2, charityId); // Favourite_charity - } - - // ---------------------------------------------------------------- - // getFavouritesForUser() - // ---------------------------------------------------------------- - - @Test - void getFavouritesForUser_returnsCharityList() throws SQLException { - when(mockStmt.executeQuery()).thenReturn(mockRs); - when(mockRs.next()).thenReturn(true, false); - - String charityId = UUID.randomUUID().toString(); - when(mockRs.getString("UUID_charities")).thenReturn(charityId); - when(mockRs.getString("org_number")).thenReturn("9999"); - when(mockRs.getString("charity_name")).thenReturn("SaveAll"); - when(mockRs.getString("charity_link")).thenReturn("saveall.org"); - when(mockRs.getString("status")).thenReturn("active"); - when(mockRs.getBoolean("pre_approved")).thenReturn(true); - when(mockRs.getString("description")).thenReturn("Saving people"); - when(mockRs.getString("logoURL")).thenReturn(null); - when(mockRs.getString("key_values")).thenReturn(null); - when(mockRs.getBytes("logoBLOB")).thenReturn(null); - when(mockRs.getString("category")).thenReturn(null); // no category - - List result = favouritesDAO.getFavouritesForUser(UUID.randomUUID().toString()); - - assertNotNull(result); - assertEquals(1, result.size()); - assertEquals(charityId, result.getFirst().getUUID().toString()); - assertEquals("SaveAll", result.getFirst().getName()); - } - - @Test - void getFavouritesForUser_returnsEmptyListWhenNoFavourites() throws SQLException { - when(mockStmt.executeQuery()).thenReturn(mockRs); - when(mockRs.next()).thenReturn(false); - - List result = favouritesDAO.getFavouritesForUser(UUID.randomUUID().toString()); - - assertNotNull(result); - assertTrue(result.isEmpty()); - } - - @Test - void getFavouritesForUser_doesNotDuplicateCharityAcrossMultipleCategoryRows() throws SQLException { - // Same charity appearing in two rows (one per category) should produce only one Charity object - when(mockStmt.executeQuery()).thenReturn(mockRs); - when(mockRs.next()).thenReturn(true, true, false); - - String charityId = UUID.randomUUID().toString(); - when(mockRs.getString("UUID_charities")).thenReturn(charityId); - when(mockRs.getString("org_number")).thenReturn("1111"); - when(mockRs.getString("charity_name")).thenReturn("EduOrg"); - when(mockRs.getString("charity_link")).thenReturn("eduorg.com"); - when(mockRs.getString("status")).thenReturn("active"); - when(mockRs.getBoolean("pre_approved")).thenReturn(false); - when(mockRs.getString("description")).thenReturn("Education"); - when(mockRs.getString("logoURL")).thenReturn(null); - when(mockRs.getString("key_values")).thenReturn(null); - when(mockRs.getBytes("logoBLOB")).thenReturn(null); - when(mockRs.getString("category")).thenReturn("Education", "Youth"); - - List result = favouritesDAO.getFavouritesForUser(UUID.randomUUID().toString()); - - assertEquals(1, result.size()); - assertEquals(2, result.getFirst().getCategory().size()); - assertTrue(result.getFirst().getCategory().contains("Education")); - assertTrue(result.getFirst().getCategory().contains("Youth")); - } - - @Test - void getFavouritesForUser_returnsDistinctCharities() throws SQLException { - when(mockStmt.executeQuery()).thenReturn(mockRs); - String userId1 = UUID.randomUUID().toString(); - - when(mockRs.next()).thenReturn(true, true, false); - - String charityId1 = UUID.randomUUID().toString(); - String charityId2 = UUID.randomUUID().toString(); - - when(mockRs.getString("UUID_charities")).thenReturn(charityId1, charityId2); - when(mockRs.getString("org_number")).thenReturn("1111", "2222"); - when(mockRs.getString("charity_name")).thenReturn("OrgA", "OrgB"); - when(mockRs.getString("charity_link")).thenReturn("orga.com", "orgb.com"); - when(mockRs.getString("status")).thenReturn("active"); - when(mockRs.getBoolean("pre_approved")).thenReturn(true); - when(mockRs.getString("description")).thenReturn("Desc"); - when(mockRs.getString("logoURL")).thenReturn(null); - when(mockRs.getString("key_values")).thenReturn(null); - when(mockRs.getBytes("logoBLOB")).thenReturn(null); - when(mockRs.getString("category")).thenReturn(null); - - List result = favouritesDAO.getFavouritesForUser(userId1); - - assertEquals(1, result.size()); - verify(mockStmt).setString(1, userId1); - - } - - - @Test - void getFavouritesForUser_passesCorrectUserIdToQuery() throws SQLException { - when(mockStmt.executeQuery()).thenReturn(mockRs); - when(mockRs.next()).thenReturn(false); - - String userId = UUID.randomUUID().toString(); - favouritesDAO.getFavouritesForUser(userId); - - verify(mockStmt).setString(1, userId); - } -} \ No newline at end of file + // --- Mocks --- + private DatabaseConnection mockDbConnection; + private Connection mockConn; + private PreparedStatement mockStmt; + private ResultSet mockRs; + + private FavouritesDAO favouritesDAO; + + @BeforeEach + void setUp() throws SQLException { + mockDbConnection = mock(DatabaseConnection.class); + mockConn = mock(Connection.class); + mockStmt = mock(PreparedStatement.class); + mockRs = mock(ResultSet.class); + + when(mockDbConnection.getMySqlConnection()).thenReturn(mockConn); + when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); + + favouritesDAO = new FavouritesDAO(mockDbConnection); + } + + // ---------------------------------------------------------------- + // Helpers + // ---------------------------------------------------------------- + + private User buildTestUser(String userId) { + User user = + new User( + userId, "TestUser", "test@example.com", "hashedpassword", Role.NORMAL_USER.toString()); + user.setSettings(new Settings(false, Language.ENGLISH, true)); + user.setInbox(new Inbox()); + return user; + } + + private Charity buildTestCharity(String charityId) { + return new Charity( + charityId, + "123456789", + "HelpOrg", + "helporg.com", + "active", + true, + "We help people", + null, + null, + null); + } + + // ---------------------------------------------------------------- + // isFavourite() + // ---------------------------------------------------------------- + + @Test + void isFavourite_returnsTrueWhenRowExists() throws SQLException { + when(mockStmt.executeQuery()).thenReturn(mockRs); + when(mockRs.next()).thenReturn(true); + + String userId = UUID.randomUUID().toString(); + String charityId = UUID.randomUUID().toString(); + + assertTrue(favouritesDAO.isFavourite(buildTestUser(userId), buildTestCharity(charityId))); + } + + @Test + void isFavourite_returnsFalseWhenNoRowExists() throws SQLException { + when(mockStmt.executeQuery()).thenReturn(mockRs); + when(mockRs.next()).thenReturn(false); + + assertFalse( + favouritesDAO.isFavourite( + buildTestUser(UUID.randomUUID().toString()), + buildTestCharity(UUID.randomUUID().toString()))); + } + + @Test + void isFavourite_returnsFalseOnSQLException() throws SQLException { + when(mockStmt.executeQuery()).thenThrow(new SQLException("Query failed")); + + assertFalse( + favouritesDAO.isFavourite( + buildTestUser(UUID.randomUUID().toString()), + buildTestCharity(UUID.randomUUID().toString()))); + } + + @Test + void isFavourite_setsCorrectParameters() throws SQLException { + when(mockStmt.executeQuery()).thenReturn(mockRs); + when(mockRs.next()).thenReturn(false); + + String userId = UUID.randomUUID().toString(); + String charityId = UUID.randomUUID().toString(); + + favouritesDAO.isFavourite(buildTestUser(userId), buildTestCharity(charityId)); + + verify(mockStmt).setString(1, userId); // Favourer + verify(mockStmt).setString(2, charityId); // Favourite_Charity + } + + // ---------------------------------------------------------------- + // addFavourite() + // ---------------------------------------------------------------- + + @Test + void addFavourite_returnsTrueOnSuccess() throws SQLException { + when(mockStmt.executeUpdate()).thenReturn(1); + + assertTrue( + favouritesDAO.addFavourite( + buildTestUser(UUID.randomUUID().toString()), + buildTestCharity(UUID.randomUUID().toString()))); + } + + @Test + void addFavourite_returnsFalseWhenNoRowsAffected() throws SQLException { + when(mockStmt.executeUpdate()).thenReturn(0); + + assertFalse( + favouritesDAO.addFavourite( + buildTestUser(UUID.randomUUID().toString()), + buildTestCharity(UUID.randomUUID().toString()))); + } + + @Test + void addFavourite_returnsFalseOnSQLException() throws SQLException { + when(mockStmt.executeUpdate()).thenThrow(new SQLException("Insert failed")); + + assertFalse( + favouritesDAO.addFavourite( + buildTestUser(UUID.randomUUID().toString()), + buildTestCharity(UUID.randomUUID().toString()))); + } + + @Test + void addFavourite_setsCorrectParameters() throws SQLException { + when(mockStmt.executeUpdate()).thenReturn(1); + + String userId = UUID.randomUUID().toString(); + String charityId = UUID.randomUUID().toString(); + + favouritesDAO.addFavourite(buildTestUser(userId), buildTestCharity(charityId)); + + verify(mockStmt).setString(1, userId); // Favourer + verify(mockStmt).setString(2, charityId); // Favourite_charity + } + + // ---------------------------------------------------------------- + // removeFavourite() + // ---------------------------------------------------------------- + + @Test + void removeFavourite_returnsTrueOnSuccess() throws SQLException { + when(mockStmt.executeUpdate()).thenReturn(1); + + assertTrue( + favouritesDAO.removeFavourite( + buildTestUser(UUID.randomUUID().toString()), + buildTestCharity(UUID.randomUUID().toString()))); + } + + @Test + void removeFavourite_returnsFalseWhenNoRowsAffected() throws SQLException { + when(mockStmt.executeUpdate()).thenReturn(0); + + assertFalse( + favouritesDAO.removeFavourite( + buildTestUser(UUID.randomUUID().toString()), + buildTestCharity(UUID.randomUUID().toString()))); + } + + @Test + void removeFavourite_returnsFalseOnSQLException() throws SQLException { + when(mockStmt.executeUpdate()).thenThrow(new SQLException("Delete failed")); + + assertFalse( + favouritesDAO.removeFavourite( + buildTestUser(UUID.randomUUID().toString()), + buildTestCharity(UUID.randomUUID().toString()))); + } + + @Test + void removeFavourite_setsCorrectParameters() throws SQLException { + when(mockStmt.executeUpdate()).thenReturn(1); + + String userId = UUID.randomUUID().toString(); + String charityId = UUID.randomUUID().toString(); + + favouritesDAO.removeFavourite(buildTestUser(userId), buildTestCharity(charityId)); + + verify(mockStmt).setString(1, userId); // Favourer + verify(mockStmt).setString(2, charityId); // Favourite_charity + } + + // ---------------------------------------------------------------- + // getFavouritesForUser() + // ---------------------------------------------------------------- + + @Test + void getFavouritesForUser_returnsCharityList() throws SQLException { + when(mockStmt.executeQuery()).thenReturn(mockRs); + when(mockRs.next()).thenReturn(true, false); + + String charityId = UUID.randomUUID().toString(); + when(mockRs.getString("UUID_charities")).thenReturn(charityId); + when(mockRs.getString("org_number")).thenReturn("9999"); + when(mockRs.getString("charity_name")).thenReturn("SaveAll"); + when(mockRs.getString("charity_link")).thenReturn("saveall.org"); + when(mockRs.getString("status")).thenReturn("active"); + when(mockRs.getBoolean("pre_approved")).thenReturn(true); + when(mockRs.getString("description")).thenReturn("Saving people"); + when(mockRs.getString("logoURL")).thenReturn(null); + when(mockRs.getString("key_values")).thenReturn(null); + when(mockRs.getBytes("logoBLOB")).thenReturn(null); + when(mockRs.getString("category")).thenReturn(null); // no category + + List result = favouritesDAO.getFavouritesForUser(UUID.randomUUID().toString()); + + assertNotNull(result); + assertEquals(1, result.size()); + assertEquals(charityId, result.getFirst().getUUID().toString()); + assertEquals("SaveAll", result.getFirst().getName()); + } + + @Test + void getFavouritesForUser_returnsEmptyListWhenNoFavourites() throws SQLException { + when(mockStmt.executeQuery()).thenReturn(mockRs); + when(mockRs.next()).thenReturn(false); + + List result = favouritesDAO.getFavouritesForUser(UUID.randomUUID().toString()); + + assertNotNull(result); + assertTrue(result.isEmpty()); + } + + @Test + void getFavouritesForUser_doesNotDuplicateCharityAcrossMultipleCategoryRows() + throws SQLException { + // Same charity appearing in two rows (one per category) should produce only one Charity object + when(mockStmt.executeQuery()).thenReturn(mockRs); + when(mockRs.next()).thenReturn(true, true, false); + + String charityId = UUID.randomUUID().toString(); + when(mockRs.getString("UUID_charities")).thenReturn(charityId); + when(mockRs.getString("org_number")).thenReturn("1111"); + when(mockRs.getString("charity_name")).thenReturn("EduOrg"); + when(mockRs.getString("charity_link")).thenReturn("eduorg.com"); + when(mockRs.getString("status")).thenReturn("active"); + when(mockRs.getBoolean("pre_approved")).thenReturn(false); + when(mockRs.getString("description")).thenReturn("Education"); + when(mockRs.getString("logoURL")).thenReturn(null); + when(mockRs.getString("key_values")).thenReturn(null); + when(mockRs.getBytes("logoBLOB")).thenReturn(null); + when(mockRs.getString("category")).thenReturn("Education", "Youth"); + + List result = favouritesDAO.getFavouritesForUser(UUID.randomUUID().toString()); + + assertEquals(1, result.size()); + assertEquals(2, result.getFirst().getCategory().size()); + assertTrue(result.getFirst().getCategory().contains("Education")); + assertTrue(result.getFirst().getCategory().contains("Youth")); + } + + @Test + void getFavouritesForUser_returnsDistinctCharities() throws SQLException { + when(mockStmt.executeQuery()).thenReturn(mockRs); + String userId1 = UUID.randomUUID().toString(); + + when(mockRs.next()).thenReturn(true, true, false); + + String charityId1 = UUID.randomUUID().toString(); + String charityId2 = UUID.randomUUID().toString(); + + when(mockRs.getString("UUID_charities")).thenReturn(charityId1, charityId2); + when(mockRs.getString("org_number")).thenReturn("1111", "2222"); + when(mockRs.getString("charity_name")).thenReturn("OrgA", "OrgB"); + when(mockRs.getString("charity_link")).thenReturn("orga.com", "orgb.com"); + when(mockRs.getString("status")).thenReturn("active"); + when(mockRs.getBoolean("pre_approved")).thenReturn(true); + when(mockRs.getString("description")).thenReturn("Desc"); + when(mockRs.getString("logoURL")).thenReturn(null); + when(mockRs.getString("key_values")).thenReturn(null); + when(mockRs.getBytes("logoBLOB")).thenReturn(null); + when(mockRs.getString("category")).thenReturn(null); + + List result = favouritesDAO.getFavouritesForUser(userId1); + + assertEquals(1, result.size()); + verify(mockStmt).setString(1, userId1); + } + + @Test + void getFavouritesForUser_passesCorrectUserIdToQuery() throws SQLException { + when(mockStmt.executeQuery()).thenReturn(mockRs); + when(mockRs.next()).thenReturn(false); + + String userId = UUID.randomUUID().toString(); + favouritesDAO.getFavouritesForUser(userId); + + verify(mockStmt).setString(1, userId); + } +} diff --git a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/database/DAO/FeedbackDAOTest.java b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/database/DAO/FeedbackDAOTest.java index 8a4b17fc..1e0ee51c 100644 --- a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/database/DAO/FeedbackDAOTest.java +++ b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/database/DAO/FeedbackDAOTest.java @@ -1,242 +1,231 @@ package ntnu.systemutvikling.team6.database.DAO; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +import java.sql.*; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.UUID; import ntnu.systemutvikling.team6.database.DatabaseConnection; import ntnu.systemutvikling.team6.models.Charity; import ntnu.systemutvikling.team6.models.Feedback; import ntnu.systemutvikling.team6.models.user.*; import org.junit.jupiter.api.*; -import java.sql.*; -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.UUID; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; -/** - * Tests made by Claude AI: Sonnet 4.6, on 24.04.206 - */ +/** Tests made by Claude AI: Sonnet 4.6, on 24.04.206 */ public class FeedbackDAOTest { - private DatabaseConnection mockDbConnection; - private Connection mockConn; - private PreparedStatement mockStmt; - private ResultSet mockRs; - - private FeedbackDAO feedbackDAO; - - @BeforeEach - void setUp() throws SQLException { - mockDbConnection = mock(DatabaseConnection.class); - mockConn = mock(Connection.class); - mockStmt = mock(PreparedStatement.class); - mockRs = mock(ResultSet.class); - - when(mockDbConnection.getMySqlConnection()).thenReturn(mockConn); - when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); - - feedbackDAO = new FeedbackDAO(mockDbConnection); - } - - // ---------------------------------------------------------------- - // Helpers - // ---------------------------------------------------------------- - - private User buildTestUser(String userId) { - Settings settings = new Settings(false, Language.ENGLISH, true); - User user = new User( - userId, - "TestUser", - "test@example.com", - "hashedpassword", - Role.NORMAL_USER.toString() - ); - user.setSettings(settings); - user.setInbox(new Inbox()); - return user; - } - - private Charity buildTestCharity(String charityId) { - return new Charity( - charityId, - "123456789", - "HelpOrg", - "helporg.com", - "active", - true, - "We help people", - null, - null, - null - ); - } - - private Feedback buildTestFeedback(User user) { - return new Feedback( - UUID.randomUUID().toString(), - user, - "Great charity!", - LocalDate.now() - ); - } - - // ---------------------------------------------------------------- - // addFeedbackToCharity() - // ---------------------------------------------------------------- - - @Test - void addFeedbackToCharity_returnsTrueOnSuccess() throws SQLException { - when(mockStmt.executeUpdate()).thenReturn(1); - - String userId = UUID.randomUUID().toString(); - String charityId = UUID.randomUUID().toString(); - - boolean result = feedbackDAO.addFeedbackToCharity( - buildTestFeedback(buildTestUser(userId)), - buildTestCharity(charityId) - ); - - assertTrue(result); - } - - @Test - void addFeedbackToCharity_returnsFalseWhenNoRowsAffected() throws SQLException { - when(mockStmt.executeUpdate()).thenReturn(0); - - boolean result = feedbackDAO.addFeedbackToCharity( - buildTestFeedback(buildTestUser(UUID.randomUUID().toString())), - buildTestCharity(UUID.randomUUID().toString()) - ); - - assertFalse(result); - } - - @Test - void addFeedbackToCharity_returnsFalseOnSQLException() throws SQLException { - when(mockStmt.executeUpdate()).thenThrow(new SQLException("Insert failed")); - - boolean result = feedbackDAO.addFeedbackToCharity( - buildTestFeedback(buildTestUser(UUID.randomUUID().toString())), - buildTestCharity(UUID.randomUUID().toString()) - ); - - assertFalse(result); - } - - @Test - void addFeedbackToCharity_setsCorrectParameterOrder() throws SQLException { - when(mockStmt.executeUpdate()).thenReturn(1); - - String userId = UUID.randomUUID().toString(); - String charityId = UUID.randomUUID().toString(); - User user = buildTestUser(userId); - Feedback feedback = buildTestFeedback(user); - Charity charity = buildTestCharity(charityId); - - feedbackDAO.addFeedbackToCharity(feedback, charity); - - verify(mockStmt).setString(1, feedback.getFeedbackId().toString()); // UUID_feedback - verify(mockStmt).setString(2, feedback.getComment()); // feedback_comment - verify(mockStmt).setDate(3, Date.valueOf(feedback.getDate())); // feedback_date - verify(mockStmt).setBoolean(4, user.getSettings().isAnonymous()); // isAnonymous - verify(mockStmt).setString(5, charityId); // charity_id - verify(mockStmt).setString(6, userId); // user_id - } - - @Test - void addFeedbackToCharity_setsAnonymousTrueWhenUserIsAnonymous() throws SQLException { - when(mockStmt.executeUpdate()).thenReturn(1); - - String userId = UUID.randomUUID().toString(); - User anonymousUser = buildTestUser(userId); - anonymousUser.setSettings(new Settings(true, Language.ENGLISH, false)); + private DatabaseConnection mockDbConnection; + private Connection mockConn; + private PreparedStatement mockStmt; + private ResultSet mockRs; + + private FeedbackDAO feedbackDAO; + + @BeforeEach + void setUp() throws SQLException { + mockDbConnection = mock(DatabaseConnection.class); + mockConn = mock(Connection.class); + mockStmt = mock(PreparedStatement.class); + mockRs = mock(ResultSet.class); + + when(mockDbConnection.getMySqlConnection()).thenReturn(mockConn); + when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); + + feedbackDAO = new FeedbackDAO(mockDbConnection); + } + + // ---------------------------------------------------------------- + // Helpers + // ---------------------------------------------------------------- + + private User buildTestUser(String userId) { + Settings settings = new Settings(false, Language.ENGLISH, true); + User user = + new User( + userId, "TestUser", "test@example.com", "hashedpassword", Role.NORMAL_USER.toString()); + user.setSettings(settings); + user.setInbox(new Inbox()); + return user; + } + + private Charity buildTestCharity(String charityId) { + return new Charity( + charityId, + "123456789", + "HelpOrg", + "helporg.com", + "active", + true, + "We help people", + null, + null, + null); + } + + private Feedback buildTestFeedback(User user) { + return new Feedback(UUID.randomUUID().toString(), user, "Great charity!", LocalDate.now()); + } + + // ---------------------------------------------------------------- + // addFeedbackToCharity() + // ---------------------------------------------------------------- + + @Test + void addFeedbackToCharity_returnsTrueOnSuccess() throws SQLException { + when(mockStmt.executeUpdate()).thenReturn(1); + + String userId = UUID.randomUUID().toString(); + String charityId = UUID.randomUUID().toString(); + + boolean result = + feedbackDAO.addFeedbackToCharity( + buildTestFeedback(buildTestUser(userId)), buildTestCharity(charityId)); + + assertTrue(result); + } + + @Test + void addFeedbackToCharity_returnsFalseWhenNoRowsAffected() throws SQLException { + when(mockStmt.executeUpdate()).thenReturn(0); + + boolean result = + feedbackDAO.addFeedbackToCharity( + buildTestFeedback(buildTestUser(UUID.randomUUID().toString())), + buildTestCharity(UUID.randomUUID().toString())); + + assertFalse(result); + } + + @Test + void addFeedbackToCharity_returnsFalseOnSQLException() throws SQLException { + when(mockStmt.executeUpdate()).thenThrow(new SQLException("Insert failed")); + boolean result = feedbackDAO.addFeedbackToCharity( - buildTestFeedback(anonymousUser), - buildTestCharity(UUID.randomUUID().toString()) - ); - - verify(mockStmt).setBoolean(4, true); - } - - // ---------------------------------------------------------------- - // getFeedbackForCharityUUID() - // ---------------------------------------------------------------- - - @Test - void getFeedbackForCharityUUID_returnsFeedbackList() throws SQLException { - when(mockStmt.executeQuery()).thenReturn(mockRs); - when(mockRs.next()).thenReturn(true, false); - - String feedbackId = UUID.randomUUID().toString(); - String userId = UUID.randomUUID().toString(); - - when(mockRs.getString("UUID_feedback")).thenReturn(feedbackId); - when(mockRs.getString("feedback_comment")).thenReturn("Great work!"); - when(mockRs.getString("feedback_date")).thenReturn(LocalDate.now().toString()); - when(mockRs.getBoolean("isAnonymous")).thenReturn(false); - - when(mockRs.getString("UUID_User")).thenReturn(userId); - when(mockRs.getString("user_name")).thenReturn("Alice"); - when(mockRs.getString("user_email")).thenReturn("alice@example.com"); - when(mockRs.getString("user_password")).thenReturn("hashedpw"); - when(mockRs.getString("role")).thenReturn(Role.NORMAL_USER.toString()); - when(mockRs.getString("language")).thenReturn(Language.ENGLISH.toString()); - when(mockRs.getBoolean("lightmode")).thenReturn(true); - - ArrayList result = feedbackDAO.getFeedbackforCharityUUID(UUID.randomUUID().toString()); - - assertNotNull(result); - assertEquals(1, result.size()); - assertEquals(feedbackId, result.getFirst().getFeedbackId().toString()); - assertEquals("Great work!", result.getFirst().getComment()); - assertEquals(userId, result.getFirst().getUser().getId().toString()); - } - - @Test - void getFeedbackForCharityUUID_returnsEmptyListWhenNoFeedback() throws SQLException { - when(mockStmt.executeQuery()).thenReturn(mockRs); - when(mockRs.next()).thenReturn(false); - - ArrayList result = feedbackDAO.getFeedbackforCharityUUID(UUID.randomUUID().toString()); - - assertNotNull(result); - assertTrue(result.isEmpty()); - } - - @Test - void getFeedbackForCharityUUID_returnsMultipleFeedbackEntries() throws SQLException { - when(mockStmt.executeQuery()).thenReturn(mockRs); - when(mockRs.next()).thenReturn(true, true, true, false); - - when(mockRs.getString("UUID_feedback")).thenReturn( - UUID.randomUUID().toString(), - UUID.randomUUID().toString(), - UUID.randomUUID().toString() - ); - when(mockRs.getString("feedback_comment")).thenReturn("Good", "Excellent", "Amazing"); - when(mockRs.getString("feedback_date")).thenReturn(LocalDate.now().toString()); - when(mockRs.getBoolean("isAnonymous")).thenReturn(false); - when(mockRs.getString("UUID_User")).thenReturn(UUID.randomUUID().toString()); - when(mockRs.getString("user_name")).thenReturn("User"); - when(mockRs.getString("user_email")).thenReturn("u@example.com"); - when(mockRs.getString("user_password")).thenReturn("pw"); - when(mockRs.getString("role")).thenReturn(Role.NORMAL_USER.toString()); - when(mockRs.getString("language")).thenReturn(Language.ENGLISH.toString()); - when(mockRs.getBoolean("lightmode")).thenReturn(false); - - ArrayList result = feedbackDAO.getFeedbackforCharityUUID(UUID.randomUUID().toString()); - - assertEquals(3, result.size()); - } - - @Test - void getFeedbackForCharityUUID_passesCorrectCharityIdToQuery() throws SQLException { - when(mockStmt.executeQuery()).thenReturn(mockRs); - when(mockRs.next()).thenReturn(false); - - String charityId = UUID.randomUUID().toString(); - feedbackDAO.getFeedbackforCharityUUID(charityId); - - verify(mockStmt).setString(1, charityId); - } -} \ No newline at end of file + buildTestFeedback(buildTestUser(UUID.randomUUID().toString())), + buildTestCharity(UUID.randomUUID().toString())); + + assertFalse(result); + } + + @Test + void addFeedbackToCharity_setsCorrectParameterOrder() throws SQLException { + when(mockStmt.executeUpdate()).thenReturn(1); + + String userId = UUID.randomUUID().toString(); + String charityId = UUID.randomUUID().toString(); + User user = buildTestUser(userId); + Feedback feedback = buildTestFeedback(user); + Charity charity = buildTestCharity(charityId); + + feedbackDAO.addFeedbackToCharity(feedback, charity); + + verify(mockStmt).setString(1, feedback.getFeedbackId().toString()); // UUID_feedback + verify(mockStmt).setString(2, feedback.getComment()); // feedback_comment + verify(mockStmt).setDate(3, Date.valueOf(feedback.getDate())); // feedback_date + verify(mockStmt).setBoolean(4, user.getSettings().isAnonymous()); // isAnonymous + verify(mockStmt).setString(5, charityId); // charity_id + verify(mockStmt).setString(6, userId); // user_id + } + + @Test + void addFeedbackToCharity_setsAnonymousTrueWhenUserIsAnonymous() throws SQLException { + when(mockStmt.executeUpdate()).thenReturn(1); + + String userId = UUID.randomUUID().toString(); + User anonymousUser = buildTestUser(userId); + anonymousUser.setSettings(new Settings(true, Language.ENGLISH, false)); + + feedbackDAO.addFeedbackToCharity( + buildTestFeedback(anonymousUser), buildTestCharity(UUID.randomUUID().toString())); + + verify(mockStmt).setBoolean(4, true); + } + + // ---------------------------------------------------------------- + // getFeedbackForCharityUUID() + // ---------------------------------------------------------------- + + @Test + void getFeedbackForCharityUUID_returnsFeedbackList() throws SQLException { + when(mockStmt.executeQuery()).thenReturn(mockRs); + when(mockRs.next()).thenReturn(true, false); + + String feedbackId = UUID.randomUUID().toString(); + String userId = UUID.randomUUID().toString(); + + when(mockRs.getString("UUID_feedback")).thenReturn(feedbackId); + when(mockRs.getString("feedback_comment")).thenReturn("Great work!"); + when(mockRs.getString("feedback_date")).thenReturn(LocalDate.now().toString()); + when(mockRs.getBoolean("isAnonymous")).thenReturn(false); + + when(mockRs.getString("UUID_User")).thenReturn(userId); + when(mockRs.getString("user_name")).thenReturn("Alice"); + when(mockRs.getString("user_email")).thenReturn("alice@example.com"); + when(mockRs.getString("user_password")).thenReturn("hashedpw"); + when(mockRs.getString("role")).thenReturn(Role.NORMAL_USER.toString()); + when(mockRs.getString("language")).thenReturn(Language.ENGLISH.toString()); + when(mockRs.getBoolean("lightmode")).thenReturn(true); + + ArrayList result = + feedbackDAO.getFeedbackforCharityUUID(UUID.randomUUID().toString()); + + assertNotNull(result); + assertEquals(1, result.size()); + assertEquals(feedbackId, result.getFirst().getFeedbackId().toString()); + assertEquals("Great work!", result.getFirst().getComment()); + assertEquals(userId, result.getFirst().getUser().getId().toString()); + } + + @Test + void getFeedbackForCharityUUID_returnsEmptyListWhenNoFeedback() throws SQLException { + when(mockStmt.executeQuery()).thenReturn(mockRs); + when(mockRs.next()).thenReturn(false); + + ArrayList result = + feedbackDAO.getFeedbackforCharityUUID(UUID.randomUUID().toString()); + + assertNotNull(result); + assertTrue(result.isEmpty()); + } + + @Test + void getFeedbackForCharityUUID_returnsMultipleFeedbackEntries() throws SQLException { + when(mockStmt.executeQuery()).thenReturn(mockRs); + when(mockRs.next()).thenReturn(true, true, true, false); + + when(mockRs.getString("UUID_feedback")) + .thenReturn( + UUID.randomUUID().toString(), + UUID.randomUUID().toString(), + UUID.randomUUID().toString()); + when(mockRs.getString("feedback_comment")).thenReturn("Good", "Excellent", "Amazing"); + when(mockRs.getString("feedback_date")).thenReturn(LocalDate.now().toString()); + when(mockRs.getBoolean("isAnonymous")).thenReturn(false); + when(mockRs.getString("UUID_User")).thenReturn(UUID.randomUUID().toString()); + when(mockRs.getString("user_name")).thenReturn("User"); + when(mockRs.getString("user_email")).thenReturn("u@example.com"); + when(mockRs.getString("user_password")).thenReturn("pw"); + when(mockRs.getString("role")).thenReturn(Role.NORMAL_USER.toString()); + when(mockRs.getString("language")).thenReturn(Language.ENGLISH.toString()); + when(mockRs.getBoolean("lightmode")).thenReturn(false); + + ArrayList result = + feedbackDAO.getFeedbackforCharityUUID(UUID.randomUUID().toString()); + + assertEquals(3, result.size()); + } + + @Test + void getFeedbackForCharityUUID_passesCorrectCharityIdToQuery() throws SQLException { + when(mockStmt.executeQuery()).thenReturn(mockRs); + when(mockRs.next()).thenReturn(false); + + String charityId = UUID.randomUUID().toString(); + feedbackDAO.getFeedbackforCharityUUID(charityId); + + verify(mockStmt).setString(1, charityId); + } +} diff --git a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/database/DAO/MessageDAOTest.java b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/database/DAO/MessageDAOTest.java index 6d36d760..a546b27f 100644 --- a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/database/DAO/MessageDAOTest.java +++ b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/database/DAO/MessageDAOTest.java @@ -1,161 +1,158 @@ package ntnu.systemutvikling.team6.database.DAO; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +import java.sql.*; +import java.time.LocalDate; +import java.util.UUID; import ntnu.systemutvikling.team6.database.DatabaseConnection; import ntnu.systemutvikling.team6.models.Charity; import ntnu.systemutvikling.team6.models.user.Message; import org.junit.jupiter.api.*; -import java.sql.*; -import java.time.LocalDate; -import java.util.UUID; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; -/** - * Tests made by Claude AI: Sonnet 4.6, on 24.04.206 - */ +/** Tests made by Claude AI: Sonnet 4.6, on 24.04.206 */ public class MessageDAOTest { - private DatabaseConnection mockDbConnection; - private Connection mockDonorConn; // used by getDonorIdsForCharity() - private PreparedStatement mockDonorStmt; - private ResultSet mockDonorRs; - - private Connection mockInsertConn; // used by the INSERT batch - private PreparedStatement mockInsertStmt; - - private MessageDAO messageDAO; - - @BeforeEach - void setUp() throws SQLException { - mockDbConnection = mock(DatabaseConnection.class); - - mockDonorConn = mock(Connection.class); - mockDonorStmt = mock(PreparedStatement.class); - mockDonorRs = mock(ResultSet.class); - - mockInsertConn = mock(Connection.class); - mockInsertStmt = mock(PreparedStatement.class); - - - when(mockDbConnection.getMySqlConnection()) - .thenReturn(mockDonorConn) - .thenReturn(mockInsertConn); - - // Wire donor connection - when(mockDonorConn.prepareStatement(anyString())).thenReturn(mockDonorStmt); - when(mockDonorStmt.executeQuery()).thenReturn(mockDonorRs); - - // Wire insert connection - when(mockInsertConn.prepareStatement(anyString())).thenReturn(mockInsertStmt); - - messageDAO = new MessageDAO(mockDbConnection); - } - - // ---------------------------------------------------------------- - // Helpers - // ---------------------------------------------------------------- - - private Message buildTestMessage(String charityId) { - Charity charity = new Charity( - charityId, - "123456789", - "HelpOrg", - "helporg.com", - "active", - true, - "We help people", - null, - null, - null - ); - return new Message("Important Update", charity, "Things are going well.", LocalDate.now()); - } - - // ---------------------------------------------------------------- - // addMessage() - // ---------------------------------------------------------------- - - @Test - void addMessage_returnsTrueWhenDonorsExistAndBatchSucceeds() throws SQLException { - String charityId = UUID.randomUUID().toString(); - String donorId = UUID.randomUUID().toString(); - - // Simulate one donor found - when(mockDonorRs.next()).thenReturn(true, false); - when(mockDonorRs.getString("user_id")).thenReturn(donorId); - - // Batch returns one affected row - when(mockInsertStmt.executeBatch()).thenReturn(new int[]{1}); - - boolean result = messageDAO.addMessage(buildTestMessage(charityId)); - - assertTrue(result); - } - - @Test - void addMessage_returnsFalseWhenNoDonorsExist() throws SQLException { - when(mockDonorRs.next()).thenReturn(false); - - boolean result = messageDAO.addMessage(buildTestMessage(UUID.randomUUID().toString())); + private DatabaseConnection mockDbConnection; + private Connection mockDonorConn; // used by getDonorIdsForCharity() + private PreparedStatement mockDonorStmt; + private ResultSet mockDonorRs; + + private Connection mockInsertConn; // used by the INSERT batch + private PreparedStatement mockInsertStmt; + + private MessageDAO messageDAO; + + @BeforeEach + void setUp() throws SQLException { + mockDbConnection = mock(DatabaseConnection.class); + + mockDonorConn = mock(Connection.class); + mockDonorStmt = mock(PreparedStatement.class); + mockDonorRs = mock(ResultSet.class); + + mockInsertConn = mock(Connection.class); + mockInsertStmt = mock(PreparedStatement.class); + + when(mockDbConnection.getMySqlConnection()) + .thenReturn(mockDonorConn) + .thenReturn(mockInsertConn); + + // Wire donor connection + when(mockDonorConn.prepareStatement(anyString())).thenReturn(mockDonorStmt); + when(mockDonorStmt.executeQuery()).thenReturn(mockDonorRs); + + // Wire insert connection + when(mockInsertConn.prepareStatement(anyString())).thenReturn(mockInsertStmt); + + messageDAO = new MessageDAO(mockDbConnection); + } + + // ---------------------------------------------------------------- + // Helpers + // ---------------------------------------------------------------- - assertFalse(result); - verify(mockDbConnection, times(1)).getMySqlConnection(); - verifyNoInteractions(mockInsertConn); - } + private Message buildTestMessage(String charityId) { + Charity charity = + new Charity( + charityId, + "123456789", + "HelpOrg", + "helporg.com", + "active", + true, + "We help people", + null, + null, + null); + return new Message("Important Update", charity, "Things are going well.", LocalDate.now()); + } - @Test - void addMessage_sendsOneBatchEntryPerDonor() throws SQLException { - String charityId = UUID.randomUUID().toString(); - String donorId1 = UUID.randomUUID().toString(); - String donorId2 = UUID.randomUUID().toString(); - String donorId3 = UUID.randomUUID().toString(); + // ---------------------------------------------------------------- + // addMessage() + // ---------------------------------------------------------------- + @Test + void addMessage_returnsTrueWhenDonorsExistAndBatchSucceeds() throws SQLException { + String charityId = UUID.randomUUID().toString(); + String donorId = UUID.randomUUID().toString(); - when(mockDonorRs.next()).thenReturn(true, true, true, false); - when(mockDonorRs.getString("user_id")).thenReturn(donorId1, donorId2, donorId3); - when(mockInsertStmt.executeBatch()).thenReturn(new int[]{1, 1, 1}); + // Simulate one donor found + when(mockDonorRs.next()).thenReturn(true, false); + when(mockDonorRs.getString("user_id")).thenReturn(donorId); - messageDAO.addMessage(buildTestMessage(charityId)); + // Batch returns one affected row + when(mockInsertStmt.executeBatch()).thenReturn(new int[] {1}); - verify(mockInsertStmt, times(3)).addBatch(); - verify(mockInsertStmt, times(1)).executeBatch(); - } + boolean result = messageDAO.addMessage(buildTestMessage(charityId)); - @Test - void addMessage_setsCorrectCharityIdOnEveryBatchEntry() throws SQLException { - String charityId = UUID.randomUUID().toString(); - String donorId = UUID.randomUUID().toString(); + assertTrue(result); + } - when(mockDonorRs.next()).thenReturn(true, false); - when(mockDonorRs.getString("user_id")).thenReturn(donorId); - when(mockInsertStmt.executeBatch()).thenReturn(new int[]{1}); + @Test + void addMessage_returnsFalseWhenNoDonorsExist() throws SQLException { + when(mockDonorRs.next()).thenReturn(false); - messageDAO.addMessage(buildTestMessage(charityId)); + boolean result = messageDAO.addMessage(buildTestMessage(UUID.randomUUID().toString())); - verify(mockInsertStmt).setString(5, charityId); - verify(mockInsertStmt).setString(6, donorId); - } + assertFalse(result); + verify(mockDbConnection, times(1)).getMySqlConnection(); + verifyNoInteractions(mockInsertConn); + } - @Test - void addMessage_throwsRuntimeExceptionWhenDonorQueryFails() throws SQLException { - when(mockDonorConn.prepareStatement(anyString())) - .thenThrow(new SQLException("Donor query failed")); + @Test + void addMessage_sendsOneBatchEntryPerDonor() throws SQLException { + String charityId = UUID.randomUUID().toString(); + String donorId1 = UUID.randomUUID().toString(); + String donorId2 = UUID.randomUUID().toString(); + String donorId3 = UUID.randomUUID().toString(); - assertThrows(RuntimeException.class, - () -> messageDAO.addMessage(buildTestMessage(UUID.randomUUID().toString()))); - } + when(mockDonorRs.next()).thenReturn(true, true, true, false); + when(mockDonorRs.getString("user_id")).thenReturn(donorId1, donorId2, donorId3); + when(mockInsertStmt.executeBatch()).thenReturn(new int[] {1, 1, 1}); + messageDAO.addMessage(buildTestMessage(charityId)); - @Test - void addMessage_returnsFalseWhenBatchReturnsEmptyArray() throws SQLException { - String donorId = UUID.randomUUID().toString(); + verify(mockInsertStmt, times(3)).addBatch(); + verify(mockInsertStmt, times(1)).executeBatch(); + } - when(mockDonorRs.next()).thenReturn(true, false); - when(mockDonorRs.getString("user_id")).thenReturn(donorId); + @Test + void addMessage_setsCorrectCharityIdOnEveryBatchEntry() throws SQLException { + String charityId = UUID.randomUUID().toString(); + String donorId = UUID.randomUUID().toString(); - when(mockInsertStmt.executeBatch()).thenReturn(new int[]{}); + when(mockDonorRs.next()).thenReturn(true, false); + when(mockDonorRs.getString("user_id")).thenReturn(donorId); + when(mockInsertStmt.executeBatch()).thenReturn(new int[] {1}); - boolean result = messageDAO.addMessage(buildTestMessage(UUID.randomUUID().toString())); + messageDAO.addMessage(buildTestMessage(charityId)); + + verify(mockInsertStmt).setString(5, charityId); + verify(mockInsertStmt).setString(6, donorId); + } + + @Test + void addMessage_throwsRuntimeExceptionWhenDonorQueryFails() throws SQLException { + when(mockDonorConn.prepareStatement(anyString())) + .thenThrow(new SQLException("Donor query failed")); + + assertThrows( + RuntimeException.class, + () -> messageDAO.addMessage(buildTestMessage(UUID.randomUUID().toString()))); + } - assertFalse(result); - } -} \ No newline at end of file + @Test + void addMessage_returnsFalseWhenBatchReturnsEmptyArray() throws SQLException { + String donorId = UUID.randomUUID().toString(); + + when(mockDonorRs.next()).thenReturn(true, false); + when(mockDonorRs.getString("user_id")).thenReturn(donorId); + + when(mockInsertStmt.executeBatch()).thenReturn(new int[] {}); + + boolean result = messageDAO.addMessage(buildTestMessage(UUID.randomUUID().toString())); + + assertFalse(result); + } +} diff --git a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/database/DAO/UserDAOTest.java b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/database/DAO/UserDAOTest.java index fbea5164..fe886162 100644 --- a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/database/DAO/UserDAOTest.java +++ b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/database/DAO/UserDAOTest.java @@ -1,5 +1,11 @@ package ntnu.systemutvikling.team6.database.DAO; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +import java.sql.*; +import java.time.LocalDate; +import java.util.UUID; import ntnu.systemutvikling.team6.database.DatabaseConnection; import ntnu.systemutvikling.team6.models.registry.UserRegistry; import ntnu.systemutvikling.team6.models.user.*; @@ -7,510 +13,497 @@ import org.junit.jupiter.api.*; import org.mockito.*; -import java.sql.*; -import java.time.LocalDate; -import java.util.UUID; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; - -/** - * Some tests made by Claude AI: Sonnet 4.6, on 24.04.206 - */ +/** Some tests made by Claude AI: Sonnet 4.6, on 24.04.206 */ public class UserDAOTest { - // --- Mocks --- - private DatabaseConnection mockDbConnection; - private Connection mockConn; - private PreparedStatement mockStmt; - private ResultSet mockRs; - - private UserDAO userDAO; - - @BeforeEach - void setUp() throws SQLException { - mockDbConnection = mock(DatabaseConnection.class); - mockConn = mock(Connection.class); - mockStmt = mock(PreparedStatement.class); - mockRs = mock(ResultSet.class); - - // Every test gets a fresh DAO wired to our fake connection - when(mockDbConnection.getMySqlConnection()).thenReturn(mockConn); - - userDAO = new UserDAO(mockDbConnection); - } - - // ---------------------------------------------------------------- - // getUserFromDBUuid() - // ---------------------------------------------------------------- - - @Test - void getUserFromDBUuid_returnsUserWhenFound() throws SQLException { - when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); - when(mockStmt.executeQuery()).thenReturn(mockRs); - when(mockRs.next()).thenReturn(true, false); - - String userId = UUID.randomUUID().toString(); - String messageId = UUID.randomUUID().toString(); - String charityId = UUID.randomUUID().toString(); - - when(mockRs.getString("UUID_User")).thenReturn(userId); - when(mockRs.getString("user_name")).thenReturn("Bob"); - when(mockRs.getString("user_email")).thenReturn("bob@example.com"); - when(mockRs.getString("user_password")).thenReturn("hashedpw"); - when(mockRs.getString("role")).thenReturn(Role.NORMAL_USER.toString()); - - when(mockRs.getString("isAnonymous")).thenReturn("false"); - when(mockRs.getBoolean("isAnonymous")).thenReturn(false); - when(mockRs.getString("language")).thenReturn(Language.ENGLISH.toString()); - when(mockRs.getBoolean("lightmode")).thenReturn(true); - - when(mockRs.getString("UUID_message")).thenReturn(messageId); - when(mockRs.getString("message_title")).thenReturn("Hello"); - when(mockRs.getString("message_content")).thenReturn("Some content"); - when(mockRs.getString("message_date")).thenReturn(LocalDate.now().toString()); - - when(mockRs.getString("UUID_charities")).thenReturn(charityId); - when(mockRs.getString("org_number")).thenReturn("9999"); - when(mockRs.getString("charity_name")).thenReturn("HelpOrg"); - when(mockRs.getString("charity_link")).thenReturn("helporg.com"); - when(mockRs.getString("status")).thenReturn("active"); - when(mockRs.getBoolean("pre_approved")).thenReturn(true); - when(mockRs.getString("description")).thenReturn("We help"); - when(mockRs.getString("logoURL")).thenReturn(null); - when(mockRs.getString("key_values")).thenReturn(null); - when(mockRs.getBytes("logoBLOB")).thenReturn(null); - - User user = userDAO.getUserFromDBUuid(userId); - - assertNotNull(user); - assertEquals(userId, user.getId().toString()); - assertEquals("Bob", user.getUsername()); - assertEquals(1, user.getInbox().getMessages().size()); - assertEquals("Hello", user.getInbox().getMessages().getFirst().getTitle()); - assertEquals(charityId, user.getInbox().getMessages().getFirst().getFrom().getUUID().toString()); - } - - @Test - void getUserFromDBUuid_returnsNullWhenNotFound() throws SQLException { - when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); - when(mockStmt.executeQuery()).thenReturn(mockRs); - when(mockRs.next()).thenReturn(false); // no rows - - User user = userDAO.getUserFromDBUuid(UUID.randomUUID().toString()); - - assertNull(user); - } - @Test - void getUserFromDBUuid_throwsRuntimeExceptionOnSQLException() throws SQLException { - when(mockConn.prepareStatement(anyString())) - .thenThrow(new SQLException("Connection lost")); - - assertThrows(RuntimeException.class, - () -> userDAO.getUserFromDBUuid(UUID.randomUUID().toString())); - } - - @Test - void getUserFromDBUuid_doesNotDuplicateMessagesAcrossRows() throws SQLException { - // Same message ID appearing in two rows should only produce one Message in the inbox - when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); - when(mockStmt.executeQuery()).thenReturn(mockRs); - when(mockRs.next()).thenReturn(true, true, false); - - String userId = UUID.randomUUID().toString(); - String messageId = UUID.randomUUID().toString(); // same ID both rows - String charityId = UUID.randomUUID().toString(); - - when(mockRs.getString("UUID_User")).thenReturn(userId); - when(mockRs.getString("user_name")).thenReturn("Bob"); - when(mockRs.getString("user_email")).thenReturn("bob@example.com"); - when(mockRs.getString("user_password")).thenReturn("hashedpw"); - when(mockRs.getString("role")).thenReturn(Role.NORMAL_USER.toString()); - when(mockRs.getString("isAnonymous")).thenReturn("false"); - when(mockRs.getBoolean("isAnonymous")).thenReturn(false); - when(mockRs.getString("language")).thenReturn(Language.ENGLISH.toString()); - when(mockRs.getBoolean("lightmode")).thenReturn(false); - when(mockRs.getString("UUID_message")).thenReturn(messageId); - when(mockRs.getString("message_title")).thenReturn("Title"); - when(mockRs.getString("message_content")).thenReturn("Content"); - when(mockRs.getString("message_date")).thenReturn(LocalDate.now().toString()); - when(mockRs.getString("UUID_charities")).thenReturn(charityId); - when(mockRs.getString("org_number")).thenReturn("1234"); - when(mockRs.getString("charity_name")).thenReturn("Org"); - when(mockRs.getString("charity_link")).thenReturn("org.com"); - when(mockRs.getString("status")).thenReturn("active"); - when(mockRs.getBoolean("pre_approved")).thenReturn(false); - when(mockRs.getString("description")).thenReturn("desc"); - when(mockRs.getString("logoURL")).thenReturn(null); - when(mockRs.getString("key_values")).thenReturn(null); - when(mockRs.getBytes("logoBLOB")).thenReturn(null); - - User user = userDAO.getUserFromDBUuid(userId); - - assertEquals(1, user.getInbox().getMessages().size()); - } - - // ---------------------------------------------------------------- - // isEmailTaken() - // ---------------------------------------------------------------- - - @Test - void isEmailTaken_returnsTrueWhenEmailExists() throws SQLException { - when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); - when(mockStmt.executeQuery()).thenReturn(mockRs); - when(mockRs.next()).thenReturn(true); // simulates a row found - - assertTrue(userDAO.isEmailTaken("test@example.com")); - } - - @Test - void isEmailTaken_returnsFalseWhenEmailDoesNotExist() throws SQLException { - when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); - when(mockStmt.executeQuery()).thenReturn(mockRs); - when(mockRs.next()).thenReturn(false); // no row → email is free - - assertFalse(userDAO.isEmailTaken("new@example.com")); - } - - @Test - void isEmailTaken_throwsOnInvalidEmail() { - // No DB call should happen — the guard clause throws immediately - assertThrows(IllegalArgumentException.class, - () -> userDAO.isEmailTaken("notanemail")); - - assertThrows(IllegalArgumentException.class, - () -> userDAO.isEmailTaken(null)); - - assertThrows(IllegalArgumentException.class, - () -> userDAO.isEmailTaken(" ")); - } - - // ---------------------------------------------------------------- - // getUsersFromDB() - // ---------------------------------------------------------------- - - @Test - void getUsersFromDB_returnsAllUsers() throws SQLException { - Statement mockStatement = mock(Statement.class); - when(mockConn.createStatement()).thenReturn(mockStatement); - when(mockStatement.executeQuery(anyString())).thenReturn(mockRs); - - String userId1 = UUID.randomUUID().toString(); - String userId2 = UUID.randomUUID().toString(); - - // Two distinct users, no messages to keep stubbing simple - when(mockRs.next()).thenReturn(true, true, false); - when(mockRs.getString("UUID_User")).thenReturn(userId1, userId2); - when(mockRs.getString("user_name")).thenReturn("Alice", "Bob"); - when(mockRs.getString("user_email")).thenReturn("alice@example.com", "bob@example.com"); - when(mockRs.getString("user_password")).thenReturn("hash1", "hash2"); - when(mockRs.getString("role")).thenReturn(Role.NORMAL_USER.toString()); - when(mockRs.getString("isAnonymous")).thenReturn(null); // no settings row - when(mockRs.getString("UUID_message")).thenReturn(null); // no messages - - UserRegistry registry = userDAO.getUsersFromDB(); - - assertNotNull(registry); - assertEquals(2, registry.getAllUsers().size()); - } - - @Test - void getUsersFromDB_returnsEmptyRegistryWhenNoUsers() throws SQLException { - Statement mockStatement = mock(Statement.class); - when(mockConn.createStatement()).thenReturn(mockStatement); - when(mockStatement.executeQuery(anyString())).thenReturn(mockRs); - when(mockRs.next()).thenReturn(false); - - UserRegistry registry = userDAO.getUsersFromDB(); - - assertNotNull(registry); - assertTrue(registry.getAllUsers().isEmpty()); - } - - // ---------------------------------------------------------------- - // getSettingsForUser() - // ---------------------------------------------------------------- - - @Test - void getSettingsForUser_returnsSettingsWhenFound() throws SQLException { - when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); - when(mockStmt.executeQuery()).thenReturn(mockRs); - when(mockRs.next()).thenReturn(true, false); - when(mockRs.getBoolean("isAnonymous")).thenReturn(true); - when(mockRs.getString("language")).thenReturn(Language.ENGLISH.toString()); - when(mockRs.getBoolean("lightmode")).thenReturn(false); - - Settings settings = userDAO.getSettingsForUser(UUID.randomUUID().toString()); - - assertNotNull(settings); - assertTrue(settings.isAnonymous()); - assertEquals(Language.ENGLISH, settings.getLanguage()); - assertFalse(settings.isLightMode()); - } - - @Test - void getSettingsForUser_returnsNullWhenNotFound() throws SQLException { - when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); - when(mockStmt.executeQuery()).thenReturn(mockRs); - when(mockRs.next()).thenReturn(false); - - Settings settings = userDAO.getSettingsForUser(UUID.randomUUID().toString()); - - assertNull(settings); - } - - @Test - void getSettingsForUser_appliesMaxRowsLimit() throws SQLException { - when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); - when(mockStmt.executeQuery()).thenReturn(mockRs); - when(mockRs.next()).thenReturn(false); - - userDAO.getSettingsForUser(UUID.randomUUID().toString()); - - // The DAO must call setMaxRows(1) to guard against multiple settings rows - verify(mockStmt).setMaxRows(1); - } - - @Test - void getSettingsForUser_throwsRuntimeExceptionOnSQLException() throws SQLException { - when(mockConn.prepareStatement(anyString())) - .thenThrow(new SQLException("DB error")); - - assertThrows(RuntimeException.class, - () -> userDAO.getSettingsForUser(UUID.randomUUID().toString())); - } - - // ---------------------------------------------------------------- - // updateUserDetails() - // ---------------------------------------------------------------- - - @Test - void updateUserDetails_returnsTrueOnSuccess() throws SQLException { - when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); - when(mockStmt.executeUpdate()).thenReturn(1); - - User user = buildTestUser(); - assertTrue(userDAO.updateUserDetails(user)); - - // Verify the three columns are set in the correct parameter order - verify(mockStmt).setString(1, user.getUsername()); - verify(mockStmt).setString(2, user.getEmail()); - verify(mockStmt).setString(3, user.getPasswordHash()); - verify(mockStmt).setString(4, user.getId().toString()); - } - - @Test - void updateUserDetails_returnsFalseWhenNoRowsAffected() throws SQLException { - when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); - when(mockStmt.executeUpdate()).thenReturn(0); - - assertFalse(userDAO.updateUserDetails(buildTestUser())); - } - - @Test - void updateUserDetails_returnsFalseOnSQLException() throws SQLException { - when(mockConn.prepareStatement(anyString())) - .thenThrow(new SQLException("Update failed")); - - assertFalse(userDAO.updateUserDetails(buildTestUser())); - } - - // ---------------------------------------------------------------- - // getInboxForUser() - // ---------------------------------------------------------------- - - @Test - void getInboxForUser_returnsInboxWithMessages() throws SQLException { - when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); - when(mockStmt.executeQuery()).thenReturn(mockRs); - when(mockRs.next()).thenReturn(true, false); - - String charityId = UUID.randomUUID().toString(); - when(mockRs.getString("UUID_charities")).thenReturn(charityId); - when(mockRs.getString("org_number")).thenReturn("5678"); - when(mockRs.getString("charity_name")).thenReturn("SaveAll"); - when(mockRs.getString("charity_link")).thenReturn("saveall.org"); - when(mockRs.getString("status")).thenReturn("active"); - when(mockRs.getBoolean("pre_approved")).thenReturn(false); - when(mockRs.getString("description")).thenReturn("We save"); - when(mockRs.getString("logoURL")).thenReturn(null); - when(mockRs.getString("key_values")).thenReturn(null); - when(mockRs.getBytes("logoBLOB")).thenReturn(null); - when(mockRs.getString("message_title")).thenReturn("Update"); - when(mockRs.getString("message_content")).thenReturn("Big news"); - when(mockRs.getString("message_date")).thenReturn(LocalDate.now().toString()); - - Inbox inbox = userDAO.getInboxForUser(UUID.randomUUID().toString()); - - assertNotNull(inbox); - assertEquals(1, inbox.getMessages().size()); - assertEquals("Update", inbox.getMessages().getFirst().getTitle()); - assertEquals(charityId, inbox.getMessages().getFirst().getFrom().getUUID().toString()); - } - - @Test - void getInboxForUser_returnsEmptyInboxWhenNoMessages() throws SQLException { - when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); - when(mockStmt.executeQuery()).thenReturn(mockRs); - when(mockRs.next()).thenReturn(false); - - Inbox inbox = userDAO.getInboxForUser(UUID.randomUUID().toString()); - - assertNotNull(inbox); - assertTrue(inbox.getMessages().isEmpty()); - } - - @Test - void getInboxForUser_throwsRuntimeExceptionOnSQLException() throws SQLException { - when(mockConn.prepareStatement(anyString())) - .thenThrow(new SQLException("Timeout")); - - assertThrows(RuntimeException.class, - () -> userDAO.getInboxForUser(UUID.randomUUID().toString())); - } - - // ---------------------------------------------------------------- - // registerUser() - // ---------------------------------------------------------------- - - @Test - void registerUser_returnsTrueOnSuccess() throws SQLException { - // Two prepared statements are created (User insert + Settings insert) - when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); - when(mockStmt.executeUpdate()).thenReturn(1); // 1 row affected each time - - User user = buildTestUser(); - assertTrue(userDAO.registerUser(user)); - - // Both inserts should have been executed - verify(mockStmt, times(2)).executeUpdate(); - // Auto-commit should have been disabled and commit called - verify(mockConn).setAutoCommit(false); - verify(mockConn).commit(); - } - - @Test - void registerUser_returnsFalseWhenInsertAffectsNoRows() throws SQLException { - when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); - when(mockStmt.executeUpdate()).thenReturn(0); // nothing inserted - - assertFalse(userDAO.registerUser(buildTestUser())); - } - - @Test - void registerUser_returnsFalseOnSQLException() throws SQLException { - when(mockConn.prepareStatement(anyString())) - .thenThrow(new SQLException("DB down")); - - assertFalse(userDAO.registerUser(buildTestUser())); - } - - // ---------------------------------------------------------------- - // getUserFromDBEmailAndPassword() - // ---------------------------------------------------------------- - - @Test - void getUserFromDB_returnsNullWhenPasswordDoesNotMatch() throws SQLException { - when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); - when(mockStmt.executeQuery()).thenReturn(mockRs); - - when(mockRs.next()).thenReturn(true, false); - when(mockRs.getString("UUID_User")).thenReturn("some-uuid"); - when(mockRs.getString("user_name")).thenReturn("Alice"); - when(mockRs.getString("user_password")).thenReturn(new PasswordHasher().getHashPassword("differentPassword")); - - User result = userDAO.getUserFromDBEmailAndPassword("alice@example.com", "wrongPassword"); - - assertNull(result); - } - - @Test - void getUserFromDB_throwsRuntimeExceptionOnSQLException() throws SQLException { - when(mockConn.prepareStatement(anyString())) - .thenThrow(new SQLException("Connection lost")); - - assertThrows(RuntimeException.class, - () -> userDAO.getUserFromDBEmailAndPassword("a@b.com", "pass")); - } - - @Test - void getUserFromDB_returnsAUserWhenCorrect() throws SQLException { - when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); - when(mockStmt.executeQuery()).thenReturn(mockRs); - when(mockRs.next()).thenReturn(true, false); - String userId = UUID.randomUUID().toString(); - when(mockRs.getString("UUID_User")).thenReturn(userId); - when(mockRs.getString("user_name")).thenReturn("name"); - when(mockRs.getString("user_email")).thenReturn("a@b.com"); - when(mockRs.getString("user_password")).thenReturn(new PasswordHasher().getHashPassword("somePassword")); - when(mockRs.getString("role")).thenReturn(Role.NORMAL_USER.toString()); - when(mockRs.getBoolean("isAnonymous")).thenReturn(false); - when(mockRs.getString("language")).thenReturn(Language.ENGLISH.toString()); - when(mockRs.getBoolean("lightmode")).thenReturn(false); - String messageId = UUID.randomUUID().toString(); - when(mockRs.getString("message_title")).thenReturn("Title"); - when(mockRs.getString("UUID_message")).thenReturn(messageId); - when(mockRs.getString("message_content")).thenReturn("blah blah blah"); - when(mockRs.getString("message_date")).thenReturn(LocalDate.now().toString()); - - String charityId = UUID.randomUUID().toString(); - when(mockRs.getString("org_number")).thenReturn("1234"); - when(mockRs.getString("charity_name")).thenReturn("charity"); - when(mockRs.getString("charity_link")).thenReturn("link.com"); - when(mockRs.getString("status")).thenReturn("Something"); - when(mockRs.getString("UUID_charities")).thenReturn(charityId); - when(mockRs.getString("description")).thenReturn(charityId); - when(mockRs.getString("logoURL")).thenReturn(null); - when(mockRs.getString("key_values")).thenReturn(null); - when(mockRs.getBytes("logoBLOB")).thenReturn(null); - - User user = userDAO.getUserFromDBEmailAndPassword("a@b.com", "somePassword"); - - assertEquals(userId, user.getId().toString()); - assertEquals("Title", user.getInbox().getMessages().getFirst().getTitle()); - assertEquals(charityId, user.getInbox().getMessages().getFirst().getFrom().getUUID().toString()); - } - - // ---------------------------------------------------------------- - // updateUserSettings() - // ---------------------------------------------------------------- - - @Test - void updateUserSettings_returnsTrueOnSuccess() throws SQLException { - when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); - when(mockStmt.executeUpdate()).thenReturn(1); - - User user = buildTestUser(); - Settings newSettings = new Settings(true, Language.ENGLISH, false); - - assertTrue(userDAO.updateUserSettings(user, newSettings)); - verify(mockStmt).setBoolean(1, true); // isAnonymous - verify(mockStmt).setBoolean(3, false); // lightmode - } - - @Test - void updateUserSettings_returnsFalseOnSQLException() throws SQLException { - when(mockConn.prepareStatement(anyString())) - .thenThrow(new SQLException("Timeout")); - - assertFalse(userDAO.updateUserSettings(buildTestUser(), new Settings(false, Language.ENGLISH, true))); - } - - // ---------------------------------------------------------------- - // Helper - // ---------------------------------------------------------------- - - private User buildTestUser() { - Settings settings = new Settings(false, Language.ENGLISH, true); - User user = new User( - UUID.randomUUID().toString(), - "TestUser", - "test@example.com", - "hashedpassword123", - Role.NORMAL_USER.toString() - ); - user.setSettings(settings); - user.setInbox(new Inbox()); - return user; - } -} \ No newline at end of file + // --- Mocks --- + private DatabaseConnection mockDbConnection; + private Connection mockConn; + private PreparedStatement mockStmt; + private ResultSet mockRs; + + private UserDAO userDAO; + + @BeforeEach + void setUp() throws SQLException { + mockDbConnection = mock(DatabaseConnection.class); + mockConn = mock(Connection.class); + mockStmt = mock(PreparedStatement.class); + mockRs = mock(ResultSet.class); + + // Every test gets a fresh DAO wired to our fake connection + when(mockDbConnection.getMySqlConnection()).thenReturn(mockConn); + + userDAO = new UserDAO(mockDbConnection); + } + + // ---------------------------------------------------------------- + // getUserFromDBUuid() + // ---------------------------------------------------------------- + + @Test + void getUserFromDBUuid_returnsUserWhenFound() throws SQLException { + when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); + when(mockStmt.executeQuery()).thenReturn(mockRs); + when(mockRs.next()).thenReturn(true, false); + + String userId = UUID.randomUUID().toString(); + String messageId = UUID.randomUUID().toString(); + String charityId = UUID.randomUUID().toString(); + + when(mockRs.getString("UUID_User")).thenReturn(userId); + when(mockRs.getString("user_name")).thenReturn("Bob"); + when(mockRs.getString("user_email")).thenReturn("bob@example.com"); + when(mockRs.getString("user_password")).thenReturn("hashedpw"); + when(mockRs.getString("role")).thenReturn(Role.NORMAL_USER.toString()); + + when(mockRs.getString("isAnonymous")).thenReturn("false"); + when(mockRs.getBoolean("isAnonymous")).thenReturn(false); + when(mockRs.getString("language")).thenReturn(Language.ENGLISH.toString()); + when(mockRs.getBoolean("lightmode")).thenReturn(true); + + when(mockRs.getString("UUID_message")).thenReturn(messageId); + when(mockRs.getString("message_title")).thenReturn("Hello"); + when(mockRs.getString("message_content")).thenReturn("Some content"); + when(mockRs.getString("message_date")).thenReturn(LocalDate.now().toString()); + + when(mockRs.getString("UUID_charities")).thenReturn(charityId); + when(mockRs.getString("org_number")).thenReturn("9999"); + when(mockRs.getString("charity_name")).thenReturn("HelpOrg"); + when(mockRs.getString("charity_link")).thenReturn("helporg.com"); + when(mockRs.getString("status")).thenReturn("active"); + when(mockRs.getBoolean("pre_approved")).thenReturn(true); + when(mockRs.getString("description")).thenReturn("We help"); + when(mockRs.getString("logoURL")).thenReturn(null); + when(mockRs.getString("key_values")).thenReturn(null); + when(mockRs.getBytes("logoBLOB")).thenReturn(null); + + User user = userDAO.getUserFromDBUuid(userId); + + assertNotNull(user); + assertEquals(userId, user.getId().toString()); + assertEquals("Bob", user.getUsername()); + assertEquals(1, user.getInbox().getMessages().size()); + assertEquals("Hello", user.getInbox().getMessages().getFirst().getTitle()); + assertEquals( + charityId, user.getInbox().getMessages().getFirst().getFrom().getUUID().toString()); + } + + @Test + void getUserFromDBUuid_returnsNullWhenNotFound() throws SQLException { + when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); + when(mockStmt.executeQuery()).thenReturn(mockRs); + when(mockRs.next()).thenReturn(false); // no rows + + User user = userDAO.getUserFromDBUuid(UUID.randomUUID().toString()); + + assertNull(user); + } + + @Test + void getUserFromDBUuid_throwsRuntimeExceptionOnSQLException() throws SQLException { + when(mockConn.prepareStatement(anyString())).thenThrow(new SQLException("Connection lost")); + + assertThrows( + RuntimeException.class, () -> userDAO.getUserFromDBUuid(UUID.randomUUID().toString())); + } + + @Test + void getUserFromDBUuid_doesNotDuplicateMessagesAcrossRows() throws SQLException { + // Same message ID appearing in two rows should only produce one Message in the inbox + when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); + when(mockStmt.executeQuery()).thenReturn(mockRs); + when(mockRs.next()).thenReturn(true, true, false); + + String userId = UUID.randomUUID().toString(); + String messageId = UUID.randomUUID().toString(); // same ID both rows + String charityId = UUID.randomUUID().toString(); + + when(mockRs.getString("UUID_User")).thenReturn(userId); + when(mockRs.getString("user_name")).thenReturn("Bob"); + when(mockRs.getString("user_email")).thenReturn("bob@example.com"); + when(mockRs.getString("user_password")).thenReturn("hashedpw"); + when(mockRs.getString("role")).thenReturn(Role.NORMAL_USER.toString()); + when(mockRs.getString("isAnonymous")).thenReturn("false"); + when(mockRs.getBoolean("isAnonymous")).thenReturn(false); + when(mockRs.getString("language")).thenReturn(Language.ENGLISH.toString()); + when(mockRs.getBoolean("lightmode")).thenReturn(false); + when(mockRs.getString("UUID_message")).thenReturn(messageId); + when(mockRs.getString("message_title")).thenReturn("Title"); + when(mockRs.getString("message_content")).thenReturn("Content"); + when(mockRs.getString("message_date")).thenReturn(LocalDate.now().toString()); + when(mockRs.getString("UUID_charities")).thenReturn(charityId); + when(mockRs.getString("org_number")).thenReturn("1234"); + when(mockRs.getString("charity_name")).thenReturn("Org"); + when(mockRs.getString("charity_link")).thenReturn("org.com"); + when(mockRs.getString("status")).thenReturn("active"); + when(mockRs.getBoolean("pre_approved")).thenReturn(false); + when(mockRs.getString("description")).thenReturn("desc"); + when(mockRs.getString("logoURL")).thenReturn(null); + when(mockRs.getString("key_values")).thenReturn(null); + when(mockRs.getBytes("logoBLOB")).thenReturn(null); + + User user = userDAO.getUserFromDBUuid(userId); + + assertEquals(1, user.getInbox().getMessages().size()); + } + + // ---------------------------------------------------------------- + // isEmailTaken() + // ---------------------------------------------------------------- + + @Test + void isEmailTaken_returnsTrueWhenEmailExists() throws SQLException { + when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); + when(mockStmt.executeQuery()).thenReturn(mockRs); + when(mockRs.next()).thenReturn(true); // simulates a row found + + assertTrue(userDAO.isEmailTaken("test@example.com")); + } + + @Test + void isEmailTaken_returnsFalseWhenEmailDoesNotExist() throws SQLException { + when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); + when(mockStmt.executeQuery()).thenReturn(mockRs); + when(mockRs.next()).thenReturn(false); // no row → email is free + + assertFalse(userDAO.isEmailTaken("new@example.com")); + } + + @Test + void isEmailTaken_throwsOnInvalidEmail() { + // No DB call should happen — the guard clause throws immediately + assertThrows(IllegalArgumentException.class, () -> userDAO.isEmailTaken("notanemail")); + + assertThrows(IllegalArgumentException.class, () -> userDAO.isEmailTaken(null)); + + assertThrows(IllegalArgumentException.class, () -> userDAO.isEmailTaken(" ")); + } + + // ---------------------------------------------------------------- + // getUsersFromDB() + // ---------------------------------------------------------------- + + @Test + void getUsersFromDB_returnsAllUsers() throws SQLException { + Statement mockStatement = mock(Statement.class); + when(mockConn.createStatement()).thenReturn(mockStatement); + when(mockStatement.executeQuery(anyString())).thenReturn(mockRs); + + String userId1 = UUID.randomUUID().toString(); + String userId2 = UUID.randomUUID().toString(); + + // Two distinct users, no messages to keep stubbing simple + when(mockRs.next()).thenReturn(true, true, false); + when(mockRs.getString("UUID_User")).thenReturn(userId1, userId2); + when(mockRs.getString("user_name")).thenReturn("Alice", "Bob"); + when(mockRs.getString("user_email")).thenReturn("alice@example.com", "bob@example.com"); + when(mockRs.getString("user_password")).thenReturn("hash1", "hash2"); + when(mockRs.getString("role")).thenReturn(Role.NORMAL_USER.toString()); + when(mockRs.getString("isAnonymous")).thenReturn(null); // no settings row + when(mockRs.getString("UUID_message")).thenReturn(null); // no messages + + UserRegistry registry = userDAO.getUsersFromDB(); + + assertNotNull(registry); + assertEquals(2, registry.getAllUsers().size()); + } + + @Test + void getUsersFromDB_returnsEmptyRegistryWhenNoUsers() throws SQLException { + Statement mockStatement = mock(Statement.class); + when(mockConn.createStatement()).thenReturn(mockStatement); + when(mockStatement.executeQuery(anyString())).thenReturn(mockRs); + when(mockRs.next()).thenReturn(false); + + UserRegistry registry = userDAO.getUsersFromDB(); + + assertNotNull(registry); + assertTrue(registry.getAllUsers().isEmpty()); + } + + // ---------------------------------------------------------------- + // getSettingsForUser() + // ---------------------------------------------------------------- + + @Test + void getSettingsForUser_returnsSettingsWhenFound() throws SQLException { + when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); + when(mockStmt.executeQuery()).thenReturn(mockRs); + when(mockRs.next()).thenReturn(true, false); + when(mockRs.getBoolean("isAnonymous")).thenReturn(true); + when(mockRs.getString("language")).thenReturn(Language.ENGLISH.toString()); + when(mockRs.getBoolean("lightmode")).thenReturn(false); + + Settings settings = userDAO.getSettingsForUser(UUID.randomUUID().toString()); + + assertNotNull(settings); + assertTrue(settings.isAnonymous()); + assertEquals(Language.ENGLISH, settings.getLanguage()); + assertFalse(settings.isLightMode()); + } + + @Test + void getSettingsForUser_returnsNullWhenNotFound() throws SQLException { + when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); + when(mockStmt.executeQuery()).thenReturn(mockRs); + when(mockRs.next()).thenReturn(false); + + Settings settings = userDAO.getSettingsForUser(UUID.randomUUID().toString()); + + assertNull(settings); + } + + @Test + void getSettingsForUser_appliesMaxRowsLimit() throws SQLException { + when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); + when(mockStmt.executeQuery()).thenReturn(mockRs); + when(mockRs.next()).thenReturn(false); + + userDAO.getSettingsForUser(UUID.randomUUID().toString()); + + // The DAO must call setMaxRows(1) to guard against multiple settings rows + verify(mockStmt).setMaxRows(1); + } + + @Test + void getSettingsForUser_throwsRuntimeExceptionOnSQLException() throws SQLException { + when(mockConn.prepareStatement(anyString())).thenThrow(new SQLException("DB error")); + + assertThrows( + RuntimeException.class, () -> userDAO.getSettingsForUser(UUID.randomUUID().toString())); + } + + // ---------------------------------------------------------------- + // updateUserDetails() + // ---------------------------------------------------------------- + + @Test + void updateUserDetails_returnsTrueOnSuccess() throws SQLException { + when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); + when(mockStmt.executeUpdate()).thenReturn(1); + + User user = buildTestUser(); + assertTrue(userDAO.updateUserDetails(user)); + + // Verify the three columns are set in the correct parameter order + verify(mockStmt).setString(1, user.getUsername()); + verify(mockStmt).setString(2, user.getEmail()); + verify(mockStmt).setString(3, user.getPasswordHash()); + verify(mockStmt).setString(4, user.getId().toString()); + } + + @Test + void updateUserDetails_returnsFalseWhenNoRowsAffected() throws SQLException { + when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); + when(mockStmt.executeUpdate()).thenReturn(0); + + assertFalse(userDAO.updateUserDetails(buildTestUser())); + } + + @Test + void updateUserDetails_returnsFalseOnSQLException() throws SQLException { + when(mockConn.prepareStatement(anyString())).thenThrow(new SQLException("Update failed")); + + assertFalse(userDAO.updateUserDetails(buildTestUser())); + } + + // ---------------------------------------------------------------- + // getInboxForUser() + // ---------------------------------------------------------------- + + @Test + void getInboxForUser_returnsInboxWithMessages() throws SQLException { + when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); + when(mockStmt.executeQuery()).thenReturn(mockRs); + when(mockRs.next()).thenReturn(true, false); + + String charityId = UUID.randomUUID().toString(); + when(mockRs.getString("UUID_charities")).thenReturn(charityId); + when(mockRs.getString("org_number")).thenReturn("5678"); + when(mockRs.getString("charity_name")).thenReturn("SaveAll"); + when(mockRs.getString("charity_link")).thenReturn("saveall.org"); + when(mockRs.getString("status")).thenReturn("active"); + when(mockRs.getBoolean("pre_approved")).thenReturn(false); + when(mockRs.getString("description")).thenReturn("We save"); + when(mockRs.getString("logoURL")).thenReturn(null); + when(mockRs.getString("key_values")).thenReturn(null); + when(mockRs.getBytes("logoBLOB")).thenReturn(null); + when(mockRs.getString("message_title")).thenReturn("Update"); + when(mockRs.getString("message_content")).thenReturn("Big news"); + when(mockRs.getString("message_date")).thenReturn(LocalDate.now().toString()); + + Inbox inbox = userDAO.getInboxForUser(UUID.randomUUID().toString()); + + assertNotNull(inbox); + assertEquals(1, inbox.getMessages().size()); + assertEquals("Update", inbox.getMessages().getFirst().getTitle()); + assertEquals(charityId, inbox.getMessages().getFirst().getFrom().getUUID().toString()); + } + + @Test + void getInboxForUser_returnsEmptyInboxWhenNoMessages() throws SQLException { + when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); + when(mockStmt.executeQuery()).thenReturn(mockRs); + when(mockRs.next()).thenReturn(false); + + Inbox inbox = userDAO.getInboxForUser(UUID.randomUUID().toString()); + + assertNotNull(inbox); + assertTrue(inbox.getMessages().isEmpty()); + } + + @Test + void getInboxForUser_throwsRuntimeExceptionOnSQLException() throws SQLException { + when(mockConn.prepareStatement(anyString())).thenThrow(new SQLException("Timeout")); + + assertThrows( + RuntimeException.class, () -> userDAO.getInboxForUser(UUID.randomUUID().toString())); + } + + // ---------------------------------------------------------------- + // registerUser() + // ---------------------------------------------------------------- + + @Test + void registerUser_returnsTrueOnSuccess() throws SQLException { + // Two prepared statements are created (User insert + Settings insert) + when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); + when(mockStmt.executeUpdate()).thenReturn(1); // 1 row affected each time + + User user = buildTestUser(); + assertTrue(userDAO.registerUser(user)); + + // Both inserts should have been executed + verify(mockStmt, times(2)).executeUpdate(); + // Auto-commit should have been disabled and commit called + verify(mockConn).setAutoCommit(false); + verify(mockConn).commit(); + } + + @Test + void registerUser_returnsFalseWhenInsertAffectsNoRows() throws SQLException { + when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); + when(mockStmt.executeUpdate()).thenReturn(0); // nothing inserted + + assertFalse(userDAO.registerUser(buildTestUser())); + } + + @Test + void registerUser_returnsFalseOnSQLException() throws SQLException { + when(mockConn.prepareStatement(anyString())).thenThrow(new SQLException("DB down")); + + assertFalse(userDAO.registerUser(buildTestUser())); + } + + // ---------------------------------------------------------------- + // getUserFromDBEmailAndPassword() + // ---------------------------------------------------------------- + + @Test + void getUserFromDB_returnsNullWhenPasswordDoesNotMatch() throws SQLException { + when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); + when(mockStmt.executeQuery()).thenReturn(mockRs); + + when(mockRs.next()).thenReturn(true, false); + when(mockRs.getString("UUID_User")).thenReturn("some-uuid"); + when(mockRs.getString("user_name")).thenReturn("Alice"); + when(mockRs.getString("user_password")) + .thenReturn(new PasswordHasher().getHashPassword("differentPassword")); + + User result = userDAO.getUserFromDBEmailAndPassword("alice@example.com", "wrongPassword"); + + assertNull(result); + } + + @Test + void getUserFromDB_throwsRuntimeExceptionOnSQLException() throws SQLException { + when(mockConn.prepareStatement(anyString())).thenThrow(new SQLException("Connection lost")); + + assertThrows( + RuntimeException.class, () -> userDAO.getUserFromDBEmailAndPassword("a@b.com", "pass")); + } + + @Test + void getUserFromDB_returnsAUserWhenCorrect() throws SQLException { + when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); + when(mockStmt.executeQuery()).thenReturn(mockRs); + when(mockRs.next()).thenReturn(true, false); + String userId = UUID.randomUUID().toString(); + when(mockRs.getString("UUID_User")).thenReturn(userId); + when(mockRs.getString("user_name")).thenReturn("name"); + when(mockRs.getString("user_email")).thenReturn("a@b.com"); + when(mockRs.getString("user_password")) + .thenReturn(new PasswordHasher().getHashPassword("somePassword")); + when(mockRs.getString("role")).thenReturn(Role.NORMAL_USER.toString()); + when(mockRs.getBoolean("isAnonymous")).thenReturn(false); + when(mockRs.getString("language")).thenReturn(Language.ENGLISH.toString()); + when(mockRs.getBoolean("lightmode")).thenReturn(false); + String messageId = UUID.randomUUID().toString(); + when(mockRs.getString("message_title")).thenReturn("Title"); + when(mockRs.getString("UUID_message")).thenReturn(messageId); + when(mockRs.getString("message_content")).thenReturn("blah blah blah"); + when(mockRs.getString("message_date")).thenReturn(LocalDate.now().toString()); + + String charityId = UUID.randomUUID().toString(); + when(mockRs.getString("org_number")).thenReturn("1234"); + when(mockRs.getString("charity_name")).thenReturn("charity"); + when(mockRs.getString("charity_link")).thenReturn("link.com"); + when(mockRs.getString("status")).thenReturn("Something"); + when(mockRs.getString("UUID_charities")).thenReturn(charityId); + when(mockRs.getString("description")).thenReturn(charityId); + when(mockRs.getString("logoURL")).thenReturn(null); + when(mockRs.getString("key_values")).thenReturn(null); + when(mockRs.getBytes("logoBLOB")).thenReturn(null); + + User user = userDAO.getUserFromDBEmailAndPassword("a@b.com", "somePassword"); + + assertEquals(userId, user.getId().toString()); + assertEquals("Title", user.getInbox().getMessages().getFirst().getTitle()); + assertEquals( + charityId, user.getInbox().getMessages().getFirst().getFrom().getUUID().toString()); + } + + // ---------------------------------------------------------------- + // updateUserSettings() + // ---------------------------------------------------------------- + + @Test + void updateUserSettings_returnsTrueOnSuccess() throws SQLException { + when(mockConn.prepareStatement(anyString())).thenReturn(mockStmt); + when(mockStmt.executeUpdate()).thenReturn(1); + + User user = buildTestUser(); + Settings newSettings = new Settings(true, Language.ENGLISH, false); + + assertTrue(userDAO.updateUserSettings(user, newSettings)); + verify(mockStmt).setBoolean(1, true); // isAnonymous + verify(mockStmt).setBoolean(3, false); // lightmode + } + + @Test + void updateUserSettings_returnsFalseOnSQLException() throws SQLException { + when(mockConn.prepareStatement(anyString())).thenThrow(new SQLException("Timeout")); + + assertFalse( + userDAO.updateUserSettings(buildTestUser(), new Settings(false, Language.ENGLISH, true))); + } + + // ---------------------------------------------------------------- + // Helper + // ---------------------------------------------------------------- + + private User buildTestUser() { + Settings settings = new Settings(false, Language.ENGLISH, true); + User user = + new User( + UUID.randomUUID().toString(), + "TestUser", + "test@example.com", + "hashedpassword123", + Role.NORMAL_USER.toString()); + user.setSettings(settings); + user.setInbox(new Inbox()); + return user; + } +} diff --git a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/CharityTest.java b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/CharityTest.java index 79118e13..0404df17 100644 --- a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/CharityTest.java +++ b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/CharityTest.java @@ -6,7 +6,6 @@ import java.util.ArrayList; import java.util.List; import java.util.UUID; - import ntnu.systemutvikling.team6.models.user.Inbox; import ntnu.systemutvikling.team6.models.user.Role; import ntnu.systemutvikling.team6.models.user.Settings; @@ -60,154 +59,137 @@ public void testIsVerifiedReturnsCorrectly() { @Test public void testDatabaseSelectConstructor() { - UUID uuid = UUID.randomUUID(); - String orgNumber = "123"; - boolean preApproved = true; - String status = "approved"; - Charity selectCharity = - new Charity( - uuid.toString(), - orgNumber, - preApproved, - status); - - assertEquals(uuid, selectCharity.getUUID()); - assertEquals(orgNumber, selectCharity.getOrg_number()); - assertEquals(preApproved, selectCharity.getPreApproved()); - assertEquals(status, selectCharity.getStatus()); + UUID uuid = UUID.randomUUID(); + String orgNumber = "123"; + boolean preApproved = true; + String status = "approved"; + Charity selectCharity = new Charity(uuid.toString(), orgNumber, preApproved, status); + + assertEquals(uuid, selectCharity.getUUID()); + assertEquals(orgNumber, selectCharity.getOrg_number()); + assertEquals(preApproved, selectCharity.getPreApproved()); + assertEquals(status, selectCharity.getStatus()); } @Test void testDatabaseConstructor() { - UUID uuid = UUID.randomUUID(); - String orgNumber = "123"; - String name = "testChair"; - boolean preApproved = true; - String status = "approved"; - String description = "describe"; - String logoURL = "www.image.png"; - String keyValues = "90,2;10,5;98,0"; - - byte[] logoBlob = new byte[] {1, 2, 3, 4, 5}; - - Charity databaseCharity = - new Charity( - uuid.toString(), - orgNumber, - name, - logoURL, - status, - preApproved, - description, - logoURL, - keyValues, - logoBlob - ); - - assertEquals(uuid, databaseCharity.getUUID()); - assertEquals(orgNumber, databaseCharity.getOrg_number()); - assertEquals(name, databaseCharity.getName()); - assertEquals(logoURL, databaseCharity.getLogoURL()); - assertEquals(status, databaseCharity.getStatus()); - assertEquals(preApproved, databaseCharity.getPreApproved()); - assertEquals(description, databaseCharity.getDescription()); - assertEquals(keyValues, databaseCharity.getKeyValues()); - assertEquals(logoBlob, databaseCharity.getLogoBlob()); + UUID uuid = UUID.randomUUID(); + String orgNumber = "123"; + String name = "testChair"; + boolean preApproved = true; + String status = "approved"; + String description = "describe"; + String logoURL = "www.image.png"; + String keyValues = "90,2;10,5;98,0"; + + byte[] logoBlob = new byte[] {1, 2, 3, 4, 5}; + + Charity databaseCharity = + new Charity( + uuid.toString(), + orgNumber, + name, + logoURL, + status, + preApproved, + description, + logoURL, + keyValues, + logoBlob); + + assertEquals(uuid, databaseCharity.getUUID()); + assertEquals(orgNumber, databaseCharity.getOrg_number()); + assertEquals(name, databaseCharity.getName()); + assertEquals(logoURL, databaseCharity.getLogoURL()); + assertEquals(status, databaseCharity.getStatus()); + assertEquals(preApproved, databaseCharity.getPreApproved()); + assertEquals(description, databaseCharity.getDescription()); + assertEquals(keyValues, databaseCharity.getKeyValues()); + assertEquals(logoBlob, databaseCharity.getLogoBlob()); } @Test void getAndSetFeedbackShouldBeCorrect() { - String validUsername = "username"; - String validEmail = "Email@gmail.com"; - String validPassword = "Password"; - Role validRole = Role.NORMAL_USER; - Settings validSettings = new Settings(); - Inbox validInbox = new Inbox(); - User user = - new User( - validUsername, - validEmail, - validPassword, - validRole, - validSettings, - validInbox); - Feedback feedback = - new Feedback( - UUID.randomUUID().toString(), - user, - "Feedback.", - LocalDate.now() - ); - ArrayListfeedbackList = new ArrayList<>(); - feedbackList.add(feedback); - - charity.setFeedbacks(feedbackList); - - assertSame(charity.getFeedbacks(), feedbackList); + String validUsername = "username"; + String validEmail = "Email@gmail.com"; + String validPassword = "Password"; + Role validRole = Role.NORMAL_USER; + Settings validSettings = new Settings(); + Inbox validInbox = new Inbox(); + User user = + new User(validUsername, validEmail, validPassword, validRole, validSettings, validInbox); + Feedback feedback = + new Feedback(UUID.randomUUID().toString(), user, "Feedback.", LocalDate.now()); + ArrayList feedbackList = new ArrayList<>(); + feedbackList.add(feedback); + + charity.setFeedbacks(feedbackList); + + assertSame(charity.getFeedbacks(), feedbackList); } @Test void setNameShouldBeCorrect() { - String name = "Bob's charity"; + String name = "Bob's charity"; - charity.setName(name); + charity.setName(name); - assertEquals(name, charity.getName()); + assertEquals(name, charity.getName()); } @Test void setCategoryShouldBeCorrect() { - String category = "Ghana"; - List categoryList = new ArrayList<>(); - categoryList.add(category); + String category = "Ghana"; + List categoryList = new ArrayList<>(); + categoryList.add(category); - charity.setCategory(categoryList); + charity.setCategory(categoryList); - assertEquals(category, charity.getCategory().getFirst()); + assertEquals(category, charity.getCategory().getFirst()); } @Test void setDescriptionShouldBeCorrect() { - String description = "blablabla"; + String description = "blablabla"; - charity.setDescription(description); + charity.setDescription(description); - assertEquals(description, charity.getDescription()); + assertEquals(description, charity.getDescription()); } @Test void setLogoUrlShouldBeCorrect() { - String logoURL = "www.image.png"; + String logoURL = "www.image.png"; - charity.setLogoURL(logoURL); + charity.setLogoURL(logoURL); - assertEquals(logoURL, charity.getLogoURL()); + assertEquals(logoURL, charity.getLogoURL()); } @Test void setKeyValuesShouldBeCorrect() { - String keyValues = "98,2;5,6;75,4"; + String keyValues = "98,2;5,6;75,4"; - charity.setKeyValues(keyValues); + charity.setKeyValues(keyValues); - assertEquals(keyValues, charity.getKeyValues()); + assertEquals(keyValues, charity.getKeyValues()); } @Test void setLogoBlobShouldBeCorrect() { - byte[] logoBlob = new byte[] {1, 2, 3, 4, 5}; + byte[] logoBlob = new byte[] {1, 2, 3, 4, 5}; - charity.setLogoBlob(logoBlob); + charity.setLogoBlob(logoBlob); - assertEquals(logoBlob, charity.getLogoBlob()); + assertEquals(logoBlob, charity.getLogoBlob()); } @Test void setUUIDFromStringShouldBeCorrect() { - UUID uuid = UUID.randomUUID(); + UUID uuid = UUID.randomUUID(); - charity.setUUIDFromString(uuid.toString()); + charity.setUUIDFromString(uuid.toString()); - assertEquals(uuid, charity.getUUID()); + assertEquals(uuid, charity.getUUID()); } } diff --git a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/DonationTest.java b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/DonationTest.java index 4a960099..18f4c299 100644 --- a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/DonationTest.java +++ b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/DonationTest.java @@ -5,7 +5,6 @@ import java.time.LocalDate; import java.time.LocalDateTime; import java.util.UUID; - import ntnu.systemutvikling.team6.models.user.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -20,13 +19,8 @@ public void setup() { charity = new Charity("Charity1", "www.aaaa.com", "Cancer", false, "unverified"); user = - new User( - "username", - "Valid@gmail.com", - "123", - Role.NORMAL_USER, - new Settings(), - new Inbox()); + new User( + "username", "Valid@gmail.com", "123", Role.NORMAL_USER, new Settings(), new Inbox()); } // --- Tests --- @@ -45,15 +39,17 @@ void testDonationInitialization() { @Test void testDonationFromDatabaseInitialization() { - LocalDateTime now = LocalDateTime.now(); + LocalDateTime now = LocalDateTime.now(); - Donation donation = new Donation(UUID.randomUUID().toString(), 500.0, LocalDate.from(now), charity, user, false); + Donation donation = + new Donation( + UUID.randomUUID().toString(), 500.0, LocalDate.from(now), charity, user, false); - assertNotNull(donation.getCharityId()); - assertEquals(500.0, donation.getAmount()); - assertEquals(LocalDate.from(now), donation.getDate()); - assertEquals(charity, donation.getCharity()); - assertEquals(user, donation.getDonor()); + assertNotNull(donation.getCharityId()); + assertEquals(500.0, donation.getAmount()); + assertEquals(LocalDate.from(now), donation.getDate()); + assertEquals(charity, donation.getCharity()); + assertEquals(user, donation.getDonor()); } @Test diff --git a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/FeedbackTest.java b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/FeedbackTest.java index 5e4af2d2..597c0f7d 100644 --- a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/FeedbackTest.java +++ b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/FeedbackTest.java @@ -6,7 +6,6 @@ import java.time.LocalDateTime; import java.time.chrono.ChronoLocalDate; import java.util.UUID; - import ntnu.systemutvikling.team6.models.user.Inbox; import ntnu.systemutvikling.team6.models.user.Role; import ntnu.systemutvikling.team6.models.user.Settings; @@ -22,13 +21,8 @@ class FeedbackTest { @BeforeEach public void setup() { user = - new User( - "username", - "Valid@gmail.com", - "123", - Role.NORMAL_USER, - new Settings(), - new Inbox()); + new User( + "username", "Valid@gmail.com", "123", Role.NORMAL_USER, new Settings(), new Inbox()); } // --- Tests --- @@ -48,19 +42,16 @@ void testFeedbackInitialization() { !feedback.getDate().isBefore(ChronoLocalDate.from(before)) && !feedback.getDate().isAfter(ChronoLocalDate.from(after))); } -@Test + + @Test void testFeedBackFromDatabaseInitialization() { - LocalDate date = LocalDate.now(); - Feedback feedback = new Feedback( - UUID.randomUUID().toString(), - user, - "Nice work!", - date); - - assertNotNull(feedback.getFeedbackId()); - assertEquals("Nice work!", feedback.getComment()); - assertEquals(user, feedback.getUser()); - assertEquals(date, feedback.getDate()); + LocalDate date = LocalDate.now(); + Feedback feedback = new Feedback(UUID.randomUUID().toString(), user, "Nice work!", date); + + assertNotNull(feedback.getFeedbackId()); + assertEquals("Nice work!", feedback.getComment()); + assertEquals(user, feedback.getUser()); + assertEquals(date, feedback.getDate()); } @Test diff --git a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/registry/CharityRegistryTest.java b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/registry/CharityRegistryTest.java index ed227924..20a53858 100644 --- a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/registry/CharityRegistryTest.java +++ b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/registry/CharityRegistryTest.java @@ -5,7 +5,6 @@ import java.util.List; import java.util.Optional; import java.util.UUID; - import ntnu.systemutvikling.team6.models.Charity; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -69,11 +68,9 @@ void testFindCharityByOrgNumber() { @Test void testFindCharityByOrgNumberNullThrowsException() { - registry.addCharity(charity); + registry.addCharity(charity); - assertThrows( - IllegalArgumentException.class, - () -> registry.findCharityByOrgnumber(null)); + assertThrows(IllegalArgumentException.class, () -> registry.findCharityByOrgnumber(null)); } @Test @@ -99,12 +96,12 @@ void testRemoveCharitySuccessfully() { @Test void testRemoveCharitySuccessfullyOrgNumber() { - registry.addCharity(charity); + registry.addCharity(charity); - boolean removed = registry.removeCharity(charity.getOrg_number()); + boolean removed = registry.removeCharity(charity.getOrg_number()); - assertTrue(removed); - assertTrue(registry.getAllCharities().isEmpty()); + assertTrue(removed); + assertTrue(registry.getAllCharities().isEmpty()); } @Test @@ -120,8 +117,7 @@ void testRemoveCharityNullThrowsException() { @Test void testRemoveCharityUUIDNullThrowsException() { - UUID uuid = null; - assertThrows(IllegalArgumentException.class, () -> registry.removeCharityUUID(uuid)); - + UUID uuid = null; + assertThrows(IllegalArgumentException.class, () -> registry.removeCharityUUID(uuid)); } } diff --git a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/registry/DonationRegistryTest.java b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/registry/DonationRegistryTest.java index 3ac15c9e..9da91272 100644 --- a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/registry/DonationRegistryTest.java +++ b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/registry/DonationRegistryTest.java @@ -7,7 +7,6 @@ import java.util.List; import java.util.Optional; import java.util.UUID; - import ntnu.systemutvikling.team6.models.Charity; import ntnu.systemutvikling.team6.models.Donation; import ntnu.systemutvikling.team6.models.user.Settings; diff --git a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/registry/UserRegistryTest.java b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/registry/UserRegistryTest.java index f4ca6253..6c0ee619 100644 --- a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/registry/UserRegistryTest.java +++ b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/registry/UserRegistryTest.java @@ -1,5 +1,9 @@ package ntnu.systemutvikling.team6.models.registry; +import static org.junit.jupiter.api.Assertions.*; + +import java.util.Optional; +import java.util.UUID; import ntnu.systemutvikling.team6.models.user.Inbox; import ntnu.systemutvikling.team6.models.user.Role; import ntnu.systemutvikling.team6.models.user.Settings; @@ -7,100 +11,79 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.Optional; -import java.util.UUID; +class UserRegistryTest { + User user; + UserRegistry userRegistry; -import static org.junit.jupiter.api.Assertions.*; + @BeforeEach + void setUp() { + String validUsername = "username"; + String validEmail = "Email@gmail.com"; + String validPassword = "Password"; + Role validRole = Role.NORMAL_USER; + Settings validSettings = new Settings(); + Inbox validInbox = new Inbox(); + this.user = + new User(validUsername, validEmail, validPassword, validRole, validSettings, validInbox); + userRegistry = new UserRegistry(); + } -class UserRegistryTest { - User user; - UserRegistry userRegistry; - - @BeforeEach - void setUp() { - String validUsername = "username"; - String validEmail = "Email@gmail.com"; - String validPassword = "Password"; - Role validRole = Role.NORMAL_USER; - Settings validSettings = new Settings(); - Inbox validInbox = new Inbox(); - this.user = - new User( - validUsername, - validEmail, - validPassword, - validRole, - validSettings, - validInbox - ); - userRegistry = new UserRegistry(); - } - - @Test - void userRegistryShouldStartEmpty() { - assertEquals(0, userRegistry.getAllUsers().size()); - } - - @Test - void addUserTest() { - userRegistry.addUser(user); - - assertEquals(user, userRegistry.getAllUsers().getFirst()); - } - - @Test - void addingNullUserShouldThrow() { - assertThrows( - IllegalArgumentException.class, - () -> userRegistry.addUser(null) - ); - } - - @Test - void removeUserTest() { - userRegistry.addUser(user); - - userRegistry.removeUserByUUID(user.getId()); - - assertEquals(0, userRegistry.getAllUsers().size()); - } - - @Test - void removeNullUserShouldThrow() { - userRegistry.addUser(user); - - assertThrows( - IllegalArgumentException.class, - () -> userRegistry.removeUserByUUID(null) - ); - } - - @Test - void getUserByUUIDTest() { - userRegistry.addUser(user); - - Optional result = userRegistry.findUserById(user.getId()); - - assertTrue(result.isPresent()); - assertEquals(result.get().getId(), user.getId()); - } - - @Test - void getUserByUUIDNonExistentUserTest() { - userRegistry.addUser(user); - - Optional result = userRegistry.findUserById(UUID.randomUUID()); - - assertFalse(result.isPresent()); - } - - @Test - void getNullUserByUUIDShouldThrow() { - userRegistry.addUser(user); - - assertThrows( - IllegalArgumentException.class, - () -> userRegistry.findUserById(null) - ); - } -} \ No newline at end of file + @Test + void userRegistryShouldStartEmpty() { + assertEquals(0, userRegistry.getAllUsers().size()); + } + + @Test + void addUserTest() { + userRegistry.addUser(user); + + assertEquals(user, userRegistry.getAllUsers().getFirst()); + } + + @Test + void addingNullUserShouldThrow() { + assertThrows(IllegalArgumentException.class, () -> userRegistry.addUser(null)); + } + + @Test + void removeUserTest() { + userRegistry.addUser(user); + + userRegistry.removeUserByUUID(user.getId()); + + assertEquals(0, userRegistry.getAllUsers().size()); + } + + @Test + void removeNullUserShouldThrow() { + userRegistry.addUser(user); + + assertThrows(IllegalArgumentException.class, () -> userRegistry.removeUserByUUID(null)); + } + + @Test + void getUserByUUIDTest() { + userRegistry.addUser(user); + + Optional result = userRegistry.findUserById(user.getId()); + + assertTrue(result.isPresent()); + assertEquals(result.get().getId(), user.getId()); + } + + @Test + void getUserByUUIDNonExistentUserTest() { + userRegistry.addUser(user); + + Optional result = userRegistry.findUserById(UUID.randomUUID()); + + assertFalse(result.isPresent()); + } + + @Test + void getNullUserByUUIDShouldThrow() { + userRegistry.addUser(user); + + assertThrows(IllegalArgumentException.class, () -> userRegistry.findUserById(null)); + } +} diff --git a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/user/InboxTest.java b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/user/InboxTest.java index dad9c3de..693f28f8 100644 --- a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/user/InboxTest.java +++ b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/user/InboxTest.java @@ -5,7 +5,6 @@ import java.util.List; import java.util.Optional; import java.util.UUID; - import ntnu.systemutvikling.team6.models.Charity; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -17,11 +16,7 @@ public class InboxTest { @BeforeEach public void setup() { - Charity charity = new Charity( - UUID.randomUUID().toString(), - "123", - false, - "approved"); + Charity charity = new Charity(UUID.randomUUID().toString(), "123", false, "approved"); inbox = new Inbox(); newMessage = new Message("Title", charity, "Somewhere"); newMessage2 = new Message("Title2", charity, "Somewhere2"); diff --git a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/user/MessageTest.java b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/user/MessageTest.java index 9b41b666..ecf5b53b 100644 --- a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/user/MessageTest.java +++ b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/user/MessageTest.java @@ -1,6 +1,7 @@ package ntnu.systemutvikling.team6.models.user; import static org.junit.jupiter.api.Assertions.*; + import java.time.LocalDate; import java.util.UUID; import ntnu.systemutvikling.team6.models.Charity; @@ -9,139 +10,92 @@ import org.junit.jupiter.api.Test; public class MessageTest { - private Charity charity; - - @BeforeEach - void setUp() { - charity = new Charity( - UUID.randomUUID().toString(), - "123", - false, - "approved"); - } - @Nested - class FirstConstructorTest { - @Test - void shouldThrowExceptionIfNameIsNullOrEmpty() { - assertThrows( - IllegalArgumentException.class, - () -> new Message( - null, - charity, - "Something Somewhere Somehow")); - assertThrows( - IllegalArgumentException.class, - () -> new Message("", - charity, - "Something Somewhere Somehow")); - } + private Charity charity; - @Test - void shouldThrowExceptionIfFromIsNull() { - assertThrows( - IllegalArgumentException.class, - () -> new Message("Title", null, "Something Somewhere Somehow")); - } + @BeforeEach + void setUp() { + charity = new Charity(UUID.randomUUID().toString(), "123", false, "approved"); + } - @Test - void shouldThrowExceptionIfContentIsNullOrEmpty() { - assertThrows( - IllegalArgumentException.class, () -> new Message( - "Title", - charity, - null)); - assertThrows(IllegalArgumentException.class, () -> new Message( - "Title", - charity, - "")); - } - - @Test - void GettersWork() { - Message newMessage = new Message( - "Title", - charity, - "Somewhere"); - assertInstanceOf(UUID.class, newMessage.getId()); - assertEquals("Title", newMessage.getTitle()); - assertEquals(charity, newMessage.getFrom()); - assertEquals("Somewhere", newMessage.getContent()); - assertEquals(LocalDate.now(), newMessage.getTimeAndDate()); - } + @Nested + class FirstConstructorTest { + @Test + void shouldThrowExceptionIfNameIsNullOrEmpty() { + assertThrows( + IllegalArgumentException.class, + () -> new Message(null, charity, "Something Somewhere Somehow")); + assertThrows( + IllegalArgumentException.class, + () -> new Message("", charity, "Something Somewhere Somehow")); } - @Nested - class secondConstructorTest { - @Test - void shouldThrowExceptionIfNameIsNullOrEmpty() { - assertThrows( - IllegalArgumentException.class, - () -> new Message( - null, - charity, - "Something Somewhere Somehow", - LocalDate.now())); - assertThrows( - IllegalArgumentException.class, - () -> new Message("", - charity, - "Something Somewhere Somehow", - LocalDate.now())); - } - - @Test - void shouldThrowExceptionIfFromIsNull() { - assertThrows( - IllegalArgumentException.class, - () -> new Message( - "Title", - null, - "Something Somewhere Somehow", - LocalDate.now())); - } + @Test + void shouldThrowExceptionIfFromIsNull() { + assertThrows( + IllegalArgumentException.class, + () -> new Message("Title", null, "Something Somewhere Somehow")); + } - @Test - void shouldThrowExceptionIfContentIsNullOrEmpty() { - assertThrows( - IllegalArgumentException.class, () -> new Message( - "Title", - charity, - null, - LocalDate.now())); - assertThrows(IllegalArgumentException.class, () -> new Message( - "Title", - charity, - "", - LocalDate.now())); - } + @Test + void shouldThrowExceptionIfContentIsNullOrEmpty() { + assertThrows(IllegalArgumentException.class, () -> new Message("Title", charity, null)); + assertThrows(IllegalArgumentException.class, () -> new Message("Title", charity, "")); + } - @Test - void shouldThrowExceptionIfDateIsNull() { - assertThrows( - IllegalArgumentException.class, - () -> new Message( - "Title", - charity, - "Something Somewhere Somehow", - null)); - } + @Test + void GettersWork() { + Message newMessage = new Message("Title", charity, "Somewhere"); + assertInstanceOf(UUID.class, newMessage.getId()); + assertEquals("Title", newMessage.getTitle()); + assertEquals(charity, newMessage.getFrom()); + assertEquals("Somewhere", newMessage.getContent()); + assertEquals(LocalDate.now(), newMessage.getTimeAndDate()); + } + } - @Test - void GettersWork() { - Message newMessage = new Message( - "Title", - charity, - "Somewhere", - LocalDate.now()); - assertInstanceOf(UUID.class, newMessage.getId()); - assertEquals("Title", newMessage.getTitle()); - assertEquals(charity, newMessage.getFrom()); - assertEquals("Somewhere", newMessage.getContent()); - assertEquals(LocalDate.now(), newMessage.getTimeAndDate()); - } + @Nested + class secondConstructorTest { + @Test + void shouldThrowExceptionIfNameIsNullOrEmpty() { + assertThrows( + IllegalArgumentException.class, + () -> new Message(null, charity, "Something Somewhere Somehow", LocalDate.now())); + assertThrows( + IllegalArgumentException.class, + () -> new Message("", charity, "Something Somewhere Somehow", LocalDate.now())); + } + @Test + void shouldThrowExceptionIfFromIsNull() { + assertThrows( + IllegalArgumentException.class, + () -> new Message("Title", null, "Something Somewhere Somehow", LocalDate.now())); } + @Test + void shouldThrowExceptionIfContentIsNullOrEmpty() { + assertThrows( + IllegalArgumentException.class, + () -> new Message("Title", charity, null, LocalDate.now())); + assertThrows( + IllegalArgumentException.class, () -> new Message("Title", charity, "", LocalDate.now())); + } + @Test + void shouldThrowExceptionIfDateIsNull() { + assertThrows( + IllegalArgumentException.class, + () -> new Message("Title", charity, "Something Somewhere Somehow", null)); + } + @Test + void GettersWork() { + Message newMessage = new Message("Title", charity, "Somewhere", LocalDate.now()); + assertInstanceOf(UUID.class, newMessage.getId()); + assertEquals("Title", newMessage.getTitle()); + assertEquals(charity, newMessage.getFrom()); + assertEquals("Somewhere", newMessage.getContent()); + assertEquals(LocalDate.now(), newMessage.getTimeAndDate()); + } + } } diff --git a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/user/UserTest.java b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/user/UserTest.java index d2a7c578..f94be0fe 100644 --- a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/user/UserTest.java +++ b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/user/UserTest.java @@ -2,11 +2,10 @@ import static org.junit.jupiter.api.Assertions.*; +import java.util.UUID; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; -import java.util.UUID; - class UserTest { @Nested @@ -18,33 +17,18 @@ class constructorTests { private final Settings validSettings = new Settings(); private final Inbox validInbox = new Inbox(); - @Test void shouldThrowIfUsernameIsNull() { assertThrows( - IllegalArgumentException.class, - () -> - new User( - null, - validEmail, - validPassword, - validRole, - validSettings, - validInbox)); + IllegalArgumentException.class, + () -> new User(null, validEmail, validPassword, validRole, validSettings, validInbox)); } @Test void shouldThrowIfUsernameIsBlank() { assertThrows( - IllegalArgumentException.class, - () -> - new User( - " ", - validEmail, - validPassword, - validRole, - validSettings, - validInbox)); + IllegalArgumentException.class, + () -> new User(" ", validEmail, validPassword, validRole, validSettings, validInbox)); } @Nested @@ -53,598 +37,368 @@ class emailTests { @Test void shouldThrowIfEmailIsNull() { assertThrows( - IllegalArgumentException.class, - () -> - new User( - validUsername, - null, - validPassword, - validRole, - validSettings, - validInbox)); + IllegalArgumentException.class, + () -> + new User(validUsername, null, validPassword, validRole, validSettings, validInbox)); } @Test void shouldThrowIfEmailIsBlank() { assertThrows( - IllegalArgumentException.class, - () -> - new User( - validUsername, - " ", - validPassword, - validRole, - validSettings, - validInbox)); + IllegalArgumentException.class, + () -> + new User(validUsername, " ", validPassword, validRole, validSettings, validInbox)); } @Test void shouldThrowIfEmailDoesNotContainAt() { assertThrows( - IllegalArgumentException.class, - () -> - new User( - validUsername, - "test.gmail.com", - validPassword, - validRole, - validSettings, - validInbox)); + IllegalArgumentException.class, + () -> + new User( + validUsername, + "test.gmail.com", + validPassword, + validRole, + validSettings, + validInbox)); } @Test void shouldThrowIfEmailDoesNotContainPeriod() { assertThrows( - IllegalArgumentException.class, - () -> - new User( - validUsername, - "test@gmailcom", - validPassword, - validRole, - validSettings, - validInbox)); + IllegalArgumentException.class, + () -> + new User( + validUsername, + "test@gmailcom", + validPassword, + validRole, + validSettings, + validInbox)); } } @Test void shouldThrowIfPasswordIsNull() { assertThrows( - IllegalArgumentException.class, - () -> - new User( - validUsername, - validEmail, - null, - validRole, - validSettings, - validInbox)); + IllegalArgumentException.class, + () -> new User(validUsername, validEmail, null, validRole, validSettings, validInbox)); } @Test void shouldThrowIfRoleIsNull() { assertThrows( - IllegalArgumentException.class, - () -> - new User( - validUsername, - validEmail, - validPassword, - null, - validSettings, - validInbox)); + IllegalArgumentException.class, + () -> + new User(validUsername, validEmail, validPassword, null, validSettings, validInbox)); } @Test void shouldThrowIfPasswordIsBlank() { assertThrows( - IllegalArgumentException.class, - () -> - new User( - validUsername, - validEmail, - " ", - validRole, - validSettings, - validInbox)); + IllegalArgumentException.class, + () -> new User(validUsername, validEmail, " ", validRole, validSettings, validInbox)); } @Test void shouldThrowIfSettingsIsNull() { assertThrows( - IllegalArgumentException.class, - () -> - new User( - validUsername, - validEmail, - validPassword, - validRole, - null, - validInbox)); + IllegalArgumentException.class, + () -> new User(validUsername, validEmail, validPassword, validRole, null, validInbox)); } @Test void shouldThrowIfInboxIsNull() { assertThrows( - IllegalArgumentException.class, - () -> - new User( - validUsername, - validEmail, - validPassword, - validRole, - validSettings, - null)); + IllegalArgumentException.class, + () -> new User(validUsername, validEmail, validPassword, validRole, validSettings, null)); } @Test void shouldCreateUser() { User user = - new User( - validUsername, - validEmail, - validPassword, - validRole, - validSettings, - validInbox); + new User(validUsername, validEmail, validPassword, validRole, validSettings, validInbox); assertAll( - () -> assertEquals(validUsername, user.getUsername()), - () -> assertEquals(validEmail, user.getEmail()), - () -> assertEquals(validRole, user.getRole()), - () -> assertEquals(validSettings, user.getSettings()), - () -> assertEquals(validInbox, user.getInbox())); + () -> assertEquals(validUsername, user.getUsername()), + () -> assertEquals(validEmail, user.getEmail()), + () -> assertEquals(validRole, user.getRole()), + () -> assertEquals(validSettings, user.getSettings()), + () -> assertEquals(validInbox, user.getInbox())); } @Test - void shouldBeCorrectPassword() { - User user = - new User( - validUsername, - validEmail, - validPassword, - validRole, - validSettings, - validInbox); + void shouldBeCorrectPassword() { + User user = + new User(validUsername, validEmail, validPassword, validRole, validSettings, validInbox); - assertTrue(user.checkPassword(validPassword)); + assertTrue(user.checkPassword(validPassword)); } @Test - void getPasswordHashShouldNotBePlaintext() { - User user = - new User( - validUsername, - validEmail, - validPassword, - validRole, - validSettings, - validInbox); + void getPasswordHashShouldNotBePlaintext() { + User user = + new User(validUsername, validEmail, validPassword, validRole, validSettings, validInbox); - String hash = user.getPasswordHash(); + String hash = user.getPasswordHash(); - assertNotEquals(hash, validPassword); + assertNotEquals(hash, validPassword); } - @Test - void getPasswordHashShouldUseSalt() { - User user1 = - new User( - validUsername, - validEmail, - validPassword, - validRole, - validSettings, - validInbox); - - User user2 = - new User( - validUsername, - validEmail, - validPassword, - validRole, - validSettings, - validInbox); - - assertNotEquals(user1.getPasswordHash(), user2.getPasswordHash()); - } + @Test + void getPasswordHashShouldUseSalt() { + User user1 = + new User(validUsername, validEmail, validPassword, validRole, validSettings, validInbox); - @Test - void setNullUsernameShouldThrow() { - User user = - new User( - validUsername, - validEmail, - validPassword, - validRole, - validSettings, - validInbox); + User user2 = + new User(validUsername, validEmail, validPassword, validRole, validSettings, validInbox); - assertThrows( - IllegalArgumentException.class, - () -> user.setUsername(null)); - } + assertNotEquals(user1.getPasswordHash(), user2.getPasswordHash()); + } - @Test - void setBlankUsernameShouldThrow() { - User user = - new User( - validUsername, - validEmail, - validPassword, - validRole, - validSettings, - validInbox); - - assertThrows( - IllegalArgumentException.class, - () -> user.setUsername(" ")); - } + @Test + void setNullUsernameShouldThrow() { + User user = + new User(validUsername, validEmail, validPassword, validRole, validSettings, validInbox); - @Test - void setUserNameShouldBeCorrect() { - User user = - new User( - validUsername, - validEmail, - validPassword, - validRole, - validSettings, - validInbox); + assertThrows(IllegalArgumentException.class, () -> user.setUsername(null)); + } - String newUsername = "usernamer123"; + @Test + void setBlankUsernameShouldThrow() { + User user = + new User(validUsername, validEmail, validPassword, validRole, validSettings, validInbox); - user.setUsername(newUsername); + assertThrows(IllegalArgumentException.class, () -> user.setUsername(" ")); + } - assertEquals(newUsername, user.getUsername()); - } + @Test + void setUserNameShouldBeCorrect() { + User user = + new User(validUsername, validEmail, validPassword, validRole, validSettings, validInbox); - @Test - void setEmailShouldChangeEmail() { - User user = - new User( - validUsername, - validEmail, - validPassword, - validRole, - validSettings, - validInbox); - - String newEmail = "email@email.com"; - user.setEmail(newEmail); - - assertEquals(newEmail, user.getEmail()); - } + String newUsername = "usernamer123"; - @Test - void setNullEmailShouldThrow() { - User user = - new User( - validUsername, - validEmail, - validPassword, - validRole, - validSettings, - validInbox); - - assertThrows( - IllegalArgumentException.class, - () -> user.setEmail(null) - ); - } + user.setUsername(newUsername); - @Test - void setBlankEmailShouldThrow() { - User user = - new User( - validUsername, - validEmail, - validPassword, - validRole, - validSettings, - validInbox); - - assertThrows( - IllegalArgumentException.class, - () -> user.setEmail(" ") - ); - } + assertEquals(newUsername, user.getUsername()); + } - @Test - void setEmailNotContainingAtSymbolShouldThrow() { - User user = - new User( - validUsername, - validEmail, - validPassword, - validRole, - validSettings, - validInbox); - - assertThrows( - IllegalArgumentException.class, - () -> user.setEmail("email.email.com") - ); - } + @Test + void setEmailShouldChangeEmail() { + User user = + new User(validUsername, validEmail, validPassword, validRole, validSettings, validInbox); - @Test - void setEmailNotContainingPeriodShouldThrow() { - User user = - new User( - validUsername, - validEmail, - validPassword, - validRole, - validSettings, - validInbox); - - assertThrows( - IllegalArgumentException.class, - () -> user.setEmail("email@emailcom") - ); - } + String newEmail = "email@email.com"; + user.setEmail(newEmail); - @Test - void setPasswordShouldChangePassword() { - User user = - new User( - validUsername, - validEmail, - validPassword, - validRole, - validSettings, - validInbox); - - String newPassword = "p@ssword"; - user.setPassword(newPassword); - - assertTrue(user.checkPassword(newPassword)); - assertFalse(user.checkPassword(validPassword)); - } + assertEquals(newEmail, user.getEmail()); + } - @Test - void setSettingsShouldChangeSettings() { - User user = - new User( - validUsername, - validEmail, - validPassword, - validRole, - validSettings, - validInbox); - - Settings newSettings = new Settings(); - user.setSettings(newSettings); - - assertSame(newSettings, user.getSettings()); - } + @Test + void setNullEmailShouldThrow() { + User user = + new User(validUsername, validEmail, validPassword, validRole, validSettings, validInbox); - @Test - void setSettingsNullShouldThrow() { - User user = - new User( - validUsername, - validEmail, - validPassword, - validRole, - validSettings, - validInbox); - - assertThrows( - IllegalArgumentException.class, - () -> user.setSettings(null) - ); - } + assertThrows(IllegalArgumentException.class, () -> user.setEmail(null)); + } - @Test - void setInboxShouldChangeInbox() { - User user = - new User( - validUsername, - validEmail, - validPassword, - validRole, - validSettings, - validInbox); - - Inbox newInbox = new Inbox(); - user.setInbox(newInbox); - - assertSame(newInbox, user.getInbox()); - } + @Test + void setBlankEmailShouldThrow() { + User user = + new User(validUsername, validEmail, validPassword, validRole, validSettings, validInbox); - @Test - void setNullInboxShouldThrow() { - User user = - new User( - validUsername, - validEmail, - validPassword, - validRole, - validSettings, - validInbox); - - assertThrows( - IllegalArgumentException.class, - () -> user.setInbox(null) - ); - } + assertThrows(IllegalArgumentException.class, () -> user.setEmail(" ")); + } - @Test - void setRoleShouldChangeRole() { - User user = - new User( - validUsername, - validEmail, - validPassword, - validRole, - validSettings, - validInbox); - - user.setRole(Role.ADMIN); - - assertSame(Role.ADMIN, user.getRole()); - } + @Test + void setEmailNotContainingAtSymbolShouldThrow() { + User user = + new User(validUsername, validEmail, validPassword, validRole, validSettings, validInbox); - @Test - void setNullRoleShouldThrow() { - User user = - new User( - validUsername, - validEmail, - validPassword, - validRole, - validSettings, - validInbox); - - assertThrows( - IllegalArgumentException.class, - () -> user.setRole(null) - ); - } + assertThrows(IllegalArgumentException.class, () -> user.setEmail("email.email.com")); + } + + @Test + void setEmailNotContainingPeriodShouldThrow() { + User user = + new User(validUsername, validEmail, validPassword, validRole, validSettings, validInbox); + + assertThrows(IllegalArgumentException.class, () -> user.setEmail("email@emailcom")); + } + + @Test + void setPasswordShouldChangePassword() { + User user = + new User(validUsername, validEmail, validPassword, validRole, validSettings, validInbox); + + String newPassword = "p@ssword"; + user.setPassword(newPassword); + + assertTrue(user.checkPassword(newPassword)); + assertFalse(user.checkPassword(validPassword)); + } + + @Test + void setSettingsShouldChangeSettings() { + User user = + new User(validUsername, validEmail, validPassword, validRole, validSettings, validInbox); + + Settings newSettings = new Settings(); + user.setSettings(newSettings); + + assertSame(newSettings, user.getSettings()); + } + + @Test + void setSettingsNullShouldThrow() { + User user = + new User(validUsername, validEmail, validPassword, validRole, validSettings, validInbox); + + assertThrows(IllegalArgumentException.class, () -> user.setSettings(null)); + } + + @Test + void setInboxShouldChangeInbox() { + User user = + new User(validUsername, validEmail, validPassword, validRole, validSettings, validInbox); + + Inbox newInbox = new Inbox(); + user.setInbox(newInbox); + + assertSame(newInbox, user.getInbox()); + } + + @Test + void setNullInboxShouldThrow() { + User user = + new User(validUsername, validEmail, validPassword, validRole, validSettings, validInbox); + + assertThrows(IllegalArgumentException.class, () -> user.setInbox(null)); + } + + @Test + void setRoleShouldChangeRole() { + User user = + new User(validUsername, validEmail, validPassword, validRole, validSettings, validInbox); + + user.setRole(Role.ADMIN); + + assertSame(Role.ADMIN, user.getRole()); + } + + @Test + void setNullRoleShouldThrow() { + User user = + new User(validUsername, validEmail, validPassword, validRole, validSettings, validInbox); + + assertThrows(IllegalArgumentException.class, () -> user.setRole(null)); + } } @Nested - class secondConstructorTests { - private final UUID validUUID = UUID.randomUUID(); - private final String validUsername = "username"; - private final String validEmail = "Email@gmail.com"; - private final String validPassword = "Password"; - private final Role validRole = Role.NORMAL_USER; - - @Test - void shouldThrowIfUUIDIsNull() { - assertThrows( - IllegalArgumentException.class, - () -> - new User( - null, - validUsername, validEmail, - validPassword, - validRole.toString())); - } + class secondConstructorTests { + private final UUID validUUID = UUID.randomUUID(); + private final String validUsername = "username"; + private final String validEmail = "Email@gmail.com"; + private final String validPassword = "Password"; + private final Role validRole = Role.NORMAL_USER; - @Test - void shouldThrowIfUUIDIsBlank() { - assertThrows( - IllegalArgumentException.class, - () -> - new User( - " ", - validUsername, - validEmail, - validPassword, - validRole.toString())); - } + @Test + void shouldThrowIfUUIDIsNull() { + assertThrows( + IllegalArgumentException.class, + () -> new User(null, validUsername, validEmail, validPassword, validRole.toString())); + } - @Test - void shouldThrowIfUsernameIsNull() { - assertThrows( - IllegalArgumentException.class, - () -> - new User( - validUUID.toString(), - null, - validEmail, - validPassword, - validRole.toString())); + @Test + void shouldThrowIfUUIDIsBlank() { + assertThrows( + IllegalArgumentException.class, + () -> new User(" ", validUsername, validEmail, validPassword, validRole.toString())); + } - } + @Test + void shouldThrowIfUsernameIsNull() { + assertThrows( + IllegalArgumentException.class, + () -> + new User( + validUUID.toString(), null, validEmail, validPassword, validRole.toString())); + } - @Test - void shouldThrowIfUsernameIsBlank() { - assertThrows( - IllegalArgumentException.class, - () -> - new User( - validUUID.toString(), - " ", - validEmail, - validPassword, - validRole.toString())); - } + @Test + void shouldThrowIfUsernameIsBlank() { + assertThrows( + IllegalArgumentException.class, + () -> + new User( + validUUID.toString(), " ", validEmail, validPassword, validRole.toString())); + } - @Test - void shouldThrowIfEmailIsNull() { - assertThrows( - IllegalArgumentException.class, - () -> - new User( - validUUID.toString(), - validUsername, - null, - validPassword, - validRole.toString())); - } + @Test + void shouldThrowIfEmailIsNull() { + assertThrows( + IllegalArgumentException.class, + () -> + new User( + validUUID.toString(), validUsername, null, validPassword, validRole.toString())); + } - @Test - void shouldThrowIfEmailIsBlank() { - assertThrows( - IllegalArgumentException.class, - () -> - new User( - validUUID.toString(), - validUsername, - " ", - validPassword, - validRole.toString())); - } + @Test + void shouldThrowIfEmailIsBlank() { + assertThrows( + IllegalArgumentException.class, + () -> + new User( + validUUID.toString(), validUsername, " ", validPassword, validRole.toString())); + } - @Test - void shouldThrowIfEmailDoesNotContainAtSymbol() { - assertThrows( - IllegalArgumentException.class, - () -> - new User( - validUUID.toString(), - validUsername, - "emailemail.com", - validPassword, - validRole.toString())); - } + @Test + void shouldThrowIfEmailDoesNotContainAtSymbol() { + assertThrows( + IllegalArgumentException.class, + () -> + new User( + validUUID.toString(), + validUsername, + "emailemail.com", + validPassword, + validRole.toString())); + } - @Test - void shouldThrowIfEmailDoesNotContainPeriod() { - assertThrows( - IllegalArgumentException.class, - () -> - new User( - validUUID.toString(), - validUsername, - "email@emailcom", - validPassword, - validRole.toString())); - } + @Test + void shouldThrowIfEmailDoesNotContainPeriod() { + assertThrows( + IllegalArgumentException.class, + () -> + new User( + validUUID.toString(), + validUsername, + "email@emailcom", + validPassword, + validRole.toString())); + } - @Test - void shouldThrowIfRoleIsNull() { - assertThrows( - IllegalArgumentException.class, - () -> - new User( - validUUID.toString(), - validUsername, - validEmail, - validPassword, - null)); - } + @Test + void shouldThrowIfRoleIsNull() { + assertThrows( + IllegalArgumentException.class, + () -> new User(validUUID.toString(), validUsername, validEmail, validPassword, null)); + } - @Test - void shouldCreateUser() { - User user = - new User( - validUUID.toString(), - validUsername, - validEmail, - validPassword, - validRole.toString()); - - assertAll( - () -> assertEquals(validUUID, user.getId()), - () -> assertEquals(validUsername, user.getUsername()), - () -> assertEquals(validEmail, user.getEmail()), - () -> assertEquals(validRole, user.getRole())); - } - } + @Test + void shouldCreateUser() { + User user = + new User( + validUUID.toString(), validUsername, validEmail, validPassword, validRole.toString()); + assertAll( + () -> assertEquals(validUUID, user.getId()), + () -> assertEquals(validUsername, user.getUsername()), + () -> assertEquals(validEmail, user.getEmail()), + () -> assertEquals(validRole, user.getRole())); + } + } } From 2783d837f1a6f531e0cd2a22fbef83d45201ec09 Mon Sep 17 00:00:00 2001 From: AdrianBalunan Date: Fri, 24 Apr 2026 10:42:59 +0200 Subject: [PATCH 2/4] Feat: Added JaCoCo for test coverage --- helpmehelpapplication/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/helpmehelpapplication/pom.xml b/helpmehelpapplication/pom.xml index c1f5d381..92e9b747 100644 --- a/helpmehelpapplication/pom.xml +++ b/helpmehelpapplication/pom.xml @@ -118,7 +118,7 @@ org.jacoco - jacoco-maven-plugin + jac'.oco-maven-plugin 0.8.13 From 2329d0de7b0d4b84268d31b071c121bd37a131f1 Mon Sep 17 00:00:00 2001 From: AdrianBalunan Date: Fri, 24 Apr 2026 10:44:36 +0200 Subject: [PATCH 3/4] Feat: Added JaCoCo for test coverage --- helpmehelpapplication/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/helpmehelpapplication/pom.xml b/helpmehelpapplication/pom.xml index 92e9b747..c1f5d381 100644 --- a/helpmehelpapplication/pom.xml +++ b/helpmehelpapplication/pom.xml @@ -118,7 +118,7 @@ org.jacoco - jac'.oco-maven-plugin + jacoco-maven-plugin 0.8.13 From 0508adda57fc2f11478f937a8d8821cd27316aad Mon Sep 17 00:00:00 2001 From: AdrianBalunan Date: Fri, 24 Apr 2026 10:46:53 +0200 Subject: [PATCH 4/4] Feat: Removed /target from and gitignore so you can see JaCoCo --- .gitignore | 3 - .../target/classes/fxml/aboutPage.fxml | 436 +++++ .../classes/fxml/available_organizations.fxml | 64 + .../target/classes/fxml/charityPage.fxml | 365 ++++ .../classes/fxml/components/categoryTag.fxml | 13 + .../classes/fxml/components/feedbackCard.fxml | 33 + .../classes/fxml/components/footer.fxml | 80 + .../classes/fxml/components/inboxCard.fxml | 43 + .../classes/fxml/components/interestCard.fxml | 76 + .../classes/fxml/components/navbar.fxml | 91 + .../fxml/components/organizationCard.fxml | 44 + .../fxml/components/profileDonationCard.fxml | 25 + .../components/profileOrgDonationCard.fxml | 35 + .../classes/fxml/creater_user_site.fxml | 162 ++ .../target/classes/fxml/dashboard.fxml | 584 +++++++ .../target/classes/fxml/donationPage.fxml | 121 ++ .../target/classes/fxml/frontPage.fxml | 177 ++ .../target/classes/fxml/giveFeedback.fxml | 127 ++ .../target/classes/fxml/loginSite.fxml | 146 ++ .../classes/fxml/profile_org_Inbox.fxml | 188 ++ .../classes/fxml/profile_org_Payments.fxml | 156 ++ .../classes/fxml/profile_org_Settings.fxml | 176 ++ .../target/classes/fxml/profile_org_edit.fxml | 166 ++ .../classes/fxml/profile_user_history.fxml | 183 ++ .../classes/fxml/profile_user_inbox.fxml | 148 ++ .../classes/fxml/profile_user_interests.fxml | 138 ++ .../classes/fxml/profile_user_settings.fxml | 225 +++ .../target/classes/images/Logo.png | Bin 0 -> 94987 bytes .../target/classes/images/img.png | Bin 0 -> 886 bytes .../target/classes/images/leggTilBilde.jpg | Bin 0 -> 9879 bytes .../team6/HmHApplication.class | Bin 0 -> 5229 bytes .../ntnu/systemutvikling/team6/Main.class | Bin 0 -> 474 bytes .../controller/AboutPageController.class | Bin 0 -> 1115 bytes .../AvailableOrganizationController.class | Bin 0 -> 6897 bytes .../controller/CharityPageController.class | Bin 0 -> 7969 bytes .../controller/CreateUserPageController.class | Bin 0 -> 4070 bytes .../controller/DonationPageController.class | Bin 0 -> 9238 bytes .../controller/FrontpageController.class | Bin 0 -> 10929 bytes .../controller/GiveFeedbackController.class | Bin 0 -> 8381 bytes .../controller/LoginPageController.class | Bin 0 -> 3596 bytes .../components/BaseController.class | Bin 0 -> 1538 bytes .../components/CategoryTagController.class | Bin 0 -> 2132 bytes .../components/DonationCardController.class | Bin 0 -> 1769 bytes .../components/FeedbackCardController.class | Bin 0 -> 1662 bytes .../components/FooterController.class | Bin 0 -> 1377 bytes .../components/InboxCardController.class | Bin 0 -> 1478 bytes .../components/InterestCardController.class | Bin 0 -> 2559 bytes .../controller/components/LoaderScene.class | Bin 0 -> 6058 bytes .../components/NavbarController.class | Bin 0 -> 3081 bytes .../OrgDonationCardController.class | Bin 0 -> 1728 bytes .../OrganizationCardController.class | Bin 0 -> 2206 bytes .../profileOrgEditController.class | Bin 0 -> 6954 bytes .../profileOrgInboxController.class | Bin 0 -> 8840 bytes .../profileOrgPaymentsController.class | Bin 0 -> 7551 bytes .../profileOrgSettingsController.class | Bin 0 -> 8759 bytes .../profileUserHistoryController.class | Bin 0 -> 8432 bytes .../profileUserInboxController.class | Bin 0 -> 7245 bytes .../profileUserInterestController.class | Bin 0 -> 7860 bytes .../profileUserSettingsController.class | Bin 0 -> 11703 bytes .../team6/database/DAO/CategoryDAO.class | Bin 0 -> 2270 bytes .../team6/database/DAO/CharityDAO.class | Bin 0 -> 7083 bytes .../team6/database/DAO/CharityUserDAO.class | Bin 0 -> 4651 bytes .../team6/database/DAO/DonationDAO.class | Bin 0 -> 8156 bytes .../team6/database/DAO/FavouritesDAO.class | Bin 0 -> 6339 bytes .../team6/database/DAO/FeedbackDAO.class | Bin 0 -> 5441 bytes .../team6/database/DAO/MessageDAO.class | Bin 0 -> 4383 bytes .../team6/database/DAO/UserDAO.class | Bin 0 -> 15600 bytes .../team6/database/DatabaseConnection.class | Bin 0 -> 1526 bytes .../team6/database/DatabaseSetup.class | Bin 0 -> 11352 bytes .../team6/models/Charity.class | Bin 0 -> 5099 bytes .../team6/models/Donation.class | Bin 0 -> 2237 bytes .../team6/models/Feedback.class | Bin 0 -> 1855 bytes .../models/registry/CharityRegistry.class | Bin 0 -> 3949 bytes .../models/registry/DonationRegistry.class | Bin 0 -> 2999 bytes .../team6/models/registry/UserRegistry.class | Bin 0 -> 2957 bytes .../team6/models/user/Inbox.class | Bin 0 -> 2983 bytes .../team6/models/user/Language.class | Bin 0 -> 1208 bytes .../team6/models/user/Message.class | Bin 0 -> 2128 bytes .../team6/models/user/Role.class | Bin 0 -> 1239 bytes .../team6/models/user/Settings.class | Bin 0 -> 1631 bytes .../team6/models/user/User.class | Bin 0 -> 4586 bytes .../team6/scraper/FullCharityScrape.class | Bin 0 -> 4012 bytes .../team6/scraper/LogoDownloader.class | Bin 0 -> 2632 bytes .../scraperComponents/APICharityData.class | Bin 0 -> 1466 bytes .../scraperComponents/APICharityScraper.class | Bin 0 -> 4141 bytes .../scraperComponents/URLCharityScraper.class | Bin 0 -> 7432 bytes .../team6/security/PasswordHasher.class | Bin 0 -> 2774 bytes .../team6/service/APIToDatabaseService.class | Bin 0 -> 8756 bytes .../team6/service/AuthenticationService.class | Bin 0 -> 3373 bytes .../team6/service/CharityService.class | Bin 0 -> 337 bytes .../team6/service/DonationService.class | Bin 0 -> 340 bytes .../team6/service/FeedbackService.class | Bin 0 -> 340 bytes .../target/classes/tempClassDiagram.puml | 307 ++++ helpmehelpapplication/target/jacoco.exec | Bin 0 -> 143384 bytes .../target/logo/test-logo.png | 1 + .../compile/default-compile/createdFiles.lst | 62 + .../compile/default-compile/inputFiles.lst | 62 + .../default-testCompile/createdFiles.lst | 33 + .../default-testCompile/inputFiles.lst | 25 + .../target/site/jacoco/index.html | 1 + .../site/jacoco/jacoco-resources/branchfc.gif | Bin 0 -> 91 bytes .../site/jacoco/jacoco-resources/branchnc.gif | Bin 0 -> 91 bytes .../site/jacoco/jacoco-resources/branchpc.gif | Bin 0 -> 91 bytes .../site/jacoco/jacoco-resources/bundle.gif | Bin 0 -> 709 bytes .../site/jacoco/jacoco-resources/class.gif | Bin 0 -> 586 bytes .../site/jacoco/jacoco-resources/down.gif | Bin 0 -> 67 bytes .../site/jacoco/jacoco-resources/greenbar.gif | Bin 0 -> 91 bytes .../site/jacoco/jacoco-resources/group.gif | Bin 0 -> 351 bytes .../site/jacoco/jacoco-resources/method.gif | Bin 0 -> 193 bytes .../site/jacoco/jacoco-resources/package.gif | Bin 0 -> 227 bytes .../site/jacoco/jacoco-resources/prettify.css | 13 + .../site/jacoco/jacoco-resources/prettify.js | 1510 +++++++++++++++++ .../site/jacoco/jacoco-resources/redbar.gif | Bin 0 -> 91 bytes .../site/jacoco/jacoco-resources/report.css | 243 +++ .../site/jacoco/jacoco-resources/report.gif | Bin 0 -> 363 bytes .../site/jacoco/jacoco-resources/session.gif | Bin 0 -> 213 bytes .../site/jacoco/jacoco-resources/sort.gif | Bin 0 -> 58 bytes .../site/jacoco/jacoco-resources/sort.js | 148 ++ .../site/jacoco/jacoco-resources/source.gif | Bin 0 -> 354 bytes .../site/jacoco/jacoco-resources/up.gif | Bin 0 -> 67 bytes .../target/site/jacoco/jacoco-sessions.html | 1 + .../target/site/jacoco/jacoco.csv | 63 + .../target/site/jacoco/jacoco.xml | 1 + .../BaseController.html | 1 + .../BaseController.java.html | 57 + .../CategoryTagController.html | 1 + .../CategoryTagController.java.html | 44 + .../DonationCardController.html | 1 + .../DonationCardController.java.html | 29 + .../FeedbackCardController.html | 1 + .../FeedbackCardController.java.html | 27 + .../FooterController.html | 1 + .../FooterController.java.html | 22 + .../InboxCardController.html | 1 + .../InboxCardController.java.html | 27 + .../InterestCardController.html | 1 + .../InterestCardController.java.html | 50 + .../LoaderScene.html | 1 + .../LoaderScene.java.html | 109 ++ .../NavbarController.html | 1 + .../NavbarController.java.html | 74 + .../OrgDonationCardController.html | 1 + .../OrgDonationCardController.java.html | 28 + .../OrganizationCardController.html | 1 + .../OrganizationCardController.java.html | 41 + .../index.html | 1 + .../index.source.html | 1 + .../index.html | 1 + .../index.source.html | 1 + .../profileOrgEditController.html | 1 + .../profileOrgEditController.java.html | 123 ++ .../profileOrgInboxController.html | 1 + .../profileOrgInboxController.java.html | 132 ++ .../profileOrgPaymentsController.html | 1 + .../profileOrgPaymentsController.java.html | 103 ++ .../profileOrgSettingsController.html | 1 + .../profileOrgSettingsController.java.html | 148 ++ .../index.html | 1 + .../index.source.html | 1 + .../profileUserHistoryController.html | 1 + .../profileUserHistoryController.java.html | 115 ++ .../profileUserInboxController.html | 1 + .../profileUserInboxController.java.html | 106 ++ .../profileUserInterestController.html | 1 + .../profileUserInterestController.java.html | 112 ++ .../profileUserSettingsController.html | 1 + .../profileUserSettingsController.java.html | 230 +++ .../AboutPageController.html | 1 + .../AboutPageController.java.html | 18 + .../AvailableOrganizationController.html | 1 + .../AvailableOrganizationController.java.html | 158 ++ .../CharityPageController.html | 1 + .../CharityPageController.java.html | 217 +++ .../CreateUserPageController.html | 1 + .../CreateUserPageController.java.html | 87 + .../DonationPageController.html | 1 + .../DonationPageController.java.html | 188 ++ .../FrontpageController.html | 1 + .../FrontpageController.java.html | 216 +++ .../GiveFeedbackController.html | 1 + .../GiveFeedbackController.java.html | 111 ++ .../LoginPageController.html | 1 + .../LoginPageController.java.html | 72 + .../index.html | 1 + .../index.source.html | 1 + .../CategoryDAO.html | 1 + .../CategoryDAO.java.html | 53 + .../CharityDAO.html | 1 + .../CharityDAO.java.html | 215 +++ .../CharityUserDAO.html | 1 + .../CharityUserDAO.java.html | 162 ++ .../DonationDAO.html | 1 + .../DonationDAO.java.html | 262 +++ .../FavouritesDAO.html | 1 + .../FavouritesDAO.java.html | 185 ++ .../FeedbackDAO.html | 1 + .../FeedbackDAO.java.html | 129 ++ .../MessageDAO.html | 1 + .../MessageDAO.java.html | 109 ++ .../UserDAO.html | 1 + .../UserDAO.java.html | 633 +++++++ .../index.html | 1 + .../index.source.html | 1 + .../DatabaseConnection.html | 1 + .../DatabaseConnection.java.html | 66 + .../DatabaseSetup.html | 1 + .../DatabaseSetup.java.html | 318 ++++ .../index.html | 1 + .../index.source.html | 1 + .../CharityRegistry.html | 1 + .../CharityRegistry.java.html | 54 + .../DonationRegistry.html | 1 + .../DonationRegistry.java.html | 40 + .../UserRegistry.html | 1 + .../UserRegistry.java.html | 38 + .../index.html | 1 + .../index.source.html | 1 + .../Inbox.html | 1 + .../Inbox.java.html | 71 + .../Language.html | 1 + .../Language.java.html | 12 + .../Message.html | 1 + .../Message.java.html | 106 ++ .../Role.html | 1 + .../Role.java.html | 13 + .../Settings.html | 1 + .../Settings.java.html | 70 + .../User.html | 1 + .../User.java.html | 212 +++ .../index.html | 1 + .../index.source.html | 1 + .../Charity.html | 1 + .../Charity.java.html | 221 +++ .../Donation.html | 1 + .../Donation.java.html | 98 ++ .../Feedback.html | 1 + .../Feedback.java.html | 78 + .../index.html | 1 + .../index.source.html | 1 + .../APICharityData.html | 1 + .../APICharityData.java.html | 90 + .../APICharityScraper.html | 1 + .../APICharityScraper.java.html | 99 ++ .../URLCharityScraper.html | 1 + .../URLCharityScraper.java.html | 291 ++++ .../index.html | 1 + .../index.source.html | 1 + .../FullCharityScrape.html | 1 + .../FullCharityScrape.java.html | 111 ++ .../LogoDownloader.html | 1 + .../LogoDownloader.java.html | 55 + .../index.html | 1 + .../index.source.html | 1 + .../PasswordHasher.html | 1 + .../PasswordHasher.java.html | 93 + .../index.html | 1 + .../index.source.html | 1 + .../APIToDatabaseService.html | 1 + .../APIToDatabaseService.java.html | 225 +++ .../AuthenticationService.html | 1 + .../AuthenticationService.java.html | 123 ++ .../CharityService.html | 1 + .../CharityService.java.html | 4 + .../DonationService.html | 1 + .../DonationService.java.html | 4 + .../FeedbackService.html | 1 + .../FeedbackService.java.html | 4 + .../index.html | 1 + .../index.source.html | 1 + .../HmHApplication.html | 1 + .../HmHApplication.java.html | 99 ++ .../ntnu.systemutvikling.team6/Main.html | 1 + .../ntnu.systemutvikling.team6/Main.java.html | 9 + .../ntnu.systemutvikling.team6/index.html | 1 + .../index.source.html | 1 + ...ing.team6.database.DAO.CategoryDAOTest.xml | 162 ++ ...ling.team6.database.DAO.CharityDAOTest.xml | 254 +++ ....team6.database.DAO.CharityUserDAOTest.xml | 361 ++++ ...ing.team6.database.DAO.DonationDAOTest.xml | 347 ++++ ...g.team6.database.DAO.FavouritesDAOTest.xml | 346 ++++ ...ing.team6.database.DAO.FeedbackDAOTest.xml | 157 ++ ...ling.team6.database.DAO.MessageDAOTest.xml | 159 ++ ...vikling.team6.database.DAO.UserDAOTest.xml | 720 ++++++++ ....team6.database.DatabaseConnectionTest.xml | 71 + ...kling.team6.database.DatabaseSetupTest.xml | 68 + ...stemutvikling.team6.models.CharityTest.xml | 77 + ...temutvikling.team6.models.DonationTest.xml | 71 + ...temutvikling.team6.models.FeedbackTest.xml | 70 + ...m6.models.registry.CharityRegistryTest.xml | 75 + ...6.models.registry.DonationRegistryTest.xml | 72 + ...team6.models.registry.UserRegistryTest.xml | 70 + ...mutvikling.team6.models.user.InboxTest.xml | 72 + ...tvikling.team6.models.user.MessageTest.xml | 71 + ...vikling.team6.models.user.SettingsTest.xml | 69 + ...emutvikling.team6.models.user.UserTest.xml | 102 ++ ...kling.team6.scraper.LogoDownloaderTest.xml | 63 + ...r.scraperComponents.APICharityDataTest.xml | 67 + ...craperComponents.APICharityScraperTest.xml | 67 + ...craperComponents.URLCharityScraperTest.xml | 87 + ...ling.team6.security.PasswordHasherTest.xml | 71 + ...ing.team6.database.DAO.CategoryDAOTest.txt | 4 + ...ling.team6.database.DAO.CharityDAOTest.txt | 4 + ....team6.database.DAO.CharityUserDAOTest.txt | 4 + ...ing.team6.database.DAO.DonationDAOTest.txt | 4 + ...g.team6.database.DAO.FavouritesDAOTest.txt | 4 + ...ing.team6.database.DAO.FeedbackDAOTest.txt | 4 + ...ling.team6.database.DAO.MessageDAOTest.txt | 4 + ...vikling.team6.database.DAO.UserDAOTest.txt | 4 + ....team6.database.DatabaseConnectionTest.txt | 4 + ...kling.team6.database.DatabaseSetupTest.txt | 4 + ...stemutvikling.team6.models.CharityTest.txt | 4 + ...temutvikling.team6.models.DonationTest.txt | 4 + ...temutvikling.team6.models.FeedbackTest.txt | 4 + ...m6.models.registry.CharityRegistryTest.txt | 4 + ...6.models.registry.DonationRegistryTest.txt | 4 + ...team6.models.registry.UserRegistryTest.txt | 4 + ...mutvikling.team6.models.user.InboxTest.txt | 4 + ...tvikling.team6.models.user.MessageTest.txt | 4 + ...vikling.team6.models.user.SettingsTest.txt | 4 + ...emutvikling.team6.models.user.UserTest.txt | 4 + ...kling.team6.scraper.LogoDownloaderTest.txt | 4 + ...r.scraperComponents.APICharityDataTest.txt | 4 + ...craperComponents.APICharityScraperTest.txt | 4 + ...craperComponents.URLCharityScraperTest.txt | 4 + ...ling.team6.security.PasswordHasherTest.txt | 4 + .../team6/database/DAO/CategoryDAOTest.class | Bin 0 -> 4390 bytes .../team6/database/DAO/CharityDAOTest.class | Bin 0 -> 12883 bytes .../database/DAO/CharityUserDAOTest.class | Bin 0 -> 9847 bytes .../team6/database/DAO/DonationDAOTest.class | Bin 0 -> 13550 bytes .../database/DAO/FavouritesDAOTest.class | Bin 0 -> 10593 bytes .../team6/database/DAO/FeedbackDAOTest.class | Bin 0 -> 9495 bytes .../team6/database/DAO/MessageDAOTest.class | Bin 0 -> 6585 bytes .../team6/database/DAO/UserDAOTest.class | Bin 0 -> 18589 bytes .../database/DatabaseConnectionTest.class | Bin 0 -> 2888 bytes .../team6/database/DatabaseSetupTest.class | Bin 0 -> 4346 bytes .../team6/models/CharityTest.class | Bin 0 -> 6665 bytes .../team6/models/DonationTest.class | Bin 0 -> 4705 bytes .../team6/models/FeedbackTest.class | Bin 0 -> 4032 bytes .../models/registry/CharityRegistryTest.class | Bin 0 -> 6238 bytes .../registry/DonationRegistryTest.class | Bin 0 -> 6058 bytes .../models/registry/UserRegistryTest.class | Bin 0 -> 4720 bytes .../team6/models/user/InboxTest.class | Bin 0 -> 5482 bytes .../MessageTest$FirstConstructorTest.class | Bin 0 -> 3892 bytes .../MessageTest$secondConstructorTest.class | Bin 0 -> 4215 bytes .../team6/models/user/MessageTest.class | Bin 0 -> 1183 bytes .../team6/models/user/SettingsTest.class | Bin 0 -> 3376 bytes ...UserTest$constructorTests$emailTests.class | Bin 0 -> 3495 bytes .../user/UserTest$constructorTests.class | Bin 0 -> 11310 bytes .../UserTest$secondConstructorTests.class | Bin 0 -> 6316 bytes .../team6/models/user/UserTest.class | Bin 0 -> 686 bytes .../team6/scraper/LogoDownloaderTest.class | Bin 0 -> 1280 bytes .../APICharityDataTest.class | Bin 0 -> 3763 bytes .../APICharityScraperTest.class | Bin 0 -> 5790 bytes .../URLCharityScraperTest$1.class | Bin 0 -> 1466 bytes .../URLCharityScraperTest.class | Bin 0 -> 7074 bytes ...sswordHasherTest$getHashPasswordTest.class | Bin 0 -> 2733 bytes ...sswordHasherTest$isValidPasswordTest.class | Bin 0 -> 3219 bytes .../team6/security/PasswordHasherTest.class | Bin 0 -> 778 bytes 358 files changed, 17407 insertions(+), 3 deletions(-) create mode 100644 helpmehelpapplication/target/classes/fxml/aboutPage.fxml create mode 100644 helpmehelpapplication/target/classes/fxml/available_organizations.fxml create mode 100644 helpmehelpapplication/target/classes/fxml/charityPage.fxml create mode 100644 helpmehelpapplication/target/classes/fxml/components/categoryTag.fxml create mode 100644 helpmehelpapplication/target/classes/fxml/components/feedbackCard.fxml create mode 100644 helpmehelpapplication/target/classes/fxml/components/footer.fxml create mode 100644 helpmehelpapplication/target/classes/fxml/components/inboxCard.fxml create mode 100644 helpmehelpapplication/target/classes/fxml/components/interestCard.fxml create mode 100644 helpmehelpapplication/target/classes/fxml/components/navbar.fxml create mode 100644 helpmehelpapplication/target/classes/fxml/components/organizationCard.fxml create mode 100644 helpmehelpapplication/target/classes/fxml/components/profileDonationCard.fxml create mode 100644 helpmehelpapplication/target/classes/fxml/components/profileOrgDonationCard.fxml create mode 100644 helpmehelpapplication/target/classes/fxml/creater_user_site.fxml create mode 100644 helpmehelpapplication/target/classes/fxml/dashboard.fxml create mode 100644 helpmehelpapplication/target/classes/fxml/donationPage.fxml create mode 100644 helpmehelpapplication/target/classes/fxml/frontPage.fxml create mode 100644 helpmehelpapplication/target/classes/fxml/giveFeedback.fxml create mode 100644 helpmehelpapplication/target/classes/fxml/loginSite.fxml create mode 100644 helpmehelpapplication/target/classes/fxml/profile_org_Inbox.fxml create mode 100644 helpmehelpapplication/target/classes/fxml/profile_org_Payments.fxml create mode 100644 helpmehelpapplication/target/classes/fxml/profile_org_Settings.fxml create mode 100644 helpmehelpapplication/target/classes/fxml/profile_org_edit.fxml create mode 100644 helpmehelpapplication/target/classes/fxml/profile_user_history.fxml create mode 100644 helpmehelpapplication/target/classes/fxml/profile_user_inbox.fxml create mode 100644 helpmehelpapplication/target/classes/fxml/profile_user_interests.fxml create mode 100644 helpmehelpapplication/target/classes/fxml/profile_user_settings.fxml create mode 100644 helpmehelpapplication/target/classes/images/Logo.png create mode 100644 helpmehelpapplication/target/classes/images/img.png create mode 100644 helpmehelpapplication/target/classes/images/leggTilBilde.jpg create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/HmHApplication.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/Main.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/controller/AboutPageController.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/controller/AvailableOrganizationController.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/controller/CharityPageController.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/controller/CreateUserPageController.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/controller/DonationPageController.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/controller/FrontpageController.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/controller/GiveFeedbackController.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/controller/LoginPageController.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/controller/components/BaseController.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/controller/components/CategoryTagController.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/controller/components/DonationCardController.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/controller/components/FeedbackCardController.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/controller/components/FooterController.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/controller/components/InboxCardController.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/controller/components/InterestCardController.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/controller/components/LoaderScene.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/controller/components/NavbarController.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/controller/components/OrgDonationCardController.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/controller/components/OrganizationCardController.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/controller/profileCharity/profileOrgEditController.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/controller/profileCharity/profileOrgInboxController.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/controller/profileCharity/profileOrgPaymentsController.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/controller/profileCharity/profileOrgSettingsController.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/controller/profileUser/profileUserHistoryController.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/controller/profileUser/profileUserInboxController.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/controller/profileUser/profileUserInterestController.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/controller/profileUser/profileUserSettingsController.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/database/DAO/CategoryDAO.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/database/DAO/CharityDAO.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/database/DAO/CharityUserDAO.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/database/DAO/DonationDAO.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/database/DAO/FavouritesDAO.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/database/DAO/FeedbackDAO.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/database/DAO/MessageDAO.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/database/DAO/UserDAO.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/database/DatabaseConnection.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/database/DatabaseSetup.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/models/Charity.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/models/Donation.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/models/Feedback.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/models/registry/CharityRegistry.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/models/registry/DonationRegistry.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/models/registry/UserRegistry.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/models/user/Inbox.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/models/user/Language.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/models/user/Message.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/models/user/Role.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/models/user/Settings.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/models/user/User.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/scraper/FullCharityScrape.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/scraper/LogoDownloader.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/scraper/scraperComponents/APICharityData.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/scraper/scraperComponents/APICharityScraper.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/scraper/scraperComponents/URLCharityScraper.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/security/PasswordHasher.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/service/APIToDatabaseService.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/service/AuthenticationService.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/service/CharityService.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/service/DonationService.class create mode 100644 helpmehelpapplication/target/classes/ntnu/systemutvikling/team6/service/FeedbackService.class create mode 100644 helpmehelpapplication/target/classes/tempClassDiagram.puml create mode 100644 helpmehelpapplication/target/jacoco.exec create mode 100644 helpmehelpapplication/target/logo/test-logo.png create mode 100644 helpmehelpapplication/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst create mode 100644 helpmehelpapplication/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst create mode 100644 helpmehelpapplication/target/maven-status/maven-compiler-plugin/testCompile/default-testCompile/createdFiles.lst create mode 100644 helpmehelpapplication/target/maven-status/maven-compiler-plugin/testCompile/default-testCompile/inputFiles.lst create mode 100644 helpmehelpapplication/target/site/jacoco/index.html create mode 100644 helpmehelpapplication/target/site/jacoco/jacoco-resources/branchfc.gif create mode 100644 helpmehelpapplication/target/site/jacoco/jacoco-resources/branchnc.gif create mode 100644 helpmehelpapplication/target/site/jacoco/jacoco-resources/branchpc.gif create mode 100644 helpmehelpapplication/target/site/jacoco/jacoco-resources/bundle.gif create mode 100644 helpmehelpapplication/target/site/jacoco/jacoco-resources/class.gif create mode 100644 helpmehelpapplication/target/site/jacoco/jacoco-resources/down.gif create mode 100644 helpmehelpapplication/target/site/jacoco/jacoco-resources/greenbar.gif create mode 100644 helpmehelpapplication/target/site/jacoco/jacoco-resources/group.gif create mode 100644 helpmehelpapplication/target/site/jacoco/jacoco-resources/method.gif create mode 100644 helpmehelpapplication/target/site/jacoco/jacoco-resources/package.gif create mode 100644 helpmehelpapplication/target/site/jacoco/jacoco-resources/prettify.css create mode 100644 helpmehelpapplication/target/site/jacoco/jacoco-resources/prettify.js create mode 100644 helpmehelpapplication/target/site/jacoco/jacoco-resources/redbar.gif create mode 100644 helpmehelpapplication/target/site/jacoco/jacoco-resources/report.css create mode 100644 helpmehelpapplication/target/site/jacoco/jacoco-resources/report.gif create mode 100644 helpmehelpapplication/target/site/jacoco/jacoco-resources/session.gif create mode 100644 helpmehelpapplication/target/site/jacoco/jacoco-resources/sort.gif create mode 100644 helpmehelpapplication/target/site/jacoco/jacoco-resources/sort.js create mode 100644 helpmehelpapplication/target/site/jacoco/jacoco-resources/source.gif create mode 100644 helpmehelpapplication/target/site/jacoco/jacoco-resources/up.gif create mode 100644 helpmehelpapplication/target/site/jacoco/jacoco-sessions.html create mode 100644 helpmehelpapplication/target/site/jacoco/jacoco.csv create mode 100644 helpmehelpapplication/target/site/jacoco/jacoco.xml create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.components/BaseController.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.components/BaseController.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.components/CategoryTagController.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.components/CategoryTagController.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.components/DonationCardController.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.components/DonationCardController.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.components/FeedbackCardController.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.components/FeedbackCardController.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.components/FooterController.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.components/FooterController.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.components/InboxCardController.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.components/InboxCardController.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.components/InterestCardController.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.components/InterestCardController.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.components/LoaderScene.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.components/LoaderScene.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.components/NavbarController.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.components/NavbarController.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.components/OrgDonationCardController.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.components/OrgDonationCardController.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.components/OrganizationCardController.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.components/OrganizationCardController.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.components/index.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.components/index.source.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.profileCharity/index.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.profileCharity/index.source.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.profileCharity/profileOrgEditController.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.profileCharity/profileOrgEditController.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.profileCharity/profileOrgInboxController.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.profileCharity/profileOrgInboxController.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.profileCharity/profileOrgPaymentsController.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.profileCharity/profileOrgPaymentsController.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.profileCharity/profileOrgSettingsController.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.profileCharity/profileOrgSettingsController.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.profileUser/index.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.profileUser/index.source.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.profileUser/profileUserHistoryController.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.profileUser/profileUserHistoryController.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.profileUser/profileUserInboxController.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.profileUser/profileUserInboxController.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.profileUser/profileUserInterestController.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.profileUser/profileUserInterestController.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.profileUser/profileUserSettingsController.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller.profileUser/profileUserSettingsController.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller/AboutPageController.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller/AboutPageController.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller/AvailableOrganizationController.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller/AvailableOrganizationController.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller/CharityPageController.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller/CharityPageController.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller/CreateUserPageController.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller/CreateUserPageController.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller/DonationPageController.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller/DonationPageController.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller/FrontpageController.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller/FrontpageController.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller/GiveFeedbackController.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller/GiveFeedbackController.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller/LoginPageController.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller/LoginPageController.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller/index.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.controller/index.source.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.database.DAO/CategoryDAO.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.database.DAO/CategoryDAO.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.database.DAO/CharityDAO.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.database.DAO/CharityDAO.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.database.DAO/CharityUserDAO.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.database.DAO/CharityUserDAO.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.database.DAO/DonationDAO.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.database.DAO/DonationDAO.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.database.DAO/FavouritesDAO.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.database.DAO/FavouritesDAO.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.database.DAO/FeedbackDAO.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.database.DAO/FeedbackDAO.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.database.DAO/MessageDAO.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.database.DAO/MessageDAO.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.database.DAO/UserDAO.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.database.DAO/UserDAO.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.database.DAO/index.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.database.DAO/index.source.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.database/DatabaseConnection.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.database/DatabaseConnection.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.database/DatabaseSetup.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.database/DatabaseSetup.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.database/index.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.database/index.source.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.models.registry/CharityRegistry.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.models.registry/CharityRegistry.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.models.registry/DonationRegistry.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.models.registry/DonationRegistry.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.models.registry/UserRegistry.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.models.registry/UserRegistry.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.models.registry/index.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.models.registry/index.source.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.models.user/Inbox.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.models.user/Inbox.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.models.user/Language.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.models.user/Language.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.models.user/Message.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.models.user/Message.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.models.user/Role.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.models.user/Role.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.models.user/Settings.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.models.user/Settings.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.models.user/User.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.models.user/User.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.models.user/index.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.models.user/index.source.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.models/Charity.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.models/Charity.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.models/Donation.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.models/Donation.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.models/Feedback.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.models/Feedback.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.models/index.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.models/index.source.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.scraper.scraperComponents/APICharityData.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.scraper.scraperComponents/APICharityData.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.scraper.scraperComponents/APICharityScraper.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.scraper.scraperComponents/APICharityScraper.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.scraper.scraperComponents/URLCharityScraper.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.scraper.scraperComponents/URLCharityScraper.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.scraper.scraperComponents/index.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.scraper.scraperComponents/index.source.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.scraper/FullCharityScrape.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.scraper/FullCharityScrape.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.scraper/LogoDownloader.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.scraper/LogoDownloader.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.scraper/index.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.scraper/index.source.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.security/PasswordHasher.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.security/PasswordHasher.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.security/index.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.security/index.source.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.service/APIToDatabaseService.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.service/APIToDatabaseService.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.service/AuthenticationService.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.service/AuthenticationService.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.service/CharityService.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.service/CharityService.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.service/DonationService.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.service/DonationService.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.service/FeedbackService.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.service/FeedbackService.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.service/index.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6.service/index.source.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6/HmHApplication.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6/HmHApplication.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6/Main.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6/Main.java.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6/index.html create mode 100644 helpmehelpapplication/target/site/jacoco/ntnu.systemutvikling.team6/index.source.html create mode 100644 helpmehelpapplication/target/surefire-reports/TEST-ntnu.systemutvikling.team6.database.DAO.CategoryDAOTest.xml create mode 100644 helpmehelpapplication/target/surefire-reports/TEST-ntnu.systemutvikling.team6.database.DAO.CharityDAOTest.xml create mode 100644 helpmehelpapplication/target/surefire-reports/TEST-ntnu.systemutvikling.team6.database.DAO.CharityUserDAOTest.xml create mode 100644 helpmehelpapplication/target/surefire-reports/TEST-ntnu.systemutvikling.team6.database.DAO.DonationDAOTest.xml create mode 100644 helpmehelpapplication/target/surefire-reports/TEST-ntnu.systemutvikling.team6.database.DAO.FavouritesDAOTest.xml create mode 100644 helpmehelpapplication/target/surefire-reports/TEST-ntnu.systemutvikling.team6.database.DAO.FeedbackDAOTest.xml create mode 100644 helpmehelpapplication/target/surefire-reports/TEST-ntnu.systemutvikling.team6.database.DAO.MessageDAOTest.xml create mode 100644 helpmehelpapplication/target/surefire-reports/TEST-ntnu.systemutvikling.team6.database.DAO.UserDAOTest.xml create mode 100644 helpmehelpapplication/target/surefire-reports/TEST-ntnu.systemutvikling.team6.database.DatabaseConnectionTest.xml create mode 100644 helpmehelpapplication/target/surefire-reports/TEST-ntnu.systemutvikling.team6.database.DatabaseSetupTest.xml create mode 100644 helpmehelpapplication/target/surefire-reports/TEST-ntnu.systemutvikling.team6.models.CharityTest.xml create mode 100644 helpmehelpapplication/target/surefire-reports/TEST-ntnu.systemutvikling.team6.models.DonationTest.xml create mode 100644 helpmehelpapplication/target/surefire-reports/TEST-ntnu.systemutvikling.team6.models.FeedbackTest.xml create mode 100644 helpmehelpapplication/target/surefire-reports/TEST-ntnu.systemutvikling.team6.models.registry.CharityRegistryTest.xml create mode 100644 helpmehelpapplication/target/surefire-reports/TEST-ntnu.systemutvikling.team6.models.registry.DonationRegistryTest.xml create mode 100644 helpmehelpapplication/target/surefire-reports/TEST-ntnu.systemutvikling.team6.models.registry.UserRegistryTest.xml create mode 100644 helpmehelpapplication/target/surefire-reports/TEST-ntnu.systemutvikling.team6.models.user.InboxTest.xml create mode 100644 helpmehelpapplication/target/surefire-reports/TEST-ntnu.systemutvikling.team6.models.user.MessageTest.xml create mode 100644 helpmehelpapplication/target/surefire-reports/TEST-ntnu.systemutvikling.team6.models.user.SettingsTest.xml create mode 100644 helpmehelpapplication/target/surefire-reports/TEST-ntnu.systemutvikling.team6.models.user.UserTest.xml create mode 100644 helpmehelpapplication/target/surefire-reports/TEST-ntnu.systemutvikling.team6.scraper.LogoDownloaderTest.xml create mode 100644 helpmehelpapplication/target/surefire-reports/TEST-ntnu.systemutvikling.team6.scraper.scraperComponents.APICharityDataTest.xml create mode 100644 helpmehelpapplication/target/surefire-reports/TEST-ntnu.systemutvikling.team6.scraper.scraperComponents.APICharityScraperTest.xml create mode 100644 helpmehelpapplication/target/surefire-reports/TEST-ntnu.systemutvikling.team6.scraper.scraperComponents.URLCharityScraperTest.xml create mode 100644 helpmehelpapplication/target/surefire-reports/TEST-ntnu.systemutvikling.team6.security.PasswordHasherTest.xml create mode 100644 helpmehelpapplication/target/surefire-reports/ntnu.systemutvikling.team6.database.DAO.CategoryDAOTest.txt create mode 100644 helpmehelpapplication/target/surefire-reports/ntnu.systemutvikling.team6.database.DAO.CharityDAOTest.txt create mode 100644 helpmehelpapplication/target/surefire-reports/ntnu.systemutvikling.team6.database.DAO.CharityUserDAOTest.txt create mode 100644 helpmehelpapplication/target/surefire-reports/ntnu.systemutvikling.team6.database.DAO.DonationDAOTest.txt create mode 100644 helpmehelpapplication/target/surefire-reports/ntnu.systemutvikling.team6.database.DAO.FavouritesDAOTest.txt create mode 100644 helpmehelpapplication/target/surefire-reports/ntnu.systemutvikling.team6.database.DAO.FeedbackDAOTest.txt create mode 100644 helpmehelpapplication/target/surefire-reports/ntnu.systemutvikling.team6.database.DAO.MessageDAOTest.txt create mode 100644 helpmehelpapplication/target/surefire-reports/ntnu.systemutvikling.team6.database.DAO.UserDAOTest.txt create mode 100644 helpmehelpapplication/target/surefire-reports/ntnu.systemutvikling.team6.database.DatabaseConnectionTest.txt create mode 100644 helpmehelpapplication/target/surefire-reports/ntnu.systemutvikling.team6.database.DatabaseSetupTest.txt create mode 100644 helpmehelpapplication/target/surefire-reports/ntnu.systemutvikling.team6.models.CharityTest.txt create mode 100644 helpmehelpapplication/target/surefire-reports/ntnu.systemutvikling.team6.models.DonationTest.txt create mode 100644 helpmehelpapplication/target/surefire-reports/ntnu.systemutvikling.team6.models.FeedbackTest.txt create mode 100644 helpmehelpapplication/target/surefire-reports/ntnu.systemutvikling.team6.models.registry.CharityRegistryTest.txt create mode 100644 helpmehelpapplication/target/surefire-reports/ntnu.systemutvikling.team6.models.registry.DonationRegistryTest.txt create mode 100644 helpmehelpapplication/target/surefire-reports/ntnu.systemutvikling.team6.models.registry.UserRegistryTest.txt create mode 100644 helpmehelpapplication/target/surefire-reports/ntnu.systemutvikling.team6.models.user.InboxTest.txt create mode 100644 helpmehelpapplication/target/surefire-reports/ntnu.systemutvikling.team6.models.user.MessageTest.txt create mode 100644 helpmehelpapplication/target/surefire-reports/ntnu.systemutvikling.team6.models.user.SettingsTest.txt create mode 100644 helpmehelpapplication/target/surefire-reports/ntnu.systemutvikling.team6.models.user.UserTest.txt create mode 100644 helpmehelpapplication/target/surefire-reports/ntnu.systemutvikling.team6.scraper.LogoDownloaderTest.txt create mode 100644 helpmehelpapplication/target/surefire-reports/ntnu.systemutvikling.team6.scraper.scraperComponents.APICharityDataTest.txt create mode 100644 helpmehelpapplication/target/surefire-reports/ntnu.systemutvikling.team6.scraper.scraperComponents.APICharityScraperTest.txt create mode 100644 helpmehelpapplication/target/surefire-reports/ntnu.systemutvikling.team6.scraper.scraperComponents.URLCharityScraperTest.txt create mode 100644 helpmehelpapplication/target/surefire-reports/ntnu.systemutvikling.team6.security.PasswordHasherTest.txt create mode 100644 helpmehelpapplication/target/test-classes/ntnu/systemutvikling/team6/database/DAO/CategoryDAOTest.class create mode 100644 helpmehelpapplication/target/test-classes/ntnu/systemutvikling/team6/database/DAO/CharityDAOTest.class create mode 100644 helpmehelpapplication/target/test-classes/ntnu/systemutvikling/team6/database/DAO/CharityUserDAOTest.class create mode 100644 helpmehelpapplication/target/test-classes/ntnu/systemutvikling/team6/database/DAO/DonationDAOTest.class create mode 100644 helpmehelpapplication/target/test-classes/ntnu/systemutvikling/team6/database/DAO/FavouritesDAOTest.class create mode 100644 helpmehelpapplication/target/test-classes/ntnu/systemutvikling/team6/database/DAO/FeedbackDAOTest.class create mode 100644 helpmehelpapplication/target/test-classes/ntnu/systemutvikling/team6/database/DAO/MessageDAOTest.class create mode 100644 helpmehelpapplication/target/test-classes/ntnu/systemutvikling/team6/database/DAO/UserDAOTest.class create mode 100644 helpmehelpapplication/target/test-classes/ntnu/systemutvikling/team6/database/DatabaseConnectionTest.class create mode 100644 helpmehelpapplication/target/test-classes/ntnu/systemutvikling/team6/database/DatabaseSetupTest.class create mode 100644 helpmehelpapplication/target/test-classes/ntnu/systemutvikling/team6/models/CharityTest.class create mode 100644 helpmehelpapplication/target/test-classes/ntnu/systemutvikling/team6/models/DonationTest.class create mode 100644 helpmehelpapplication/target/test-classes/ntnu/systemutvikling/team6/models/FeedbackTest.class create mode 100644 helpmehelpapplication/target/test-classes/ntnu/systemutvikling/team6/models/registry/CharityRegistryTest.class create mode 100644 helpmehelpapplication/target/test-classes/ntnu/systemutvikling/team6/models/registry/DonationRegistryTest.class create mode 100644 helpmehelpapplication/target/test-classes/ntnu/systemutvikling/team6/models/registry/UserRegistryTest.class create mode 100644 helpmehelpapplication/target/test-classes/ntnu/systemutvikling/team6/models/user/InboxTest.class create mode 100644 helpmehelpapplication/target/test-classes/ntnu/systemutvikling/team6/models/user/MessageTest$FirstConstructorTest.class create mode 100644 helpmehelpapplication/target/test-classes/ntnu/systemutvikling/team6/models/user/MessageTest$secondConstructorTest.class create mode 100644 helpmehelpapplication/target/test-classes/ntnu/systemutvikling/team6/models/user/MessageTest.class create mode 100644 helpmehelpapplication/target/test-classes/ntnu/systemutvikling/team6/models/user/SettingsTest.class create mode 100644 helpmehelpapplication/target/test-classes/ntnu/systemutvikling/team6/models/user/UserTest$constructorTests$emailTests.class create mode 100644 helpmehelpapplication/target/test-classes/ntnu/systemutvikling/team6/models/user/UserTest$constructorTests.class create mode 100644 helpmehelpapplication/target/test-classes/ntnu/systemutvikling/team6/models/user/UserTest$secondConstructorTests.class create mode 100644 helpmehelpapplication/target/test-classes/ntnu/systemutvikling/team6/models/user/UserTest.class create mode 100644 helpmehelpapplication/target/test-classes/ntnu/systemutvikling/team6/scraper/LogoDownloaderTest.class create mode 100644 helpmehelpapplication/target/test-classes/ntnu/systemutvikling/team6/scraper/scraperComponents/APICharityDataTest.class create mode 100644 helpmehelpapplication/target/test-classes/ntnu/systemutvikling/team6/scraper/scraperComponents/APICharityScraperTest.class create mode 100644 helpmehelpapplication/target/test-classes/ntnu/systemutvikling/team6/scraper/scraperComponents/URLCharityScraperTest$1.class create mode 100644 helpmehelpapplication/target/test-classes/ntnu/systemutvikling/team6/scraper/scraperComponents/URLCharityScraperTest.class create mode 100644 helpmehelpapplication/target/test-classes/ntnu/systemutvikling/team6/security/PasswordHasherTest$getHashPasswordTest.class create mode 100644 helpmehelpapplication/target/test-classes/ntnu/systemutvikling/team6/security/PasswordHasherTest$isValidPasswordTest.class create mode 100644 helpmehelpapplication/target/test-classes/ntnu/systemutvikling/team6/security/PasswordHasherTest.class diff --git a/.gitignore b/.gitignore index 6c187836..c8d3e6c6 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,4 @@ # Adrian .vscode/ .idea/ -helpmehelpapplication/target -.target/ -.helpmehelpapplication\target/ .helpmehelpapplication\.idea/ diff --git a/helpmehelpapplication/target/classes/fxml/aboutPage.fxml b/helpmehelpapplication/target/classes/fxml/aboutPage.fxml new file mode 100644 index 00000000..1d6bbe4b --- /dev/null +++ b/helpmehelpapplication/target/classes/fxml/aboutPage.fxml @@ -0,0 +1,436 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/helpmehelpapplication/target/classes/fxml/available_organizations.fxml b/helpmehelpapplication/target/classes/fxml/available_organizations.fxml new file mode 100644 index 00000000..bce73a20 --- /dev/null +++ b/helpmehelpapplication/target/classes/fxml/available_organizations.fxml @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + + + + + +

+ + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + diff --git a/helpmehelpapplication/target/classes/fxml/charityPage.fxml b/helpmehelpapplication/target/classes/fxml/charityPage.fxml new file mode 100644 index 00000000..8b7309f3 --- /dev/null +++ b/helpmehelpapplication/target/classes/fxml/charityPage.fxml @@ -0,0 +1,365 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/helpmehelpapplication/target/classes/fxml/components/categoryTag.fxml b/helpmehelpapplication/target/classes/fxml/components/categoryTag.fxml new file mode 100644 index 00000000..3e509532 --- /dev/null +++ b/helpmehelpapplication/target/classes/fxml/components/categoryTag.fxml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/helpmehelpapplication/target/classes/fxml/components/inboxCard.fxml b/helpmehelpapplication/target/classes/fxml/components/inboxCard.fxml new file mode 100644 index 00000000..112ef98f --- /dev/null +++ b/helpmehelpapplication/target/classes/fxml/components/inboxCard.fxml @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/helpmehelpapplication/target/classes/fxml/components/interestCard.fxml b/helpmehelpapplication/target/classes/fxml/components/interestCard.fxml new file mode 100644 index 00000000..5ffb4967 --- /dev/null +++ b/helpmehelpapplication/target/classes/fxml/components/interestCard.fxml @@ -0,0 +1,76 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/helpmehelpapplication/target/classes/fxml/components/navbar.fxml b/helpmehelpapplication/target/classes/fxml/components/navbar.fxml new file mode 100644 index 00000000..30cb898f --- /dev/null +++ b/helpmehelpapplication/target/classes/fxml/components/navbar.fxml @@ -0,0 +1,91 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/helpmehelpapplication/target/classes/fxml/components/organizationCard.fxml b/helpmehelpapplication/target/classes/fxml/components/organizationCard.fxml new file mode 100644 index 00000000..9076186d --- /dev/null +++ b/helpmehelpapplication/target/classes/fxml/components/organizationCard.fxml @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/helpmehelpapplication/target/classes/fxml/components/profileDonationCard.fxml b/helpmehelpapplication/target/classes/fxml/components/profileDonationCard.fxml new file mode 100644 index 00000000..7eb9f7e8 --- /dev/null +++ b/helpmehelpapplication/target/classes/fxml/components/profileDonationCard.fxml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + diff --git a/helpmehelpapplication/target/classes/fxml/components/profileOrgDonationCard.fxml b/helpmehelpapplication/target/classes/fxml/components/profileOrgDonationCard.fxml new file mode 100644 index 00000000..948a86d9 --- /dev/null +++ b/helpmehelpapplication/target/classes/fxml/components/profileOrgDonationCard.fxml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/helpmehelpapplication/target/classes/fxml/creater_user_site.fxml b/helpmehelpapplication/target/classes/fxml/creater_user_site.fxml new file mode 100644 index 00000000..670c659d --- /dev/null +++ b/helpmehelpapplication/target/classes/fxml/creater_user_site.fxml @@ -0,0 +1,162 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/helpmehelpapplication/target/classes/fxml/dashboard.fxml b/helpmehelpapplication/target/classes/fxml/dashboard.fxml new file mode 100644 index 00000000..b1b6bbec --- /dev/null +++ b/helpmehelpapplication/target/classes/fxml/dashboard.fxml @@ -0,0 +1,584 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/helpmehelpapplication/target/classes/fxml/frontPage.fxml b/helpmehelpapplication/target/classes/fxml/frontPage.fxml new file mode 100644 index 00000000..a564a0b2 --- /dev/null +++ b/helpmehelpapplication/target/classes/fxml/frontPage.fxml @@ -0,0 +1,177 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +