From a5ffd20cfa60dbd79853f2e518f5d8a46e0b6846 Mon Sep 17 00:00:00 2001 From: Tini Tran <tinit@stud.ntnu.no> Date: Fri, 3 May 2024 12:11:46 +0200 Subject: [PATCH 01/13] checkstyled the service class for the mockbank --- .../mockBank/service/AccountService.java | 14 ++--- .../service/BankTransactionService.java | 45 +++++++++------- .../mockBank/service/CustomerService.java | 10 ++-- .../service/MockBankAccountService.java | 34 +++++++----- .../mockBank/service/MockDataConfig.java | 4 +- .../sparesti/service/ChallengeService.java | 54 ++++++++++--------- 6 files changed, 90 insertions(+), 71 deletions(-) diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/service/AccountService.java b/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/service/AccountService.java index 192749a..19ff286 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/service/AccountService.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/service/AccountService.java @@ -3,18 +3,18 @@ package idatt2106.systemutvikling.sparesti.mockBank.service; import idatt2106.systemutvikling.sparesti.mockBank.dao.AccountDAO; import idatt2106.systemutvikling.sparesti.mockBank.dao.CustomerDAO; import idatt2106.systemutvikling.sparesti.mockBank.repository.AccountRepository; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; import idatt2106.systemutvikling.sparesti.service.AccountServiceInterface; - import java.util.List; import java.util.Optional; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; /** * Service class for the Account entity. */ @Service -public class AccountService implements AccountServiceInterface{ +public class AccountService implements AccountServiceInterface { + private final AccountRepository accountRepository; private final CustomerService customerService; @@ -31,8 +31,10 @@ public class AccountService implements AccountServiceInterface{ * @return the account entity as AccountDAO */ public AccountDAO findAccountByAccountNr(Long accountNumber) { - Optional<AccountDAO> accountDAOOptional = accountRepository.findAccountDAOByAccountNr(accountNumber); - return accountDAOOptional.orElseThrow(() -> new RuntimeException(accountNumber+" was not found")); + Optional<AccountDAO> accountDAOOptional = accountRepository.findAccountDAOByAccountNr( + accountNumber); + return accountDAOOptional.orElseThrow( + () -> new RuntimeException(accountNumber + " was not found")); } /** diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/service/BankTransactionService.java b/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/service/BankTransactionService.java index db63dac..bd946aa 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/service/BankTransactionService.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/service/BankTransactionService.java @@ -6,14 +6,13 @@ import idatt2106.systemutvikling.sparesti.mockBank.mapper.MockBankTransactionMap import idatt2106.systemutvikling.sparesti.mockBank.repository.TransactionRepository; import idatt2106.systemutvikling.sparesti.model.Transaction; import idatt2106.systemutvikling.sparesti.service.TransactionServiceInterface; -import lombok.AllArgsConstructor; -import org.springframework.stereotype.Service; - import java.time.LocalDate; import java.time.ZoneId; import java.util.Date; import java.util.List; import java.util.logging.Logger; +import lombok.AllArgsConstructor; +import org.springframework.stereotype.Service; /** * Service class for the BankTransaction entity. @@ -32,44 +31,50 @@ public class BankTransactionService implements TransactionServiceInterface { * will trick the system to think that the date is 30th of March 2024. * * @param accountNumber The account number of the specified account. - * @param dateLimit Transactions older than this date will not be fetched. - * @return List<Transaction> The list of transactions. + * @param dateLimit Transactions older than this date will not be fetched. + * @return {@link List} The list of {@link Transaction}. */ @Override public List<Transaction> getLatestExpensesForAccountNumber(Long accountNumber, Date dateLimit) { - List<AccountDAO> allAccountsForUser = accountService.findOtherAccountsOwnedBySameUser(accountNumber); + List<AccountDAO> allAccountsForUser = accountService.findOtherAccountsOwnedBySameUser( + accountNumber); List<Long> accounts = allAccountsForUser.stream().map(AccountDAO::getAccountNr).toList(); List<TransactionDAO> fetchedTransactions; if (mockProperties.isEnabled()) { // Use fixed date of 30th March 2024 and subtract 30 days LocalDate fixedDate = LocalDate.of(2024, 3, 30); - Date date30DaysAgo = Date.from(fixedDate.minusDays(30).atStartOfDay(ZoneId.systemDefault()).toInstant()); - fetchedTransactions = transactionRepository.findByAccountDAO_AccountNrAndTimeAfter(accountNumber, date30DaysAgo); + Date date30DaysAgo = Date.from( + fixedDate.minusDays(30).atStartOfDay(ZoneId.systemDefault()).toInstant()); + fetchedTransactions = transactionRepository.findByAccountDAO_AccountNrAndTimeAfter( + accountNumber, date30DaysAgo); } else { - fetchedTransactions = transactionRepository.findByAccountDAO_AccountNrAndTimeAfter(accountNumber, dateLimit); + fetchedTransactions = transactionRepository.findByAccountDAO_AccountNrAndTimeAfter( + accountNumber, dateLimit); } return fetchedTransactions.stream() - .filter((TransactionDAO t) -> t.getDebtorAccount().equals(accountNumber)) - .filter((TransactionDAO t) -> accounts.stream().noneMatch((Long acId) -> t.getCreditorAccount().equals(acId))) - .map(MockBankTransactionMapper::toModel) - .toList(); + .filter((TransactionDAO t) -> t.getDebtorAccount().equals(accountNumber)) + .filter((TransactionDAO t) -> accounts.stream() + .noneMatch((Long acId) -> t.getCreditorAccount().equals(acId))) + .map(MockBankTransactionMapper::toModel) + .toList(); } /** * Creates a transaction and saves it to the database. * - * @param debtorName The name of the debtor. - * @param creditorName The name of the creditor. + * @param debtorName The name of the debtor. + * @param creditorName The name of the creditor. * @param transactionTitle The title of the transaction. - * @param debtorAccount The account number of the debtor. - * @param creditorAccount The account number of the creditor. - * @param amount The amount of the transaction. - * @param currency The currency of the transaction. + * @param debtorAccount The account number of the debtor. + * @param creditorAccount The account number of the creditor. + * @param amount The amount of the transaction. + * @param currency The currency of the transaction. * @return TransactionDAO The saved transaction DAO. */ - public Boolean createTransaction(String debtorName, String creditorName, String transactionTitle, Long debtorAccount, Long creditorAccount, Long amount, String currency) { + public Boolean createTransaction(String debtorName, String creditorName, String transactionTitle, + Long debtorAccount, Long creditorAccount, Long amount, String currency) { try { TransactionDAO transactionDAO = new TransactionDAO(); diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/service/CustomerService.java b/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/service/CustomerService.java index 6f31e56..6016e7c 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/service/CustomerService.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/service/CustomerService.java @@ -5,13 +5,10 @@ import idatt2106.systemutvikling.sparesti.mockBank.dao.CustomerDAO; import idatt2106.systemutvikling.sparesti.mockBank.repository.AccountRepository; import idatt2106.systemutvikling.sparesti.mockBank.repository.CustomerRepository; import idatt2106.systemutvikling.sparesti.service.CustomerServiceInterface; -import lombok.AllArgsConstructor; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import javax.swing.text.html.Option; import java.util.List; import java.util.Optional; +import lombok.AllArgsConstructor; +import org.springframework.stereotype.Service; /** * Service class for the Customer entity. @@ -44,8 +41,9 @@ public class CustomerService implements CustomerServiceInterface { public boolean hasTwoAccounts(String username) { Optional<CustomerDAO> customerOpt = customerRepository.findByUsername(username); - if (customerOpt.isEmpty()) + if (customerOpt.isEmpty()) { return false; + } List<AccountDAO> accounts = accountRepository.findAccountDAOSByCustomerDAO(customerOpt.get()); diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/service/MockBankAccountService.java b/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/service/MockBankAccountService.java index 115bfb3..88d6c15 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/service/MockBankAccountService.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/service/MockBankAccountService.java @@ -7,23 +7,24 @@ import idatt2106.systemutvikling.sparesti.mockBank.repository.AccountRepository; import idatt2106.systemutvikling.sparesti.model.BankAccount; import idatt2106.systemutvikling.sparesti.model.PSUConsent; import idatt2106.systemutvikling.sparesti.service.BankAccountServiceInterface; +import java.util.List; +import java.util.Optional; import lombok.NonNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import java.util.List; -import java.util.Optional; - /** * Service class for the BankAccount entity. */ @Service public class MockBankAccountService implements BankAccountServiceInterface { + private final AccountRepository accountRepository; private final CustomerService customerService; @Autowired - public MockBankAccountService(AccountRepository accountRepository, CustomerService customerService) { + public MockBankAccountService(AccountRepository accountRepository, + CustomerService customerService) { this.accountRepository = accountRepository; this.customerService = customerService; } @@ -35,8 +36,10 @@ public class MockBankAccountService implements BankAccountServiceInterface { * @return the account entity as AccountDAO */ public AccountDAO findAccountByAccountNr(Long accountNumber) { - Optional<AccountDAO> accountDAOOptional = accountRepository.findAccountDAOByAccountNr(accountNumber); - return accountDAOOptional.orElseThrow(() -> new RuntimeException(accountNumber+" was not found")); + Optional<AccountDAO> accountDAOOptional = accountRepository.findAccountDAOByAccountNr( + accountNumber); + return accountDAOOptional.orElseThrow( + () -> new RuntimeException(accountNumber + " was not found")); } /** @@ -57,13 +60,17 @@ public class MockBankAccountService implements BankAccountServiceInterface { * @return a list of account numbers */ public List<AccountDAO> findOtherAccountsOwnedBySameUser(@NonNull Long accountNumber) { - AccountDAO originalAccount = accountRepository.findAccountDAOByAccountNr(accountNumber).orElse(null); - if (originalAccount == null) + AccountDAO originalAccount = accountRepository.findAccountDAOByAccountNr(accountNumber) + .orElse(null); + if (originalAccount == null) { return null; + } - CustomerDAO c = customerService.findCustomerByUsername(originalAccount.getCustomerDAO().getUsername()); - if (c == null) + CustomerDAO c = customerService.findCustomerByUsername( + originalAccount.getCustomerDAO().getUsername()); + if (c == null) { return null; + } return accountRepository.findAccountDAOSByCustomerDAO(c); } @@ -78,11 +85,12 @@ public class MockBankAccountService implements BankAccountServiceInterface { String username = consent.getPsuId(); List<AccountDAO> daos = accountRepository.findByCustomerDAO_Username(username); - if (daos == null || daos.isEmpty()) + if (daos == null || daos.isEmpty()) { return null; + } return daos.stream() - .map(MockBankAccountMapper::toModel) - .toList(); + .map(MockBankAccountMapper::toModel) + .toList(); } } diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/service/MockDataConfig.java b/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/service/MockDataConfig.java index 01455cf..0c49bb0 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/service/MockDataConfig.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/service/MockDataConfig.java @@ -5,8 +5,8 @@ import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; /** - * Configuration class for the mock data. This class is used to configure the mock data and - * is determined by the application.properties file. + * Configuration class for the mock data. This class is used to configure the mock data and is + * determined by the application.properties file. */ @Component @ConfigurationProperties(prefix = "mock.data") diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/service/ChallengeService.java b/src/main/java/idatt2106/systemutvikling/sparesti/service/ChallengeService.java index ed540bd..26ccbc3 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/service/ChallengeService.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/service/ChallengeService.java @@ -9,18 +9,19 @@ import idatt2106.systemutvikling.sparesti.exceptions.NotFoundInDatabaseException import idatt2106.systemutvikling.sparesti.mapper.ChallengeMapper; import idatt2106.systemutvikling.sparesti.repository.ChallengeLogRepository; import idatt2106.systemutvikling.sparesti.repository.ChallengeRepository; - -import java.util.logging.Logger; - import idatt2106.systemutvikling.sparesti.repository.MilestoneRepository; import jakarta.transaction.Transactional; -import lombok.AllArgsConstructor; -import org.springframework.data.domain.*; -import org.springframework.stereotype.Service; - import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; +import java.util.logging.Logger; +import lombok.AllArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.stereotype.Service; /** * Service class for handling challenges. @@ -222,18 +223,22 @@ public class ChallengeService { final String username = CurrentUserService.getCurrentUsername(); // Fetch data - ChallengeDAO challenge = challengeRepository.findByChallengeIdAndUserDAO_Username(challengeId, username); - MilestoneDAO milestone = dbMilestone.findMilestoneDAOByMilestoneIdAndUserDAO_Username(milestoneId, username); + ChallengeDAO challenge = challengeRepository.findByChallengeIdAndUserDAO_Username(challengeId, + username); + MilestoneDAO milestone = dbMilestone.findMilestoneDAOByMilestoneIdAndUserDAO_Username( + milestoneId, username); // Verify existence of the requested challenge - if (challenge == null) - throw new NotFoundInDatabaseException("No challenge found with the requested ID for the user"); + if (challenge == null) { + throw new NotFoundInDatabaseException( + "No challenge found with the requested ID for the user"); + } // Verify existence of the requested milestone - if (milestone == null) - throw new NotFoundInDatabaseException("No milestone found with the requested ID for the user"); - - + if (milestone == null) { + throw new NotFoundInDatabaseException( + "No milestone found with the requested ID for the user"); + } // Define transfer amount as the difference between the goal and the current sum long transferAmount = challenge.getGoalSum() - challenge.getCurrentSum(); @@ -242,23 +247,23 @@ public class ChallengeService { boolean success = transactionService.createSavingsTransferForCurrentUser(transferAmount); // Verify transaction success - if (!success) + if (!success) { throw new BankConnectionErrorException("Failed to transfer funds to savings"); - + } // Transfer achieved currency to milestone - MilestoneDAO savedEntry = milestoneService.increaseMilestonesCurrentSum(milestoneId, challenge.getGoalSum()); - + MilestoneDAO savedEntry = milestoneService.increaseMilestonesCurrentSum(milestoneId, + challenge.getGoalSum()); // Archive challenge archiveActiveChallenge(challenge.getChallengeId()); } /** - * Performs the changes - local to the challenge repository - needed for a challenge to be considered as 'completed'. - * This function creates a log entry from the selected challenge (specified by the id-parameter) - * and stores it in the database. The challenge is deleted from the table of active challenges, - * but the log entry persists. + * Performs the changes - local to the challenge repository - needed for a challenge to be + * considered as 'completed'. This function creates a log entry from the selected challenge + * (specified by the id-parameter) and stores it in the database. The challenge is deleted from + * the table of active challenges, but the log entry persists. * * @param challengeId the id of the challenge to complete * @return The log entry that is persisted by this function. @@ -268,8 +273,9 @@ public class ChallengeService { ChallengeDAO challengeDAO = challengeRepository.findChallengeDAOByChallengeId(challengeId); // Verify existence of the active challenge - if (challengeDAO == null) + if (challengeDAO == null) { return null; + } // Create log entry from the active challenge ChallengeLogDAO challengeLogDAO = createChallengeLog(challengeDAO); -- GitLab From e7615e685b9bb7c50a44003486a7af602f9aacea Mon Sep 17 00:00:00 2001 From: Tini Tran <tinit@stud.ntnu.no> Date: Fri, 3 May 2024 12:19:43 +0200 Subject: [PATCH 02/13] checkstyled the repository interfaces --- .../repository/AchievementRepository.java | 19 ++++++------ .../repository/ChallengeLogRepository.java | 6 ++-- .../repository/ChallengeRepository.java | 13 +++----- .../repository/ConditionRepository.java | 3 +- .../repository/ManualSavingRepository.java | 31 +++++++++---------- .../repository/MilestoneLogRepository.java | 9 +++--- .../repository/MilestoneRepository.java | 13 ++++---- .../sparesti/repository/UserRepository.java | 1 + 8 files changed, 44 insertions(+), 51 deletions(-) diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/repository/AchievementRepository.java b/src/main/java/idatt2106/systemutvikling/sparesti/repository/AchievementRepository.java index a0b3ae0..83d436a 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/repository/AchievementRepository.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/repository/AchievementRepository.java @@ -1,18 +1,17 @@ package idatt2106.systemutvikling.sparesti.repository; import idatt2106.systemutvikling.sparesti.dao.AchievementDAO; +import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; -import java.util.List; - /** * Repository for the AchievementDAO entity. */ @Repository -public interface AchievementRepository extends JpaRepository<AchievementDAO, String>{ +public interface AchievementRepository extends JpaRepository<AchievementDAO, String> { /** * Method to find achievement by id @@ -20,7 +19,7 @@ public interface AchievementRepository extends JpaRepository<AchievementDAO, Str * @param id the id of a certain achievement * @return the achievement */ - AchievementDAO findAchievementDAOByAchievementId (long id); + AchievementDAO findAchievementDAOByAchievementId(long id); /** * Method to find all achievements tied to a user @@ -29,10 +28,10 @@ public interface AchievementRepository extends JpaRepository<AchievementDAO, Str * @return a list of achievements that belong to the user with the given username */ @Query(value = "SELECT a.* " + - "FROM achievementdao a " + - "JOIN user_achievements ua ON a.achievement_id = ua.achievement_id " + - "JOIN userdao u ON ua.username = u.username " + - "WHERE u.username = :username", nativeQuery = true) + "FROM achievementdao a " + + "JOIN user_achievements ua ON a.achievement_id = ua.achievement_id " + + "JOIN userdao u ON ua.username = u.username " + + "WHERE u.username = :username", nativeQuery = true) List<AchievementDAO> findAchievementDAOByUsername(@Param("username") String username); /** @@ -41,7 +40,7 @@ public interface AchievementRepository extends JpaRepository<AchievementDAO, Str * @param title the title of the achievement * @return the achievement */ - AchievementDAO findAchievementDAOByAchievementTitle (String title); + AchievementDAO findAchievementDAOByAchievementTitle(String title); /** * Method to find achievement based off of title @@ -49,5 +48,5 @@ public interface AchievementRepository extends JpaRepository<AchievementDAO, Str * @param description the description of the achievement * @return the achievement */ - AchievementDAO findAchievementDAOByAchievementDescription (String description); + AchievementDAO findAchievementDAOByAchievementDescription(String description); } diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/repository/ChallengeLogRepository.java b/src/main/java/idatt2106/systemutvikling/sparesti/repository/ChallengeLogRepository.java index e789629..36a17d8 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/repository/ChallengeLogRepository.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/repository/ChallengeLogRepository.java @@ -1,11 +1,10 @@ package idatt2106.systemutvikling.sparesti.repository; import idatt2106.systemutvikling.sparesti.dao.ChallengeLogDAO; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - import java.time.LocalDateTime; import java.util.List; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; /** * Repository for the ChallengeLogDAO entity. @@ -77,6 +76,5 @@ public interface ChallengeLogRepository extends JpaRepository<ChallengeLogDAO, L List<ChallengeLogDAO> findChallengeLogDAOByUserDAO_Username(String username); - void deleteAllByUserDAO_Username(String username); } diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/repository/ChallengeRepository.java b/src/main/java/idatt2106/systemutvikling/sparesti/repository/ChallengeRepository.java index 4246123..120b2a0 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/repository/ChallengeRepository.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/repository/ChallengeRepository.java @@ -1,16 +1,14 @@ package idatt2106.systemutvikling.sparesti.repository; +import idatt2106.systemutvikling.sparesti.dao.ChallengeDAO; import idatt2106.systemutvikling.sparesti.enums.RecurringInterval; +import java.time.LocalDateTime; +import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; -import idatt2106.systemutvikling.sparesti.dao.ChallengeDAO; - -import java.time.LocalDateTime; -import java.util.List; - /** * Repository for the ChallengeDAO entity. */ @@ -44,7 +42,8 @@ public interface ChallengeRepository extends JpaRepository<ChallengeDAO, Long> { List<ChallengeDAO> findChallengeDAOSByUserDAO_Username(String username); - Page<ChallengeDAO> findChallengeDAOSByUserDAO_UsernameAndActive(String username, boolean active, Pageable pageable); + Page<ChallengeDAO> findChallengeDAOSByUserDAO_UsernameAndActive(String username, boolean active, + Pageable pageable); /** * Method to find all challenges that have a start date after the given start date and an @@ -116,10 +115,8 @@ public interface ChallengeRepository extends JpaRepository<ChallengeDAO, Long> { List<ChallengeDAO> findChallengeDAOByActiveAndUserDAO_Username(boolean active, String username); - void deleteAllByUserDAO_Username(String username); - ChallengeDAO findByChallengeIdAndUserDAO_Username(Long id, String username); } diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/repository/ConditionRepository.java b/src/main/java/idatt2106/systemutvikling/sparesti/repository/ConditionRepository.java index ee606a5..c721556 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/repository/ConditionRepository.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/repository/ConditionRepository.java @@ -1,11 +1,10 @@ package idatt2106.systemutvikling.sparesti.repository; import idatt2106.systemutvikling.sparesti.dao.ConditionDAO; +import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; -import java.util.List; - /** * Repository for the ConditionDAO entity. */ diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/repository/ManualSavingRepository.java b/src/main/java/idatt2106/systemutvikling/sparesti/repository/ManualSavingRepository.java index da2dcc5..e2ce1f2 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/repository/ManualSavingRepository.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/repository/ManualSavingRepository.java @@ -1,29 +1,28 @@ package idatt2106.systemutvikling.sparesti.repository; import idatt2106.systemutvikling.sparesti.dao.ManualSavingDAO; -import org.springframework.data.jpa.repository.JpaRepository; - import java.util.Date; import java.util.List; +import org.springframework.data.jpa.repository.JpaRepository; /** * Repository for the ManualSavingDAO entity. */ public interface ManualSavingRepository extends JpaRepository<ManualSavingDAO, Long> { - /** - * Method to find a manual saving by its id and username of the user - * - * @param username the username of the user - * @param threshold the threshold date - * @return a list of manual savings that belong to the user with the given username - */ - List<ManualSavingDAO> findByUser_UsernameAndTimeOfTransferAfter(String username, Date threshold); + /** + * Method to find a manual saving by its id and username of the user + * + * @param username the username of the user + * @param threshold the threshold date + * @return a list of manual savings that belong to the user with the given username + */ + List<ManualSavingDAO> findByUser_UsernameAndTimeOfTransferAfter(String username, Date threshold); - /** - * Method to delete all manual savings to a user. - * - * @param username the username of the user - */ - void deleteAllByUser_Username(String username); + /** + * Method to delete all manual savings to a user. + * + * @param username the username of the user + */ + void deleteAllByUser_Username(String username); } diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/repository/MilestoneLogRepository.java b/src/main/java/idatt2106/systemutvikling/sparesti/repository/MilestoneLogRepository.java index fbe5d96..4d7a226 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/repository/MilestoneLogRepository.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/repository/MilestoneLogRepository.java @@ -1,14 +1,13 @@ package idatt2106.systemutvikling.sparesti.repository; import idatt2106.systemutvikling.sparesti.dao.MilestoneLogDAO; +import java.time.LocalDateTime; +import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; -import java.time.LocalDateTime; -import java.util.List; - /** * Repository for the MilestoneLogDAO entity. */ @@ -41,13 +40,15 @@ public interface MilestoneLogRepository extends JpaRepository<MilestoneLogDAO, L Page<MilestoneLogDAO> findMilestoneLogDAOByUserDAO_Username(String username, Pageable pageable); List<MilestoneLogDAO> findMilestoneLogDAOByUserDAO_Username(String username); + /** * Method to find all milestone logs that have a completion date after the given completion date * * @param completionDate the completion date * @return a list of milestone logs that have a completion date after the given date */ - Page<MilestoneLogDAO> findMilestoneLogDAOSByCompletionDate(LocalDateTime completionDate, Pageable pageable); + Page<MilestoneLogDAO> findMilestoneLogDAOSByCompletionDate(LocalDateTime completionDate, + Pageable pageable); /** * Method to find all milestone logs that have a completion date before the given completion date diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/repository/MilestoneRepository.java b/src/main/java/idatt2106/systemutvikling/sparesti/repository/MilestoneRepository.java index b1af266..88eea95 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/repository/MilestoneRepository.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/repository/MilestoneRepository.java @@ -1,16 +1,13 @@ package idatt2106.systemutvikling.sparesti.repository; -import idatt2106.systemutvikling.sparesti.dao.ChallengeLogDAO; import idatt2106.systemutvikling.sparesti.dao.MilestoneDAO; -import idatt2106.systemutvikling.sparesti.dao.UserDAO; +import java.time.LocalDateTime; +import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; -import java.time.LocalDateTime; -import java.util.List; - /** * Repository for the MilestoneDAO entity. */ @@ -46,13 +43,15 @@ public interface MilestoneRepository extends JpaRepository<MilestoneDAO, Long> { /** - * Method to find all milestones that have a start date after the given start date and a deadline date before the given deadline date + * Method to find all milestones that have a start date after the given start date and a deadline + * date before the given deadline date * * @param startDate the start date * @param deadlineDate the deadline date * @return a list of milestones that have a start date after the given date */ - List<MilestoneDAO> findMilestoneDAOSByStartDateAfterAndDeadlineDateBefore(LocalDateTime startDate, LocalDateTime deadlineDate); + List<MilestoneDAO> findMilestoneDAOSByStartDateAfterAndDeadlineDateBefore(LocalDateTime startDate, + LocalDateTime deadlineDate); /** * Method to find all milestones that have a start date after the given start date diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/repository/UserRepository.java b/src/main/java/idatt2106/systemutvikling/sparesti/repository/UserRepository.java index 28af700..9f5dc66 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/repository/UserRepository.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/repository/UserRepository.java @@ -28,6 +28,7 @@ public interface UserRepository extends JpaRepository<UserDAO, String> { /** * Deletes the user identified by the specified username. + * * @param username The username identifying the user to be deleted. */ void deleteByUsername(String username); -- GitLab From 61d593a11e79d4ee8d3e14552cb0be2bd0d4c029 Mon Sep 17 00:00:00 2001 From: Tini Tran <tinit@stud.ntnu.no> Date: Fri, 3 May 2024 12:20:58 +0200 Subject: [PATCH 03/13] checkstyled the mockbank models --- .../systemutvikling/sparesti/model/BankAccount.java | 12 ++++++------ .../systemutvikling/sparesti/model/PSUConsent.java | 12 ++++++------ .../systemutvikling/sparesti/model/Transaction.java | 5 ++++- 3 files changed, 16 insertions(+), 13 deletions(-) diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/model/BankAccount.java b/src/main/java/idatt2106/systemutvikling/sparesti/model/BankAccount.java index 57486e7..9d54c11 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/model/BankAccount.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/model/BankAccount.java @@ -14,15 +14,15 @@ import lombok.Setter; @NoArgsConstructor public class BankAccount { - private Long accountNr; + private Long accountNr; - private String username; + private String username; - private Long balance; + private Long balance; - private String name; + private String name; - private String type; + private String type; - private String currency; + private String currency; } diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/model/PSUConsent.java b/src/main/java/idatt2106/systemutvikling/sparesti/model/PSUConsent.java index 771a491..0a5d805 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/model/PSUConsent.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/model/PSUConsent.java @@ -14,11 +14,11 @@ import lombok.Setter; @NoArgsConstructor public class PSUConsent { - String consentId; - String psuId; - String validUntil; + String consentId; + String psuId; + String validUntil; - boolean accessAccounts; - boolean accessBalances; - boolean accessTransactions; + boolean accessAccounts; + boolean accessBalances; + boolean accessTransactions; } diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/model/Transaction.java b/src/main/java/idatt2106/systemutvikling/sparesti/model/Transaction.java index c25ca65..7d88cca 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/model/Transaction.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/model/Transaction.java @@ -16,6 +16,7 @@ import lombok.ToString; @ToString @AllArgsConstructor public class Transaction { + private Long transactionId; private Long accountNr; private String transactionTitle; @@ -29,7 +30,9 @@ public class Transaction { private String currency; private TransactionCategory category; - public Transaction(Long transactionId, Long accountNr, String transactionTitle, Date time, Long debtorAccount, String debtorName, Long creditorAccount, String creditorName, Long amount, String currency) { + public Transaction(Long transactionId, Long accountNr, String transactionTitle, Date time, + Long debtorAccount, String debtorName, Long creditorAccount, String creditorName, Long amount, + String currency) { this.transactionId = transactionId; this.accountNr = accountNr; this.transactionTitle = transactionTitle; -- GitLab From 67a710aeda2d0048f9de4e1206327f6aa8f673da Mon Sep 17 00:00:00 2001 From: Tini Tran <tinit@stud.ntnu.no> Date: Fri, 3 May 2024 12:21:19 +0200 Subject: [PATCH 04/13] checkstyled the security configs --- .../security/JWTAuthorizationFilter.java | 34 +++++++++---------- .../sparesti/security/SecretsConfig.java | 24 ++++++------- .../sparesti/security/SecurityConfig.java | 5 ++- 3 files changed, 31 insertions(+), 32 deletions(-) diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/security/JWTAuthorizationFilter.java b/src/main/java/idatt2106/systemutvikling/sparesti/security/JWTAuthorizationFilter.java index 7583cb0..6eea04b 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/security/JWTAuthorizationFilter.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/security/JWTAuthorizationFilter.java @@ -10,6 +10,10 @@ import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; import lombok.AllArgsConstructor; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -19,16 +23,12 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.filter.OncePerRequestFilter; -import java.io.IOException; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - /** * Class for filtering the request and setting the user context. */ @AllArgsConstructor public class JWTAuthorizationFilter extends OncePerRequestFilter { + private static final Logger LOGGER = LogManager.getLogger(JWTAuthorizationFilter.class); public static final String USER = "USER"; @@ -43,17 +43,17 @@ public class JWTAuthorizationFilter extends OncePerRequestFilter { * passed to the next filter in the chain. If the token is valid, the user context is set and the * request is passed to the next filter in the chain. * - * @param request the http servlet request - * @param response the http servlet response + * @param request the http servlet request + * @param response the http servlet response * @param filterChain the filter chain * @throws ServletException if an error occurs - * @throws IOException if an error occurs + * @throws IOException if an error occurs */ @Override protected void doFilterInternal( - HttpServletRequest request, - HttpServletResponse response, - FilterChain filterChain) throws ServletException, IOException { + HttpServletRequest request, + HttpServletResponse response, + FilterChain filterChain) throws ServletException, IOException { final String header = request.getHeader(HttpHeaders.AUTHORIZATION); if (header == null || !header.startsWith("Bearer ")) { @@ -75,20 +75,20 @@ public class JWTAuthorizationFilter extends OncePerRequestFilter { final String username = jwt.getSubject(); final String role = jwt.getClaim("role").asString(); - logger.info("Setting user context for user: {}"+ username); + logger.info("Setting user context for user: {}" + username); UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken( - username, - null, - Collections.singletonList(new SimpleGrantedAuthority(role))); + username, + null, + Collections.singletonList(new SimpleGrantedAuthority(role))); - logger.info("Setting user context for user: {}"+ username); + logger.info("Setting user context for user: {}" + username); Map<String, Object> userDetails = new HashMap<>(); userDetails.put(CurrentUserService.KEY_USERNAME, username); auth.setDetails(userDetails); - logger.info("Setting user context for user: {}"+ username); + logger.info("Setting user context for user: {}" + username); SecurityContextHolder.getContext().setAuthentication(auth); diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/security/SecretsConfig.java b/src/main/java/idatt2106/systemutvikling/sparesti/security/SecretsConfig.java index 29df214..6b68cdd 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/security/SecretsConfig.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/security/SecretsConfig.java @@ -14,18 +14,18 @@ import org.springframework.stereotype.Component; @Component public class SecretsConfig { - /** - * The secret that is used to sign the JWT token. - */ - private String jwt = "DefaultJWTSecret"; + /** + * The secret that is used to sign the JWT token. + */ + private String jwt = "DefaultJWTSecret"; - /** - * The secret that is used to salt the password before hashing it. - */ - private String salt = "DefaultSALT"; + /** + * The secret that is used to salt the password before hashing it. + */ + private String salt = "DefaultSALT"; - /** - * The algorithm that is used to hash the password. - */ - private String messageDigestAlgorithm = "SHA-256"; + /** + * The algorithm that is used to hash the password. + */ + private String messageDigestAlgorithm = "SHA-256"; } \ No newline at end of file diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/security/SecurityConfig.java b/src/main/java/idatt2106/systemutvikling/sparesti/security/SecurityConfig.java index 817341d..bde67e0 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/security/SecurityConfig.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/security/SecurityConfig.java @@ -1,5 +1,7 @@ package idatt2106.systemutvikling.sparesti.security; +import java.util.Arrays; +import java.util.List; import lombok.AllArgsConstructor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -11,9 +13,6 @@ import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.web.cors.CorsConfiguration; -import java.util.Arrays; -import java.util.List; - /** * Class for configuring the security of the application. */ -- GitLab From a6c877a8308dcda00eb39440e047b22b56e57213 Mon Sep 17 00:00:00 2001 From: Tini Tran <tinit@stud.ntnu.no> Date: Fri, 3 May 2024 12:23:54 +0200 Subject: [PATCH 05/13] checkstyled the service classes --- .../service/AccountServiceInterface.java | 8 +- .../sparesti/service/AchievementService.java | 13 +-- .../sparesti/service/BankAccountService.java | 27 +++--- .../service/BankAccountServiceInterface.java | 17 ++-- .../sparesti/service/ChallengeLogService.java | 33 ++++--- .../sparesti/service/ConditionService.java | 31 ++++--- .../sparesti/service/CurrentUserService.java | 89 ++++++++++--------- .../service/CustomerServiceInterface.java | 48 +++++----- .../sparesti/service/JWTService.java | 40 +++++---- .../sparesti/service/ManualSavingService.java | 24 ++--- .../sparesti/service/MilestoneLogService.java | 36 ++++---- .../sparesti/service/MilestoneService.java | 25 +++--- .../sparesti/service/OpenAIService.java | 4 +- .../sparesti/service/PasswordService.java | 5 +- .../TransactionCategoryCacheService.java | 5 +- .../sparesti/service/TransactionService.java | 5 +- .../service/TransactionServiceInterface.java | 58 ++++++------ .../sparesti/service/UserService.java | 33 ++++--- .../ChallengeGeneratorImpl.java | 2 +- 19 files changed, 269 insertions(+), 234 deletions(-) diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/service/AccountServiceInterface.java b/src/main/java/idatt2106/systemutvikling/sparesti/service/AccountServiceInterface.java index 28801b9..cb440bc 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/service/AccountServiceInterface.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/service/AccountServiceInterface.java @@ -1,8 +1,6 @@ package idatt2106.systemutvikling.sparesti.service; import idatt2106.systemutvikling.sparesti.mockBank.dao.AccountDAO; -import idatt2106.systemutvikling.sparesti.mockBank.dao.CustomerDAO; - import java.util.List; /** @@ -11,7 +9,8 @@ import java.util.List; public interface AccountServiceInterface { /** - * Method to find an account by the account number. The method finds the account based on the account number + * Method to find an account by the account number. The method finds the account based on the + * account number * * @param accountNr the account number of the account * @return the account with the account number @@ -28,7 +27,8 @@ public interface AccountServiceInterface { List<AccountDAO> findAccountsByUsername(String username); /** - * Method to find an account by the account number. The method finds the account based on the account number + * Method to find an account by the account number. The method finds the account based on the + * account number * * @param username the username of the account * @return the account with the account number diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/service/AchievementService.java b/src/main/java/idatt2106/systemutvikling/sparesti/service/AchievementService.java index 29114a8..0c3404c 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/service/AchievementService.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/service/AchievementService.java @@ -9,12 +9,10 @@ import idatt2106.systemutvikling.sparesti.mapper.AchievementMapper; import idatt2106.systemutvikling.sparesti.repository.AchievementRepository; import idatt2106.systemutvikling.sparesti.repository.ConditionRepository; import idatt2106.systemutvikling.sparesti.repository.UserRepository; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Service; - import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; +import org.springframework.stereotype.Service; /** * Service class for managing achievements. @@ -96,9 +94,12 @@ public class AchievementService { boolean achievementUnlocked; for (AchievementDAO achievement : lockedAchievement) { conditions = conditionRepository.findAllByAchievementDAO_AchievementId( - achievement.getAchievementId()); - if (!conditions.isEmpty()) achievementUnlocked = true; - else break; + achievement.getAchievementId()); + if (!conditions.isEmpty()) { + achievementUnlocked = true; + } else { + break; + } for (ConditionDAO condition : conditions) { if (!conditionService.isConditionMet(condition)) { achievementUnlocked = false; diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/service/BankAccountService.java b/src/main/java/idatt2106/systemutvikling/sparesti/service/BankAccountService.java index 343fbc5..18c0450 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/service/BankAccountService.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/service/BankAccountService.java @@ -2,11 +2,10 @@ package idatt2106.systemutvikling.sparesti.service; import idatt2106.systemutvikling.sparesti.model.BankAccount; import idatt2106.systemutvikling.sparesti.model.PSUConsent; +import java.util.List; import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; -import java.util.List; - /** * Service class for handling BankAccountServiceInterface. */ @@ -14,19 +13,19 @@ import java.util.List; @AllArgsConstructor public class BankAccountService { - private BankAccountServiceInterface accountSocket; + private BankAccountServiceInterface accountSocket; - /** - * Method to get all accounts of a user. The method gets all accounts of a user based on - * the consent of the PSU and returns a list of accounts. - * - * @return the account with the account number - */ - public List<BankAccount> getAllAccountsForCurrentUser() { + /** + * Method to get all accounts of a user. The method gets all accounts of a user based on the + * consent of the PSU and returns a list of accounts. + * + * @return the account with the account number + */ + public List<BankAccount> getAllAccountsForCurrentUser() { - PSUConsent consent = new PSUConsent(); - consent.setPsuId(CurrentUserService.getCurrentUsername()); + PSUConsent consent = new PSUConsent(); + consent.setPsuId(CurrentUserService.getCurrentUsername()); - return accountSocket.getAllAccountsOfUser(consent); - } + return accountSocket.getAllAccountsOfUser(consent); + } } diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/service/BankAccountServiceInterface.java b/src/main/java/idatt2106/systemutvikling/sparesti/service/BankAccountServiceInterface.java index 1a24958..0a47dfb 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/service/BankAccountServiceInterface.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/service/BankAccountServiceInterface.java @@ -2,7 +2,6 @@ package idatt2106.systemutvikling.sparesti.service; import idatt2106.systemutvikling.sparesti.model.BankAccount; import idatt2106.systemutvikling.sparesti.model.PSUConsent; - import java.util.List; /** @@ -10,12 +9,12 @@ import java.util.List; */ public interface BankAccountServiceInterface { - /** - * Method to get all accounts of a user. The method gets all accounts of a user based on - * the consent of the PSU and returns a list of accounts. - * - * @param consent the consent of the PSU - * @return the account with the account number - */ - List<BankAccount> getAllAccountsOfUser(PSUConsent consent); + /** + * Method to get all accounts of a user. The method gets all accounts of a user based on the + * consent of the PSU and returns a list of accounts. + * + * @param consent the consent of the PSU + * @return the account with the account number + */ + List<BankAccount> getAllAccountsOfUser(PSUConsent consent); } diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/service/ChallengeLogService.java b/src/main/java/idatt2106/systemutvikling/sparesti/service/ChallengeLogService.java index e7d6a36..f902533 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/service/ChallengeLogService.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/service/ChallengeLogService.java @@ -23,8 +23,9 @@ public class ChallengeLogService { private final Logger logger = Logger.getLogger(ChallengeLogService.class.getName()); /** - * Method to get the challenge completion rate for a user based on the challenge logs. - * The completion rate is calculated by summing the achieved sum of all challenges and dividing it by the goal sum. + * Method to get the challenge completion rate for a user based on the challenge logs. The + * completion rate is calculated by summing the achieved sum of all challenges and dividing it by + * the goal sum. * * @param username the username of the user * @return A double between 0 and 1 representing the challenge completion rate @@ -54,8 +55,9 @@ public class ChallengeLogService { } /** - * Method to get the challenge acceptance rate for a user based on the challenge logs. - * The acceptance rate is calculated by summing the amount of accepted challenges and dividing it by the total amount of challenges. + * Method to get the challenge acceptance rate for a user based on the challenge logs. The + * acceptance rate is calculated by summing the amount of accepted challenges and dividing it by + * the total amount of challenges. * * @param username the username of the user * @return A double between 0 and 1 representing the challenge acceptance rate @@ -85,10 +87,11 @@ public class ChallengeLogService { } /** - * Method to get the challenge logs for a user based on the completion date and username. - * The method returns a list of challenge logs that have a completion date after the given start date. + * Method to get the challenge logs for a user based on the completion date and username. The + * method returns a list of challenge logs that have a completion date after the given start + * date. * - * @param username username of the user + * @param username username of the user * @param startDate start date of the challenge * @return list of challenge logs */ @@ -110,8 +113,9 @@ public class ChallengeLogService { } /** - * Method to get a map of challenges by category ratio for a user. The ratio is calculated by dividing the amount of challenges - * in a category by the total amount of challenges. The method returns a map with the category as the key and the ratio as the value. + * Method to get a map of challenges by category ratio for a user. The ratio is calculated by + * dividing the amount of challenges in a category by the total amount of challenges. The method + * returns a map with the category as the key and the ratio as the value. * * @param username username of the user * @return map of challenges by category ratio @@ -147,8 +151,10 @@ public class ChallengeLogService { } /** - * Method to get a map of challenges by category accepted ratio for a user. The ratio is calculated by dividing the amount of accepted challenges - * in a category by the total amount of challenges in that category. The method returns a map with the category as the key and the ratio as the value. + * Method to get a map of challenges by category accepted ratio for a user. The ratio is + * calculated by dividing the amount of accepted challenges in a category by the total amount of + * challenges in that category. The method returns a map with the category as the key and the + * ratio as the value. * * @param username username of the user * @return map of challenges by category accepted ratio @@ -189,8 +195,9 @@ public class ChallengeLogService { } /** - * Method to get a map of challenges by theme ratio for a user. The ratio is calculated by dividing the amount of challenges - * in a theme by the total amount of challenges. The method returns a map with the theme as the key and the ratio as the value. + * Method to get a map of challenges by theme ratio for a user. The ratio is calculated by + * dividing the amount of challenges in a theme by the total amount of challenges. The method + * returns a map with the theme as the key and the ratio as the value. * * @param username username of the user * @return map of challenges by theme ratio diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/service/ConditionService.java b/src/main/java/idatt2106/systemutvikling/sparesti/service/ConditionService.java index bc62f9e..ed78bae 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/service/ConditionService.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/service/ConditionService.java @@ -8,30 +8,32 @@ import idatt2106.systemutvikling.sparesti.enums.ConditionType; import idatt2106.systemutvikling.sparesti.repository.ChallengeLogRepository; import idatt2106.systemutvikling.sparesti.repository.MilestoneLogRepository; import idatt2106.systemutvikling.sparesti.repository.MilestoneRepository; -import org.springframework.stereotype.Service; - import java.util.List; import java.util.logging.Logger; +import org.springframework.stereotype.Service; /** * Service class for handling conditions. */ @Service public class ConditionService { + private final MilestoneLogRepository milestoneLogRepository; private final MilestoneRepository milestoneRepository; private final ChallengeLogRepository challengeLogRepository; private final Logger logger = Logger.getLogger(ConditionService.class.getName()); - public ConditionService(MilestoneLogRepository milestoneLogRepository, MilestoneRepository milestoneRepository, ChallengeLogRepository challengeLogRepository) { + public ConditionService(MilestoneLogRepository milestoneLogRepository, + MilestoneRepository milestoneRepository, ChallengeLogRepository challengeLogRepository) { this.milestoneLogRepository = milestoneLogRepository; this.milestoneRepository = milestoneRepository; this.challengeLogRepository = challengeLogRepository; } /** - * Method to check if a condition is met. The method checks the condition type and calls the appropriate method. + * Method to check if a condition is met. The method checks the condition type and calls the + * appropriate method. * * @param condition the condition to check * @return true if the condition is met, false otherwise @@ -54,23 +56,27 @@ public class ConditionService { } /** - * Method to check if the milestones condition is met. The method checks if the user has completed the required amount of milestones. + * Method to check if the milestones condition is met. The method checks if the user has completed + * the required amount of milestones. * * @param condition the condition to check * @return true if the condition is met, false otherwise */ private boolean isMilestonesConditionMet(ConditionDAO condition) { - return condition.getQuantity() <= milestoneLogRepository.findMilestoneLogDAOByUserDAO_Username(CurrentUserService.getCurrentUsername()).size(); + return condition.getQuantity() <= milestoneLogRepository.findMilestoneLogDAOByUserDAO_Username( + CurrentUserService.getCurrentUsername()).size(); } /** - * Method to check if the challenges condition is met. The method checks if the user has completed the required amount of challenges. + * Method to check if the challenges condition is met. The method checks if the user has completed + * the required amount of challenges. * * @param condition the condition to check * @return true if the condition is met, false otherwise */ private boolean isChallengesConditionMet(ConditionDAO condition) { - List<ChallengeLogDAO> challengeLogDAOS = challengeLogRepository.findChallengeLogDAOByUserDAO_Username(CurrentUserService.getCurrentUsername()); + List<ChallengeLogDAO> challengeLogDAOS = challengeLogRepository.findChallengeLogDAOByUserDAO_Username( + CurrentUserService.getCurrentUsername()); Long count = 0L; for (ChallengeLogDAO challengeLogDAO : challengeLogDAOS) { if (challengeLogDAO.getGoalSum() <= challengeLogDAO.getChallengeAchievedSum()) { @@ -81,14 +87,17 @@ public class ConditionService { } /** - * Method to check if the savings condition is met. The method checks if the user has saved the required amount of money. + * Method to check if the savings condition is met. The method checks if the user has saved the + * required amount of money. * * @param condition the condition to check * @return true if the condition is met, false otherwise */ private boolean isSavingsConditionMet(ConditionDAO condition) { - List<MilestoneLogDAO> milestoneLogDAOS = milestoneLogRepository.findMilestoneLogDAOByUserDAO_Username(CurrentUserService.getCurrentUsername()); - List<MilestoneDAO> milestoneDAOS = milestoneRepository.findMilestoneDAOByUserDAO_Username(CurrentUserService.getCurrentUsername()); + List<MilestoneLogDAO> milestoneLogDAOS = milestoneLogRepository.findMilestoneLogDAOByUserDAO_Username( + CurrentUserService.getCurrentUsername()); + List<MilestoneDAO> milestoneDAOS = milestoneRepository.findMilestoneDAOByUserDAO_Username( + CurrentUserService.getCurrentUsername()); Long total = 0L; for (MilestoneLogDAO milestoneLogDAO : milestoneLogDAOS) { total += milestoneLogDAO.getMilestoneAchievedSum(); diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/service/CurrentUserService.java b/src/main/java/idatt2106/systemutvikling/sparesti/service/CurrentUserService.java index 9b38036..6b6c792 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/service/CurrentUserService.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/service/CurrentUserService.java @@ -1,57 +1,58 @@ package idatt2106.systemutvikling.sparesti.service; import idatt2106.systemutvikling.sparesti.security.SecurityConfig; +import java.util.Map; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; -import java.util.Map; - /** - * A service for delivering information about the current user. - * The information is based on the authentication registered in the current SecurityContext. + * A service for delivering information about the current user. The information is based on the + * authentication registered in the current SecurityContext. */ @Service public class CurrentUserService { - public static String KEY_USERNAME = "Username"; - - /** - * Method to get the current username. If the user is not authenticated, null is returned. - * The username is stored in the SecurityContext of the token. - * - * @return the username of the current user - */ - public static String getCurrentUsername() { - if (!SecurityContextHolder.getContext().getAuthentication().isAuthenticated()) - return null; - - Map<String, Object> userDetails = (Map<String, Object>) SecurityContextHolder.getContext().getAuthentication().getDetails(); - - return (String) userDetails.get(KEY_USERNAME); - } - - /** - * Method to check if the current user is a complete user. - * A user is complete if they have two accounts. - * - * @return true if the user is complete, false otherwise - */ - public static boolean isCompleteUser() { - return SecurityContextHolder - .getContext() - .getAuthentication() - .getAuthorities() - .contains(new SimpleGrantedAuthority(SecurityConfig.ROLE_COMPLETE)); - } - - /** - * Method to get the details of the current user. - * The details are stored in the SecurityContext of the token. - * - * @return the details of the current user - */ - public Object getUserDetails () { - return SecurityContextHolder.getContext().getAuthentication().getDetails(); - } + public static String KEY_USERNAME = "Username"; + + /** + * Method to get the current username. If the user is not authenticated, null is returned. The + * username is stored in the SecurityContext of the token. + * + * @return the username of the current user + */ + public static String getCurrentUsername() { + if (!SecurityContextHolder.getContext().getAuthentication().isAuthenticated()) { + return null; + } + + Map<String, Object> userDetails = (Map<String, Object>) SecurityContextHolder.getContext() + .getAuthentication().getDetails(); + + return (String) userDetails.get(KEY_USERNAME); + } + + /** + * Method to check if the current user is a complete user. A user is complete if they have two + * accounts. + * + * @return true if the user is complete, false otherwise + */ + public static boolean isCompleteUser() { + return SecurityContextHolder + .getContext() + .getAuthentication() + .getAuthorities() + .contains(new SimpleGrantedAuthority(SecurityConfig.ROLE_COMPLETE)); + } + + /** + * Method to get the details of the current user. The details are stored in the SecurityContext of + * the token. + * + * @return the details of the current user + */ + public Object getUserDetails() { + return SecurityContextHolder.getContext().getAuthentication().getDetails(); + } } diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/service/CustomerServiceInterface.java b/src/main/java/idatt2106/systemutvikling/sparesti/service/CustomerServiceInterface.java index 3e9184d..f915356 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/service/CustomerServiceInterface.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/service/CustomerServiceInterface.java @@ -7,29 +7,31 @@ import idatt2106.systemutvikling.sparesti.mockBank.dao.CustomerDAO; */ public interface CustomerServiceInterface { - /** - * Method to check if a customer exists in the database. The method checks if the customer exists based on the username - * and returns true if the customer exists, false otherwise. - * - * @param username the username of the customer - * @return true if the customer exists, false otherwise - */ - boolean customerExists(String username); + /** + * Method to check if a customer exists in the database. The method checks if the customer exists + * based on the username and returns true if the customer exists, false otherwise. + * + * @param username the username of the customer + * @return true if the customer exists, false otherwise + */ + boolean customerExists(String username); - /** - * Method to check if a customer has two accounts. The method checks if the customer has two accounts based on the username - * and returns true if the customer has two accounts, false otherwise. - * - * @param username the username of the customer - * @return true if the customer has two accounts, false otherwise - */ - boolean hasTwoAccounts(String username); + /** + * Method to check if a customer has two accounts. The method checks if the customer has two + * accounts based on the username and returns true if the customer has two accounts, false + * otherwise. + * + * @param username the username of the customer + * @return true if the customer has two accounts, false otherwise + */ + boolean hasTwoAccounts(String username); - /** - * Method to find a customer by the username. The method finds the customer based on the username and returns the customer. - * - * @param username the username of the customer - * @return the customer with the username - */ - CustomerDAO findCustomerByUsername(String username); + /** + * Method to find a customer by the username. The method finds the customer based on the username + * and returns the customer. + * + * @param username the username of the customer + * @return the customer with the username + */ + CustomerDAO findCustomerByUsername(String username); } diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/service/JWTService.java b/src/main/java/idatt2106/systemutvikling/sparesti/service/JWTService.java index a8d2301..03f7e69 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/service/JWTService.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/service/JWTService.java @@ -6,13 +6,12 @@ import com.auth0.jwt.exceptions.JWTVerificationException; import com.auth0.jwt.interfaces.DecodedJWT; import idatt2106.systemutvikling.sparesti.security.SecretsConfig; import idatt2106.systemutvikling.sparesti.security.SecurityConfig; +import java.time.Duration; +import java.time.Instant; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Service; -import java.time.Duration; -import java.time.Instant; - /** * Service class for JWT. */ @@ -25,15 +24,16 @@ public class JWTService { private static final Duration JWT_TOKEN_VALIDITY = Duration.ofMinutes(6); - public JWTService(SecretsConfig secrets, CustomerServiceInterface customerService, CustomerServiceInterface customerService1) { + public JWTService(SecretsConfig secrets, CustomerServiceInterface customerService, + CustomerServiceInterface customerService1) { this.secrets = secrets; this.customerService = customerService; } /** - * Generate a JWT token for the given user. The token is valid for 6 minutes. - * The token is signed with the HMAC512 algorithm. The token contains the username and the role of the user. - * The role is either "complete" or "basic". A user is complete if they have two accounts. + * Generate a JWT token for the given user. The token is valid for 6 minutes. The token is signed + * with the HMAC512 algorithm. The token contains the username and the role of the user. The role + * is either "complete" or "basic". A user is complete if they have two accounts. * * @param username the username of the user * @return the generated token @@ -47,18 +47,18 @@ public class JWTService { String role = isCompleteUser ? SecurityConfig.ROLE_COMPLETE : SecurityConfig.ROLE_BASIC; return JWT.create() - .withSubject(username) - .withIssuer("SparestiTokenIssuerApp") - .withIssuedAt(now) - .withExpiresAt(now.plusMillis(JWT_TOKEN_VALIDITY.toMillis())) - .withClaim("role", role) - .sign(hmac512); + .withSubject(username) + .withIssuer("SparestiTokenIssuerApp") + .withIssuedAt(now) + .withExpiresAt(now.plusMillis(JWT_TOKEN_VALIDITY.toMillis())) + .withClaim("role", role) + .sign(hmac512); } /** - * Method to extract username from token. The token is validated with the HMAC512 algorithm. - * The token must be in the format "Bearer <token>". If the token is invalid, null is returned. - * Method extracts the username from the token as the subject. + * Method to extract username from token. The token is validated with the HMAC512 algorithm. The + * token must be in the format "Bearer <token>". If the token is invalid, null is returned. Method + * extracts the username from the token as the subject. * * @param token the token to extract username from * @return the username if the token is valid, null otherwise @@ -71,7 +71,8 @@ public class JWTService { try { final Algorithm hmac512 = Algorithm.HMAC512(secrets.getJwt()); - DecodedJWT jwt = JWT.require(hmac512).build().verify(token.substring(7)); // remove "Bearer " from token + DecodedJWT jwt = JWT.require(hmac512).build() + .verify(token.substring(7)); // remove "Bearer " from token return jwt.getSubject(); } catch (final JWTVerificationException verificationEx) { LOGGER.warn("token is invalid: {}", verificationEx.getMessage()); @@ -80,8 +81,9 @@ public class JWTService { } /** - * Method to validate token and get the DecodedJWT object. The token is validated with the HMAC512 algorithm. - * The token must be in the format "Bearer <token>". If the token is invalid, null is returned. + * Method to validate token and get the DecodedJWT object. The token is validated with the HMAC512 + * algorithm. The token must be in the format "Bearer <token>". If the token is invalid, null is + * returned. * * @param token the token to validate * @return boolean if the token is valid or not diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/service/ManualSavingService.java b/src/main/java/idatt2106/systemutvikling/sparesti/service/ManualSavingService.java index b1b7cd8..7f7254c 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/service/ManualSavingService.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/service/ManualSavingService.java @@ -5,12 +5,11 @@ import idatt2106.systemutvikling.sparesti.dao.UserDAO; import idatt2106.systemutvikling.sparesti.repository.ManualSavingRepository; import idatt2106.systemutvikling.sparesti.repository.UserRepository; import java.time.LocalDateTime; +import java.util.Date; import java.util.List; import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; -import java.util.Date; - /** * Service class for handling manual saving entries. */ @@ -21,16 +20,17 @@ public class ManualSavingService { private final UserRepository dbUser; private final ManualSavingRepository dbManualSaving; - /** - * Registers a new manual saving entry in the database. The entry is saved with the current time. - * - * @param milestoneId the milestone id to save the manual saving entry to - * @param amount the amount to save - * @param username the username of the user to save the manual saving entry for - * @return the saved ManualSavingDAO - */ - public ManualSavingDAO registerNewManualSavingDAO(Long milestoneId, Long amount, String username) { - ManualSavingDAO dao = new ManualSavingDAO(); + /** + * Registers a new manual saving entry in the database. The entry is saved with the current time. + * + * @param milestoneId the milestone id to save the manual saving entry to + * @param amount the amount to save + * @param username the username of the user to save the manual saving entry for + * @return the saved ManualSavingDAO + */ + public ManualSavingDAO registerNewManualSavingDAO(Long milestoneId, Long amount, + String username) { + ManualSavingDAO dao = new ManualSavingDAO(); if (username == null) { return null; diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/service/MilestoneLogService.java b/src/main/java/idatt2106/systemutvikling/sparesti/service/MilestoneLogService.java index b46af78..7807aab 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/service/MilestoneLogService.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/service/MilestoneLogService.java @@ -1,18 +1,21 @@ package idatt2106.systemutvikling.sparesti.service; +import idatt2106.systemutvikling.sparesti.dao.MilestoneLogDAO; import idatt2106.systemutvikling.sparesti.dto.MilestoneDTO; +import idatt2106.systemutvikling.sparesti.mapper.MilestoneMapper; import idatt2106.systemutvikling.sparesti.repository.MilestoneLogRepository; import idatt2106.systemutvikling.sparesti.repository.MilestoneRepository; import idatt2106.systemutvikling.sparesti.repository.UserRepository; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.*; -import org.springframework.stereotype.Service; -import idatt2106.systemutvikling.sparesti.dao.MilestoneLogDAO; -import idatt2106.systemutvikling.sparesti.mapper.MilestoneMapper; - import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.stereotype.Service; /** * Service class for handling MilestoneLogDAOs. @@ -31,7 +34,8 @@ public class MilestoneLogService { Logger logger = Logger.getLogger(MilestoneLogService.class.getName()); @Autowired - public MilestoneLogService(MilestoneRepository milestoneRepository, JWTService jwtService, UserRepository userRepository, MilestoneLogRepository milestoneLogRepository) { + public MilestoneLogService(MilestoneRepository milestoneRepository, JWTService jwtService, + UserRepository userRepository, MilestoneLogRepository milestoneLogRepository) { this.milestoneRepository = milestoneRepository; this.jwtService = jwtService; this.userRepository = userRepository; @@ -42,7 +46,7 @@ public class MilestoneLogService { * Method to complete a milestone and save it to database. * * @param milestoneLogDAO the milestone log to save - */ + */ public void completeMilestone(MilestoneLogDAO milestoneLogDAO) { milestoneLogRepository.save(milestoneLogDAO); } @@ -54,15 +58,16 @@ public class MilestoneLogService { * @param username The username of the user to get milestones for. * @return List of MilestoneLogDAOs. */ - public Page<MilestoneDTO> getMilestoneLogsByUsernamePaginated(String username, Pageable pageable) { + public Page<MilestoneDTO> getMilestoneLogsByUsernamePaginated(String username, + Pageable pageable) { try { Pageable sortedPageable = PageRequest.of( - pageable.getPageNumber(), - pageable.getPageSize(), - Sort.by("completionDate").descending()); + pageable.getPageNumber(), + pageable.getPageSize(), + Sort.by("completionDate").descending()); Page<MilestoneLogDAO> milestoneLogDAOs = - milestoneLogRepository.findMilestoneLogDAOByUserDAO_Username(username, sortedPageable); + milestoneLogRepository.findMilestoneLogDAOByUserDAO_Username(username, sortedPageable); if (milestoneLogDAOs == null) { return Page.empty(); @@ -89,7 +94,7 @@ public class MilestoneLogService { public List<MilestoneDTO> getMilestoneLogsByUsername(String username) { try { List<MilestoneLogDAO> milestoneLogDAOs = - milestoneLogRepository.findMilestoneLogDAOByUserDAO_Username(username); + milestoneLogRepository.findMilestoneLogDAOByUserDAO_Username(username); List<MilestoneDTO> milestoneDTOS = new ArrayList<>(); for (MilestoneLogDAO milestoneDAO : milestoneLogDAOs) { @@ -111,7 +116,8 @@ public class MilestoneLogService { */ public MilestoneDTO getMilestoneLogById(long id) { try { - return MilestoneMapper.DAOLogToDTO(milestoneLogRepository.findMilestoneLogDAOByMilestoneId(id)); + return MilestoneMapper.DAOLogToDTO( + milestoneLogRepository.findMilestoneLogDAOByMilestoneId(id)); } catch (Exception e) { logger.severe("Error when getting milestone: " + e.getMessage()); return null; diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/service/MilestoneService.java b/src/main/java/idatt2106/systemutvikling/sparesti/service/MilestoneService.java index 1935004..eb36f1b 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/service/MilestoneService.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/service/MilestoneService.java @@ -1,24 +1,27 @@ package idatt2106.systemutvikling.sparesti.service; -import idatt2106.systemutvikling.sparesti.dao.*; -import idatt2106.systemutvikling.sparesti.mapper.Base64Mapper; -import idatt2106.systemutvikling.sparesti.repository.MilestoneRepository; +import idatt2106.systemutvikling.sparesti.dao.MilestoneDAO; +import idatt2106.systemutvikling.sparesti.dao.MilestoneLogDAO; +import idatt2106.systemutvikling.sparesti.dao.UserDAO; import idatt2106.systemutvikling.sparesti.dto.MilestoneDTO; +import idatt2106.systemutvikling.sparesti.mapper.Base64Mapper; import idatt2106.systemutvikling.sparesti.mapper.MilestoneMapper; - +import idatt2106.systemutvikling.sparesti.repository.MilestoneRepository; +import idatt2106.systemutvikling.sparesti.repository.UserRepository; import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; import java.util.Objects; +import java.util.logging.Logger; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.*; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; -import java.util.ArrayList; -import java.util.logging.Logger; -import idatt2106.systemutvikling.sparesti.repository.UserRepository; - -import java.util.List; - /** * Service class for handling Milestones. */ diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/service/OpenAIService.java b/src/main/java/idatt2106/systemutvikling/sparesti/service/OpenAIService.java index 6ce2cb5..12fe78c 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/service/OpenAIService.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/service/OpenAIService.java @@ -39,8 +39,8 @@ public class OpenAIService { } /** - * Method to chat with OpenAI. This method sends a prompt to OpenAI and returns the response. - * The prompt should be a string that the AI can respond to. + * Method to chat with OpenAI. This method sends a prompt to OpenAI and returns the response. The + * prompt should be a string that the AI can respond to. * * @param prompt the prompt to chat with * @return the response from OpenAI diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/service/PasswordService.java b/src/main/java/idatt2106/systemutvikling/sparesti/service/PasswordService.java index e18a6d2..76d1e03 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/service/PasswordService.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/service/PasswordService.java @@ -1,11 +1,11 @@ package idatt2106.systemutvikling.sparesti.service; +import idatt2106.systemutvikling.sparesti.dao.UserDAO; +import idatt2106.systemutvikling.sparesti.repository.UserRepository; import java.util.logging.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; -import idatt2106.systemutvikling.sparesti.dao.UserDAO; -import idatt2106.systemutvikling.sparesti.repository.UserRepository; /** * Service class for security operations. @@ -25,6 +25,7 @@ public class PasswordService { /** * Method to check if the password is correct for a given username with salt and hash. + * * @param username the username of the user * @param password the password to check from frontend unhashed * @return true if the password is correct, false otherwise diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/service/TransactionCategoryCacheService.java b/src/main/java/idatt2106/systemutvikling/sparesti/service/TransactionCategoryCacheService.java index 15b4389..fe2fa7d 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/service/TransactionCategoryCacheService.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/service/TransactionCategoryCacheService.java @@ -3,7 +3,6 @@ package idatt2106.systemutvikling.sparesti.service; import idatt2106.systemutvikling.sparesti.dao.TransactionCategoryDAO; import idatt2106.systemutvikling.sparesti.enums.TransactionCategory; import idatt2106.systemutvikling.sparesti.repository.TransactionCategoryCacheRepository; -import java.time.LocalDateTime; import java.util.Date; import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; @@ -21,8 +20,8 @@ public class TransactionCategoryCacheService { * Method to set a category in the cache. * * @param transactionId the id of the transaction - * @param category the category to set - * @param createdAt the time the category was set + * @param category the category to set + * @param createdAt the time the category was set * @return the saved TransactionCategoryDAO */ public TransactionCategoryDAO setCategoryCache(Long transactionId, TransactionCategory category, diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/service/TransactionService.java b/src/main/java/idatt2106/systemutvikling/sparesti/service/TransactionService.java index f82205f..bf7aead 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/service/TransactionService.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/service/TransactionService.java @@ -8,17 +8,14 @@ import idatt2106.systemutvikling.sparesti.exceptions.UserNotFoundException; import idatt2106.systemutvikling.sparesti.mapper.KeywordMapper; import idatt2106.systemutvikling.sparesti.model.Transaction; import idatt2106.systemutvikling.sparesti.repository.UserRepository; - -import java.util.ArrayList; import java.util.Date; +import java.util.List; import java.util.logging.Logger; import lombok.AllArgsConstructor; import lombok.NonNull; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; -import java.util.List; - /** * Service class for handling transactions. */ diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/service/TransactionServiceInterface.java b/src/main/java/idatt2106/systemutvikling/sparesti/service/TransactionServiceInterface.java index 10541cc..c69bb75 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/service/TransactionServiceInterface.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/service/TransactionServiceInterface.java @@ -1,8 +1,6 @@ package idatt2106.systemutvikling.sparesti.service; -import idatt2106.systemutvikling.sparesti.mockBank.dao.TransactionDAO; import idatt2106.systemutvikling.sparesti.model.Transaction; - import java.util.Date; import java.util.List; @@ -11,32 +9,34 @@ import java.util.List; */ public interface TransactionServiceInterface { - /** - * Retrieves all outgoing transactions for a specific account. - * A transaction is considered outgoing when it moves currency from the specified account to any account - * not owned by the owner of the specified account. A transaction is not considered outgoing if it is an internal - * transaction; moving currency between accounts owned by the same user. - * The implementation of this method is expected to fetch all transactions from now until 'dateLimit' - * where the specified accountNumber is either the debtor or creditor. Then, it will filter out any transactions that - * are either internal or incoming (relative to the account's owner). This is the easiest form of implementation - * when connecting to a standard PSD2 API. - * @param accountNumber The account number of the specified account. - * @param dateLimit Transactions older than this date will not be fetched. - * @return A List of transactions moving currency OUT of the specified account. - */ - List<Transaction> getLatestExpensesForAccountNumber(Long accountNumber, Date dateLimit); + /** + * Retrieves all outgoing transactions for a specific account. A transaction is considered + * outgoing when it moves currency from the specified account to any account not owned by the + * owner of the specified account. A transaction is not considered outgoing if it is an internal + * transaction; moving currency between accounts owned by the same user. The implementation of + * this method is expected to fetch all transactions from now until 'dateLimit' where the + * specified accountNumber is either the debtor or creditor. Then, it will filter out any + * transactions that are either internal or incoming (relative to the account's owner). This is + * the easiest form of implementation when connecting to a standard PSD2 API. + * + * @param accountNumber The account number of the specified account. + * @param dateLimit Transactions older than this date will not be fetched. + * @return A List of transactions moving currency OUT of the specified account. + */ + List<Transaction> getLatestExpensesForAccountNumber(Long accountNumber, Date dateLimit); - /** - * Creates a transaction with the given details and returns the created transaction DAO. - * - * @param debtorName The name of the debtor. - * @param creditorName The name of the creditor. - * @param transactionTitle The title of the transaction. - * @param debtorAccount The account number of the debtor. - * @param creditorAccount The account number of the creditor. - * @param amount The amount of the transaction. - * @param currency The currency of the transaction. - * @return TransactionDAO The transaction DAO representing the created transaction. - */ - Boolean createTransaction(String debtorName, String creditorName, String transactionTitle, Long debtorAccount, Long creditorAccount, Long amount, String currency); + /** + * Creates a transaction with the given details and returns the created transaction DAO. + * + * @param debtorName The name of the debtor. + * @param creditorName The name of the creditor. + * @param transactionTitle The title of the transaction. + * @param debtorAccount The account number of the debtor. + * @param creditorAccount The account number of the creditor. + * @param amount The amount of the transaction. + * @param currency The currency of the transaction. + * @return TransactionDAO The transaction DAO representing the created transaction. + */ + Boolean createTransaction(String debtorName, String creditorName, String transactionTitle, + Long debtorAccount, Long creditorAccount, Long amount, String currency); } diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/service/UserService.java b/src/main/java/idatt2106/systemutvikling/sparesti/service/UserService.java index a48d9b7..a58f7b3 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/service/UserService.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/service/UserService.java @@ -10,7 +10,15 @@ import idatt2106.systemutvikling.sparesti.exceptions.InvalidCredentialsException import idatt2106.systemutvikling.sparesti.exceptions.UserNotFoundException; import idatt2106.systemutvikling.sparesti.mapper.Base64Mapper; import idatt2106.systemutvikling.sparesti.mapper.UserMapper; -import idatt2106.systemutvikling.sparesti.repository.*; +import idatt2106.systemutvikling.sparesti.repository.ChallengeLogRepository; +import idatt2106.systemutvikling.sparesti.repository.ChallengeRepository; +import idatt2106.systemutvikling.sparesti.repository.ManualSavingRepository; +import idatt2106.systemutvikling.sparesti.repository.MilestoneLogRepository; +import idatt2106.systemutvikling.sparesti.repository.MilestoneRepository; +import idatt2106.systemutvikling.sparesti.repository.UserRepository; +import java.util.List; +import java.util.Objects; +import java.util.logging.Logger; import lombok.AllArgsConstructor; import lombok.NonNull; import org.springframework.http.HttpStatus; @@ -18,16 +26,13 @@ import org.springframework.http.ResponseEntity; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; -import java.util.List; -import java.util.Objects; -import java.util.logging.Logger; - /** * Service class for the services related to the User entity. */ @Service @AllArgsConstructor public class UserService { + private PasswordEncoder passwordEncoder; private final CustomerServiceInterface customerService; private final AccountServiceInterface accountService; @@ -82,10 +87,11 @@ public class UserService { } /** - * Calculates the total amount saved by all users in the system by summing up the savings - * of each individual user. + * Calculates the total amount saved by all users in the system by summing up the savings of each + * individual user. * - * @return The total amount saved by all users, or {@code null} if an error occurs during calculation. + * @return The total amount saved by all users, or {@code null} if an error occurs during + * calculation. */ public Long getTotalAmountSavedByAllUsers() { Long result = 0L; @@ -149,7 +155,8 @@ public class UserService { } if (Objects.nonNull(updatedUserDTO.getProfilePictureBase64())) { - existingUser.setProfilePicture(Base64Mapper.toByteArray(updatedUserDTO.getProfilePictureBase64())); + existingUser.setProfilePicture( + Base64Mapper.toByteArray(updatedUserDTO.getProfilePictureBase64())); } if (Objects.nonNull(updatedUserDTO.getCurrentAccount())) { @@ -238,7 +245,7 @@ public class UserService { public String updatePassword(UserCredentialsDTO userCredentialsDTO) { UserDAO userDAO = userRepository.findByUsername(CurrentUserService.getCurrentUsername()); if (!passwordEncoder.matches(userCredentialsDTO.getPassword(), userDAO.getPassword()) - || userCredentialsDTO.getNewPassword() == null) { + || userCredentialsDTO.getNewPassword() == null) { throw new InvalidCredentialsException("Invalid password"); } if (userCredentialsDTO.getNewPassword().length() <= 8) { @@ -259,8 +266,9 @@ public class UserService { public boolean deleteCurrentUser() { String username = CurrentUserService.getCurrentUsername(); - if (username == null) + if (username == null) { return false; + } return deleteUserByUsername(username); } @@ -268,8 +276,9 @@ public class UserService { public boolean deleteUserByUsername(@NonNull String username) { // Check whether user exists - if (userRepository.findByUsername(username) == null) + if (userRepository.findByUsername(username) == null) { return false; + } // Delete manual savings dbSaving.deleteAllByUser_Username(username); diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/service/challengeGeneration/ChallengeGeneratorImpl.java b/src/main/java/idatt2106/systemutvikling/sparesti/service/challengeGeneration/ChallengeGeneratorImpl.java index 1220612..2bfb8e1 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/service/challengeGeneration/ChallengeGeneratorImpl.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/service/challengeGeneration/ChallengeGeneratorImpl.java @@ -4,8 +4,8 @@ import idatt2106.systemutvikling.sparesti.dao.ChallengeDAO; import idatt2106.systemutvikling.sparesti.enums.ChallengeTheme; import idatt2106.systemutvikling.sparesti.enums.RecurringInterval; import idatt2106.systemutvikling.sparesti.enums.TransactionCategory; -import idatt2106.systemutvikling.sparesti.model.challengeGeneration.ChallengeData; import idatt2106.systemutvikling.sparesti.model.Transaction; +import idatt2106.systemutvikling.sparesti.model.challengeGeneration.ChallengeData; import idatt2106.systemutvikling.sparesti.model.challengeGeneration.ChallengeTitleAndDescription; import idatt2106.systemutvikling.sparesti.repository.ChallengeRepository; import idatt2106.systemutvikling.sparesti.service.OpenAIService; -- GitLab From 3c133c3fef40b1a67eb93ec40448e42c717dd454 Mon Sep 17 00:00:00 2001 From: Tini Tran <tinit@stud.ntnu.no> Date: Fri, 3 May 2024 12:24:57 +0200 Subject: [PATCH 06/13] checkstyled the repository interfaces for the mockbank --- .../repository/AccountRepository.java | 5 ++--- .../repository/CustomerRepository.java | 3 +-- .../repository/TransactionRepository.java | 19 +++++++++---------- 3 files changed, 12 insertions(+), 15 deletions(-) diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/repository/AccountRepository.java b/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/repository/AccountRepository.java index 801815f..d0e2096 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/repository/AccountRepository.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/repository/AccountRepository.java @@ -2,11 +2,10 @@ package idatt2106.systemutvikling.sparesti.mockBank.repository; import idatt2106.systemutvikling.sparesti.mockBank.dao.AccountDAO; import idatt2106.systemutvikling.sparesti.mockBank.dao.CustomerDAO; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - import java.util.List; import java.util.Optional; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; /** * Repository interface for the Account entity. diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/repository/CustomerRepository.java b/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/repository/CustomerRepository.java index eb78384..e963479 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/repository/CustomerRepository.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/repository/CustomerRepository.java @@ -1,11 +1,10 @@ package idatt2106.systemutvikling.sparesti.mockBank.repository; import idatt2106.systemutvikling.sparesti.mockBank.dao.CustomerDAO; +import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; -import java.util.Optional; - /** * Repository interface for the Customer entity. */ diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/repository/TransactionRepository.java b/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/repository/TransactionRepository.java index e795570..6f41a84 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/repository/TransactionRepository.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/repository/TransactionRepository.java @@ -1,15 +1,12 @@ package idatt2106.systemutvikling.sparesti.mockBank.repository; import idatt2106.systemutvikling.sparesti.mockBank.dao.AccountDAO; -import idatt2106.systemutvikling.sparesti.mockBank.dao.CustomerDAO; import idatt2106.systemutvikling.sparesti.mockBank.dao.TransactionDAO; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; -import org.springframework.data.domain.Pageable; - - import java.util.Date; import java.util.List; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; /** * Repository interface for the Transaction entity. @@ -29,13 +26,15 @@ public interface TransactionRepository extends JpaRepository<TransactionDAO, Lon * Method to find all transactions that belong to an account with a given account number. * * @param debtorAccountNumber the account number of the account - * @param pageable the page number + * @param pageable the page number * @return a list of transaction entities as TransactionDAO */ - List<TransactionDAO> findTransactionDAOByDebtorAccount(Long debtorAccountNumber, Pageable pageable); + List<TransactionDAO> findTransactionDAOByDebtorAccount(Long debtorAccountNumber, + Pageable pageable); /** - * Method to find all transactions that belong to an account with a given account number and a date limit. + * Method to find all transactions that belong to an account with a given account number and a + * date limit. * * @param accountNr the account number of the account * @param dateLimit the date limit @@ -43,7 +42,7 @@ public interface TransactionRepository extends JpaRepository<TransactionDAO, Lon */ List<TransactionDAO> findByAccountDAO_AccountNrAndTimeAfter(Long accountNr, Date dateLimit); - /** + /** * Method to find all transactions that belong to an account with a given account number. * * @param accountNr the account number of the account -- GitLab From c17d12873c16517a6a1b772021aca271537d5f78 Mon Sep 17 00:00:00 2001 From: Tini Tran <tinit@stud.ntnu.no> Date: Fri, 3 May 2024 12:25:15 +0200 Subject: [PATCH 07/13] checkstyled the mapper classes for the mockbank --- .../mapper/MockBankAccountMapper.java | 32 +++++++------- .../mapper/MockBankTransactionMapper.java | 42 +++++++++---------- 2 files changed, 37 insertions(+), 37 deletions(-) diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/mapper/MockBankAccountMapper.java b/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/mapper/MockBankAccountMapper.java index 33945e2..2bb4ccd 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/mapper/MockBankAccountMapper.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/mapper/MockBankAccountMapper.java @@ -8,20 +8,20 @@ import idatt2106.systemutvikling.sparesti.model.BankAccount; */ public class MockBankAccountMapper { - /** - * Method to map a BankAccount to an AccountDAO. - * - * @param dao the BankAccount to map - * @return the AccountDAO - */ - public static BankAccount toModel(AccountDAO dao) { - return new BankAccount( - dao.getAccountNr(), - dao.getCustomerDAO().getUsername(), - dao.getBalance(), - dao.getName(), - dao.getType(), - dao.getCurrency() - ); - } + /** + * Method to map a BankAccount to an AccountDAO. + * + * @param dao the BankAccount to map + * @return the AccountDAO + */ + public static BankAccount toModel(AccountDAO dao) { + return new BankAccount( + dao.getAccountNr(), + dao.getCustomerDAO().getUsername(), + dao.getBalance(), + dao.getName(), + dao.getType(), + dao.getCurrency() + ); + } } diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/mapper/MockBankTransactionMapper.java b/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/mapper/MockBankTransactionMapper.java index a33c251..5252c5e 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/mapper/MockBankTransactionMapper.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/mapper/MockBankTransactionMapper.java @@ -9,25 +9,25 @@ import idatt2106.systemutvikling.sparesti.model.Transaction; */ public class MockBankTransactionMapper { - /** - * Method to map a TransactionDAO to a Transaction. - * - * @param dao the TransactionDAO to map - * @return the Transaction - */ - public static Transaction toModel(TransactionDAO dao) { - return new Transaction( - dao.getTransactionId(), - dao.getAccountDAO().getAccountNr(), - dao.getTransactionTitle(), - dao.getTime(), - dao.getDebtorAccount(), - dao.getDebtorName(), - dao.getCreditorAccount(), - dao.getCreditorName(), - dao.getAmount(), - dao.getCurrency(), - TransactionCategory.NOT_CATEGORIZED - ); - } + /** + * Method to map a TransactionDAO to a Transaction. + * + * @param dao the TransactionDAO to map + * @return the Transaction + */ + public static Transaction toModel(TransactionDAO dao) { + return new Transaction( + dao.getTransactionId(), + dao.getAccountDAO().getAccountNr(), + dao.getTransactionTitle(), + dao.getTime(), + dao.getDebtorAccount(), + dao.getDebtorName(), + dao.getCreditorAccount(), + dao.getCreditorName(), + dao.getAmount(), + dao.getCurrency(), + TransactionCategory.NOT_CATEGORIZED + ); + } } -- GitLab From 7285a9059a2ef8a713e6d3d7a9aecb49907b5ed0 Mon Sep 17 00:00:00 2001 From: Tini Tran <tinit@stud.ntnu.no> Date: Fri, 3 May 2024 12:25:53 +0200 Subject: [PATCH 08/13] checkstyled the dao classes for the mockbank --- .../sparesti/mockBank/dao/AccountDAO.java | 8 +++++++- .../sparesti/mockBank/dao/CustomerDAO.java | 8 +++++--- .../sparesti/mockBank/dao/TransactionDAO.java | 11 ++++++++++- 3 files changed, 22 insertions(+), 5 deletions(-) diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/dao/AccountDAO.java b/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/dao/AccountDAO.java index 39a788e..a221b4a 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/dao/AccountDAO.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/dao/AccountDAO.java @@ -1,6 +1,12 @@ package idatt2106.systemutvikling.sparesti.mockBank.dao; -import jakarta.persistence.*; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; import jakarta.validation.constraints.NotNull; import lombok.Getter; import lombok.NoArgsConstructor; diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/dao/CustomerDAO.java b/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/dao/CustomerDAO.java index 18c0807..9cdd3fa 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/dao/CustomerDAO.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/dao/CustomerDAO.java @@ -1,13 +1,14 @@ package idatt2106.systemutvikling.sparesti.mockBank.dao; -import jakarta.persistence.*; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; import jakarta.validation.constraints.NotNull; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import java.util.List; - /** * Data access object for the Customer entity. */ @@ -17,6 +18,7 @@ import java.util.List; @NoArgsConstructor @Table(name = "mock_customer") public class CustomerDAO { + @Id @NotNull @Column(name = "username") diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/dao/TransactionDAO.java b/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/dao/TransactionDAO.java index 826ffb9..5130cd2 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/dao/TransactionDAO.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/mockBank/dao/TransactionDAO.java @@ -1,6 +1,15 @@ package idatt2106.systemutvikling.sparesti.mockBank.dao; -import jakarta.persistence.*; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; +import jakarta.persistence.Temporal; +import jakarta.persistence.TemporalType; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Positive; import java.util.Date; -- GitLab From d9421710944f718b9b517c8d52b657339281b3bd Mon Sep 17 00:00:00 2001 From: Tini Tran <tinit@stud.ntnu.no> Date: Fri, 3 May 2024 12:28:16 +0200 Subject: [PATCH 09/13] checkstyled the mapper classes --- .../sparesti/mapper/AchievementMapper.java | 10 +- .../sparesti/mapper/BankAccountMapper.java | 32 +++---- .../sparesti/mapper/Base64Mapper.java | 7 +- .../sparesti/mapper/ChallengeMapper.java | 8 +- .../sparesti/mapper/MilestoneMapper.java | 91 ++++++++++--------- .../sparesti/mapper/TransactionMapper.java | 43 ++++----- 6 files changed, 98 insertions(+), 93 deletions(-) diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/mapper/AchievementMapper.java b/src/main/java/idatt2106/systemutvikling/sparesti/mapper/AchievementMapper.java index 1eafa4b..8fb2ecd 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/mapper/AchievementMapper.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/mapper/AchievementMapper.java @@ -2,7 +2,6 @@ package idatt2106.systemutvikling.sparesti.mapper; import idatt2106.systemutvikling.sparesti.dao.AchievementDAO; import idatt2106.systemutvikling.sparesti.dto.AchievementDTO; - import java.util.ArrayList; import java.util.List; @@ -10,6 +9,7 @@ import java.util.List; * Mapper class for AchievementDAO and AchievementDTO */ public class AchievementMapper { + /** * Maps AchievementDTO to AchievementDAO * @@ -51,7 +51,9 @@ public class AchievementMapper { */ public static List<AchievementDAO> toDAOList(List<AchievementDTO> dtos) { List<AchievementDAO> daos = new ArrayList<>(); - for (AchievementDTO dto : dtos) daos.add(toDAO(dto)); + for (AchievementDTO dto : dtos) { + daos.add(toDAO(dto)); + } return daos; } @@ -63,7 +65,9 @@ public class AchievementMapper { */ public static List<AchievementDTO> toDTOList(List<AchievementDAO> daos) { List<AchievementDTO> dtos = new ArrayList<>(); - for (AchievementDAO dao : daos) dtos.add(toDTO(dao)); + for (AchievementDAO dao : daos) { + dtos.add(toDTO(dao)); + } return dtos; } diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/mapper/BankAccountMapper.java b/src/main/java/idatt2106/systemutvikling/sparesti/mapper/BankAccountMapper.java index a69c809..2df8ab5 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/mapper/BankAccountMapper.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/mapper/BankAccountMapper.java @@ -8,20 +8,20 @@ import idatt2106.systemutvikling.sparesti.model.BankAccount; */ public class BankAccountMapper { - /** - * Maps a BankAccount to a BankAccountDTO. - * - * @param b the BankAccount to map - * @return the BankAccountDTO - */ - public static BankAccountDTO toDTO(BankAccount b) { - return new BankAccountDTO( - b.getAccountNr(), - b.getUsername(), - b.getBalance(), - b.getName(), - b.getType(), - b.getCurrency() - ); - } + /** + * Maps a BankAccount to a BankAccountDTO. + * + * @param b the BankAccount to map + * @return the BankAccountDTO + */ + public static BankAccountDTO toDTO(BankAccount b) { + return new BankAccountDTO( + b.getAccountNr(), + b.getUsername(), + b.getBalance(), + b.getName(), + b.getType(), + b.getCurrency() + ); + } } diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/mapper/Base64Mapper.java b/src/main/java/idatt2106/systemutvikling/sparesti/mapper/Base64Mapper.java index e80b118..75520d1 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/mapper/Base64Mapper.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/mapper/Base64Mapper.java @@ -7,6 +7,7 @@ import java.util.logging.Logger; * Mapper class for converting images to base64 strings and vice versa. */ public class Base64Mapper { + static Logger logger = Logger.getLogger(Base64Mapper.class.getName()); /** @@ -37,16 +38,16 @@ public class Base64Mapper { if (base64String != null) { // Check if the base64 string starts with "data:image/" if (base64String.startsWith("data:image/")) { - // Find the index of the comma separating the image type and the base64 string + // Find the index of the comma separating the image type and the base64 string int commaIndex = base64String.indexOf(","); if (commaIndex != -1) { // Extract the image type from the base64 string String imageType = base64String.substring("data:image/".length(), commaIndex); logger.info("Image type: " + imageType); - // Remove the image type from the base64 string + // Remove the image type from the base64 string base64String = base64String.substring(commaIndex + 1); logger.info("Converting base64 string to image"); - return Base64.getDecoder().decode(base64String); + return Base64.getDecoder().decode(base64String); } } else { return Base64.getDecoder().decode(base64String); diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/mapper/ChallengeMapper.java b/src/main/java/idatt2106/systemutvikling/sparesti/mapper/ChallengeMapper.java index ddfc7b1..2c0a8ed 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/mapper/ChallengeMapper.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/mapper/ChallengeMapper.java @@ -9,6 +9,7 @@ import idatt2106.systemutvikling.sparesti.enums.RecurringInterval; * Mapper class for ChallengeDAO and ChallengeDAO */ public class ChallengeMapper { + /** * Maps ChallengeDTO to ChallengeDAO * @@ -41,13 +42,14 @@ public class ChallengeMapper { private static RecurringInterval mapRecurringInterval(int recurring) { return switch (recurring) { case 0 -> RecurringInterval.NONE; - case 24*60*60 -> RecurringInterval.DAILY; - case 60*60*24*7 -> RecurringInterval.WEEKLY; - case 60*60*24*30 -> RecurringInterval.MONTHLY; + case 24 * 60 * 60 -> RecurringInterval.DAILY; + case 60 * 60 * 24 * 7 -> RecurringInterval.WEEKLY; + case 60 * 60 * 24 * 30 -> RecurringInterval.MONTHLY; default -> throw new IllegalArgumentException("Invalid recurring interval value: " + recurring); }; } + /** * Maps ChallengeDTO to ChallengeDAO * diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/mapper/MilestoneMapper.java b/src/main/java/idatt2106/systemutvikling/sparesti/mapper/MilestoneMapper.java index 0efc994..38f5ae6 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/mapper/MilestoneMapper.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/mapper/MilestoneMapper.java @@ -9,28 +9,29 @@ import idatt2106.systemutvikling.sparesti.dto.MilestoneDTO; * Mapper class for MilestoneDAO and MilestoneDTO */ public class MilestoneMapper { -/** - * Maps MilestoneDTO to MilestoneDAO - * - * @param dto MilestoneDTO to be mapped - * @return MilestoneDAO - */ -public static MilestoneDAO toDAO(MilestoneDTO dto) { - MilestoneDAO dao = new MilestoneDAO(); - dao.setMilestoneId(dto.getMilestoneId()); - UserDAO userDAO = new UserDAO(); - userDAO.setUsername(dto.getUsername()); - dao.setUserDAO(userDAO); - dao.setMilestoneTitle(dto.getMilestoneTitle()); - dao.setMilestoneDescription(dto.getMilestoneDescription()); - dao.setMilestoneGoalSum(dto.getMilestoneGoalSum()); - dao.setMilestoneCurrentSum(dto.getMilestoneCurrentSum()); - dao.setMilestoneImage(Base64Mapper.toByteArray(dto.getMilestoneImage())); - dao.setDeadlineDate(dto.getDeadlineDate()); - dao.setStartDate(dto.getStartDate()); - return dao; -} + /** + * Maps MilestoneDTO to MilestoneDAO + * + * @param dto MilestoneDTO to be mapped + * @return MilestoneDAO + */ + public static MilestoneDAO toDAO(MilestoneDTO dto) { + MilestoneDAO dao = new MilestoneDAO(); + dao.setMilestoneId(dto.getMilestoneId()); + UserDAO userDAO = new UserDAO(); + userDAO.setUsername(dto.getUsername()); + dao.setUserDAO(userDAO); + dao.setMilestoneTitle(dto.getMilestoneTitle()); + dao.setMilestoneDescription(dto.getMilestoneDescription()); + dao.setMilestoneGoalSum(dto.getMilestoneGoalSum()); + dao.setMilestoneCurrentSum(dto.getMilestoneCurrentSum()); + dao.setMilestoneImage(Base64Mapper.toByteArray(dto.getMilestoneImage())); + dao.setDeadlineDate(dto.getDeadlineDate()); + dao.setStartDate(dto.getStartDate()); + + return dao; + } /** * Maps MilestoneDAO to MilestoneDTO @@ -39,19 +40,19 @@ public static MilestoneDAO toDAO(MilestoneDTO dto) { * @return MilestoneDTO */ public static MilestoneDTO toDTO(MilestoneDAO dao) { - MilestoneDTO dto = new MilestoneDTO(); - dto.setMilestoneId(dao.getMilestoneId()); - dto.setUsername(dao.getUserDAO().getUsername()); - dto.setMilestoneTitle(dao.getMilestoneTitle()); - dto.setMilestoneDescription(dao.getMilestoneDescription()); - dto.setMilestoneGoalSum(dao.getMilestoneGoalSum()); - dto.setMilestoneCurrentSum(dao.getMilestoneCurrentSum()); - dto.setMilestoneImage(Base64Mapper.toBase64String(dao.getMilestoneImage())); - dto.setDeadlineDate(dao.getDeadlineDate()); - dto.setStartDate(dao.getStartDate()); + MilestoneDTO dto = new MilestoneDTO(); + dto.setMilestoneId(dao.getMilestoneId()); + dto.setUsername(dao.getUserDAO().getUsername()); + dto.setMilestoneTitle(dao.getMilestoneTitle()); + dto.setMilestoneDescription(dao.getMilestoneDescription()); + dto.setMilestoneGoalSum(dao.getMilestoneGoalSum()); + dto.setMilestoneCurrentSum(dao.getMilestoneCurrentSum()); + dto.setMilestoneImage(Base64Mapper.toBase64String(dao.getMilestoneImage())); + dto.setDeadlineDate(dao.getDeadlineDate()); + dto.setStartDate(dao.getStartDate()); - return dto; -} + return dto; + } /** * Maps MilestoneDAO to MilestoneLogDAO @@ -60,19 +61,19 @@ public static MilestoneDAO toDAO(MilestoneDTO dto) { * @return MilestoneLogDAO */ public static MilestoneLogDAO toLogDAO(MilestoneDAO dao) { - MilestoneLogDAO logDAO = new MilestoneLogDAO(); - UserDAO userDAO = new UserDAO(); - userDAO.setUsername(dao.getUserDAO().getUsername()); - logDAO.setUserDAO(userDAO); - logDAO.setMilestoneTitle(dao.getMilestoneTitle()); - logDAO.setMilestoneDescription(dao.getMilestoneDescription()); - logDAO.setMilestoneGoalSum(dao.getMilestoneGoalSum()); - logDAO.setMilestoneAchievedSum(dao.getMilestoneCurrentSum()); - logDAO.setMilestoneImage(dao.getMilestoneImage()); - logDAO.setCompletionDate(dao.getDeadlineDate()); + MilestoneLogDAO logDAO = new MilestoneLogDAO(); + UserDAO userDAO = new UserDAO(); + userDAO.setUsername(dao.getUserDAO().getUsername()); + logDAO.setUserDAO(userDAO); + logDAO.setMilestoneTitle(dao.getMilestoneTitle()); + logDAO.setMilestoneDescription(dao.getMilestoneDescription()); + logDAO.setMilestoneGoalSum(dao.getMilestoneGoalSum()); + logDAO.setMilestoneAchievedSum(dao.getMilestoneCurrentSum()); + logDAO.setMilestoneImage(dao.getMilestoneImage()); + logDAO.setCompletionDate(dao.getDeadlineDate()); - return logDAO; -} + return logDAO; + } /** * Maps MilestoneLogDAO to MilestoneDTO diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/mapper/TransactionMapper.java b/src/main/java/idatt2106/systemutvikling/sparesti/mapper/TransactionMapper.java index 6439df4..8942358 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/mapper/TransactionMapper.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/mapper/TransactionMapper.java @@ -1,36 +1,33 @@ package idatt2106.systemutvikling.sparesti.mapper; import idatt2106.systemutvikling.sparesti.dto.TransactionDTO; -import idatt2106.systemutvikling.sparesti.mockBank.dao.TransactionDAO; import idatt2106.systemutvikling.sparesti.model.Transaction; -import java.util.Date; - /** * Mapper class for the Transaction entity. */ public class TransactionMapper { - /** - * Maps a TransactionDAO to a Transaction. - * - * @param t the TransactionDAO to map - * @return the Transaction - */ - public static TransactionDTO toDTO(Transaction t) { - TransactionDTO dto = new TransactionDTO(); + /** + * Maps a TransactionDAO to a Transaction. + * + * @param t the TransactionDAO to map + * @return the Transaction + */ + public static TransactionDTO toDTO(Transaction t) { + TransactionDTO dto = new TransactionDTO(); - dto.setTransactionId(t.getTransactionId()); - dto.setAmount(t.getAmount()); - dto.setTime(t.getTime()); - dto.setCurrency(t.getCurrency()); - dto.setTransactionTitle(t.getTransactionTitle()); - dto.setCreditorAccount(t.getCreditorAccount()); - dto.setCreditorName(t.getCreditorName()); - dto.setDebtorAccount(t.getDebtorAccount()); - dto.setDebtorName(t.getDebtorName()); - dto.setTransactionCategory(t.getCategory()); + dto.setTransactionId(t.getTransactionId()); + dto.setAmount(t.getAmount()); + dto.setTime(t.getTime()); + dto.setCurrency(t.getCurrency()); + dto.setTransactionTitle(t.getTransactionTitle()); + dto.setCreditorAccount(t.getCreditorAccount()); + dto.setCreditorName(t.getCreditorName()); + dto.setDebtorAccount(t.getDebtorAccount()); + dto.setDebtorName(t.getDebtorName()); + dto.setTransactionCategory(t.getCategory()); - return dto; - } + return dto; + } } -- GitLab From 7efee09fe1a1cd9d39aba4577b68025e588ec9bd Mon Sep 17 00:00:00 2001 From: Tini Tran <tinit@stud.ntnu.no> Date: Fri, 3 May 2024 12:29:31 +0200 Subject: [PATCH 10/13] checkstyled the exceptions --- .../sparesti/exceptions/BankConnectionErrorException.java | 2 +- .../systemutvikling/sparesti/exceptions/ConflictException.java | 2 +- .../sparesti/exceptions/InvalidCredentialsException.java | 2 +- .../sparesti/exceptions/InvalidTokenException.java | 2 +- .../sparesti/exceptions/NotFoundInDatabaseException.java | 2 +- .../systemutvikling/sparesti/exceptions/OpenAIException.java | 2 +- .../sparesti/exceptions/UserNotFoundException.java | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/exceptions/BankConnectionErrorException.java b/src/main/java/idatt2106/systemutvikling/sparesti/exceptions/BankConnectionErrorException.java index 3142f82..e370621 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/exceptions/BankConnectionErrorException.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/exceptions/BankConnectionErrorException.java @@ -25,7 +25,7 @@ public class BankConnectionErrorException extends RuntimeException { * Constructor for BankConnectionErrorException. * * @param message the message to be displayed - * @param cause the cause of the exception + * @param cause the cause of the exception */ public BankConnectionErrorException(String message, Throwable cause) { super(message, cause); diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/exceptions/ConflictException.java b/src/main/java/idatt2106/systemutvikling/sparesti/exceptions/ConflictException.java index 00b7ab9..572b800 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/exceptions/ConflictException.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/exceptions/ConflictException.java @@ -18,7 +18,7 @@ public class ConflictException extends RuntimeException { * Constructor for ConflictException. * * @param message the message to be displayed - * @param cause the cause of the exception + * @param cause the cause of the exception */ public ConflictException(String message, Throwable cause) { super(message, cause); diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/exceptions/InvalidCredentialsException.java b/src/main/java/idatt2106/systemutvikling/sparesti/exceptions/InvalidCredentialsException.java index c420536..b7a3dfc 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/exceptions/InvalidCredentialsException.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/exceptions/InvalidCredentialsException.java @@ -18,7 +18,7 @@ public class InvalidCredentialsException extends RuntimeException { * Constructor for InvalidCredentialsException. * * @param message the message to be displayed - * @param cause the cause of the exception + * @param cause the cause of the exception */ public InvalidCredentialsException(String message, Throwable cause) { super(message, cause); diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/exceptions/InvalidTokenException.java b/src/main/java/idatt2106/systemutvikling/sparesti/exceptions/InvalidTokenException.java index 3019867..ad84ce5 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/exceptions/InvalidTokenException.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/exceptions/InvalidTokenException.java @@ -18,7 +18,7 @@ public class InvalidTokenException extends RuntimeException { * Constructor for InvalidTokenException. * * @param message the message to be displayed - * @param cause the cause of the exception + * @param cause the cause of the exception */ public InvalidTokenException(String message, Throwable cause) { super(message, cause); diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/exceptions/NotFoundInDatabaseException.java b/src/main/java/idatt2106/systemutvikling/sparesti/exceptions/NotFoundInDatabaseException.java index 781b53a..8ff2ac3 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/exceptions/NotFoundInDatabaseException.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/exceptions/NotFoundInDatabaseException.java @@ -18,7 +18,7 @@ public class NotFoundInDatabaseException extends RuntimeException { * Constructor for NotFoundInDatabaseException. * * @param message the message to be displayed - * @param cause the cause of the exception + * @param cause the cause of the exception */ public NotFoundInDatabaseException(String message, Throwable cause) { super(message, cause); diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/exceptions/OpenAIException.java b/src/main/java/idatt2106/systemutvikling/sparesti/exceptions/OpenAIException.java index edff656..f4f024d 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/exceptions/OpenAIException.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/exceptions/OpenAIException.java @@ -19,7 +19,7 @@ public class OpenAIException extends RuntimeException { * Constructor for OpenAIException. * * @param message the message to be displayed - * @param cause the cause of the exception + * @param cause the cause of the exception */ public OpenAIException(String message, Throwable cause) { super(message, cause); diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/exceptions/UserNotFoundException.java b/src/main/java/idatt2106/systemutvikling/sparesti/exceptions/UserNotFoundException.java index 427f04c..6d294ef 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/exceptions/UserNotFoundException.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/exceptions/UserNotFoundException.java @@ -19,7 +19,7 @@ public class UserNotFoundException extends RuntimeException { * Constructor for UserNotFoundException. * * @param message the message to be displayed - * @param cause the cause of the exception + * @param cause the cause of the exception */ public UserNotFoundException(String message, Throwable cause) { super(message, cause); -- GitLab From 57c228bd46d9107ac56e1d209fd405ffa27bd176 Mon Sep 17 00:00:00 2001 From: Tini Tran <tinit@stud.ntnu.no> Date: Fri, 3 May 2024 12:31:28 +0200 Subject: [PATCH 11/13] checkstyled the dto classes --- .../sparesti/dto/BankAccountDTO.java | 12 +++---- .../sparesti/dto/ChallengeDTO.java | 10 ++++-- .../sparesti/dto/ManualSavingDTO.java | 4 +-- .../sparesti/dto/MilestoneDTO.java | 31 ++++++++++--------- .../sparesti/dto/PaginatedRequestDTO.java | 4 +-- .../sparesti/dto/TransactionDTO.java | 31 +++++++++---------- .../sparesti/dto/UserCredentialsDTO.java | 12 +++---- .../systemutvikling/sparesti/dto/UserDTO.java | 6 ++-- 8 files changed, 57 insertions(+), 53 deletions(-) diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/dto/BankAccountDTO.java b/src/main/java/idatt2106/systemutvikling/sparesti/dto/BankAccountDTO.java index e48a820..6ffad98 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/dto/BankAccountDTO.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/dto/BankAccountDTO.java @@ -14,15 +14,15 @@ import lombok.Setter; @NoArgsConstructor public class BankAccountDTO { - private Long accountNumber; + private Long accountNumber; - private String username; + private String username; - private Long balance; + private Long balance; - private String name; + private String name; - private String type; + private String type; - private String currency; + private String currency; } diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/dto/ChallengeDTO.java b/src/main/java/idatt2106/systemutvikling/sparesti/dto/ChallengeDTO.java index 9a0a80d..d359506 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/dto/ChallengeDTO.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/dto/ChallengeDTO.java @@ -2,8 +2,11 @@ package idatt2106.systemutvikling.sparesti.dto; import jakarta.validation.constraints.NotNull; import java.time.LocalDateTime; - -import lombok.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; /** * A Data Transfer Object representing a challenge @@ -12,8 +15,9 @@ import lombok.*; @Setter @AllArgsConstructor @NoArgsConstructor -@Builder(toBuilder=true) +@Builder(toBuilder = true) public class ChallengeDTO { + @NotNull private Long challengeId; diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/dto/ManualSavingDTO.java b/src/main/java/idatt2106/systemutvikling/sparesti/dto/ManualSavingDTO.java index f2dac51..1337dfc 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/dto/ManualSavingDTO.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/dto/ManualSavingDTO.java @@ -14,7 +14,7 @@ import lombok.Setter; @AllArgsConstructor public class ManualSavingDTO { - private Long milestoneId; + private Long milestoneId; - private Long amount; + private Long amount; } diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/dto/MilestoneDTO.java b/src/main/java/idatt2106/systemutvikling/sparesti/dto/MilestoneDTO.java index 574cbf3..c99f395 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/dto/MilestoneDTO.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/dto/MilestoneDTO.java @@ -2,28 +2,31 @@ package idatt2106.systemutvikling.sparesti.dto; import jakarta.validation.constraints.NotNull; import java.time.LocalDateTime; - -import lombok.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; /** - * Data transfer object for Milestone - * Used to transfer milestone data between layers + * Data transfer object for Milestone Used to transfer milestone data between layers */ @Getter @Setter @AllArgsConstructor @NoArgsConstructor -@Builder(toBuilder=true) +@Builder(toBuilder = true) public class MilestoneDTO { + @NotNull -private Long milestoneId; -private String username; -private String milestoneTitle; -private String milestoneDescription; -private Long milestoneGoalSum; -private Long milestoneCurrentSum; -private String milestoneImage; -private LocalDateTime deadlineDate; -private LocalDateTime startDate; + private Long milestoneId; + private String username; + private String milestoneTitle; + private String milestoneDescription; + private Long milestoneGoalSum; + private Long milestoneCurrentSum; + private String milestoneImage; + private LocalDateTime deadlineDate; + private LocalDateTime startDate; } diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/dto/PaginatedRequestDTO.java b/src/main/java/idatt2106/systemutvikling/sparesti/dto/PaginatedRequestDTO.java index 60b74bd..3a632b8 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/dto/PaginatedRequestDTO.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/dto/PaginatedRequestDTO.java @@ -14,7 +14,7 @@ import lombok.Setter; @NoArgsConstructor public class PaginatedRequestDTO { - int pageNum; + int pageNum; - int pageSize; + int pageSize; } diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/dto/TransactionDTO.java b/src/main/java/idatt2106/systemutvikling/sparesti/dto/TransactionDTO.java index 9bd201e..ea1d9d2 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/dto/TransactionDTO.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/dto/TransactionDTO.java @@ -1,17 +1,13 @@ package idatt2106.systemutvikling.sparesti.dto; import idatt2106.systemutvikling.sparesti.enums.TransactionCategory; -import idatt2106.systemutvikling.sparesti.mockBank.dao.AccountDAO; -import jakarta.persistence.*; import jakarta.validation.constraints.NotNull; -import jakarta.validation.constraints.Positive; +import java.util.Date; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import java.util.Date; - /** * Data transfer object for Transaction */ @@ -20,24 +16,25 @@ import java.util.Date; @AllArgsConstructor @NoArgsConstructor public class TransactionDTO { - private Long transactionId; - private String transactionTitle; + private Long transactionId; + + private String transactionTitle; - private Date time; + private Date time; - @NotNull - private Long debtorAccount; + @NotNull + private Long debtorAccount; - private String debtorName; - @NotNull - private Long creditorAccount; + private String debtorName; + @NotNull + private Long creditorAccount; - private String creditorName; + private String creditorName; - private Long amount; + private Long amount; - private String currency; + private String currency; - private TransactionCategory transactionCategory; + private TransactionCategory transactionCategory; } diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/dto/UserCredentialsDTO.java b/src/main/java/idatt2106/systemutvikling/sparesti/dto/UserCredentialsDTO.java index 53840ad..9ee4210 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/dto/UserCredentialsDTO.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/dto/UserCredentialsDTO.java @@ -1,12 +1,11 @@ package idatt2106.systemutvikling.sparesti.dto; +import java.time.LocalDate; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import org.springframework.lang.Nullable; -import java.time.LocalDate; - /** * Data transfer object for UserCredentials */ @@ -14,16 +13,17 @@ import java.time.LocalDate; @Setter @NoArgsConstructor public class UserCredentialsDTO { + private String username; private String password; @Nullable private String newPassword; - @ Nullable + @Nullable private String email; - @ Nullable + @Nullable private String firstName; - @ Nullable + @Nullable private String lastName; - @ Nullable + @Nullable private LocalDate birthDate; } diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/dto/UserDTO.java b/src/main/java/idatt2106/systemutvikling/sparesti/dto/UserDTO.java index 89183d3..5ac34ce 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/dto/UserDTO.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/dto/UserDTO.java @@ -1,13 +1,12 @@ package idatt2106.systemutvikling.sparesti.dto; +import java.time.LocalDate; +import java.util.List; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import org.springframework.lang.Nullable; -import java.time.LocalDate; -import java.util.List; - /** * Data transfer object for User */ @@ -15,6 +14,7 @@ import java.util.List; @Setter @NoArgsConstructor public class UserDTO { + private String username; @Nullable private String email; -- GitLab From 68d5a30f5c1e25d534be8db090586338e13920af Mon Sep 17 00:00:00 2001 From: Tini Tran <tinit@stud.ntnu.no> Date: Fri, 3 May 2024 12:32:17 +0200 Subject: [PATCH 12/13] checkstyled the dao classes --- .../sparesti/dao/AchievementDAO.java | 38 +++++++----- .../sparesti/dao/ChallengeDAO.java | 12 +++- .../sparesti/dao/ChallengeLogDAO.java | 7 ++- .../sparesti/dao/ConditionDAO.java | 22 +++++-- .../sparesti/dao/ManualSavingDAO.java | 61 +++++++++++-------- .../sparesti/dao/MilestoneDAO.java | 42 +++++++------ .../sparesti/dao/MilestoneLogDAO.java | 37 ++++++----- .../sparesti/dao/TransactionCategoryDAO.java | 7 ++- .../systemutvikling/sparesti/dao/UserDAO.java | 60 ++++++++++-------- 9 files changed, 173 insertions(+), 113 deletions(-) diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/dao/AchievementDAO.java b/src/main/java/idatt2106/systemutvikling/sparesti/dao/AchievementDAO.java index f9f332c..c03abcb 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/dao/AchievementDAO.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/dao/AchievementDAO.java @@ -1,13 +1,19 @@ package idatt2106.systemutvikling.sparesti.dao; -import jakarta.persistence.*; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Lob; +import jakarta.persistence.ManyToMany; +import jakarta.persistence.Table; +import java.util.List; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import java.util.List; - /** * Data Access Object for Achievement */ @@ -18,21 +24,21 @@ import java.util.List; @Table(name = "achievement") public class AchievementDAO { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Setter - private Long achievementId; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Setter + private Long achievementId; - @Setter - private String achievementTitle; + @Setter + private String achievementTitle; - @Setter - private String achievementDescription; + @Setter + private String achievementDescription; - @Lob - @Setter - private byte[] badge; + @Lob + @Setter + private byte[] badge; - @ManyToMany(mappedBy = "achievements", fetch = FetchType.LAZY) - private List<UserDAO> users; + @ManyToMany(mappedBy = "achievements", fetch = FetchType.LAZY) + private List<UserDAO> users; } diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/dao/ChallengeDAO.java b/src/main/java/idatt2106/systemutvikling/sparesti/dao/ChallengeDAO.java index 97f723c..4f64f38 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/dao/ChallengeDAO.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/dao/ChallengeDAO.java @@ -2,10 +2,16 @@ package idatt2106.systemutvikling.sparesti.dao; import idatt2106.systemutvikling.sparesti.enums.ChallengeTheme; import idatt2106.systemutvikling.sparesti.enums.RecurringInterval; -import jakarta.persistence.*; - +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; import java.time.LocalDateTime; - import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/dao/ChallengeLogDAO.java b/src/main/java/idatt2106/systemutvikling/sparesti/dao/ChallengeLogDAO.java index 723e7f5..c6e9e4c 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/dao/ChallengeLogDAO.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/dao/ChallengeLogDAO.java @@ -1,8 +1,11 @@ package idatt2106.systemutvikling.sparesti.dao; import idatt2106.systemutvikling.sparesti.enums.ChallengeTheme; -import jakarta.persistence.*; - +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; import java.time.LocalDateTime; import lombok.Getter; import lombok.NoArgsConstructor; diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/dao/ConditionDAO.java b/src/main/java/idatt2106/systemutvikling/sparesti/dao/ConditionDAO.java index 581d8be..9bb20b5 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/dao/ConditionDAO.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/dao/ConditionDAO.java @@ -1,7 +1,16 @@ package idatt2106.systemutvikling.sparesti.dao; import idatt2106.systemutvikling.sparesti.enums.ConditionType; -import jakarta.persistence.*; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @@ -15,13 +24,14 @@ import lombok.Setter; @Entity @Table(name = "conditions") public class ConditionDAO { + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long conditionId; -@ManyToOne (cascade = CascadeType.ALL) -@JoinColumn(name = "achievementId", referencedColumnName = "achievementId") -private AchievementDAO achievementDAO; -private Long quantity; + @ManyToOne(cascade = CascadeType.ALL) + @JoinColumn(name = "achievementId", referencedColumnName = "achievementId") + private AchievementDAO achievementDAO; + private Long quantity; @Enumerated(EnumType.STRING) -private ConditionType conditionType; + private ConditionType conditionType; } diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/dao/ManualSavingDAO.java b/src/main/java/idatt2106/systemutvikling/sparesti/dao/ManualSavingDAO.java index 8b53ff1..e2deb80 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/dao/ManualSavingDAO.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/dao/ManualSavingDAO.java @@ -1,12 +1,21 @@ package idatt2106.systemutvikling.sparesti.dao; -import jakarta.persistence.*; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; +import jakarta.persistence.Temporal; +import jakarta.persistence.TemporalType; +import java.util.Date; import lombok.Getter; import lombok.Setter; import org.springframework.lang.Nullable; -import java.util.Date; - /** * Data Access Object for ManualSaving */ @@ -15,27 +24,27 @@ import java.util.Date; @Getter public class ManualSavingDAO { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id") - private Long id; - - @Column(name = "amount") - @Setter - private Long amount; - - @Column(name = "time_of_transfer") - @Temporal(TemporalType.TIMESTAMP) - @Setter - private Date timeOfTransfer; - - @Setter - @Nullable - @Column(name = "milestone_id") - private Long milestoneId; - - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "user_id") - @Setter - private UserDAO user; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + + @Column(name = "amount") + @Setter + private Long amount; + + @Column(name = "time_of_transfer") + @Temporal(TemporalType.TIMESTAMP) + @Setter + private Date timeOfTransfer; + + @Setter + @Nullable + @Column(name = "milestone_id") + private Long milestoneId; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "user_id") + @Setter + private UserDAO user; } diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/dao/MilestoneDAO.java b/src/main/java/idatt2106/systemutvikling/sparesti/dao/MilestoneDAO.java index 67f8a2d..4511160 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/dao/MilestoneDAO.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/dao/MilestoneDAO.java @@ -1,7 +1,14 @@ package idatt2106.systemutvikling.sparesti.dao; -import jakarta.persistence.*; - +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.Lob; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; import java.time.LocalDateTime; import lombok.Getter; import lombok.NoArgsConstructor; @@ -16,21 +23,22 @@ import lombok.Setter; @Entity @Table(name = "milestone") public class MilestoneDAO { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long milestoneId; - @ManyToOne - @JoinColumn(name = "username", referencedColumnName = "username") - private UserDAO userDAO; - private String milestoneTitle; - private String milestoneDescription; - private Long milestoneGoalSum; - private Long milestoneCurrentSum; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long milestoneId; + + @ManyToOne + @JoinColumn(name = "username", referencedColumnName = "username") + private UserDAO userDAO; + private String milestoneTitle; + private String milestoneDescription; + private Long milestoneGoalSum; + private Long milestoneCurrentSum; - @Lob - @Column(length = 100000) - private byte[] milestoneImage; - private LocalDateTime deadlineDate; - private LocalDateTime startDate; + @Lob + @Column(length = 100000) + private byte[] milestoneImage; + private LocalDateTime deadlineDate; + private LocalDateTime startDate; } diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/dao/MilestoneLogDAO.java b/src/main/java/idatt2106/systemutvikling/sparesti/dao/MilestoneLogDAO.java index a4a2d81..f4adee8 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/dao/MilestoneLogDAO.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/dao/MilestoneLogDAO.java @@ -1,10 +1,17 @@ package idatt2106.systemutvikling.sparesti.dao; -import jakarta.persistence.*; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.Lob; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; +import java.time.LocalDateTime; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import java.time.LocalDateTime; /** * Data Access Object for MilestoneLog @@ -16,24 +23,24 @@ import java.time.LocalDateTime; @Table(name = "milestone_log") public class MilestoneLogDAO { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long milestoneId; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long milestoneId; - @ManyToOne - @JoinColumn(name = "username", referencedColumnName = "username") - private UserDAO userDAO; + @ManyToOne + @JoinColumn(name = "username", referencedColumnName = "username") + private UserDAO userDAO; - private String milestoneTitle; + private String milestoneTitle; - private String milestoneDescription; + private String milestoneDescription; - private Long milestoneGoalSum; + private Long milestoneGoalSum; - private Long milestoneAchievedSum; + private Long milestoneAchievedSum; - @Lob - private byte[] milestoneImage; + @Lob + private byte[] milestoneImage; - private LocalDateTime completionDate; + private LocalDateTime completionDate; } diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/dao/TransactionCategoryDAO.java b/src/main/java/idatt2106/systemutvikling/sparesti/dao/TransactionCategoryDAO.java index 844e77d..f75a980 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/dao/TransactionCategoryDAO.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/dao/TransactionCategoryDAO.java @@ -1,8 +1,11 @@ package idatt2106.systemutvikling.sparesti.dao; import idatt2106.systemutvikling.sparesti.enums.TransactionCategory; -import jakarta.persistence.*; -import java.time.LocalDateTime; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.Id; +import jakarta.persistence.Table; import java.util.Date; import lombok.AllArgsConstructor; import lombok.Getter; diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/dao/UserDAO.java b/src/main/java/idatt2106/systemutvikling/sparesti/dao/UserDAO.java index 53d64c5..6e0d0c3 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/dao/UserDAO.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/dao/UserDAO.java @@ -1,11 +1,19 @@ package idatt2106.systemutvikling.sparesti.dao; -import jakarta.persistence.*; - +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.JoinTable; +import jakarta.persistence.Lob; +import jakarta.persistence.ManyToMany; +import jakarta.persistence.OneToMany; +import jakarta.persistence.Table; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; - import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @@ -20,29 +28,29 @@ import lombok.Setter; @Table(name = "users") public class UserDAO { - @Id - private String username; - @Column(name = "password_hash") - private String password; - private String email; - private String firstName; - private String lastName; - private LocalDate birthDate; - @Lob - @Column(length=67000) - private byte[] profilePicture; - private Long monthlyIncome; - private Long monthlySavings; - private Long monthlyFixedExpenses; - private Long currentAccount; - private Long savingsAccount; + @Id + private String username; + @Column(name = "password_hash") + private String password; + private String email; + private String firstName; + private String lastName; + private LocalDate birthDate; + @Lob + @Column(length = 67000) + private byte[] profilePicture; + private Long monthlyIncome; + private Long monthlySavings; + private Long monthlyFixedExpenses; + private Long currentAccount; + private Long savingsAccount; - @ManyToMany - @JoinTable(name = "user_achievements", - joinColumns = @JoinColumn(name = "username"), - inverseJoinColumns = @JoinColumn(name = "achievement_id")) - private List<AchievementDAO> achievements = new ArrayList<>(); + @ManyToMany + @JoinTable(name = "user_achievements", + joinColumns = @JoinColumn(name = "username"), + inverseJoinColumns = @JoinColumn(name = "achievement_id")) + private List<AchievementDAO> achievements = new ArrayList<>(); - @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "user") - private List<ManualSavingDAO> manualSavings = new ArrayList<>(); + @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "user") + private List<ManualSavingDAO> manualSavings = new ArrayList<>(); } -- GitLab From 40ea400628843c655ed3d1bd9ec8938885a7f84f Mon Sep 17 00:00:00 2001 From: Tini Tran <tinit@stud.ntnu.no> Date: Fri, 3 May 2024 12:39:09 +0200 Subject: [PATCH 13/13] checkstyled the controller classes --- .../controller/AchievementController.java | 41 +- .../controller/BankAccountController.java | 10 +- .../controller/ChallengeController.java | 508 +++++++++--------- .../controller/MilestoneController.java | 101 ++-- .../controller/MilestoneLogController.java | 72 +-- .../sparesti/controller/TokenController.java | 78 ++- .../controller/TransactionController.java | 47 +- .../sparesti/controller/UserController.java | 31 +- .../controller/UserCredentialsController.java | 75 +-- 9 files changed, 509 insertions(+), 454 deletions(-) diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/controller/AchievementController.java b/src/main/java/idatt2106/systemutvikling/sparesti/controller/AchievementController.java index 3c96ee5..72e36c5 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/controller/AchievementController.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/controller/AchievementController.java @@ -7,15 +7,14 @@ import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; +import java.util.List; +import java.util.logging.Logger; import lombok.AllArgsConstructor; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import java.util.List; -import java.util.logging.Logger; - /** * Controller for handling achievements. */ @@ -28,39 +27,39 @@ public class AchievementController { private final AchievementService achievementService; @Operation( - summary = "Get all locked achievements", - description = "Get all locked achievements for the current user." + summary = "Get all locked achievements", + description = "Get all locked achievements for the current user." ) @ApiResponse( - responseCode = "200", - description = "Locked achievements returned", - content = { - @Content(mediaType = "application/json", - schema = @Schema(implementation = AchievementDTO.class)) - } + responseCode = "200", + description = "Locked achievements returned", + content = { + @Content(mediaType = "application/json", + schema = @Schema(implementation = AchievementDTO.class)) + } ) @GetMapping("/locked") public ResponseEntity<List<AchievementDTO>> getLockedAchievements() { logger.info("Received request to get locked achievements."); return ResponseEntity.ok( - achievementService.getLockedAchievementsAsDTOS(CurrentUserService.getCurrentUsername())); + achievementService.getLockedAchievementsAsDTOS(CurrentUserService.getCurrentUsername())); } @Operation( - summary = "Get all unlocked achievements", - description = "Get all unlocked achievements for the current user." + summary = "Get all unlocked achievements", + description = "Get all unlocked achievements for the current user." ) @ApiResponse( - responseCode = "200", - description = "Unlocked achievements returned", - content = { - @Content(mediaType = "application/json", - schema = @Schema(implementation = AchievementDTO.class)) - } + responseCode = "200", + description = "Unlocked achievements returned", + content = { + @Content(mediaType = "application/json", + schema = @Schema(implementation = AchievementDTO.class)) + } ) @GetMapping("/newUnlocked") public ResponseEntity<List<AchievementDTO>> getNewUnlockedAchievements() { return ResponseEntity.ok( - achievementService.checkForUnlockedAchievements(CurrentUserService.getCurrentUsername())); + achievementService.checkForUnlockedAchievements(CurrentUserService.getCurrentUsername())); } } diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/controller/BankAccountController.java b/src/main/java/idatt2106/systemutvikling/sparesti/controller/BankAccountController.java index fb70eca..165f1d6 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/controller/BankAccountController.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/controller/BankAccountController.java @@ -3,22 +3,20 @@ package idatt2106.systemutvikling.sparesti.controller; import idatt2106.systemutvikling.sparesti.dto.BankAccountDTO; import idatt2106.systemutvikling.sparesti.exceptions.NotFoundInDatabaseException; import idatt2106.systemutvikling.sparesti.mapper.BankAccountMapper; -import idatt2106.systemutvikling.sparesti.service.BankAccountService; import idatt2106.systemutvikling.sparesti.model.BankAccount; -import java.util.logging.Logger; - +import idatt2106.systemutvikling.sparesti.service.BankAccountService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; +import java.util.List; +import java.util.logging.Logger; import lombok.AllArgsConstructor; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import java.util.List; - /** * Controller for handling bank accounts. */ @@ -40,7 +38,7 @@ public class BankAccountController { description = "Bank accounts found", content = { @Content(mediaType = "application/json", - schema = @Schema(implementation = BankAccountDTO.class)) + schema = @Schema(implementation = BankAccountDTO.class)) } ) @GetMapping diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/controller/ChallengeController.java b/src/main/java/idatt2106/systemutvikling/sparesti/controller/ChallengeController.java index 4f676c7..d9990d3 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/controller/ChallengeController.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/controller/ChallengeController.java @@ -11,15 +11,22 @@ import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; +import java.util.logging.Logger; import lombok.AllArgsConstructor; import lombok.NonNull; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - -import java.util.logging.Logger; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; /** * Controller for handling challenges. @@ -29,268 +36,281 @@ import java.util.logging.Logger; @AllArgsConstructor public class ChallengeController { - private final ChallengeService challengeService; - private final MilestoneService milestoneService; - private final Logger logger = Logger.getLogger(ChallengeController.class.getName()); - - @Operation( - summary = "Get all active challenges", - description = "Get all active challenges for the current user" - ) - @ApiResponses(value = { - @ApiResponse( - responseCode = "200", - description = "Challenges found", - content = { - @Content(mediaType = "application/json") - } - )} - ) - @GetMapping("/paginated/active") - @ResponseBody - public ResponseEntity<Page<ChallengeDTO>> getActiveChallenges(@NonNull Pageable pageable) { - return ResponseEntity.ok().body( - challengeService.getActiveChallenges(CurrentUserService.getCurrentUsername(), pageable)); - } - - @Operation( - summary = "Get all inactive challenges", - description = "Get all inactive challenges for the current user" - ) - @ApiResponses(value = { - @ApiResponse( - responseCode = "200", - description = "Challenges found", - content = { - @Content(mediaType = "application/json") - } - )} - ) - @Parameter( - name = "pageable", - description = "The pageable object containing page number and page size", - content = { - @Content(mediaType = "application/json") - } - ) - @GetMapping("/paginated/inactive") - @ResponseBody - public ResponseEntity<Page<ChallengeDTO>> getInactiveChallenges(@NonNull Pageable pageable) { - return ResponseEntity.ok().body( - challengeService.getInactiveChallenges(CurrentUserService.getCurrentUsername(), pageable)); - } + private final ChallengeService challengeService; + private final MilestoneService milestoneService; + private final Logger logger = Logger.getLogger(ChallengeController.class.getName()); - @Operation( - summary = "Get challenge by id", - description = "Get challenge by id" - ) - @ApiResponses(value = { - @ApiResponse( - responseCode = "200", - description = "Challenge found", - content = { - @Content(mediaType = "application/json") - } - ), - @ApiResponse( - responseCode = "403", - description = "Lacking ownership of the specified challenge", - content = @Content - )} - ) - @Parameter( - name = "challengeId", - description = "The id of the challenge", - content = { - @Content(mediaType = "application/json") - } - ) - @GetMapping("/{challengeId}") - @ResponseBody - public ResponseEntity<ChallengeDTO> getChallenge(@PathVariable @NonNull Long challengeId) { + @Operation( + summary = "Get all active challenges", + description = "Get all active challenges for the current user" + ) + @ApiResponses(value = { + @ApiResponse( + responseCode = "200", + description = "Challenges found", + content = { + @Content(mediaType = "application/json") + } + )} + ) + @GetMapping("/paginated/active") + @ResponseBody + public ResponseEntity<Page<ChallengeDTO>> getActiveChallenges(@NonNull Pageable pageable) { + return ResponseEntity.ok().body( + challengeService.getActiveChallenges(CurrentUserService.getCurrentUsername(), pageable)); + } - // Fetch challenge - final ChallengeDTO challenge = challengeService.getChallenge(challengeId); + @Operation( + summary = "Get all inactive challenges", + description = "Get all inactive challenges for the current user" + ) + @ApiResponses(value = { + @ApiResponse( + responseCode = "200", + description = "Challenges found", + content = { + @Content(mediaType = "application/json") + } + )} + ) + @Parameter( + name = "pageable", + description = "The pageable object containing page number and page size", + content = { + @Content(mediaType = "application/json") + } + ) + @GetMapping("/paginated/inactive") + @ResponseBody + public ResponseEntity<Page<ChallengeDTO>> getInactiveChallenges(@NonNull Pageable pageable) { + return ResponseEntity.ok().body( + challengeService.getInactiveChallenges(CurrentUserService.getCurrentUsername(), pageable)); + } - // Verify ownership of the challenge - if (!challenge.getUsername().equals(CurrentUserService.getCurrentUsername())) - return ResponseEntity.status(HttpStatus.FORBIDDEN).build(); + @Operation( + summary = "Get challenge by id", + description = "Get challenge by id" + ) + @ApiResponses(value = { + @ApiResponse( + responseCode = "200", + description = "Challenge found", + content = { + @Content(mediaType = "application/json") + } + ), + @ApiResponse( + responseCode = "403", + description = "Lacking ownership of the specified challenge", + content = @Content + )} + ) + @Parameter( + name = "challengeId", + description = "The id of the challenge", + content = { + @Content(mediaType = "application/json") + } + ) + @GetMapping("/{challengeId}") + @ResponseBody + public ResponseEntity<ChallengeDTO> getChallenge(@PathVariable @NonNull Long challengeId) { - return ResponseEntity.ok().body(challenge); - } + // Fetch challenge + final ChallengeDTO challenge = challengeService.getChallenge(challengeId); - @Operation( - summary = "Create challenge", - description = "Create a new challenge" - ) - @ApiResponses(value = { - @ApiResponse( - responseCode = "201", - description = "Challenge created", - content = { - @Content(mediaType = "application/json", - schema = @Schema(implementation = ChallengeDTO.class)) - } - ), - @ApiResponse( - responseCode = "400", - description = "Invalid input for challenge", - content = @Content - )} - ) - @Parameter( - name = "challengeDTO", - description = "The challenge to be created", - content = { - @Content(mediaType = "application/json", - schema = @Schema(implementation = ChallengeDTO.class)) - } - ) - @PostMapping("/create") - @ResponseBody - public ResponseEntity<ChallengeDTO> createChallenge(@RequestBody @NonNull ChallengeDTO challengeDTO) { - return ResponseEntity.status(HttpStatus.CREATED) - .body(ChallengeMapper.toDTO(challengeService.createChallenge(challengeDTO))); + // Verify ownership of the challenge + if (!challenge.getUsername().equals(CurrentUserService.getCurrentUsername())) { + return ResponseEntity.status(HttpStatus.FORBIDDEN).build(); } - @Operation( - summary = "Activate challenge", - description = "Activate a challenge" - ) - @ApiResponses(value = { - @ApiResponse( - responseCode = "200", - description = "Challenge activated", - content = { - @Content(mediaType = "application/json", - schema = @Schema(implementation = ChallengeDTO.class)) - } - ), - @ApiResponse( - responseCode = "403", - description = "Lacking ownership of the specified challenge", - content = @Content - ), - @ApiResponse( - responseCode = "409", - description = "The challenge is already active", - content = @Content - )} - ) - @Parameter( - name = "challengeId", - description = "The id of the challenge", - content = { - @Content(mediaType = "application/json") - } - ) - @PostMapping("/activate/{challengeId}") - @ResponseBody - public ResponseEntity<ChallengeDTO> activateChallenge(@PathVariable @NonNull Long challengeId) { + return ResponseEntity.ok().body(challenge); + } - // Fetch challenge - final ChallengeDTO challenge = challengeService.getChallenge(challengeId); + @Operation( + summary = "Create challenge", + description = "Create a new challenge" + ) + @ApiResponses(value = { + @ApiResponse( + responseCode = "201", + description = "Challenge created", + content = { + @Content(mediaType = "application/json", + schema = @Schema(implementation = ChallengeDTO.class)) + } + ), + @ApiResponse( + responseCode = "400", + description = "Invalid input for challenge", + content = @Content + )} + ) + @Parameter( + name = "challengeDTO", + description = "The challenge to be created", + content = { + @Content(mediaType = "application/json", + schema = @Schema(implementation = ChallengeDTO.class)) + } + ) + @PostMapping("/create") + @ResponseBody + public ResponseEntity<ChallengeDTO> createChallenge( + @RequestBody @NonNull ChallengeDTO challengeDTO) { + return ResponseEntity.status(HttpStatus.CREATED) + .body(ChallengeMapper.toDTO(challengeService.createChallenge(challengeDTO))); + } - // Verify ownership of the challenge - if (!challenge.getUsername().equals(CurrentUserService.getCurrentUsername())) - return ResponseEntity.status(HttpStatus.FORBIDDEN).build(); + @Operation( + summary = "Activate challenge", + description = "Activate a challenge" + ) + @ApiResponses(value = { + @ApiResponse( + responseCode = "200", + description = "Challenge activated", + content = { + @Content(mediaType = "application/json", + schema = @Schema(implementation = ChallengeDTO.class)) + } + ), + @ApiResponse( + responseCode = "403", + description = "Lacking ownership of the specified challenge", + content = @Content + ), + @ApiResponse( + responseCode = "409", + description = "The challenge is already active", + content = @Content + )} + ) + @Parameter( + name = "challengeId", + description = "The id of the challenge", + content = { + @Content(mediaType = "application/json") + } + ) + @PostMapping("/activate/{challengeId}") + @ResponseBody + public ResponseEntity<ChallengeDTO> activateChallenge(@PathVariable @NonNull Long challengeId) { - // Verify that the challenge is inactive - if (challenge.isActive()) - return ResponseEntity.status(HttpStatus.CONFLICT).build(); + // Fetch challenge + final ChallengeDTO challenge = challengeService.getChallenge(challengeId); - // Return 200 OK - return ResponseEntity.ok().body(ChallengeMapper.toDTO(challengeService.activateChallenge(challengeId))); + // Verify ownership of the challenge + if (!challenge.getUsername().equals(CurrentUserService.getCurrentUsername())) { + return ResponseEntity.status(HttpStatus.FORBIDDEN).build(); } - @Operation( - summary = "Complete challenge", - description = "Complete a challenge and transfer money to milestone, and log the challenge" - ) - @ApiResponses(value = { - @ApiResponse( - responseCode = "200", - description = "Challenge completed", - content = { - @Content(mediaType = "application/json", - schema = @Schema(implementation = String.class) - ) - } - ), - @ApiResponse( - responseCode = "403", - description = "Lacking ownership of the specified challenge or the specified milestone", - content = @Content - )} - ) - @Parameter( - name = "challengeId", - description = "The id of the challenge", - content = { - @Content(mediaType = "application/json", - schema = @Schema(implementation = Long.class) - ) - } - ) - @PostMapping("/complete") - @ResponseBody - public ResponseEntity<String> completeChallenge(@RequestParam("challengeId") @NonNull Long challengeId, - @RequestParam("milestoneId") @NonNull Long milestoneId) { + // Verify that the challenge is inactive + if (challenge.isActive()) { + return ResponseEntity.status(HttpStatus.CONFLICT).build(); + } - // Verify ownership of the requested challenge - if (!challengeService.getChallenge(challengeId).getUsername() - .equals(CurrentUserService.getCurrentUsername())) - return ResponseEntity.status(HttpStatus.FORBIDDEN).body("You are not the owner of this challenge"); + // Return 200 OK + return ResponseEntity.ok() + .body(ChallengeMapper.toDTO(challengeService.activateChallenge(challengeId))); + } - // Verify ownership of the requested milestone - if (!milestoneService.getMilestoneDTOById(milestoneId).getUsername() - .equals(CurrentUserService.getCurrentUsername())) - return ResponseEntity.status(HttpStatus.FORBIDDEN).body("You are not the owner of this milestone"); + @Operation( + summary = "Complete challenge", + description = "Complete a challenge and transfer money to milestone, and log the challenge" + ) + @ApiResponses(value = { + @ApiResponse( + responseCode = "200", + description = "Challenge completed", + content = { + @Content(mediaType = "application/json", + schema = @Schema(implementation = String.class) + ) + } + ), + @ApiResponse( + responseCode = "403", + description = "Lacking ownership of the specified challenge or the specified milestone", + content = @Content + )} + ) + @Parameter( + name = "challengeId", + description = "The id of the challenge", + content = { + @Content(mediaType = "application/json", + schema = @Schema(implementation = Long.class) + ) + } + ) + @PostMapping("/complete") + @ResponseBody + public ResponseEntity<String> completeChallenge( + @RequestParam("challengeId") @NonNull Long challengeId, + @RequestParam("milestoneId") @NonNull Long milestoneId) { - // Perform requested operation - challengeService.completeChallengeForCurrentUser(challengeId, milestoneId); + // Verify ownership of the requested challenge + if (!challengeService.getChallenge(challengeId).getUsername() + .equals(CurrentUserService.getCurrentUsername())) { + return ResponseEntity.status(HttpStatus.FORBIDDEN) + .body("You are not the owner of this challenge"); + } - // Return 200 OK - return ResponseEntity.ok().body("Challenge completed"); + // Verify ownership of the requested milestone + if (!milestoneService.getMilestoneDTOById(milestoneId).getUsername() + .equals(CurrentUserService.getCurrentUsername())) { + return ResponseEntity.status(HttpStatus.FORBIDDEN) + .body("You are not the owner of this milestone"); } - @Operation( - summary = "Delete challenge", - description = "Delete a challenge" - ) - @ApiResponses(value = { - @ApiResponse( - responseCode = "200", - description = "Challenge deleted", - content = { - @Content(mediaType = "application/json", - schema = @Schema(implementation = ChallengeDTO.class)) - } - ), - @ApiResponse( - responseCode = "403", - description = "Challenge with the specified challenge ID is not owned by the authenticated user", - content = @Content - )} - ) - @Parameter( - name = "challengeId", - description = "The id of the challenge", - content = { - @Content(mediaType = "application/json", - schema = @Schema(implementation = ChallengeDTO.class) - )}) - @DeleteMapping("/delete/{challengeId}") - @ResponseBody - public ResponseEntity<String> moveChallengeToLog(@PathVariable @NonNull Long challengeId) { + // Perform requested operation + challengeService.completeChallengeForCurrentUser(challengeId, milestoneId); - // Verify ownership of the challenge - if (!challengeService.getChallenge(challengeId).getUsername().equals(CurrentUserService.getCurrentUsername())) - return ResponseEntity.status(HttpStatus.FORBIDDEN).body("You are not the owner of this challenge"); + // Return 200 OK + return ResponseEntity.ok().body("Challenge completed"); + } - // Perform the service layer function - challengeService.moveChallengeToLog(challengeId); + @Operation( + summary = "Delete challenge", + description = "Delete a challenge" + ) + @ApiResponses(value = { + @ApiResponse( + responseCode = "200", + description = "Challenge deleted", + content = { + @Content(mediaType = "application/json", + schema = @Schema(implementation = ChallengeDTO.class)) + } + ), + @ApiResponse( + responseCode = "403", + description = "Challenge with the specified challenge ID is not owned by the authenticated user", + content = @Content + )} + ) + @Parameter( + name = "challengeId", + description = "The id of the challenge", + content = { + @Content(mediaType = "application/json", + schema = @Schema(implementation = ChallengeDTO.class) + )}) + @DeleteMapping("/delete/{challengeId}") + @ResponseBody + public ResponseEntity<String> moveChallengeToLog(@PathVariable @NonNull Long challengeId) { - return ResponseEntity.ok().body("Challenge deleted"); + // Verify ownership of the challenge + if (!challengeService.getChallenge(challengeId).getUsername() + .equals(CurrentUserService.getCurrentUsername())) { + return ResponseEntity.status(HttpStatus.FORBIDDEN) + .body("You are not the owner of this challenge"); } + + // Perform the service layer function + challengeService.moveChallengeToLog(challengeId); + + return ResponseEntity.ok().body("Challenge deleted"); + } } diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/controller/MilestoneController.java b/src/main/java/idatt2106/systemutvikling/sparesti/controller/MilestoneController.java index 26f9e1a..03778ba 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/controller/MilestoneController.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/controller/MilestoneController.java @@ -4,22 +4,33 @@ import idatt2106.systemutvikling.sparesti.dao.ManualSavingDAO; import idatt2106.systemutvikling.sparesti.dao.MilestoneDAO; import idatt2106.systemutvikling.sparesti.dto.ManualSavingDTO; import idatt2106.systemutvikling.sparesti.dto.MilestoneDTO; -import idatt2106.systemutvikling.sparesti.service.*; +import idatt2106.systemutvikling.sparesti.service.CurrentUserService; +import idatt2106.systemutvikling.sparesti.service.JWTService; +import idatt2106.systemutvikling.sparesti.service.ManualSavingService; +import idatt2106.systemutvikling.sparesti.service.MilestoneService; +import idatt2106.systemutvikling.sparesti.service.TransactionService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; +import java.util.List; +import java.util.logging.Logger; import lombok.AllArgsConstructor; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - -import java.util.List; -import java.util.logging.Logger; +import org.springframework.web.bind.annotation.CrossOrigin; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; /** * Controller for handling milestones. @@ -50,22 +61,23 @@ public class MilestoneController { description = "Milestones found", content = { @Content(mediaType = "application/json", - schema = @Schema(implementation = MilestoneDTO.class)) + schema = @Schema(implementation = MilestoneDTO.class)) } ) @Parameter( - name = "pageable", - description = "Pageable object for pagination", - required = true, - content = { - @Content(mediaType = "application/json", - schema = @Schema(implementation = Pageable.class)) - } + name = "pageable", + description = "Pageable object for pagination", + required = true, + content = { + @Content(mediaType = "application/json", + schema = @Schema(implementation = Pageable.class)) + } ) @GetMapping("/user/paginated") public ResponseEntity<Page<MilestoneDTO>> getUserMilestonesPaginated(Pageable pageable) { logger.info("Received request to get paginated list of user milestones."); - return ResponseEntity.ok(milestoneService.getActiveMilestonesDTOsByUsernamePaginated(CurrentUserService.getCurrentUsername(), pageable)); + return ResponseEntity.ok(milestoneService.getActiveMilestonesDTOsByUsernamePaginated( + CurrentUserService.getCurrentUsername(), pageable)); } @Operation( @@ -77,13 +89,14 @@ public class MilestoneController { description = "Milestones found", content = { @Content(mediaType = "application/json", - schema = @Schema(implementation = MilestoneDTO.class)) + schema = @Schema(implementation = MilestoneDTO.class)) } ) @GetMapping("/user") public ResponseEntity<List<MilestoneDTO>> getUserMilestones() { logger.info("Received request to get list of user milestones."); - return ResponseEntity.ok().body(milestoneService.getActiveMilestonesDTOsByUsername(CurrentUserService.getCurrentUsername())); + return ResponseEntity.ok().body(milestoneService.getActiveMilestonesDTOsByUsername( + CurrentUserService.getCurrentUsername())); } @Operation( @@ -95,7 +108,7 @@ public class MilestoneController { description = "Milestones found", content = { @Content(mediaType = "application/json", - schema = @Schema(implementation = MilestoneDTO.class)) + schema = @Schema(implementation = MilestoneDTO.class)) } ) @Parameter( @@ -104,7 +117,7 @@ public class MilestoneController { required = true, content = { @Content(mediaType = "application/json", - schema = @Schema(implementation = Pageable.class)) + schema = @Schema(implementation = Pageable.class)) } ) @PostMapping("/create") @@ -122,7 +135,7 @@ public class MilestoneController { description = "Milestone found", content = { @Content(mediaType = "application/json", - schema = @Schema(implementation = MilestoneDTO.class)) + schema = @Schema(implementation = MilestoneDTO.class)) } ) @Parameter( @@ -131,7 +144,7 @@ public class MilestoneController { required = true, content = { @Content(mediaType = "application/json", - schema = @Schema(implementation = Long.class)) + schema = @Schema(implementation = Long.class)) } ) @GetMapping("/{id}") @@ -149,7 +162,7 @@ public class MilestoneController { description = "Milestone completed", content = { @Content(mediaType = "application/json", - schema = @Schema(implementation = MilestoneDTO.class)) + schema = @Schema(implementation = MilestoneDTO.class)) } ) @Parameter( @@ -158,7 +171,7 @@ public class MilestoneController { required = true, content = { @Content(mediaType = "application/json", - schema = @Schema(implementation = Long.class)) + schema = @Schema(implementation = Long.class)) } ) @PostMapping("/complete") @@ -176,7 +189,7 @@ public class MilestoneController { description = "Milestone updated", content = { @Content(mediaType = "application/json", - schema = @Schema(implementation = MilestoneDTO.class)) + schema = @Schema(implementation = MilestoneDTO.class)) } ) @Parameter( @@ -185,13 +198,14 @@ public class MilestoneController { required = true, content = { @Content(mediaType = "application/json", - schema = @Schema(implementation = MilestoneDTO.class)) + schema = @Schema(implementation = MilestoneDTO.class)) } ) @PostMapping("/update") public ResponseEntity<MilestoneDTO> updateMilestone(@RequestBody MilestoneDTO milestoneDTO) { logger.info("Received request to update milestone."); - return ResponseEntity.ok(milestoneService.updateMilestoneDTO(CurrentUserService.getCurrentUsername(), milestoneDTO)); + return ResponseEntity.ok( + milestoneService.updateMilestoneDTO(CurrentUserService.getCurrentUsername(), milestoneDTO)); } @Operation( @@ -203,7 +217,7 @@ public class MilestoneController { description = "Milestone edited", content = { @Content(mediaType = "application/json", - schema = @Schema(implementation = MilestoneDTO.class)) + schema = @Schema(implementation = MilestoneDTO.class)) } ) @Parameter( @@ -212,13 +226,14 @@ public class MilestoneController { required = true, content = { @Content(mediaType = "application/json", - schema = @Schema(implementation = MilestoneDTO.class)) + schema = @Schema(implementation = MilestoneDTO.class)) } ) @PutMapping("/edit") - public ResponseEntity<MilestoneDTO> editMilestone(@RequestBody MilestoneDTO milestoneDTO){ + public ResponseEntity<MilestoneDTO> editMilestone(@RequestBody MilestoneDTO milestoneDTO) { logger.info("Received request to edit milestone"); - return ResponseEntity.ok(milestoneService.editMilestone(CurrentUserService.getCurrentUsername(), milestoneDTO)); + return ResponseEntity.ok( + milestoneService.editMilestone(CurrentUserService.getCurrentUsername(), milestoneDTO)); } @Operation( @@ -235,7 +250,7 @@ public class MilestoneController { required = true, content = { @Content(mediaType = "application/json", - schema = @Schema(implementation = Long.class)) + schema = @Schema(implementation = Long.class)) } ) @DeleteMapping("/delete/{id}") @@ -259,36 +274,44 @@ public class MilestoneController { required = true, content = { @Content(mediaType = "application/json", - schema = @Schema(implementation = ManualSavingDTO.class)) + schema = @Schema(implementation = ManualSavingDTO.class)) } ) @PostMapping("/inject") public ResponseEntity<?> manualInjectionIntoMilestone(@RequestBody ManualSavingDTO dto) { // Create new record - ManualSavingDAO manualSavingDAO = manualSavingService.registerNewManualSavingDAO(dto.getMilestoneId(), dto.getAmount(), CurrentUserService.getCurrentUsername()); + ManualSavingDAO manualSavingDAO = manualSavingService.registerNewManualSavingDAO( + dto.getMilestoneId(), dto.getAmount(), CurrentUserService.getCurrentUsername()); // If unsuccessful, return UNPROCESSABLE_ENTITY - if (manualSavingDAO == null) - return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body("Failed to register record for manual saving"); + if (manualSavingDAO == null) { + return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY) + .body("Failed to register record for manual saving"); + } // Update milestone - MilestoneDAO milestoneDAO = milestoneService.increaseMilestonesCurrentSum(dto.getMilestoneId(), dto.getAmount()); + MilestoneDAO milestoneDAO = milestoneService.increaseMilestonesCurrentSum(dto.getMilestoneId(), + dto.getAmount()); // If unsuccessful, cleanup and return UNPROCESSABLE_ENTITY if (milestoneDAO == null) { manualSavingService.removeManualSavingEntry(manualSavingDAO); // Cleanup - return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body("Failed to update milestone"); + return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY) + .body("Failed to update milestone"); } // Perform transaction - boolean transactionSuccessful = transactionService.createSavingsTransferForCurrentUser(dto.getAmount()); + boolean transactionSuccessful = transactionService.createSavingsTransferForCurrentUser( + dto.getAmount()); // If unsuccessful, cleanup and return UNPROCESSABLE_ENTITY if (!transactionSuccessful) { - milestoneService.decreaseMilestonesCurrentSum(dto.getMilestoneId(), dto.getAmount()); // Cleanup + milestoneService.decreaseMilestonesCurrentSum(dto.getMilestoneId(), + dto.getAmount()); // Cleanup manualSavingService.removeManualSavingEntry(manualSavingDAO); // Cleanup - return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body("Failed to perform transaction"); + return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY) + .body("Failed to perform transaction"); } logger.info("User performed manual saving towards milestone."); diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/controller/MilestoneLogController.java b/src/main/java/idatt2106/systemutvikling/sparesti/controller/MilestoneLogController.java index ddf0440..90f7658 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/controller/MilestoneLogController.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/controller/MilestoneLogController.java @@ -9,13 +9,16 @@ import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; +import java.util.logging.Logger; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - -import java.util.logging.Logger; +import org.springframework.web.bind.annotation.CrossOrigin; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; /** * Controller for handling milestone logs. @@ -36,53 +39,54 @@ public class MilestoneLogController { } @Operation( - summary = "Get user milestones", - description = "Get all milestones for the current user" + summary = "Get user milestones", + description = "Get all milestones for the current user" ) @ApiResponse( - responseCode = "200", - description = "Milestones found", - content = { - @Content(mediaType = "application/json", - schema = @Schema(implementation = MilestoneDTO.class)) - } + responseCode = "200", + description = "Milestones found", + content = { + @Content(mediaType = "application/json", + schema = @Schema(implementation = MilestoneDTO.class)) + } ) @Parameter( - name = "pageable", - description = "The pageable object", - content = { - @Content(mediaType = "application/json", - schema = @Schema(implementation = Pageable.class) - ) - } + name = "pageable", + description = "The pageable object", + content = { + @Content(mediaType = "application/json", + schema = @Schema(implementation = Pageable.class) + ) + } ) @GetMapping("/user") public ResponseEntity<Page<MilestoneDTO>> getUserMilestones(Pageable pageable) { String username = CurrentUserService.getCurrentUsername(); logger.info("Received request to get user milestones."); - return ResponseEntity.ok(milestoneLogService.getMilestoneLogsByUsernamePaginated(username, pageable)); + return ResponseEntity.ok( + milestoneLogService.getMilestoneLogsByUsernamePaginated(username, pageable)); } @Operation( - summary = "Get milestone by id", - description = "Get a milestone by its id" + summary = "Get milestone by id", + description = "Get a milestone by its id" ) @ApiResponse( - responseCode = "200", - description = "Milestone found", - content = { - @Content(mediaType = "application/json", - schema = @Schema(implementation = MilestoneDTO.class)) - } + responseCode = "200", + description = "Milestone found", + content = { + @Content(mediaType = "application/json", + schema = @Schema(implementation = MilestoneDTO.class)) + } ) @Parameter( - name = "milestoneLogId", - description = "The id of the milestone", - content = { - @Content(mediaType = "application/json", - schema = @Schema(implementation = Long.class) - ) - } + name = "milestoneLogId", + description = "The id of the milestone", + content = { + @Content(mediaType = "application/json", + schema = @Schema(implementation = Long.class) + ) + } ) @GetMapping("/id") public ResponseEntity<MilestoneDTO> getMilestoneLogById(@RequestBody Long milestoneLogId) { diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/controller/TokenController.java b/src/main/java/idatt2106/systemutvikling/sparesti/controller/TokenController.java index 6586c73..45a0cf6 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/controller/TokenController.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/controller/TokenController.java @@ -1,13 +1,8 @@ package idatt2106.systemutvikling.sparesti.controller; -import com.auth0.jwt.JWT; -import com.auth0.jwt.algorithms.Algorithm; import idatt2106.systemutvikling.sparesti.dto.UserCredentialsDTO; import idatt2106.systemutvikling.sparesti.repository.UserRepository; -import idatt2106.systemutvikling.sparesti.security.SecretsConfig; -import idatt2106.systemutvikling.sparesti.security.SecurityConfig; import idatt2106.systemutvikling.sparesti.service.CurrentUserService; -import idatt2106.systemutvikling.sparesti.service.CustomerServiceInterface; import idatt2106.systemutvikling.sparesti.service.JWTService; import idatt2106.systemutvikling.sparesti.service.PasswordService; import io.swagger.v3.oas.annotations.Operation; @@ -15,15 +10,17 @@ import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; +import java.util.logging.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - -import java.time.Duration; -import java.time.Instant; -import java.util.logging.Logger; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; /** * Controller for handling tokens. @@ -40,30 +37,30 @@ public class TokenController { @Autowired public TokenController(PasswordService passwordService, JWTService jwtService, - UserRepository userRepository) { + UserRepository userRepository) { this.passwordService = passwordService; this.jwtService = jwtService; this.userRepository = userRepository; } @Operation( - summary = "Login", - description = "Login with username and password" + summary = "Login", + description = "Login with username and password" ) @ApiResponses(value = { - @ApiResponse( - responseCode = "201", - description = "Login successful", - content = { - @Content(mediaType = "application/json", - schema = @Schema(implementation = String.class)) - } - ), - @ApiResponse( - responseCode = "401", - description = "Access denied, wrong credentials", - content = @Content - ) + @ApiResponse( + responseCode = "201", + description = "Login successful", + content = { + @Content(mediaType = "application/json", + schema = @Schema(implementation = String.class)) + } + ), + @ApiResponse( + responseCode = "401", + description = "Access denied, wrong credentials", + content = @Content + ) }) @PostMapping(value = "/login") @ResponseStatus(value = HttpStatus.CREATED) @@ -75,26 +72,26 @@ public class TokenController { if (userRepository.findByUsername(loginRequest.getUsername()) == null) { logger.warning("Access denied, wrong credentials: User does not exist."); return ResponseEntity.status(HttpStatus.UNAUTHORIZED) - .body("Access denied, wrong credentials: User does not exist."); + .body("Access denied, wrong credentials: User does not exist."); } } catch (Exception e) { logger.warning("Access denied, wrong credentials: " + e.getMessage()); return ResponseEntity.status(HttpStatus.UNAUTHORIZED) - .body("Access denied, wrong credentials"); + .body("Access denied, wrong credentials"); } try { success = passwordService.correctPassword(loginRequest.getUsername(), - loginRequest.getPassword()); + loginRequest.getPassword()); } catch (Exception e) { logger.warning("Access denied, wrong credentials: " + e.getMessage()); return ResponseEntity.status(HttpStatus.UNAUTHORIZED) - .body("Access denied, wrong credentials"); + .body("Access denied, wrong credentials"); } if (!success) { return ResponseEntity.status(HttpStatus.UNAUTHORIZED) - .body("Access denied, wrong credentials"); + .body("Access denied, wrong credentials"); } String token = jwtService.generateToken(loginRequest.getUsername()); @@ -103,23 +100,24 @@ public class TokenController { } @Operation( - summary = "Refresh token", - description = "Refresh" + summary = "Refresh token", + description = "Refresh" ) @ApiResponse( - responseCode = "201", - description = "Token refreshed", - content = { - @Content(mediaType = "application/json", - schema = @Schema(implementation = String.class)) - } + responseCode = "201", + description = "Token refreshed", + content = { + @Content(mediaType = "application/json", + schema = @Schema(implementation = String.class)) + } ) @GetMapping(value = "/refresh") @ResponseStatus(value = HttpStatus.CREATED) public ResponseEntity<String> refreshToken() { logger.info("Received request to refresh token."); - return ResponseEntity.ok().body(jwtService.generateToken(CurrentUserService.getCurrentUsername())); + return ResponseEntity.ok() + .body(jwtService.generateToken(CurrentUserService.getCurrentUsername())); } } diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/controller/TransactionController.java b/src/main/java/idatt2106/systemutvikling/sparesti/controller/TransactionController.java index 2910a88..e923425 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/controller/TransactionController.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/controller/TransactionController.java @@ -9,13 +9,13 @@ import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; +import java.util.List; import lombok.AllArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - -import java.util.Date; -import java.util.List; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; /** * Controller for handling transactions. @@ -28,34 +28,35 @@ public class TransactionController { private final TransactionService transactionService; @Operation( - summary = "Get latest transactions", - description = "Get the last 30 days of transactions for the current user" + summary = "Get latest transactions", + description = "Get the last 30 days of transactions for the current user" ) @ApiResponses(value = { - @ApiResponse( - responseCode = "200", - description = "Transactions found", - content = { - @Content(mediaType = "application/json", - schema = @Schema(implementation = TransactionDTO.class)) - } - ), - @ApiResponse( - responseCode = "404", - description = "No transactions found", - content = @Content - ) + @ApiResponse( + responseCode = "200", + description = "Transactions found", + content = { + @Content(mediaType = "application/json", + schema = @Schema(implementation = TransactionDTO.class)) + } + ), + @ApiResponse( + responseCode = "404", + description = "No transactions found", + content = @Content + ) }) @GetMapping("/30-day-expenses") public ResponseEntity<List<TransactionDTO>> getLatestExpenses_LastMonth_Categorized() { List<Transaction> transactions = transactionService.getLatestExpensesForCurrentUser_CheckingAccount_Categorized(); - if (transactions == null) + if (transactions == null) { return ResponseEntity.status(HttpStatus.NOT_FOUND).build(); + } List<TransactionDTO> body = transactions - .stream() - .map(TransactionMapper::toDTO) - .toList(); + .stream() + .map(TransactionMapper::toDTO) + .toList(); return ResponseEntity.ok().body(body); } diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/controller/UserController.java b/src/main/java/idatt2106/systemutvikling/sparesti/controller/UserController.java index 2fd28d2..103a68e 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/controller/UserController.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/controller/UserController.java @@ -1,21 +1,26 @@ package idatt2106.systemutvikling.sparesti.controller; import idatt2106.systemutvikling.sparesti.dto.UserDTO; - -import java.util.logging.Logger; - +import idatt2106.systemutvikling.sparesti.service.CurrentUserService; +import idatt2106.systemutvikling.sparesti.service.UserService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import jakarta.transaction.Transactional; -import idatt2106.systemutvikling.sparesti.service.CurrentUserService; +import java.util.logging.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; -import idatt2106.systemutvikling.sparesti.service.UserService; +import org.springframework.web.bind.annotation.CrossOrigin; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; /** * Controller for handling user information. @@ -59,7 +64,9 @@ public class UserController { logger.info("Received request to get total savings for all users."); Long savings = userService.getTotalAmountSavedByAllUsers(); - if (savings == null) return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); + if (savings == null) { + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); + } return ResponseEntity.ok(savings); } @@ -89,7 +96,9 @@ public class UserController { logger.info("Received request to get user total savings."); Long savings = userService.getTotalAmountSavedByUser(CurrentUserService.getCurrentUsername()); - if (savings == null) return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); + if (savings == null) { + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); + } return ResponseEntity.ok(savings); } @@ -141,14 +150,14 @@ public class UserController { boolean deleted = userService.deleteCurrentUser(); return deleted ? - ResponseEntity.ok().body("User deleted successfully") : - ResponseEntity.status(HttpStatus.NOT_FOUND).body("No user found"); + ResponseEntity.ok().body("User deleted successfully") : + ResponseEntity.status(HttpStatus.NOT_FOUND).body("No user found"); } /** * Method for updating user information. * - * @param token the token + * @param token the token * @param updatedUserDTO the updated user information * @return response entity */ diff --git a/src/main/java/idatt2106/systemutvikling/sparesti/controller/UserCredentialsController.java b/src/main/java/idatt2106/systemutvikling/sparesti/controller/UserCredentialsController.java index b12bde5..461cb83 100644 --- a/src/main/java/idatt2106/systemutvikling/sparesti/controller/UserCredentialsController.java +++ b/src/main/java/idatt2106/systemutvikling/sparesti/controller/UserCredentialsController.java @@ -3,17 +3,19 @@ package idatt2106.systemutvikling.sparesti.controller; import idatt2106.systemutvikling.sparesti.dto.UserCredentialsDTO; import idatt2106.systemutvikling.sparesti.dto.UserDTO; import idatt2106.systemutvikling.sparesti.service.UserService; - -import java.util.logging.Logger; - import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; +import java.util.logging.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.CrossOrigin; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; /** * Controller for handling user credentials. @@ -32,25 +34,25 @@ public class UserCredentialsController { } @Operation( - summary = "Create user", - description = "Create a new user" + summary = "Create user", + description = "Create a new user" ) @ApiResponse( - responseCode = "200", - description = "User created", - content = { - @Content(mediaType = "application/json", - schema = @Schema(implementation = UserDTO.class)) - } + responseCode = "200", + description = "User created", + content = { + @Content(mediaType = "application/json", + schema = @Schema(implementation = UserDTO.class)) + } ) @Parameter( - name = "user", - description = "The user to create", - content = { - @Content(mediaType = "application/json", - schema = @Schema(implementation = UserCredentialsDTO.class) - ) - } + name = "user", + description = "The user to create", + content = { + @Content(mediaType = "application/json", + schema = @Schema(implementation = UserCredentialsDTO.class) + ) + } ) @RequestMapping("/create") public ResponseEntity<UserDTO> createUser(@RequestBody UserCredentialsDTO user) { @@ -59,31 +61,32 @@ public class UserCredentialsController { } @Operation( - summary = "Update password", - description = "Update the password for a user" + summary = "Update password", + description = "Update the password for a user" ) @ApiResponse( - responseCode = "200", - description = "Password updated", - content = { - @Content(mediaType = "application/json", - schema = @Schema(implementation = String.class) - ) - } + responseCode = "200", + description = "Password updated", + content = { + @Content(mediaType = "application/json", + schema = @Schema(implementation = String.class) + ) + } ) @Parameter( - name = "userCredentialsDTO", - description = "The user credentials to update", - content = { - @Content(mediaType = "application/json", - schema = @Schema(implementation = UserCredentialsDTO.class) - ) - } + name = "userCredentialsDTO", + description = "The user credentials to update", + content = { + @Content(mediaType = "application/json", + schema = @Schema(implementation = UserCredentialsDTO.class) + ) + } ) @PutMapping("/updatePassword") public ResponseEntity<String> updatePassword(@RequestBody UserCredentialsDTO userCredentialsDTO) { logger.info( - "Received request to update password for user with username: " + userCredentialsDTO.getUsername() + "."); + "Received request to update password for user with username: " + + userCredentialsDTO.getUsername() + "."); return ResponseEntity.ok(userService.updatePassword(userCredentialsDTO)); } -- GitLab