From 52fb5df459f3a6543a2ce3e1dd1fecd8ca646308 Mon Sep 17 00:00:00 2001 From: AdrianBalunan Date: Mon, 16 Mar 2026 22:58:05 +0100 Subject: [PATCH] Maven clean. --- .../team6/DAO/DonationDAO.java | 55 ++-- .../systemutvikling/team6/HmHApplication.java | 6 +- .../java/ntnu/systemutvikling/team6/Main.java | 1 - .../controller/CharityPageController.java | 41 +-- .../controller/DonationPageController.java | 203 +++++++------- .../team6/controller/FrontpageController.java | 78 +++--- .../team6/controller/LoaderScene.java | 84 +++--- .../OrganizationCardController.java | 24 +- .../team6/database/DatabaseConnection.java | 2 - .../team6/database/DatabaseManager.java | 72 ++--- .../systemutvikling/team6/models/Charity.java | 16 +- .../team6/models/Donation.java | 5 +- .../team6/scraper/APICharityData.java | 4 +- .../team6/scraper/APICharityScraper.java | 5 +- .../team6/DAO/DonationDAOTest.java | 60 ++--- .../database/DatabaseConnectionTest.java | 82 +++--- .../team6/database/DatabaseManagerTest.java | 251 ++++++++---------- .../team6/models/CharityRegistryTest.java | 156 ++++++----- .../team6/models/CharityTest.java | 18 +- .../team6/models/DonationRegistryTest.java | 144 +++++----- .../team6/models/DonationTest.java | 3 +- .../team6/models/user/InboxTest.java | 131 +++++---- .../team6/models/user/MessegeTest.java | 75 +++--- .../team6/scraper/APICharityScraperTest.java | 185 ++++++------- 24 files changed, 829 insertions(+), 872 deletions(-) diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/DAO/DonationDAO.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/DAO/DonationDAO.java index 87674bf..c99056f 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/DAO/DonationDAO.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/DAO/DonationDAO.java @@ -1,44 +1,43 @@ package ntnu.systemutvikling.team6.DAO; -import ntnu.systemutvikling.team6.database.DatabaseConnection; -import ntnu.systemutvikling.team6.models.Charity; - import java.sql.*; -import java.util.Calendar; import java.util.UUID; +import ntnu.systemutvikling.team6.database.DatabaseConnection; +import ntnu.systemutvikling.team6.models.Charity; /** - * This class is responsible for sending concurrent information about the donation to the Donation Database. - * Usally called from the DonationPageController, where the user confirms their donation. + * This class is responsible for sending concurrent information about the donation to the Donation + * Database. Usally called from the DonationPageController, where the user confirms their donation. */ - public class DonationDAO { - private static final DatabaseConnection connection = new DatabaseConnection(); + private static final DatabaseConnection connection = new DatabaseConnection(); - /** - * Gets the total ammount of donations for a given charity, and sends it to the database throught MySQL. - * @param charity - * @param amount - */ - public static void addDonation(Charity charity, double amount){ - String sql_query = - """ + /** + * Gets the total ammount of donations for a given charity, and sends it to the database throught + * MySQL. + * + * @param charity + * @param amount + */ + public static void addDonation(Charity charity, double amount) { + String sql_query = + """ INSERT INTO Donations (UUID_Donations, amount, date, Charities_UUID_charities) VALUES (?, ?, ?, ?) """; - try (Connection conn = connection.getMySqlConnection(); - PreparedStatement ps = conn.prepareStatement(sql_query)){ - conn.setAutoCommit(false); + try (Connection conn = connection.getMySqlConnection(); + PreparedStatement ps = conn.prepareStatement(sql_query)) { + conn.setAutoCommit(false); - ps.setString(1, UUID.randomUUID().toString()); - ps.setDouble(2, amount); - ps.setDate(3, new Date(System.currentTimeMillis())); - ps.setString(4, charity.getUUID().toString()); + ps.setString(1, UUID.randomUUID().toString()); + ps.setDouble(2, amount); + ps.setDate(3, new Date(System.currentTimeMillis())); + ps.setString(4, charity.getUUID().toString()); - ps.executeUpdate(); - conn.commit(); - } catch (SQLException e) { - throw new RuntimeException(e); - } + ps.executeUpdate(); + conn.commit(); + } catch (SQLException e) { + throw new RuntimeException(e); } + } } diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/HmHApplication.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/HmHApplication.java index afa349d..293aa2d 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/HmHApplication.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/HmHApplication.java @@ -4,7 +4,6 @@ import java.net.http.HttpClient; import java.util.Objects; - import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; @@ -21,7 +20,10 @@ public void start(Stage stage) throws Exception { FXMLLoader fxmlLoader = new FXMLLoader(HmHApplication.class.getResource("/fxml/frontPage.fxml")); Scene scene = new Scene(fxmlLoader.load()); - Image icon = new Image(Objects.requireNonNull(HmHApplication.class.getResource("/images/Logo.png")).openStream()); + Image icon = + new Image( + Objects.requireNonNull(HmHApplication.class.getResource("/images/Logo.png")) + .openStream()); stage.getIcons().add(icon); stage.setTitle("Help Me Help"); stage.setScene(scene); diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/Main.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/Main.java index ead8b5c..d039f90 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/Main.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/Main.java @@ -1,6 +1,5 @@ package ntnu.systemutvikling.team6; - public class Main { // Make sure you're connected to the NTNU network for this to work public static void main(String[] args) { 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 ea63c91..8eb853f 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/CharityPageController.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/CharityPageController.java @@ -2,59 +2,60 @@ import javafx.event.ActionEvent; import javafx.fxml.FXML; -import javafx.fxml.FXMLLoader; -import javafx.scene.Node; -import javafx.scene.Parent; -import javafx.scene.Scene; import javafx.scene.control.Label; -import javafx.scene.layout.FlowPane; -import javafx.stage.Stage; -import ntnu.systemutvikling.team6.HmHApplication; import ntnu.systemutvikling.team6.models.Charity; -import java.io.IOException; - /** - * This controller represents the charity page, where the user can read about the charity and choose to donate to it. - * It also has a button to return to the front page. + * This controller represents the charity page, where the user can read about the charity and choose + * to donate to it. It also has a button to return to the front page. */ public class CharityPageController { @FXML private Label CharityDescription; @FXML private Label CharityName; - @FXML public void initialize() {} + @FXML + public void initialize() {} private Charity charity; /** - * This method is used to set the charity that is being displayed on the page. It also updates the labels with the charity's name and description. - * It acts like an initializer for the charity page, since the charity is not known until the user clicks on a charity from the front page. - * Param charity is the charity that is being displayed on the page, - * AND is called on from the front page when the user clicks on a charity, to set the charity that is being displayed on the page. + * This method is used to set the charity that is being displayed on the page. It also updates the + * labels with the charity's name and description. It acts like an initializer for the charity + * page, since the charity is not known until the user clicks on a charity from the front page. + * Param charity is the charity that is being displayed on the page, AND is called on from the + * front page when the user clicks on a charity, to set the charity that is being displayed on the + * page. + * * @param charity */ @FXML - public void setCharity(Charity charity){ + public void setCharity(Charity charity) { this.charity = charity; CharityDescription.setText(charity.getDescription()); CharityName.setText(charity.getName()); - } /** * This method is used to switch to the front page. + * * @param event */ - public void switchToFrontPage(ActionEvent event){ + @FXML + public void switchToFrontPage(ActionEvent event) { + System.out.println("Click"); LoaderScene.LoadScene("FrontPage", event, charity); } + /** * This method is used to switch to the donation page. + * * @param event */ - public void switchToDonationPage(ActionEvent event){ + @FXML + public void switchToDonationPage(ActionEvent event) { + System.out.println("Click"); LoaderScene.LoadScene("donationPage", event, charity); } } 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 a355c46..839a3e8 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/DonationPageController.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/DonationPageController.java @@ -1,5 +1,6 @@ package ntnu.systemutvikling.team6.controller; +import java.util.Optional; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Alert; @@ -9,110 +10,124 @@ import ntnu.systemutvikling.team6.DAO.DonationDAO; import ntnu.systemutvikling.team6.models.Charity; -import java.util.Optional; /** - * This controller represents the donation page, where the user can enter a donation amount and confirm their donation to the charity. - * It also has a button to return to the front page. + * This controller represents the donation page, where the user can enter a donation amount and + * confirm their donation to the charity. It also has a button to return to the front page. */ - public class DonationPageController { - @FXML private Charity charity; - - @FXML private TextField donatioAmount; - - @FXML private Label CharityName; - - - /** - * Initialize method for the donation page. Sets the charity name label to the name of the charity that is being donated to. - * The charity is set from the original page it was called from when the user clicks on the donate button, and is passed as a parameter to this method. - * - * @param charity - */ - @FXML - public void setCharity(Charity charity) { - this.charity = charity; - - CharityName.setText(charity.getName()); + @FXML private Charity charity; + + @FXML private TextField donatioAmount; + + @FXML private Label CharityName; + + /** + * Initialize method for the donation page. Sets the charity name label to the name of the charity + * that is being donated to. The charity is set from the original page it was called from when the + * user clicks on the donate button, and is passed as a parameter to this method. + * + * @param charity + */ + @FXML + public void setCharity(Charity charity) { + this.charity = charity; + + CharityName.setText(charity.getName()); + } + + /** + * This method is used to switch back to the front page when the user clicks the back button. + * + * @param event + */ + public void switchToFrontPage(ActionEvent event) { + LoaderScene.LoadScene("FrontPage", event, null); + } + + /** + * 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); + } + + /** + * This method is used to process the donation when the user clicks the donate button. Checks if + * the input is valid and displays appropriate error messages if it is not. If the input is valid, + * it shows a confirmation dialog to the user. Shows a confirmation dialog. If the user confirms, + * the donation is processed and the user is taken back to the front page. + * + * @param event + */ + public void Donate(ActionEvent event) { + String input = donatioAmount.getText().trim(); + + if (input.isEmpty()) { + showAlert(Alert.AlertType.ERROR, "Invalid input", "Please enter a donation amount."); + return; } + double amount; - /** - * This method is used to switch back to the front page when the user clicks the back button. - * @param event - */ - - public void switchToFrontPage(ActionEvent event) { - LoaderScene.LoadScene("FrontPage", event, null); + try { + amount = Double.parseDouble(input); + } catch (NumberFormatException e) { + showAlert(Alert.AlertType.ERROR, "Invalid input", "Please enter a valid number."); + return; } - /** - * This method is used to process the donation when the user clicks the donate button. - * Checks if the input is valid and displays appropriate error messages if it is not. If the input is valid, it shows a confirmation dialog to the user. - * Shows a confirmation dialog. If the user confirms, the donation is processed and the user is taken back to the front page. - * @param event - */ - public void Donate(ActionEvent event){ - String input = donatioAmount.getText().trim(); - - if (input.isEmpty()) { - showAlert(Alert.AlertType.ERROR, "Invalid input", "Please enter a donation amount."); - return; - } - double amount; - - try { - amount = Double.parseDouble(input); - } catch (NumberFormatException e) { - showAlert(Alert.AlertType.ERROR, "Invalid input", "Please enter a valid number."); - return; - } - - if (amount <= 0) { - showAlert(Alert.AlertType.ERROR, "Invalid amount", "Donation must be greater than 0."); - return; - } - - if (amount > 100_000) { - showAlert(Alert.AlertType.WARNING, "Amount too high", "Maximum donation is 100,000."); - return; - } - - Alert confirm = new Alert(Alert.AlertType.CONFIRMATION); - confirm.setTitle("Confirm Donation"); - confirm.setHeaderText("You're about to donate " + amount + " to " + charity.getName()); - confirm.setContentText("Are you sure?"); - Optional result = confirm.showAndWait(); - - if (result.isPresent() && result.get() == ButtonType.OK) { - // Process donation - processDonation(charity,amount); - showAlert(Alert.AlertType.INFORMATION, "Thank you!", "You have donated " + amount + " to " + charity.getName()); - donatioAmount.clear(); - LoaderScene.LoadScene("FrontPage", event, null); - } + if (amount <= 0) { + showAlert(Alert.AlertType.ERROR, "Invalid amount", "Donation must be greater than 0."); + return; } - /** - * Invoke DAO object to add the donation to the database. - * This method is called from the Donate method after the user confirms their donation. - * @param charity - * @param amount - */ - public void processDonation(Charity charity, double amount){ - DonationDAO.addDonation(charity, amount); + if (amount > 100_000) { + showAlert(Alert.AlertType.WARNING, "Amount too high", "Maximum donation is 100,000."); + return; } - /** - * Show an JavaFx alert dialog with the specified type, title, and message. - * @param type - * @param title - * @param message - */ - private 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(); + Alert confirm = new Alert(Alert.AlertType.CONFIRMATION); + confirm.setTitle("Confirm Donation"); + confirm.setHeaderText("You're about to donate " + amount + " to " + charity.getName()); + confirm.setContentText("Are you sure?"); + Optional result = confirm.showAndWait(); + + if (result.isPresent() && result.get() == ButtonType.OK) { + // Process donation + processDonation(charity, amount); + showAlert( + Alert.AlertType.INFORMATION, + "Thank you!", + "You have donated " + amount + " to " + charity.getName()); + donatioAmount.clear(); + LoaderScene.LoadScene("FrontPage", event, null); } + } + + /** + * Invoke DAO object to add the donation to the database. This method is called from the Donate + * method after the user confirms their donation. + * + * @param charity + * @param amount + */ + public void processDonation(Charity charity, double amount) { + DonationDAO.addDonation(charity, amount); + } + + /** + * Show an JavaFx alert dialog with the specified type, title, and message. + * + * @param type + * @param title + * @param message + */ + private 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(); + } } 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 5e7b1fe..f8ffc2a 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/FrontpageController.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/FrontpageController.java @@ -1,5 +1,6 @@ package ntnu.systemutvikling.team6.controller; +import java.util.Random; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; @@ -12,43 +13,35 @@ import ntnu.systemutvikling.team6.models.Donation; import ntnu.systemutvikling.team6.models.DonationRegistry; -import java.util.Random; -import java.util.stream.Collectors; - /** - * Landing page's controller. This is the first page the user sees when they open the application. It displays a random featured charity, some statistics about the charities and donations, and a list of all charities in the database. The user can click on a charity to see more details about 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 + * Landing page's controller. This is the first page the user sees when they open the application. + * It displays a random featured charity, some statistics about the charities and donations, and a + * list of all charities in the database. The user can click on a charity to see more details about + * 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 { - @FXML - private Charity featuredCharity; + @FXML private Charity featuredCharity; - @FXML - private FlowPane cardsContainer; + @FXML private FlowPane cardsContainer; - - @FXML - private Label Carosel_Organisasjon; - - @FXML - private Label Carosel_Beskrivelse; - - @FXML - private Label Total_Orgnisasjon; - - @FXML - private Label Total_Donations; - - @FXML - private Label PreApproved_Percentage; + @FXML private Label Carosel_Organisasjon; + + @FXML private Label Carosel_Beskrivelse; + + @FXML private Label Total_Orgnisasjon; + + @FXML private Label Total_Donations; + + @FXML private Label PreApproved_Percentage; /** - * Initialize method for the front page. This method is called when the front page is loaded. - * It retrieves the list of charities and donations from the database. - * The list of charities is displayed as a list of cards, where each card represents a charity from the Innsamlingskontrollen - * A random charity is selected to be featured on the page, and its name and description are displayed in the carousel section. - * The total number of charities, total amount of donations, and percentage of pre-approved charities are also displayed on the page. + * Initialize method for the front page. This method is called when the front page is loaded. It + * retrieves the list of charities and donations from the database. The list of charities is + * displayed as a list of cards, where each card represents a charity from the + * Innsamlingskontrollen A random charity is selected to be featured on the page, and its name and + * description are displayed in the carousel section. The total number of charities, total amount + * of donations, and percentage of pre-approved charities are also displayed on the page. */ @FXML public void initialize() { @@ -58,14 +51,14 @@ public void initialize() { DonationRegistry Donations = db.getDonationFromDB(); for (Charity ch : Charities.getAllCharities()) { - FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/organizationCard.fxml")); Parent card = loader.load(); OrganizationCardController cardController = loader.getController(); - // System.out.println("Added Name: " + ch.getName() + " Added Description: " + ch.getDescription()); + // System.out.println("Added Name: " + ch.getName() + " Added Description: " + + // ch.getDescription()); cardController.setOrganization(ch); cardsContainer.getChildren().add(card); @@ -80,10 +73,16 @@ public void initialize() { Carosel_Beskrivelse.setText(randomCharity.getDescription()); Total_Orgnisasjon.setText(Integer.toString(Charities_size)); - Total_Donations.setText(Double.toString(Donations.getAllDonations().stream().mapToDouble(Donation::getAmount).sum())); + Total_Donations.setText( + Double.toString( + Donations.getAllDonations().stream().mapToDouble(Donation::getAmount).sum())); PreApproved_Percentage.setText( - String.format("%.2f", Charities.getAllCharities().stream().filter(Charity::getPreApproved).count() * 100.0 / Charities_size) - + "%"); + String.format( + "%.2f", + Charities.getAllCharities().stream().filter(Charity::getPreApproved).count() + * 100.0 + / Charities_size) + + "%"); } catch (Exception e) { e.printStackTrace(); @@ -92,18 +91,19 @@ public void initialize() { /** * This method is used to switch to the charity page for the selected charity - * + * * @param event */ - public void switchToCharityPage(ActionEvent event){ + public void switchToCharityPage(ActionEvent event) { LoaderScene.LoadScene("CharityPage", event, featuredCharity); } + /** * This method is used to switch to the donation page for the selected charity. - * + * * @param event */ - public void switchToDonationPage(ActionEvent event){ + public void switchToDonationPage(ActionEvent event) { LoaderScene.LoadScene("DonationPage", event, featuredCharity); } } diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/LoaderScene.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/LoaderScene.java index e8b7036..83ace1e 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/LoaderScene.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/LoaderScene.java @@ -1,5 +1,7 @@ package ntnu.systemutvikling.team6.controller; +import java.io.IOException; +import java.util.Objects; import javafx.event.ActionEvent; import javafx.fxml.FXMLLoader; import javafx.scene.Node; @@ -10,52 +12,52 @@ import ntnu.systemutvikling.team6.HmHApplication; import ntnu.systemutvikling.team6.models.Charity; -import java.io.IOException; -import java.util.Objects; - /** - * This class is a utility class that is used to load different scenes in the application. - * For now, It is used to switch between the front page, charity page, and donation page. - * It takes care of loading the FXML file, setting the controller, and switching the scene. + * This class is a utility class that is used to load different scenes in the application. For now, + * It is used to switch between the front page, charity page, and donation page. It takes care of + * loading the FXML file, setting the controller, and switching the scene. */ - public class LoaderScene { - /** - * When going to a new scene, this method is called to load the new scene. - * 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). - * 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, ActionEvent event, Charity charity){ - try { - System.out.println(HmHApplication.class.getResource("/fxml/"+ sceneName +".fxml")); - FXMLLoader fxmlLoader = - new FXMLLoader(HmHApplication.class.getResource("/fxml/"+ sceneName +".fxml")); - Parent root = fxmlLoader.load(); + /** + * When going to a new scene, this method is called to load the new scene. 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). 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, ActionEvent event, Charity charity) { + try { + System.out.println(HmHApplication.class.getResource("/fxml/" + sceneName + ".fxml")); + FXMLLoader fxmlLoader = + new FXMLLoader(HmHApplication.class.getResource("/fxml/" + sceneName + ".fxml")); + Parent root = fxmlLoader.load(); - System.out.println("Controller: " + fxmlLoader.getController()); - Object controller = fxmlLoader.getController(); + System.out.println("Controller: " + fxmlLoader.getController()); + Object controller = fxmlLoader.getController(); - // Needs to be expanded when more pages get implemented. - if (controller instanceof CharityPageController charityController) { - charityController.setCharity(charity); - } - if (controller instanceof DonationPageController donationController) { - donationController.setCharity(charity); - } + // Needs to be expanded when more pages get implemented. + if (controller instanceof CharityPageController charityController) { + charityController.setCharity(charity); + } + if (controller instanceof DonationPageController donationController) { + donationController.setCharity(charity); + } - Stage stage = (Stage) ((Node)event.getSource()).getScene().getWindow(); - Image icon = new Image(Objects.requireNonNull(HmHApplication.class.getResource("/images/Logo.png")).openStream()); - stage.getIcons().add(icon); - Scene scene = new Scene(root); - stage.setScene(scene); - stage.setFullScreen(true); - stage.show(); - } catch (IOException e) { - throw new RuntimeException(e); - } + Stage stage = (Stage) ((Node) event.getSource()).getScene().getWindow(); + Image icon = + new Image( + Objects.requireNonNull(HmHApplication.class.getResource("/images/Logo.png")) + .openStream()); + stage.getIcons().add(icon); + Scene scene = new Scene(root); + stage.setScene(scene); + stage.setFullScreen(true); + stage.show(); + } catch (IOException e) { + throw new RuntimeException(e); } + } } diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/OrganizationCardController.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/OrganizationCardController.java index 5ac3006..b51e530 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/OrganizationCardController.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/controller/OrganizationCardController.java @@ -2,23 +2,14 @@ import javafx.event.ActionEvent; import javafx.fxml.FXML; -import javafx.fxml.FXMLLoader; -import javafx.scene.Node; -import javafx.scene.Parent; -import javafx.scene.Scene; import javafx.scene.control.Label; -import javafx.stage.Stage; -import ntnu.systemutvikling.team6.HmHApplication; import ntnu.systemutvikling.team6.models.Charity; -import java.io.IOException; -import java.util.Objects; - /** - * This controller represents the organization card that is displayed on the front page and is looped upon in FronpageController. - * It is used to display the name and description of a charity, and to switch to the charity page or donation page when the user clicks on the card. + * This controller represents the organization card that is displayed on the front page and is + * looped upon in FronpageController. It is used to display the name and description of a charity, + * and to switch to the charity page or donation page when the user clicks on the card. */ - public class OrganizationCardController { @FXML private Label organizationName; @@ -35,10 +26,11 @@ public void setOrganization(Charity charity) { } /* EVENTS */ - public void switchToCharityPage(ActionEvent event){ - LoaderScene.LoadScene("CharityPage", event, charity); + public void switchToCharityPage(ActionEvent event) { + LoaderScene.LoadScene("CharityPage", event, charity); } - public void switchToDonationPage(ActionEvent event){ - LoaderScene.LoadScene("DonationPage", event, charity); + + public void switchToDonationPage(ActionEvent event) { + LoaderScene.LoadScene("DonationPage", event, charity); } } diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DatabaseConnection.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DatabaseConnection.java index 1222288..28c325d 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DatabaseConnection.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DatabaseConnection.java @@ -17,13 +17,11 @@ public class DatabaseConnection { * @throws IllegalStateException if either databaseURL, username, or password is {@code null} or * blank */ - public DatabaseConnection() { this.databaseURL = "jdbc:mysql://namox.idi.ntnu.no:3306/apbaluna?useSSL=false&serverTimezone=UTC"; this.username = "apbaluna"; this.password = "GYntUFPG"; - } /** diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DatabaseManager.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DatabaseManager.java index 0017f63..a4007a0 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DatabaseManager.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/DatabaseManager.java @@ -3,8 +3,6 @@ import java.sql.*; import java.util.List; import java.util.UUID; - -import ntnu.systemutvikling.team6.DAO.DonationDAO; import ntnu.systemutvikling.team6.models.Charity; import ntnu.systemutvikling.team6.models.CharityRegistry; import ntnu.systemutvikling.team6.models.Donation; @@ -12,12 +10,13 @@ import ntnu.systemutvikling.team6.scraper.APICharityData; /** - * Manages the Database with MySQL tables and JDBC. + * Manages the Database with MySQL tables and JDBC. * - * This class is responsible for creating the tables needed for the application, if not done - * already and maintaining the {@code charities} table based on data retrieved from the IK API. - * It is also responsible for retrieving the data from the database and sending it to the application through the CharityRegistry and DonationRegistry. - * It is used by the FrontpageController to retrieve the data needed to display the charities + *

This class is responsible for creating the tables needed for the application, if not done + * already and maintaining the {@code charities} table based on data retrieved from the IK API. It + * is also responsible for retrieving the data from the database and sending it to the application + * through the CharityRegistry and DonationRegistry. It is used by the FrontpageController to + * retrieve the data needed to display the charities */ public class DatabaseManager { private final DatabaseConnection connection; @@ -58,7 +57,7 @@ public boolean testConnection() { /** * Creates the {@code Charities} and {@code Donations} tables if they do not already exist. * - *

The table structure for Charities is based on fields from {@link APICharityData}.

+ *

The table structure for Charities is based on fields from {@link APICharityData}. * * @throws RuntimeException if a {@link SQLException} occurs while creating the table */ @@ -112,11 +111,13 @@ REFERENCES Charities (`UUID_charities`) } /** - * This method is used to verify the integrity of the data in the {@code charities} table and to update it based on the data retrieved from the IK API. - * The param charities are retrieved from the IK API through the APICharityData class. - * Called in initialize method in HmHApplication.java, which is the main class of the application, to ensure that the data is up to date when the application starts. - * Uses a a temp table to ensure that the data in the database is consistent with the data from the API. - * + * This method is used to verify the integrity of the data in the {@code charities} table and to + * update it based on the data retrieved from the IK API. The param charities are retrieved from + * the IK API through the APICharityData class. Called in initialize method in + * HmHApplication.java, which is the main class of the application, to ensure that the data is up + * to date when the application starts. Uses a a temp table to ensure that the data in the + * database is consistent with the data from the API. + * * @param charities */ public void addAPIDataToTable(List charities) { @@ -155,7 +156,8 @@ INSERT INTO Charities (UUID_charities, org_number, charity_name, charity_link, p } // -- Intergerty Check: - String createTemp = """ + String createTemp = + """ CREATE TEMPORARY TABLE temp_api_charities ( org_number VARCHAR(20) PRIMARY KEY ) @@ -170,14 +172,15 @@ org_number VARCHAR(20) PRIMARY KEY try (PreparedStatement ps = conn.prepareStatement(insertTemp)) { for (Charity charity : charities) { - ps.setString(1, charity.getOrg_number().replaceAll("\\s","")); + ps.setString(1, charity.getOrg_number().replaceAll("\\s", "")); ps.addBatch(); } ps.executeBatch(); } - String deleteSql = """ + String deleteSql = + """ DELETE FROM Charities c WHERE NOT EXISTS ( SELECT 1 @@ -214,25 +217,27 @@ WHERE NOT EXISTS ( } } } - public CharityRegistry getCharitiesFromDB(){ + + public CharityRegistry getCharitiesFromDB() { CharityRegistry registry = null; Connection conn = null; try { conn = connection.getMySqlConnection(); - String sql_query = "SELECT UUID_charities, org_number, charity_name, charity_link, pre_approved, status FROM Charities"; + String sql_query = + "SELECT UUID_charities, org_number, charity_name, charity_link, pre_approved, status FROM Charities"; Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql_query); registry = new CharityRegistry(); - while (rs.next()){ - Charity charity = new Charity( + while (rs.next()) { + Charity charity = + new Charity( rs.getString("UUID_charities"), - rs.getString("org_number" ), + rs.getString("org_number"), rs.getString("charity_link"), rs.getString("charity_name"), rs.getBoolean("pre_approved"), - rs.getString("status") - ); + rs.getString("status")); registry.addCharity(charity); } } catch (SQLException e) { @@ -242,13 +247,14 @@ public CharityRegistry getCharitiesFromDB(){ return registry; } - public DonationRegistry getDonationFromDB(){ + public DonationRegistry getDonationFromDB() { DonationRegistry registry = null; Connection conn = null; try { conn = connection.getMySqlConnection(); - String sql_query = """ - SELECT + String sql_query = + """ + SELECT d.UUID_Donations, d.amount, d.date, @@ -266,22 +272,22 @@ public DonationRegistry getDonationFromDB(){ ResultSet rs = stmt.executeQuery(sql_query); registry = new DonationRegistry(); - while (rs.next()){ - Charity charity = new Charity( + while (rs.next()) { + Charity charity = + new Charity( rs.getString("UUID_charities"), rs.getString("org_number"), rs.getString("charity_name"), rs.getString("charity_link"), rs.getBoolean("pre_approved"), - rs.getString("status") - ); + rs.getString("status")); - Donation donation = new Donation( + Donation donation = + new Donation( rs.getString("UUID_Donations"), rs.getDouble("amount"), rs.getDate("date").toLocalDate(), - charity - ); + charity); registry.addDonation(donation); } } catch (SQLException e) { diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/models/Charity.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/models/Charity.java index 4f5a9ec..d97d996 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/models/Charity.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/models/Charity.java @@ -34,8 +34,6 @@ public class Charity { /* List that contains the charity's Feedbacks */ private List feedbacks; - - /** * Contructor for creating a new charity. Taylored to match data given from Api. Other attributes * will just be initialized as empty @@ -56,17 +54,23 @@ public Charity( this.feedbacks = new ArrayList<>(); this.category = ""; } + /** - * Contructor for creating a new charity. Taylored to match data given from DATABASE. Other attributes - * will just be initialized as empty + * Contructor for creating a new charity. Taylored to match data given from DATABASE. Other + * attributes will just be initialized as empty * * @param org_number matches from innsamlingkontrollen * @param name matches from innsamlingkontrollen * @param is_pre_approved name matches from innsamlingkontrollen * @param status name matches from innsamlingkontrollen */ - public Charity(String uuid, - String org_number, String link, String name, boolean is_pre_approved, String status) { + public Charity( + String uuid, + String org_number, + String link, + String name, + boolean is_pre_approved, + String status) { this.UUID = UUID.fromString(uuid); this.org_number = org_number.replaceAll("\\s", ""); this.name = name; diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/models/Donation.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/models/Donation.java index 63ca280..64d8733 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/models/Donation.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/models/Donation.java @@ -1,8 +1,6 @@ package ntnu.systemutvikling.team6.models; import java.time.LocalDate; -import java.time.LocalDateTime; -import java.util.Date; import java.util.UUID; import ntnu.systemutvikling.team6.models.user.User; @@ -44,7 +42,8 @@ public Donation(double amount, LocalDate date, Charity charity, User donor) { } /** - * Constructor for creating a new donation. Taylored for getting info FROM DATABASE. NEEDS TO BE CHANGED in phase 3. + * Constructor for creating a new donation. Taylored for getting info FROM DATABASE. NEEDS TO BE + * CHANGED in phase 3. * * @param amount * @param date diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/scraper/APICharityData.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/scraper/APICharityData.java index d4a6e90..10a489d 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/scraper/APICharityData.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/scraper/APICharityData.java @@ -19,8 +19,8 @@ public class APICharityData { private final boolean is_pre_approved; /** - * Constructs a new APICharityData object. - * This class represents the data provided from the IK Api, and is used expand and provide data to our design of a charity. + * Constructs a new APICharityData object. This class represents the data provided from the IK + * Api, and is used expand and provide data to our design of a charity. * * @param org_number a unique number that identifies the organization * @param name the name of the organization diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/scraper/APICharityScraper.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/scraper/APICharityScraper.java index 7b341b7..89422a1 100644 --- a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/scraper/APICharityScraper.java +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/scraper/APICharityScraper.java @@ -64,9 +64,8 @@ public String getJSONData() throws IOException, InterruptedException { } /** - * Parses the JSON data using gson and translates the {@code APICharityData} into our predefined charity classes - * and puts it in a CharityRegistry object. - * + * Parses the JSON data using gson and translates the {@code APICharityData} into our predefined + * charity classes and puts it in a CharityRegistry object. * * @param JSONData the {@code String} of JSON data to be parsed * @return a CharityRegistry class object diff --git a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/DAO/DonationDAOTest.java b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/DAO/DonationDAOTest.java index cdef6b0..d3522ed 100644 --- a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/DAO/DonationDAOTest.java +++ b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/DAO/DonationDAOTest.java @@ -1,56 +1,48 @@ package ntnu.systemutvikling.team6.DAO; +import static org.junit.jupiter.api.Assertions.*; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; import ntnu.systemutvikling.team6.database.DatabaseConnection; import ntnu.systemutvikling.team6.database.DatabaseManager; import ntnu.systemutvikling.team6.models.Charity; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; - -import static org.junit.jupiter.api.Assertions.*; - class DonationDAOTest { - private Charity charity; + private Charity charity; - @BeforeEach - void setUp() { - DatabaseManager manager = new DatabaseManager(); - manager.createTables(); + @BeforeEach + void setUp() { + DatabaseManager manager = new DatabaseManager(); + manager.createTables(); - charity = new Charity( - "123456", - "https://test.org", - "Test Charity", - true, - "approved" - ); + charity = new Charity("123456", "https://test.org", "Test Charity", true, "approved"); - manager.addAPIDataToTable(java.util.List.of(charity)); - } + manager.addAPIDataToTable(java.util.List.of(charity)); + } - @Test - void addDonationShouldInsertDonationIntoDatabase() throws Exception { - double amount = 100.0; + @Test + void addDonationShouldInsertDonationIntoDatabase() throws Exception { + double amount = 100.0; - DonationDAO.addDonation(charity, amount); + DonationDAO.addDonation(charity, amount); - try (Connection conn = new DatabaseConnection().getMySqlConnection()) { + try (Connection conn = new DatabaseConnection().getMySqlConnection()) { - PreparedStatement stmt = - conn.prepareStatement("SELECT amount FROM Donations WHERE Charities_UUID_charities = ?"); + PreparedStatement stmt = + conn.prepareStatement("SELECT amount FROM Donations WHERE Charities_UUID_charities = ?"); - stmt.setString(1, charity.getUUID().toString()); + stmt.setString(1, charity.getUUID().toString()); - ResultSet rs = stmt.executeQuery(); + ResultSet rs = stmt.executeQuery(); - assertTrue(rs.next(), "Donation should exist in database"); + assertTrue(rs.next(), "Donation should exist in database"); - assertEquals(amount, rs.getDouble("amount")); - } + assertEquals(amount, rs.getDouble("amount")); } -} \ No newline at end of file + } +} diff --git a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/database/DatabaseConnectionTest.java b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/database/DatabaseConnectionTest.java index 0bfc9b6..4269e1a 100644 --- a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/database/DatabaseConnectionTest.java +++ b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/database/DatabaseConnectionTest.java @@ -1,56 +1,58 @@ package ntnu.systemutvikling.team6.database; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; import java.sql.Connection; import java.sql.SQLException; - -import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; class DatabaseConnectionTest { - @Test - void constructorShouldCreateInstanceWithValidCredentials() { - DatabaseConnection db = new DatabaseConnection( - "jdbc:mysql://localhost:3306/test", - "user", - "password" - ); - - assertNotNull(db); - } - - @Test - void constructorShouldThrowExceptionIfUrlIsNull() { - assertThrows(IllegalArgumentException.class, () -> { - new DatabaseConnection(null, "user", "password"); - }); - } + @Test + void constructorShouldCreateInstanceWithValidCredentials() { + DatabaseConnection db = + new DatabaseConnection("jdbc:mysql://localhost:3306/test", "user", "password"); - @Test - void constructorShouldThrowExceptionIfUsernameIsBlank() { - assertThrows(IllegalArgumentException.class, () -> { - new DatabaseConnection("jdbc:mysql://localhost:3306/test", "", "password"); - }); - } + assertNotNull(db); + } - @Test - void constructorShouldThrowExceptionIfPasswordIsBlank() { - assertThrows(IllegalArgumentException.class, () -> { - new DatabaseConnection("jdbc:mysql://localhost:3306/test", "user", ""); + @Test + void constructorShouldThrowExceptionIfUrlIsNull() { + assertThrows( + IllegalArgumentException.class, + () -> { + new DatabaseConnection(null, "user", "password"); + }); + } + + @Test + void constructorShouldThrowExceptionIfUsernameIsBlank() { + assertThrows( + IllegalArgumentException.class, + () -> { + new DatabaseConnection("jdbc:mysql://localhost:3306/test", "", "password"); + }); + } + + @Test + void constructorShouldThrowExceptionIfPasswordIsBlank() { + assertThrows( + IllegalArgumentException.class, + () -> { + new DatabaseConnection("jdbc:mysql://localhost:3306/test", "user", ""); }); - } + } - @Test - void getMySqlConnectionShouldReturnConnection() throws SQLException { + @Test + void getMySqlConnectionShouldReturnConnection() throws SQLException { - DatabaseConnection db = new DatabaseConnection(); + DatabaseConnection db = new DatabaseConnection(); - Connection connection = db.getMySqlConnection(); + Connection connection = db.getMySqlConnection(); - assertNotNull(connection); - assertFalse(connection.isClosed()); + assertNotNull(connection); + assertFalse(connection.isClosed()); - connection.close(); - } -} \ No newline at end of file + connection.close(); + } +} diff --git a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/database/DatabaseManagerTest.java b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/database/DatabaseManagerTest.java index 51aa6e6..086ed69 100644 --- a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/database/DatabaseManagerTest.java +++ b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/database/DatabaseManagerTest.java @@ -1,169 +1,130 @@ package ntnu.systemutvikling.team6.database; -import ntnu.systemutvikling.team6.database.DatabaseConnection; -import ntnu.systemutvikling.team6.models.Charity; -import ntnu.systemutvikling.team6.models.CharityRegistry; -import ntnu.systemutvikling.team6.scraper.APICharityData; -import ntnu.systemutvikling.team6.database.DatabaseManager; -import org.junit.jupiter.api.*; +import static org.junit.jupiter.api.Assertions.*; + import java.sql.*; import java.util.ArrayList; import java.util.List; -import java.util.Optional; - -import org.h2.jdbc.JdbcSQLNonTransientException; -import static org.junit.jupiter.api.Assertions.*; +import ntnu.systemutvikling.team6.models.Charity; +import ntnu.systemutvikling.team6.models.CharityRegistry; +import org.junit.jupiter.api.*; class DatabaseManagerTest { - private DatabaseManager dbManager; + private DatabaseManager dbManager; - @BeforeEach - public void setUp() throws SQLException{ - this.dbManager = new DatabaseManager(); - } + @BeforeEach + public void setUp() throws SQLException { + this.dbManager = new DatabaseManager(); + } - // Make sure you're connected to the NTNU network for this to work - @Test - public void testConnectionShouldReturnTrue(){ - assertTrue(dbManager.testConnection()); - } - @Test - void createCharitiesTableShouldCreateTableSuccessfully() throws SQLException { - dbManager.createTables(); + // Make sure you're connected to the NTNU network for this to work + @Test + public void testConnectionShouldReturnTrue() { + assertTrue(dbManager.testConnection()); + } - try (Connection conn = new DatabaseConnection().getMySqlConnection()) { - ResultSet rs = conn.getMetaData().getTables(null, null, - "Charities", null); + @Test + void createCharitiesTableShouldCreateTableSuccessfully() throws SQLException { + dbManager.createTables(); - assertTrue(rs.next()); - } + try (Connection conn = new DatabaseConnection().getMySqlConnection()) { + ResultSet rs = conn.getMetaData().getTables(null, null, "Charities", null); + + assertTrue(rs.next()); } + } - @Test - void updateCharitiesShouldInsertCorrectData() throws SQLException { - dbManager.createTables(); - - String org_number = "12345"; - String name = "Test Charity"; - String status = "approved"; - String url = "https://www.svindel.no"; - boolean is_pre_approved = false; - - Charity charity = new Charity( - org_number, - url, - name, - is_pre_approved, - status - ); - dbManager.addAPIDataToTable(List.of(charity)); - - Charity charity2 = new Charity( - org_number, - url, - name + " Updated", - is_pre_approved, - status - ); - dbManager.addAPIDataToTable(List.of(charity2)); - - dbManager.createTables(); - - CharityRegistry registry = dbManager.getCharitiesFromDB(); - Charity insertedCharity = registry.findCharityByOrgnumber("12345").get(); - assertEquals("Test Charity Updated", insertedCharity.getName()); + @Test + void updateCharitiesShouldInsertCorrectData() throws SQLException { + dbManager.createTables(); - } + String org_number = "12345"; + String name = "Test Charity"; + String status = "approved"; + String url = "https://www.svindel.no"; + boolean is_pre_approved = false; - @Test - void updateCharitiesShouldRemoveDataNotInList() throws SQLException { - String org_number = "12345"; - String name = "Svindelorg"; - String status = "approved"; - String url = "https://www.svindel.no"; - boolean is_pre_approved = false; - - var charity1 = new Charity( - org_number, - url, - name, - is_pre_approved, - status - - ); - - org_number = "23456"; - name = "SvindelKoin"; - status = "approved"; - url = "https://www.svindel.net"; - is_pre_approved = true; - - var charity2 = new Charity( - org_number, - url, - name, - is_pre_approved, - status - ); - - org_number = "345672"; - name = "Arme Svindlere"; - status = "approved"; - url = "https://www.armesvindlere.com"; - is_pre_approved = false; - - var charity3 = new Charity( - org_number, - url, - name, - is_pre_approved, - status - ); - - List charityListBefore = new ArrayList<>(); - charityListBefore.add(charity1); - charityListBefore.add(charity2); - charityListBefore.add(charity3); - - dbManager.addAPIDataToTable(charityListBefore); - - List charityListNew = new ArrayList<>(); - charityListNew.add(charity1); - charityListNew.add(charity3); - - dbManager.addAPIDataToTable(charityListNew); - - try (Connection conn = new DatabaseConnection().getMySqlConnection()) { - PreparedStatement stmt = conn.prepareStatement("SELECT COUNT(org_number) AS number_a FROM Charities"); + Charity charity = new Charity(org_number, url, name, is_pre_approved, status); + dbManager.addAPIDataToTable(List.of(charity)); - ResultSet rs = stmt.executeQuery(); + Charity charity2 = new Charity(org_number, url, name + " Updated", is_pre_approved, status); + dbManager.addAPIDataToTable(List.of(charity2)); - assertTrue(rs.next(), "Charities count row should exist."); - assertEquals(2, rs.getInt("number_a"), "The amount of org_numbers in the table" + - "should be 2 due to removal of 1 table."); - } - } + dbManager.createTables(); - @Test - void tempTableShouldNotExistAfterUpdating() throws SQLException{ - Charity charity = new Charity( - "99999", - "https://temp.no", - "Temp Charity", - false, - "approved" - ); + CharityRegistry registry = dbManager.getCharitiesFromDB(); + Charity insertedCharity = registry.findCharityByOrgnumber("12345").get(); + assertEquals("Test Charity Updated", insertedCharity.getName()); + } - dbManager.addAPIDataToTable(List.of(charity)); + @Test + void updateCharitiesShouldRemoveDataNotInList() throws SQLException { + String org_number = "12345"; + String name = "Svindelorg"; + String status = "approved"; + String url = "https://www.svindel.no"; + boolean is_pre_approved = false; - try (Connection conn = new DatabaseConnection().getMySqlConnection()) { - PreparedStatement stmt = conn.prepareStatement("SELECT * FROM temp_api_charities"); + var charity1 = new Charity(org_number, url, name, is_pre_approved, status); + org_number = "23456"; + name = "SvindelKoin"; + status = "approved"; + url = "https://www.svindel.net"; + is_pre_approved = true; - assertThrows(java.sql.SQLSyntaxErrorException.class, () -> { - ResultSet rs = stmt.executeQuery(); - }); - } + var charity2 = new Charity(org_number, url, name, is_pre_approved, status); + + org_number = "345672"; + name = "Arme Svindlere"; + status = "approved"; + url = "https://www.armesvindlere.com"; + is_pre_approved = false; + + var charity3 = new Charity(org_number, url, name, is_pre_approved, status); + + List charityListBefore = new ArrayList<>(); + charityListBefore.add(charity1); + charityListBefore.add(charity2); + charityListBefore.add(charity3); + + dbManager.addAPIDataToTable(charityListBefore); + + List charityListNew = new ArrayList<>(); + charityListNew.add(charity1); + charityListNew.add(charity3); + + dbManager.addAPIDataToTable(charityListNew); + + try (Connection conn = new DatabaseConnection().getMySqlConnection()) { + PreparedStatement stmt = + conn.prepareStatement("SELECT COUNT(org_number) AS number_a FROM Charities"); + + ResultSet rs = stmt.executeQuery(); + + assertTrue(rs.next(), "Charities count row should exist."); + assertEquals( + 2, + rs.getInt("number_a"), + "The amount of org_numbers in the table" + "should be 2 due to removal of 1 table."); + } + } + + @Test + void tempTableShouldNotExistAfterUpdating() throws SQLException { + Charity charity = new Charity("99999", "https://temp.no", "Temp Charity", false, "approved"); + + dbManager.addAPIDataToTable(List.of(charity)); + + try (Connection conn = new DatabaseConnection().getMySqlConnection()) { + PreparedStatement stmt = conn.prepareStatement("SELECT * FROM temp_api_charities"); + + assertThrows( + java.sql.SQLSyntaxErrorException.class, + () -> { + ResultSet rs = stmt.executeQuery(); + }); } -} \ No newline at end of file + } +} diff --git a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/CharityRegistryTest.java b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/CharityRegistryTest.java index 1ac0261..f60568b 100644 --- a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/CharityRegistryTest.java +++ b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/CharityRegistryTest.java @@ -13,89 +13,87 @@ * * @author Adrian Balunan */ - public class CharityRegistryTest { private CharityRegistry registry; private Charity charity; /* Setting up variables */ - @BeforeEach - public void setup() { - registry = new CharityRegistry(); - charity = new Charity("1239813", "www.aaaa.com", "Charity1", false, "unverified"); - - } - - @Test - void testAddCharitySuccessfully() { - registry.addCharity(charity); - - assertEquals(1, registry.getAllCharities().size()); - assertTrue(registry.getAllCharities().contains(charity)); - } - - @Test - void testAddCharityNullThrowsException() { - assertThrows(IllegalArgumentException.class, () -> registry.addCharity(null)); - } - - @Test - void testGetAllCharitiesReturnsUnmodifiableList() { - registry.addCharity(charity); - - List charities = registry.getAllCharities(); - assertThrows(UnsupportedOperationException.class, () -> charities.add(charity)); - } - - @Test - void testFindCharityByIdFound() { - registry.addCharity(charity); - - Optional result = registry.findCharityByUUID(charity.getUUID()); - - assertTrue(result.isPresent()); - assertEquals(charity, result.get()); - } - @Test - void testFindCharityByOrgNumber() { - registry.addCharity(charity); - - Optional result = registry.findCharityByOrgnumber(charity.getOrg_number()); - - assertTrue(result.isPresent()); - assertEquals(charity, result.get()); - } - - @Test - void testFindCharityByIdNotFound() { - Optional result = registry.findCharityByUUID(UUID.randomUUID()); - assertTrue(result.isEmpty()); - } - - @Test - void testFindCharityByIdNullThrowsException() { - assertThrows(IllegalArgumentException.class, () -> registry.findCharityByUUID(null)); - } - - @Test - void testRemoveCharitySuccessfully() { - registry.addCharity(charity); - - boolean removed = registry.removeCharityUUID(charity.getUUID()); - - assertTrue(removed); - assertTrue(registry.getAllCharities().isEmpty()); - } - - @Test - void testRemoveCharityNotFound() { - boolean removed = registry.removeCharityUUID(UUID.randomUUID()); - assertFalse(removed); - } - - @Test - void testRemoveCharityNullThrowsException() { - assertThrows(IllegalArgumentException.class, () -> registry.removeCharity(null)); - } + @BeforeEach + public void setup() { + registry = new CharityRegistry(); + charity = new Charity("1239813", "www.aaaa.com", "Charity1", false, "unverified"); + } + + @Test + void testAddCharitySuccessfully() { + registry.addCharity(charity); + + assertEquals(1, registry.getAllCharities().size()); + assertTrue(registry.getAllCharities().contains(charity)); + } + + @Test + void testAddCharityNullThrowsException() { + assertThrows(IllegalArgumentException.class, () -> registry.addCharity(null)); + } + + @Test + void testGetAllCharitiesReturnsUnmodifiableList() { + registry.addCharity(charity); + + List charities = registry.getAllCharities(); + assertThrows(UnsupportedOperationException.class, () -> charities.add(charity)); + } + + @Test + void testFindCharityByIdFound() { + registry.addCharity(charity); + + Optional result = registry.findCharityByUUID(charity.getUUID()); + + assertTrue(result.isPresent()); + assertEquals(charity, result.get()); + } + + @Test + void testFindCharityByOrgNumber() { + registry.addCharity(charity); + + Optional result = registry.findCharityByOrgnumber(charity.getOrg_number()); + + assertTrue(result.isPresent()); + assertEquals(charity, result.get()); + } + + @Test + void testFindCharityByIdNotFound() { + Optional result = registry.findCharityByUUID(UUID.randomUUID()); + assertTrue(result.isEmpty()); + } + + @Test + void testFindCharityByIdNullThrowsException() { + assertThrows(IllegalArgumentException.class, () -> registry.findCharityByUUID(null)); } + @Test + void testRemoveCharitySuccessfully() { + registry.addCharity(charity); + + boolean removed = registry.removeCharityUUID(charity.getUUID()); + + assertTrue(removed); + assertTrue(registry.getAllCharities().isEmpty()); + } + + @Test + void testRemoveCharityNotFound() { + boolean removed = registry.removeCharityUUID(UUID.randomUUID()); + assertFalse(removed); + } + + @Test + void testRemoveCharityNullThrowsException() { + assertThrows(IllegalArgumentException.class, () -> registry.removeCharity(null)); + } +} 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 b13533c..e382fe5 100644 --- a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/CharityTest.java +++ b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/CharityTest.java @@ -11,7 +11,6 @@ * * @author Adrian Balunan */ - public class CharityTest { private Charity charity; @@ -42,13 +41,12 @@ public void testGettingDescriptionShouldWork() { } /** Getter and setter for IsVerified should be able to switch between true and false */ - @Test - public void testIsVerifiedReturnsCorrectly() { - assertEquals("approved", charity.getStatus()); - charity.setUnverified(); - assertEquals("Veto", charity.getStatus()); - charity.setVerified(); - assertEquals("approved", charity.getStatus()); - } + @Test + public void testIsVerifiedReturnsCorrectly() { + assertEquals("approved", charity.getStatus()); + charity.setUnverified(); + assertEquals("Veto", charity.getStatus()); + charity.setVerified(); + assertEquals("approved", charity.getStatus()); } - +} diff --git a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/DonationRegistryTest.java b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/DonationRegistryTest.java index b62ad0d..924ca4f 100644 --- a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/DonationRegistryTest.java +++ b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/DonationRegistryTest.java @@ -7,110 +7,100 @@ import java.util.List; import java.util.Optional; import java.util.UUID; - -import ntnu.systemutvikling.team6.models.user.User; import ntnu.systemutvikling.team6.models.user.Settings; - +import ntnu.systemutvikling.team6.models.user.User; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class DonationRegistryTest { - private DonationRegistry registry; - private Donation donation; + private DonationRegistry registry; + private Donation donation; - @BeforeEach - void setUp() { - registry = new DonationRegistry(); + @BeforeEach + void setUp() { + registry = new DonationRegistry(); - Charity charity = mock(Charity.class); - User user = mock(User.class); - Settings settings = mock(Settings.class); + Charity charity = mock(Charity.class); + User user = mock(User.class); + Settings settings = mock(Settings.class); - when(user.getSettings()).thenReturn(settings); - when(settings.isAnonymous()).thenReturn(false); + when(user.getSettings()).thenReturn(settings); + when(settings.isAnonymous()).thenReturn(false); - donation = new Donation( - 100, - LocalDate.now(), - charity, - user - ); - } + donation = new Donation(100, LocalDate.now(), charity, user); + } - @Test - void constructor_shouldCreateEmptyRegistry() { - assertTrue(registry.getAllDonations().isEmpty()); - } + @Test + void constructor_shouldCreateEmptyRegistry() { + assertTrue(registry.getAllDonations().isEmpty()); + } - @Test - void addDonation_shouldAddDonation() { - registry.addDonation(donation); + @Test + void addDonation_shouldAddDonation() { + registry.addDonation(donation); - List donations = registry.getAllDonations(); + List donations = registry.getAllDonations(); - assertEquals(1, donations.size()); - assertTrue(donations.contains(donation)); - } + assertEquals(1, donations.size()); + assertTrue(donations.contains(donation)); + } - @Test - void addDonation_nullDonation_shouldThrowException() { - assertThrows(IllegalArgumentException.class, () -> registry.addDonation(null)); - } + @Test + void addDonation_nullDonation_shouldThrowException() { + assertThrows(IllegalArgumentException.class, () -> registry.addDonation(null)); + } - @Test - void getAllDonations_shouldReturnUnmodifiableList() { - registry.addDonation(donation); + @Test + void getAllDonations_shouldReturnUnmodifiableList() { + registry.addDonation(donation); - List donations = registry.getAllDonations(); + List donations = registry.getAllDonations(); - assertThrows(UnsupportedOperationException.class, - () -> donations.add(donation)); - } + assertThrows(UnsupportedOperationException.class, () -> donations.add(donation)); + } - @Test - void findDonationById_shouldReturnDonationIfFound() { - registry.addDonation(donation); + @Test + void findDonationById_shouldReturnDonationIfFound() { + registry.addDonation(donation); - Optional result = registry.findDonationById(donation.getCharityId()); + Optional result = registry.findDonationById(donation.getCharityId()); - assertTrue(result.isPresent()); - assertEquals(donation, result.get()); - } + assertTrue(result.isPresent()); + assertEquals(donation, result.get()); + } - @Test - void findDonationById_shouldReturnEmptyIfNotFound() { - Optional result = registry.findDonationById(UUID.randomUUID()); + @Test + void findDonationById_shouldReturnEmptyIfNotFound() { + Optional result = registry.findDonationById(UUID.randomUUID()); - assertTrue(result.isEmpty()); - } + assertTrue(result.isEmpty()); + } - @Test - void findDonationById_nullId_shouldThrowException() { - assertThrows(IllegalArgumentException.class, - () -> registry.findDonationById(null)); - } + @Test + void findDonationById_nullId_shouldThrowException() { + assertThrows(IllegalArgumentException.class, () -> registry.findDonationById(null)); + } - @Test - void removeDonation_shouldRemoveDonation() { - registry.addDonation(donation); + @Test + void removeDonation_shouldRemoveDonation() { + registry.addDonation(donation); - boolean removed = registry.removeDonation(donation.getCharityId()); + boolean removed = registry.removeDonation(donation.getCharityId()); - assertTrue(removed); - assertTrue(registry.getAllDonations().isEmpty()); - } + assertTrue(removed); + assertTrue(registry.getAllDonations().isEmpty()); + } - @Test - void removeDonation_shouldReturnFalseIfNotFound() { - boolean removed = registry.removeDonation(UUID.randomUUID()); + @Test + void removeDonation_shouldReturnFalseIfNotFound() { + boolean removed = registry.removeDonation(UUID.randomUUID()); - assertFalse(removed); - } + assertFalse(removed); + } - @Test - void removeDonation_nullId_shouldThrowException() { - assertThrows(IllegalArgumentException.class, - () -> registry.removeDonation(null)); - } -} \ No newline at end of file + @Test + void removeDonation_nullId_shouldThrowException() { + assertThrows(IllegalArgumentException.class, () -> registry.removeDonation(null)); + } +} 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 12a017e..b0c12f9 100644 --- a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/DonationTest.java +++ b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/DonationTest.java @@ -19,8 +19,7 @@ class DonationTest { // -- Setup -- @BeforeEach public void setup() { - charity = - new Charity("Charity1", "www.aaaa.com", "Cancer", false, "unverified"); + charity = new Charity("Charity1", "www.aaaa.com", "Cancer", false, "unverified"); user = new User("Name", "Valid@gmail.com", "123", Role.NORMAL_USER, new Settings(), new Inbox()); 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 250d270..2dc7fa2 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 @@ -1,95 +1,94 @@ package ntnu.systemutvikling.team6.models.user; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; import java.util.List; import java.util.Optional; import java.util.UUID; - -import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class InboxTest { - private Inbox inbox; - private Message newMessage; - private Message newMessage2; + private Inbox inbox; + private Message newMessage; + private Message newMessage2; - @BeforeEach - public void setup(){ - inbox = new Inbox(); - newMessage = new Message("Title", "Someone", "Somewhere"); - newMessage2 = new Message("Title2", "Someone2", "Somewhere2"); - } + @BeforeEach + public void setup() { + inbox = new Inbox(); + newMessage = new Message("Title", "Someone", "Somewhere"); + newMessage2 = new Message("Title2", "Someone2", "Somewhere2"); + } - @Test - void constructor_shouldCreateEmptyInbox() { - assertTrue(inbox.getMessages().isEmpty()); - } + @Test + void constructor_shouldCreateEmptyInbox() { + assertTrue(inbox.getMessages().isEmpty()); + } - @Test - void addMessage_shouldAddMessageToInbox() { - inbox.addMessage(newMessage); + @Test + void addMessage_shouldAddMessageToInbox() { + inbox.addMessage(newMessage); - List messages = inbox.getMessages(); - assertEquals(1, messages.size()); - assertTrue(messages.contains(newMessage)); - } + List messages = inbox.getMessages(); + assertEquals(1, messages.size()); + assertTrue(messages.contains(newMessage)); + } - @Test - void addMessage_nullMessage_shouldThrowException() { - assertThrows(IllegalArgumentException.class, () -> inbox.addMessage(null)); - } + @Test + void addMessage_nullMessage_shouldThrowException() { + assertThrows(IllegalArgumentException.class, () -> inbox.addMessage(null)); + } - @Test - void getMessages_shouldReturnUnmodifiableList() { - inbox.addMessage(newMessage); + @Test + void getMessages_shouldReturnUnmodifiableList() { + inbox.addMessage(newMessage); - List messages = inbox.getMessages(); + List messages = inbox.getMessages(); - assertThrows(UnsupportedOperationException.class, () -> messages.add(newMessage2)); - } + assertThrows(UnsupportedOperationException.class, () -> messages.add(newMessage2)); + } - @Test - void findMessageById_shouldReturnMessageWhenFound() { - inbox.addMessage(newMessage); + @Test + void findMessageById_shouldReturnMessageWhenFound() { + inbox.addMessage(newMessage); - Optional result = inbox.findMessageById(newMessage.getId()); + Optional result = inbox.findMessageById(newMessage.getId()); - assertTrue(result.isPresent()); - assertEquals(newMessage, result.get()); - } + assertTrue(result.isPresent()); + assertEquals(newMessage, result.get()); + } - @Test - void findMessageById_shouldReturnEmptyWhenNotFound() { - Optional result = inbox.findMessageById(UUID.randomUUID()); + @Test + void findMessageById_shouldReturnEmptyWhenNotFound() { + Optional result = inbox.findMessageById(UUID.randomUUID()); - assertTrue(result.isEmpty()); - } + assertTrue(result.isEmpty()); + } - @Test - void findMessageById_nullId_shouldThrowException() { - assertThrows(IllegalArgumentException.class, () -> inbox.findMessageById(null)); - } + @Test + void findMessageById_nullId_shouldThrowException() { + assertThrows(IllegalArgumentException.class, () -> inbox.findMessageById(null)); + } - @Test - void removeMessage_shouldRemoveExistingMessage() { - inbox.addMessage(newMessage); + @Test + void removeMessage_shouldRemoveExistingMessage() { + inbox.addMessage(newMessage); - boolean removed = inbox.removeMessage(newMessage.getId()); + boolean removed = inbox.removeMessage(newMessage.getId()); - assertTrue(removed); - assertTrue(inbox.getMessages().isEmpty()); - } + assertTrue(removed); + assertTrue(inbox.getMessages().isEmpty()); + } - @Test - void removeMessage_shouldReturnFalseIfNotFound() { - boolean removed = inbox.removeMessage(UUID.randomUUID()); + @Test + void removeMessage_shouldReturnFalseIfNotFound() { + boolean removed = inbox.removeMessage(UUID.randomUUID()); - assertFalse(removed); - } + assertFalse(removed); + } - @Test - void removeMessage_nullId_shouldThrowException() { - assertThrows(IllegalArgumentException.class, () -> inbox.removeMessage(null)); - } + @Test + void removeMessage_nullId_shouldThrowException() { + assertThrows(IllegalArgumentException.class, () -> inbox.removeMessage(null)); + } } diff --git a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/user/MessegeTest.java b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/user/MessegeTest.java index ff71841..faae3ad 100644 --- a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/user/MessegeTest.java +++ b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/models/user/MessegeTest.java @@ -1,50 +1,45 @@ package ntnu.systemutvikling.team6.models.user; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; import java.time.LocalDate; -import java.time.LocalDateTime; import java.util.UUID; - -import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; public class MessegeTest { - @Test - void shouldThrowExceptionIfNameIsNullOrEmpty() { - assertThrows( - IllegalArgumentException.class, - () -> new Message(null, "Someone", "Something Somewhere Somehow")); - assertThrows( - IllegalArgumentException.class, - () -> new Message("", "Someone", "Something Somewhere Somehow")); - } + @Test + void shouldThrowExceptionIfNameIsNullOrEmpty() { + assertThrows( + IllegalArgumentException.class, + () -> new Message(null, "Someone", "Something Somewhere Somehow")); + assertThrows( + IllegalArgumentException.class, + () -> new Message("", "Someone", "Something Somewhere Somehow")); + } + + @Test + void shouldThrowExceptionIfFromIsNullOrEmpty() { + assertThrows( + IllegalArgumentException.class, + () -> new Message("Title", null, "Something Somewhere Somehow")); + assertThrows( + IllegalArgumentException.class, + () -> new Message("Title", "", "Something Somewhere Somehow")); + } - @Test - void shouldThrowExceptionIfFromIsNullOrEmpty() { - assertThrows( - IllegalArgumentException.class, - () -> new Message("Title", null, "Something Somewhere Somehow")); - assertThrows( - IllegalArgumentException.class, - () -> new Message("Title", "", "Something Somewhere Somehow")); - } - @Test - void shouldThrowExceptionIfContentIsNullOrEmpty() { - assertThrows( - IllegalArgumentException.class, - () -> new Message("Title", "Someone", null)); - assertThrows( - IllegalArgumentException.class, - () -> new Message("Title", "Someone", "")); - } + @Test + void shouldThrowExceptionIfContentIsNullOrEmpty() { + assertThrows(IllegalArgumentException.class, () -> new Message("Title", "Someone", null)); + assertThrows(IllegalArgumentException.class, () -> new Message("Title", "Someone", "")); + } - @Test - void GettersWork(){ - Message newMessage = new Message("Title", "Someone", "Somewhere"); - assertInstanceOf(UUID.class, newMessage.getId()); - assertEquals("Title", newMessage.getTitle()); - assertEquals("Someone", newMessage.getFrom()); - assertEquals("Somewhere", newMessage.getContent()); - assertEquals(LocalDate.now(), newMessage.getTimeAndDate().toLocalDate()); - } + @Test + void GettersWork() { + Message newMessage = new Message("Title", "Someone", "Somewhere"); + assertInstanceOf(UUID.class, newMessage.getId()); + assertEquals("Title", newMessage.getTitle()); + assertEquals("Someone", newMessage.getFrom()); + assertEquals("Somewhere", newMessage.getContent()); + assertEquals(LocalDate.now(), newMessage.getTimeAndDate().toLocalDate()); + } } diff --git a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/scraper/APICharityScraperTest.java b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/scraper/APICharityScraperTest.java index bf2eacd..40c3ce4 100644 --- a/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/scraper/APICharityScraperTest.java +++ b/helpmehelpapplication/src/test/java/ntnu/systemutvikling/team6/scraper/APICharityScraperTest.java @@ -1,98 +1,105 @@ package ntnu.systemutvikling.team6.scraper; -import ntnu.systemutvikling.team6.models.Charity; -import ntnu.systemutvikling.team6.models.CharityRegistry; -import ntnu.systemutvikling.team6.scraper.APICharityData; -import ntnu.systemutvikling.team6.scraper.APICharityScraper; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + import java.io.IOException; import java.net.URISyntaxException; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; -import java.util.List; - -import static org.mockito.Mockito.*; - -import static org.junit.jupiter.api.Assertions.*; +import ntnu.systemutvikling.team6.models.Charity; +import ntnu.systemutvikling.team6.models.CharityRegistry; +import org.junit.jupiter.api.Test; class APICharityScraperTest { - @Test - void checkConnectionShouldReturnTrueOn200ResponseCode() throws IOException, URISyntaxException, InterruptedException { - HttpClient mockClient = mock(HttpClient.class); - var mockResponse = mock(HttpResponse.class); - - when(mockResponse.statusCode()).thenReturn(200); - when(mockClient.send(any(HttpRequest.class), any(HttpResponse.BodyHandler.class))).thenReturn(mockResponse); - - var con = new APICharityScraper(mockClient); - - assertTrue(con.checkConnection(), "Get response should be 200 (success)"); - } - - @Test - void checkConnectionShouldThrowRuntimeExceptionIfConnectionIsNotASuccess() throws URISyntaxException, IOException, InterruptedException { - var mockClient = mock(HttpClient.class); - HttpResponse mockResponse = mock(HttpResponse.class); - - when(mockResponse.statusCode()).thenReturn(500); - when(mockResponse.body()).thenReturn("Internal server error."); - when(mockClient.send(any(HttpRequest.class), any(HttpResponse.BodyHandler.class))).thenReturn(mockResponse); - - var con = new APICharityScraper(mockClient); - - assertThrows(RuntimeException.class, con::checkConnection, - "The connection is not successful and should throw a RuntimeException."); - } - - @Test - void getJSONDataShouldReturnCorrectJSONString() throws IOException, InterruptedException, URISyntaxException { - String response = "[{\"org_number\":\"938419264\",\"name\":\"Misjonsalliansen\",\"status\":\"approved\"," + - "\"url\":\"https:\\/\\/www.innsamlingskontrollen.no\\/organisasjoner\\/misjonsalliansen\\/\"," + - "\"is_pre_approved\":false}]"; - - var mockClient = mock(HttpClient.class); - var mockResponse = mock(HttpResponse.class); - - when(mockResponse.body()).thenReturn(response); - when(mockClient.send(any(HttpRequest.class), any(HttpResponse.BodyHandler.class))).thenReturn(mockResponse); - - var con = new APICharityScraper(mockClient); - - assertEquals(response, con.getJSONData(), "The extracted JSON data should be the same " + - "as the data from the API."); - } - - - @Test - void parsedJSONShouldHaveCorrectValues() throws URISyntaxException { - APICharityScraper con = new APICharityScraper(HttpClient.newHttpClient()); - - String JSONData = "[{\"org_number\":\"938419264\",\"name\":\"Misjonsalliansen\",\"status\":\"approved\"," + - "\"url\":\"https://www.innsamlingskontrollen.no/organisasjoner/misjonsalliansen/\",\"" + - "is_pre_approved\":false}]"; - CharityRegistry list = con.parseJSON(JSONData); - - Charity d = list.getAllCharities().get(0); - - assertEquals("938419264", d.getOrg_number(), "Org_number parameter " + - "should be correct."); - assertEquals("Misjonsalliansen", d.getName(), "Name parameter should be correct."); - assertEquals("approved", d.getStatus(), "Status parameter should be correct."); - assertEquals("Les mer her: https://www.innsamlingskontrollen.no/organisasjoner/misjonsalliansen/", d.getDescription(), - "Url parameter should be correct."); - assertFalse(d.getPreApproved(), "Is_pre_approved parameter should be correct."); - } - - @Test - void parsedJSONOfNullShouldReturnEmptyList() throws URISyntaxException { - APICharityScraper con = new APICharityScraper(HttpClient.newHttpClient()); - - CharityRegistry list = con.parseJSON(null); - - assertTrue(list.getAllCharities().isEmpty(), "List should be empty due to only parsing " + - "null objects."); - } - - } - + @Test + void checkConnectionShouldReturnTrueOn200ResponseCode() + throws IOException, URISyntaxException, InterruptedException { + HttpClient mockClient = mock(HttpClient.class); + var mockResponse = mock(HttpResponse.class); + + when(mockResponse.statusCode()).thenReturn(200); + when(mockClient.send(any(HttpRequest.class), any(HttpResponse.BodyHandler.class))) + .thenReturn(mockResponse); + + var con = new APICharityScraper(mockClient); + + assertTrue(con.checkConnection(), "Get response should be 200 (success)"); + } + + @Test + void checkConnectionShouldThrowRuntimeExceptionIfConnectionIsNotASuccess() + throws URISyntaxException, IOException, InterruptedException { + var mockClient = mock(HttpClient.class); + HttpResponse mockResponse = mock(HttpResponse.class); + + when(mockResponse.statusCode()).thenReturn(500); + when(mockResponse.body()).thenReturn("Internal server error."); + when(mockClient.send(any(HttpRequest.class), any(HttpResponse.BodyHandler.class))) + .thenReturn(mockResponse); + + var con = new APICharityScraper(mockClient); + + assertThrows( + RuntimeException.class, + con::checkConnection, + "The connection is not successful and should throw a RuntimeException."); + } + + @Test + void getJSONDataShouldReturnCorrectJSONString() + throws IOException, InterruptedException, URISyntaxException { + String response = + "[{\"org_number\":\"938419264\",\"name\":\"Misjonsalliansen\",\"status\":\"approved\"," + + "\"url\":\"https:\\/\\/www.innsamlingskontrollen.no\\/organisasjoner\\/misjonsalliansen\\/\"," + + "\"is_pre_approved\":false}]"; + + var mockClient = mock(HttpClient.class); + var mockResponse = mock(HttpResponse.class); + + when(mockResponse.body()).thenReturn(response); + when(mockClient.send(any(HttpRequest.class), any(HttpResponse.BodyHandler.class))) + .thenReturn(mockResponse); + + var con = new APICharityScraper(mockClient); + + assertEquals( + response, + con.getJSONData(), + "The extracted JSON data should be the same " + "as the data from the API."); + } + + @Test + void parsedJSONShouldHaveCorrectValues() throws URISyntaxException { + APICharityScraper con = new APICharityScraper(HttpClient.newHttpClient()); + + String JSONData = + "[{\"org_number\":\"938419264\",\"name\":\"Misjonsalliansen\",\"status\":\"approved\"," + + "\"url\":\"https://www.innsamlingskontrollen.no/organisasjoner/misjonsalliansen/\",\"" + + "is_pre_approved\":false}]"; + CharityRegistry list = con.parseJSON(JSONData); + + Charity d = list.getAllCharities().get(0); + + assertEquals("938419264", d.getOrg_number(), "Org_number parameter " + "should be correct."); + assertEquals("Misjonsalliansen", d.getName(), "Name parameter should be correct."); + assertEquals("approved", d.getStatus(), "Status parameter should be correct."); + assertEquals( + "Les mer her: https://www.innsamlingskontrollen.no/organisasjoner/misjonsalliansen/", + d.getDescription(), + "Url parameter should be correct."); + assertFalse(d.getPreApproved(), "Is_pre_approved parameter should be correct."); + } + + @Test + void parsedJSONOfNullShouldReturnEmptyList() throws URISyntaxException { + APICharityScraper con = new APICharityScraper(HttpClient.newHttpClient()); + + CharityRegistry list = con.parseJSON(null); + + assertTrue( + list.getAllCharities().isEmpty(), + "List should be empty due to only parsing " + "null objects."); + } +}