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 e6d599f..32a05ce 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 3e13f25..99633da 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 48ceb2e..2b9a812 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 5fecbbc..1a4540a 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 596f18d..34caf90 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 987c731..17bb8f3 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 05e25d1..c6e800b 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 be0b2b0..d26e9d7 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 e7aec6f..73dc1e5 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 5adc1c0..173c394 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 8052ef1..ceca589 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 5fcbe69..00b144b 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 3d7c53e..24a7c52 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 12c0094..1828c3c 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 335e944..c0dd5db 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 5d505e3..32c2b26 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 f9d3acc..c8c3824 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 2881058..9756867 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 3935270..0292d38 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 7ebffcf..00c1f13 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 8e0ef07..7e92fea 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 49a0ae7..bcc16ba 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 85e73dc..85393a8 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 ee324f7..8b7fe70 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 8fd3b1a..1e6c1cc 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 2c15d9d..f945028 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 4b7a5a3..e546e87 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 0ad6b9a..3d141d8 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 b570d8b..c362714 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 4b138de..8d8d69b 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 9a2e07c..ad2370c 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 fde91f9..2e03c72 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 0d96d14..639e086 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 1b93019..ef07c9e 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 857a207..7215aa1 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 3e26569..13f7f16 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 52f1177..2fb7fc2 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 b11e934..6ae1654 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 8a4b17f..1e0ee51 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 6d36d76..a546b27 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 fbea516..fe88616 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 79118e1..0404df1 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 4a96009..18f4c29 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 5e4af2d..597c0f7 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 ed22792..20a5385 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 3ac15c9..9da9127 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 f4ca625..6c0ee61 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 dad9c3d..693f28f 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 9b41b66..ecf5b53 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 d2a7c57..f94be0f 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()));
+ }
+ }
}