Skip to content

Commit

Permalink
Merge branch 'refs/heads/refactor/improve-validation' into develop
Browse files Browse the repository at this point in the history
# Conflicts:
#	src/main/java/edu/ntnu/idatt2105/quizapp/exception/RestExceptionHandler.java
#	src/main/java/edu/ntnu/idatt2105/quizapp/services/UserService.java
  • Loading branch information
Ramtin Forouzandehjoo Samavat committed Apr 5, 2024
2 parents 1142d33 + 323236e commit 4362c64
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 40 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public class UserController {
public ResponseEntity<Void> editUserInformation(@RequestBody EditUserDto editUserDto,
Principal principal) {
String username = principal.getName();
log.info("Editing user information for user {}. {}", username, editUserDto);
log.info("Editing user information for user {}.", username);
userService.editUser(username, editUserDto);
log.info("User information for {} successfully updated.", username);
return new ResponseEntity<>(HttpStatus.OK);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,14 +70,17 @@ public ResponseEntity<ErrorResponse> handleUsernameNotFoundException(Exception e
}

/**
* The method handles generic exceptions.
* The method handles unexpected exceptions that may occur during the execution of the application.
*
* @param ex The exception to handle.
* @return ResponseEntity containing the ErrorResponse with HTTP status code 500 (INTERNAL_SERVER_ERROR).
*/
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleGenericException(Exception ex) {
return buildResponseEntityWithErrorResponse(ex, HttpStatus.INTERNAL_SERVER_ERROR);
public ResponseEntity<ErrorResponse> handleUnexpectedException(Exception ex) {
log.error("{}: {}", ex.getClass().getSimpleName(), ex.getMessage());
log.debug("Stack Trace:", ex);
ErrorResponse errorResponse = new ErrorResponse("Internal Server Error");
return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}

/**
Expand All @@ -96,13 +99,12 @@ public ResponseEntity<ErrorResponse> handleOptimisticLockingFailureException(Exc
* The method builds a ResponseEntity containing an ErrorResponse based on the given
* exception and HTTP status.
*
* @param ex The exception to handle.
* @param ex The exception to handle.
* @param status The HTTP status to set in the response.
* @return ResponseEntity containing the ErrorResponse with the specified HTTP status.
*/
private ResponseEntity<ErrorResponse> buildResponseEntityWithErrorResponse(
Exception ex, HttpStatus status) {

Exception ex, HttpStatus status) {
log.error("{}: {}", ex.getClass().getSimpleName(), ex.getMessage());
ErrorResponse errorResponse = new ErrorResponse(ex.getMessage());
return new ResponseEntity<>(errorResponse, status);
Expand Down
74 changes: 41 additions & 33 deletions src/main/java/edu/ntnu/idatt2105/quizapp/services/UserService.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
* It uses the {@link UserRepository} to perform the operations in the database.
*
* @author Ramtin Samavat
* @version 1.0
* @version 1.0
*/
@Service
@RequiredArgsConstructor
Expand All @@ -47,37 +47,45 @@ public class UserService {
/**
* The method updates the user information of an existing user in the database.
*
* @param username The username of the user to be updated.
* @param username The username of the user to be updated.
* @param editUserDto The DTO containing the new user information.
* @throws UsernameNotFoundException If the user is not found in the database.
* @throws UsernameNotFoundException If the user is not found in the database.
* @throws EmailAlreadyExistsException If the email already exists.
*/
public void editUser(@NonNull String username, @NonNull EditUserDto editUserDto)
throws UsernameNotFoundException, IllegalArgumentException {

User user = userRepository.findUserByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException(
"User with username " + username + " not found."));
throws UsernameNotFoundException, IllegalArgumentException {

UserValidator.validateEmail(editUserDto.getNewEmail());
User user = userRepository.findUserByUsername(username).orElseThrow(() ->
new UsernameNotFoundException("User with username " + username + " not found."));

Optional<User> existingUserWithEmail = userRepository
.findUserByEmail(editUserDto.getNewEmail());
.findUserByEmail(editUserDto.getNewEmail());

if (existingUserWithEmail.isPresent() && !existingUserWithEmail
.get().getUsername().equals(user.getUsername())) {

.get().getUsername().equals(user.getUsername())) {
throw new EmailAlreadyExistsException();
}

UserValidator.validatePassword(editUserDto.getNewPassword());
UserValidator.validateName(editUserDto.getNewName());
UserValidator.validateSurname(editUserDto.getNewSurname());
if (!editUserDto.getNewEmail().isBlank()) {
UserValidator.validateEmail(editUserDto.getNewEmail());
user.setEmail(editUserDto.getNewEmail());
}

if (!editUserDto.getNewPassword().isBlank()) {
UserValidator.validatePassword(editUserDto.getNewPassword());
user.setPassword(passwordEncoder.encode(editUserDto.getNewPassword()));
}

if (!editUserDto.getNewName().isBlank()) {
UserValidator.validateName(editUserDto.getNewName());
user.setName(editUserDto.getNewName());
}

if (!editUserDto.getNewSurname().isBlank()) {
UserValidator.validateSurname(editUserDto.getNewSurname());
user.setSurName(editUserDto.getNewSurname());
}

user.setEmail(editUserDto.getNewEmail());
user.setPassword(passwordEncoder.encode(editUserDto.getNewPassword()));
user.setName(editUserDto.getNewName());
user.setSurName(editUserDto.getNewSurname());
userRepository.save(user);
}

Expand All @@ -90,29 +98,29 @@ public void editUser(@NonNull String username, @NonNull EditUserDto editUserDto)
*/
public UserDetailsDto getUserDetails(@NonNull String username) throws UsernameNotFoundException {
User user = userRepository.findUserByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException(
"User with username " + username + " not found."));
.orElseThrow(() -> new UsernameNotFoundException(
"User with username " + username + " not found."));

return UserDetailsDto.builder()
.email(user.getEmail())
.name(user.getName())
.surname(user.getSurName())
.build();
.email(user.getEmail())
.name(user.getName())
.surname(user.getSurName())
.build();

}

/**
* Finds a list of public profile DTOs based on the search parameter.
*
* @param searchString the search parameter.
* @param pageable the pageable used to find a specified page.
* @param pageable the pageable used to find a specified page.
* @return a list of public profile DTOs based on the search parameter.
*/
public List<PublicUserInformationDTO> findPublicProfilesFromUsername(
String searchString, Pageable pageable) {
String searchString, Pageable pageable) {

return userRepository.findAllByUsernameContainingIgnoreCase(searchString, pageable)
.stream().map(userMapper::mapToPublicUserInformation).toList();
.stream().map(userMapper::mapToPublicUserInformation).toList();
}

/**
Expand All @@ -133,8 +141,8 @@ public UserStatsDto getUserStats(@NonNull String username) {
List<QuizAttempt> quizAttempts = quizAttemptRepository.findQuizAttemptByUser_Username(username);

List<QuizAttempt> attemptsLastDays = quizAttempts.stream()
.filter(attempt -> attempt.getTimestamp().isAfter(sevenDaysAgo))
.toList();
.filter(attempt -> attempt.getTimestamp().isAfter(sevenDaysAgo))
.toList();

for (QuizAttempt attempt : attemptsLastDays) {
LocalDate attemptDate = attempt.getTimestamp().atStartOfDay().toLocalDate();
Expand All @@ -146,9 +154,9 @@ public UserStatsDto getUserStats(@NonNull String username) {
int totalScore = quizAttempts.stream().mapToInt(QuizAttempt::getScore).sum();

return UserStatsDto.builder()
.quizAttemptsLastSevenDays(attemptsLastSevenDays)
.totalQuizAttempts(totalAttempts)
.totalScore(totalScore).build();
.quizAttemptsLastSevenDays(attemptsLastSevenDays)
.totalQuizAttempts(totalAttempts)
.totalScore(totalScore).build();
}

/**
Expand Down

0 comments on commit 4362c64

Please sign in to comment.