Skip to content

Commit 701e893

Browse files
authored
Clean up variable names and use final where appropriate (#17)
1 parent 00123fb commit 701e893

File tree

12 files changed

+69
-72
lines changed

12 files changed

+69
-72
lines changed

src/main/java/org/openpodcastapi/opa/advice/GlobalExceptionHandler.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ public ResponseEntity<ValidationErrorResponse> handleValidationException(MethodA
4444
.map(fe -> new ValidationErrorResponse.FieldError(fe.getField(), fe.getDefaultMessage()))
4545
.toList();
4646

47-
ValidationErrorResponse body = new ValidationErrorResponse(
47+
var body = new ValidationErrorResponse(
4848
Instant.now(),
4949
HttpStatus.BAD_REQUEST.value(),
5050
errors

src/main/java/org/openpodcastapi/opa/advice/GlobalModelAttributeAdvice.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,14 @@ public class GlobalModelAttributeAdvice {
1616
@ModelAttribute
1717
public void addAuthenticationFlag(Model model) {
1818
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
19-
boolean isAuthenticated = authentication != null && authentication.isAuthenticated()
19+
var isAuthenticated = authentication != null && authentication.isAuthenticated()
2020
&& !"anonymousUser".equals(authentication.getPrincipal());
2121
model.addAttribute("isAuthenticated", isAuthenticated);
2222
}
2323

2424
@ModelAttribute
2525
public void addUserDetails(Principal principal, Model model) {
26-
String username = principal != null ? principal.getName() : "Guest";
26+
var username = principal != null ? principal.getName() : "Guest";
2727
model.addAttribute("username", username);
2828
}
2929
}

src/main/java/org/openpodcastapi/opa/auth/JwtAccessDeniedHandler.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ public void handle(HttpServletRequest request,
2727
// Set content type to JSON
2828
response.setContentType("application/json");
2929

30-
AuthDTO.ErrorMessageDTO message = new AuthDTO.ErrorMessageDTO("Forbidden", "You do not have permission to access this resource");
30+
final var message = new AuthDTO.ErrorMessageDTO("Forbidden", "You do not have permission to access this resource");
3131

3232
response.getWriter().write(objectMapper.writeValueAsString(message));
3333
}

src/main/java/org/openpodcastapi/opa/auth/JwtAuthenticationFilter.java

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
4242
/// @throws EntityNotFoundException if no matching user is found
4343
private static UsernamePasswordAuthenticationToken getUsernamePasswordAuthenticationToken(UserEntity userEntity) throws EntityNotFoundException {
4444
// Create a new CustomUserDetails entity with the fetched user
45-
CustomUserDetails userDetails =
45+
final var userDetails =
4646
new CustomUserDetails(userEntity.getId(),
4747
userEntity.getUuid(),
4848
userEntity.getUsername(),
@@ -68,8 +68,8 @@ private static UsernamePasswordAuthenticationToken getUsernamePasswordAuthentica
6868
protected void doFilterInternal(HttpServletRequest req, @Nonnull HttpServletResponse res, @Nonnull FilterChain chain)
6969
throws ServletException, IOException {
7070

71-
String header = req.getHeader(HttpHeaders.AUTHORIZATION);
72-
SecretKey key = Keys.hmacShaKeyFor(jwtSecret.getBytes(StandardCharsets.UTF_8));
71+
final String header = req.getHeader(HttpHeaders.AUTHORIZATION);
72+
final SecretKey key = Keys.hmacShaKeyFor(jwtSecret.getBytes(StandardCharsets.UTF_8));
7373

7474
// If the value is missing or is not a valid bearer token, filter the response
7575
if (header == null || !header.startsWith("Bearer ")) {
@@ -78,25 +78,24 @@ protected void doFilterInternal(HttpServletRequest req, @Nonnull HttpServletResp
7878
}
7979

8080
// Check that a valid Bearer token is in the headers
81-
String token = header.substring(7);
81+
final var token = header.substring(7);
8282

8383
try {
8484
// Extract the claims from the JWT
85-
Claims claims = Jwts.parser()
85+
final Claims claims = Jwts.parser()
8686
.verifyWith(key)
8787
.build()
8888
.parseSignedClaims(token)
8989
.getPayload();
9090

9191
// Extract the user's UUID from the claims
92-
String userUuid = claims.getSubject();
93-
UUID parsedUuid = UUID.fromString(userUuid);
92+
final var parsedUuid = UUID.fromString(claims.getSubject());
9493

9594
// Fetch the matching user
96-
UserEntity userEntity = repository.getUserByUuid(parsedUuid).orElseThrow(() -> new EntityNotFoundException("No matching user found"));
95+
final var userEntity = repository.getUserByUuid(parsedUuid).orElseThrow(() -> new EntityNotFoundException("No matching user found"));
9796

9897
// Create a user
99-
UsernamePasswordAuthenticationToken authentication = getUsernamePasswordAuthenticationToken(userEntity);
98+
final UsernamePasswordAuthenticationToken authentication = getUsernamePasswordAuthenticationToken(userEntity);
10099

101100
SecurityContextHolder.getContext().setAuthentication(authentication);
102101
} catch (Exception e) {

src/main/java/org/openpodcastapi/opa/controllers/api/AuthController.java

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -37,31 +37,31 @@ public ResponseEntity<AuthDTO.LoginSuccessResponse> login(@RequestBody @NotNull
3737
SecurityContextHolder.getContext().setAuthentication(authentication);
3838

3939
// Fetch the user record from the database
40-
UserEntity userEntity = userRepository.findByUsername(loginRequest.username()).orElseThrow(() -> new EntityNotFoundException("No userEntity with username " + loginRequest.username() + " found"));
40+
final var userEntity = userRepository.findByUsername(loginRequest.username()).orElseThrow(() -> new EntityNotFoundException("No userEntity with username " + loginRequest.username() + " found"));
4141

4242
// Generate the access and refresh tokens for the user
43-
String accessToken = tokenService.generateAccessToken(userEntity);
44-
String refreshToken = tokenService.generateRefreshToken(userEntity);
43+
final String accessToken = tokenService.generateAccessToken(userEntity);
44+
final String refreshToken = tokenService.generateRefreshToken(userEntity);
4545

4646
// Format the tokens and expiration time into a DTO
47-
AuthDTO.LoginSuccessResponse response = new AuthDTO.LoginSuccessResponse(accessToken, refreshToken, String.valueOf(tokenService.getExpirationTime()));
47+
final var response = new AuthDTO.LoginSuccessResponse(accessToken, refreshToken, String.valueOf(tokenService.getExpirationTime()));
4848

4949
return ResponseEntity.ok(response);
5050
}
5151

5252
// === Refresh token endpoint ===
5353
@PostMapping("/api/auth/refresh")
5454
public ResponseEntity<AuthDTO.RefreshTokenResponse> getRefreshToken(@RequestBody @NotNull AuthDTO.RefreshTokenRequest refreshTokenRequest) {
55-
UserEntity targetUserEntity = userRepository.findByUsername(refreshTokenRequest.username()).orElseThrow(() -> new EntityNotFoundException("No user with username " + refreshTokenRequest.username() + " found"));
55+
final var targetUserEntity = userRepository.findByUsername(refreshTokenRequest.username()).orElseThrow(() -> new EntityNotFoundException("No user with username " + refreshTokenRequest.username() + " found"));
5656

5757
// Validate the existing refresh token
58-
UserEntity userEntity = tokenService.validateRefreshToken(refreshTokenRequest.refreshToken(), targetUserEntity);
58+
final UserEntity userEntity = tokenService.validateRefreshToken(refreshTokenRequest.refreshToken(), targetUserEntity);
5959

6060
// Generate new access token
61-
String newAccessToken = tokenService.generateAccessToken(userEntity);
61+
final String newAccessToken = tokenService.generateAccessToken(userEntity);
6262

6363
// Format the token and expiration time into a DTO
64-
AuthDTO.RefreshTokenResponse response = new AuthDTO.RefreshTokenResponse(newAccessToken, String.valueOf(tokenService.getExpirationTime()));
64+
final var response = new AuthDTO.RefreshTokenResponse(newAccessToken, String.valueOf(tokenService.getExpirationTime()));
6565

6666
return ResponseEntity.ok(response);
6767
}

src/main/java/org/openpodcastapi/opa/security/TokenService.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ public UserEntity validateRefreshToken(String rawToken, UserEntity userEntity) {
9393
token.getExpiresAt().isAfter(Instant.now())) {
9494
// Update the expiry date on the refresh token
9595
token.setExpiresAt(Instant.now().plusSeconds(refreshTokenDays * 24 * 3600));
96-
RefreshTokenEntity updatedToken = repository.save(token);
96+
final RefreshTokenEntity updatedToken = repository.save(token);
9797

9898
// Return the user to confirm the token is valid
9999
return updatedToken.getUser();

src/main/java/org/openpodcastapi/opa/subscription/SubscriptionRestController.java

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -58,10 +58,10 @@ public ResponseEntity<SubscriptionDTO.SubscriptionPageDTO> getAllSubscriptionsFo
5858
public ResponseEntity<SubscriptionDTO.UserSubscriptionDTO> getSubscriptionByUuid(@PathVariable String uuid, @AuthenticationPrincipal CustomUserDetails user) throws EntityNotFoundException {
5959
// Attempt to validate the UUID value from the provided string
6060
// If the value is invalid, the GlobalExceptionHandler will throw a 400.
61-
UUID uuidValue = UUID.fromString(uuid);
61+
final var uuidValue = UUID.fromString(uuid);
6262

6363
// Fetch the subscription, throw an EntityNotFoundException if this fails
64-
SubscriptionDTO.UserSubscriptionDTO dto = service.getUserSubscriptionBySubscriptionUuid(uuidValue, user.id());
64+
final var dto = service.getUserSubscriptionBySubscriptionUuid(uuidValue, user.id());
6565

6666
// Return the mapped subscriptionEntity entry
6767
return new ResponseEntity<>(dto, HttpStatus.OK);
@@ -79,9 +79,9 @@ public ResponseEntity<SubscriptionDTO.UserSubscriptionDTO> getSubscriptionByUuid
7979
public ResponseEntity<SubscriptionDTO.UserSubscriptionDTO> unsubscribeUserFromFeed(@PathVariable String uuid, @AuthenticationPrincipal CustomUserDetails user) {
8080
// Attempt to validate the UUID value from the provided string
8181
// If the value is invalid, the GlobalExceptionHandler will throw a 400.
82-
UUID uuidValue = UUID.fromString(uuid);
82+
final var uuidValue = UUID.fromString(uuid);
8383

84-
SubscriptionDTO.UserSubscriptionDTO dto = service.unsubscribeUserFromFeed(uuidValue, user.id());
84+
final var dto = service.unsubscribeUserFromFeed(uuidValue, user.id());
8585

8686
return new ResponseEntity<>(dto, HttpStatus.OK);
8787
}
@@ -93,7 +93,7 @@ public ResponseEntity<SubscriptionDTO.UserSubscriptionDTO> unsubscribeUserFromFe
9393
@PostMapping
9494
@PreAuthorize("hasRole('USER')")
9595
public ResponseEntity<SubscriptionDTO.BulkSubscriptionResponseDTO> createUserSubscriptions(@RequestBody List<SubscriptionDTO.SubscriptionCreateDTO> request, @AuthenticationPrincipal CustomUserDetails user) {
96-
SubscriptionDTO.BulkSubscriptionResponseDTO response = service.addSubscriptions(request, user.id());
96+
final var response = service.addSubscriptions(request, user.id());
9797

9898
if (response.success().isEmpty() && !response.failure().isEmpty()) {
9999
// If all requests failed, return a 400 error

src/main/java/org/openpodcastapi/opa/subscription/SubscriptionService.java

Lines changed: 20 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
import jakarta.persistence.EntityNotFoundException;
44
import lombok.RequiredArgsConstructor;
55
import lombok.extern.log4j.Log4j2;
6-
import org.openpodcastapi.opa.user.UserEntity;
76
import org.openpodcastapi.opa.user.UserRepository;
87
import org.springframework.data.domain.Page;
98
import org.springframework.data.domain.Pageable;
@@ -29,7 +28,7 @@ public class SubscriptionService {
2928
/// @param dto the [SubscriptionDTO.SubscriptionCreateDTO] containing the subscription data
3029
/// @return the fetched or created [SubscriptionEntity]
3130
protected SubscriptionEntity fetchOrCreateSubscription(SubscriptionDTO.SubscriptionCreateDTO dto) {
32-
UUID feedUuid = UUID.fromString(dto.uuid());
31+
final var feedUuid = UUID.fromString(dto.uuid());
3332
return subscriptionRepository
3433
.findByUuid(feedUuid)
3534
.orElseGet(() -> {
@@ -47,11 +46,11 @@ protected SubscriptionEntity fetchOrCreateSubscription(SubscriptionDTO.Subscript
4746
@Transactional(readOnly = true)
4847
public SubscriptionDTO.UserSubscriptionDTO getUserSubscriptionBySubscriptionUuid(UUID subscriptionUuid, Long userId) {
4948
log.debug("Fetching subscription {} for userEntity {}", subscriptionUuid, userId);
50-
UserSubscriptionEntity subscription = userSubscriptionRepository.findByUserIdAndSubscriptionUuid(userId, subscriptionUuid)
49+
final var userSubscription = userSubscriptionRepository.findByUserIdAndSubscriptionUuid(userId, subscriptionUuid)
5150
.orElseThrow(() -> new EntityNotFoundException("subscription not found for userEntity"));
5251

5352
log.debug("Subscription {} for userEntity {} found", subscriptionUuid, userId);
54-
return userSubscriptionMapper.toDto(subscription);
53+
return userSubscriptionMapper.toDto(userSubscription);
5554
}
5655

5756
/// Gets all subscriptions for the authenticated userEntity
@@ -61,7 +60,8 @@ public SubscriptionDTO.UserSubscriptionDTO getUserSubscriptionBySubscriptionUuid
6160
@Transactional(readOnly = true)
6261
public Page<SubscriptionDTO.UserSubscriptionDTO> getAllSubscriptionsForUser(Long userId, Pageable pageable) {
6362
log.debug("Fetching subscriptions for {}", userId);
64-
return userSubscriptionRepository.findAllByUserId(userId, pageable)
63+
return userSubscriptionRepository
64+
.findAllByUserId(userId, pageable)
6565
.map(userSubscriptionMapper::toDto);
6666
}
6767

@@ -83,16 +83,17 @@ public Page<SubscriptionDTO.UserSubscriptionDTO> getAllActiveSubscriptionsForUse
8383
/// @return a [SubscriptionDTO.UserSubscriptionDTO] representation of the subscription link
8484
/// @throws EntityNotFoundException if no matching user is found
8585
protected SubscriptionDTO.UserSubscriptionDTO persistUserSubscription(SubscriptionEntity subscriptionEntity, Long userId) {
86-
UserEntity userEntity = userRepository.findById(userId).orElseThrow(() -> new EntityNotFoundException("userEntity not found"));
86+
final var userEntity = userRepository.findById(userId).orElseThrow(() -> new EntityNotFoundException("user not found"));
87+
8788
log.debug("{}", userEntity);
8889

89-
UserSubscriptionEntity newSubscription = userSubscriptionRepository.findByUserIdAndSubscriptionUuid(userId, subscriptionEntity.getUuid()).orElseGet(() -> {
90+
final var newSubscription = userSubscriptionRepository.findByUserIdAndSubscriptionUuid(userId, subscriptionEntity.getUuid()).orElseGet(() -> {
9091
log.debug("Creating new subscription for user {} and subscription {}", userId, subscriptionEntity.getUuid());
91-
UserSubscriptionEntity createdSubscription = new UserSubscriptionEntity();
92-
createdSubscription.setIsSubscribed(true);
93-
createdSubscription.setUser(userEntity);
94-
createdSubscription.setSubscription(subscriptionEntity);
95-
return userSubscriptionRepository.save(createdSubscription);
92+
final var createdSubscriptionEntity = new UserSubscriptionEntity();
93+
createdSubscriptionEntity.setIsSubscribed(true);
94+
createdSubscriptionEntity.setUser(userEntity);
95+
createdSubscriptionEntity.setSubscription(subscriptionEntity);
96+
return userSubscriptionRepository.save(createdSubscriptionEntity);
9697
});
9798

9899
newSubscription.setIsSubscribed(true);
@@ -111,19 +112,19 @@ public SubscriptionDTO.BulkSubscriptionResponseDTO addSubscriptions(List<Subscri
111112

112113
log.info("{}", requests);
113114

114-
for (SubscriptionDTO.SubscriptionCreateDTO dto : requests) {
115+
for (var subscriptionObject : requests) {
115116
try {
116117
// Fetch or create the subscription object to subscribe the user to
117-
SubscriptionEntity subscriptionEntity = this.fetchOrCreateSubscription(dto);
118+
final var subscriptionEntity = this.fetchOrCreateSubscription(subscriptionObject);
118119
log.debug("{}", subscriptionEntity);
119120
// If all is successful, persist the new UserSubscriptionEntity and add a UserSubscriptionDTO to the successes list
120121
successes.add(persistUserSubscription(subscriptionEntity, userId));
121122
} catch (IllegalArgumentException _) {
122123
// If the UUID of the feed is invalid, add a new failure to the failures list
123-
failures.add(new SubscriptionDTO.SubscriptionFailureDTO(dto.uuid(), dto.feedUrl(), "invalid UUID format"));
124+
failures.add(new SubscriptionDTO.SubscriptionFailureDTO(subscriptionObject.uuid(), subscriptionObject.feedUrl(), "invalid UUID format"));
124125
} catch (Exception e) {
125126
// If another failure is encountered, add it to the failures list
126-
failures.add(new SubscriptionDTO.SubscriptionFailureDTO(dto.uuid(), dto.feedUrl(), e.getMessage()));
127+
failures.add(new SubscriptionDTO.SubscriptionFailureDTO(subscriptionObject.uuid(), subscriptionObject.feedUrl(), e.getMessage()));
127128
}
128129
}
129130

@@ -138,10 +139,10 @@ public SubscriptionDTO.BulkSubscriptionResponseDTO addSubscriptions(List<Subscri
138139
/// @return a [SubscriptionDTO.UserSubscriptionDTO] containing the updated object
139140
@Transactional
140141
public SubscriptionDTO.UserSubscriptionDTO unsubscribeUserFromFeed(UUID feedUUID, Long userId) {
141-
UserSubscriptionEntity subscription = userSubscriptionRepository.findByUserIdAndSubscriptionUuid(userId, feedUUID)
142+
final var userSubscriptionEntity = userSubscriptionRepository.findByUserIdAndSubscriptionUuid(userId, feedUUID)
142143
.orElseThrow(() -> new EntityNotFoundException("no subscription found"));
143144

144-
subscription.setIsSubscribed(false);
145-
return userSubscriptionMapper.toDto(userSubscriptionRepository.save(subscription));
145+
userSubscriptionEntity.setIsSubscribed(false);
146+
return userSubscriptionMapper.toDto(userSubscriptionRepository.save(userSubscriptionEntity));
146147
}
147148
}

src/main/java/org/openpodcastapi/opa/user/UserRepository.java

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,7 @@ public interface UserRepository extends JpaRepository<UserEntity, Long> {
1212

1313
Optional<UserEntity> getUserByUsername(String username);
1414

15-
Boolean existsUserByUsername(String username);
16-
17-
Boolean existsUserByEmail(String email);
15+
Boolean existsUserByEmailOrUsername(String email, String username);
1816

1917
Optional<UserEntity> findByUsername(String username);
2018
}

0 commit comments

Comments
 (0)