Skip to content

Commit c66d36b

Browse files
committed
794: refactor to use optional
1 parent 82932b7 commit c66d36b

14 files changed

Lines changed: 196 additions & 123 deletions

File tree

src/main/java/org/patinanetwork/codebloom/api/admin/AdminController.java

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -98,11 +98,12 @@ public ResponseEntity<ApiResponder<Empty>> createLeaderboard(
9898
// BE VERY CAREFUL WITH THIS ROUTE. IT WILL DEACTIVATE THE PREVIOUS LEADERBOARD
9999
// (however, it should be in a recoverable state, as it just gets toggled to be
100100
// deactivated, not deleted).
101-
Leaderboard currentLeaderboard = leaderboardRepository.getRecentLeaderboardMetadata();
102-
if (currentLeaderboard != null) {
101+
Optional<Leaderboard> currentLeaderboard = leaderboardRepository.getRecentLeaderboardMetadata();
102+
if (currentLeaderboard.isPresent()) {
103103
discordClubManager.sendLeaderboardCompletedDiscordMessageToAllClubs();
104104
leaderboardManager.generateAchievementsForAllWinners();
105-
leaderboardRepository.disableLeaderboardById(currentLeaderboard.getId());
105+
leaderboardRepository.disableLeaderboardById(
106+
currentLeaderboard.get().getId());
106107
}
107108

108109
OffsetDateTime shouldExpireBy = StandardizedOffsetDateTime.normalize(newLeaderboardBody.getShouldExpireBy());
@@ -117,8 +118,8 @@ public ResponseEntity<ApiResponder<Empty>> createLeaderboard(
117118

118119
Leaderboard newLeaderboard = Leaderboard.builder()
119120
.name(name)
120-
.shouldExpireBy(shouldExpireBy != null ? shouldExpireBy.toLocalDateTime() : null)
121-
.syntaxHighlightingLanguage(newLeaderboardBody.getSyntaxHighlightingLanguage())
121+
.shouldExpireBy(Optional.ofNullable(shouldExpireBy != null ? shouldExpireBy.toLocalDateTime() : null))
122+
.syntaxHighlightingLanguage(Optional.ofNullable(newLeaderboardBody.getSyntaxHighlightingLanguage()))
122123
.build();
123124

124125
leaderboardRepository.addNewLeaderboard(newLeaderboard);

src/main/java/org/patinanetwork/codebloom/api/auth/security/CustomAuthenticationSuccessHandler.java

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import java.time.LocalDateTime;
1010
import java.util.List;
1111
import java.util.Map;
12+
import java.util.Optional;
1213
import java.util.stream.Collectors;
1314
import net.dv8tion.jda.api.entities.Guild;
1415
import net.dv8tion.jda.api.entities.Member;
@@ -111,8 +112,9 @@ public void onAuthenticationSuccess(
111112
.discordName(discordName)
112113
.build();
113114
userRepository.createUser(newUser);
114-
Leaderboard leaderboard = leaderboardRepository.getRecentLeaderboardMetadata();
115-
leaderboardRepository.addUserToLeaderboard(newUser.getId(), leaderboard.getId());
115+
Optional<Leaderboard> leaderboard = leaderboardRepository.getRecentLeaderboardMetadata();
116+
leaderboardRepository.addUserToLeaderboard(
117+
newUser.getId(), leaderboard.get().getId());
116118
existingUser = newUser;
117119
}
118120

src/main/java/org/patinanetwork/codebloom/api/leaderboard/LeaderboardController.java

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import io.swagger.v3.oas.annotations.tags.Tag;
1010
import jakarta.servlet.http.HttpServletRequest;
1111
import java.util.List;
12+
import java.util.Optional;
1213
import org.patinanetwork.codebloom.common.components.LeaderboardManager;
1314
import org.patinanetwork.codebloom.common.db.models.leaderboard.Leaderboard;
1415
import org.patinanetwork.codebloom.common.db.models.user.UserWithScore;
@@ -72,15 +73,15 @@ public ResponseEntity<ApiResponder<LeaderboardDto>> getLeaderboardMetadataByLead
7273
final @PathVariable String leaderboardId, final HttpServletRequest request) {
7374
FakeLag.sleep(650);
7475

75-
Leaderboard leaderboardData = leaderboardManager.getLeaderboardMetadata(leaderboardId);
76+
Optional<Leaderboard> leaderboardData = leaderboardManager.getLeaderboardMetadata(leaderboardId);
7677

7778
if (leaderboardData == null) {
7879
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Leaderboard cannot be found or does not exist.");
7980
}
8081

8182
return ResponseEntity.ok()
8283
.body(ApiResponder.success(
83-
"Leaderboard metadata found!", LeaderboardDto.fromLeaderboard(leaderboardData)));
84+
"Leaderboard metadata found!", LeaderboardDto.fromLeaderboard(leaderboardData.get())));
8485
}
8586

8687
@GetMapping("/{leaderboardId}/user/all")
@@ -177,11 +178,12 @@ public ResponseEntity<ApiResponder<LeaderboardDto>> getCurrentLeaderboardMetadat
177178
final HttpServletRequest request) {
178179
FakeLag.sleep(650);
179180

180-
Leaderboard leaderboardData = leaderboardManager.getLeaderboardMetadata(
181-
leaderboardRepository.getRecentLeaderboardMetadata().getId());
181+
Optional<Leaderboard> leaderboardData = leaderboardManager.getLeaderboardMetadata(
182+
leaderboardRepository.getRecentLeaderboardMetadata().get().getId());
182183

183184
return ResponseEntity.ok()
184-
.body(ApiResponder.success("All leaderboards found!", LeaderboardDto.fromLeaderboard(leaderboardData)));
185+
.body(ApiResponder.success(
186+
"All leaderboards found!", LeaderboardDto.fromLeaderboard(leaderboardData.get())));
185187
}
186188

187189
@GetMapping("/current/user/all")
@@ -257,7 +259,7 @@ public ResponseEntity<ApiResponder<Page<Indexed<UserWithScoreDto>>>> getCurrentL
257259
.build();
258260

259261
String currentLeaderboardId =
260-
leaderboardRepository.getRecentLeaderboardMetadata().getId();
262+
leaderboardRepository.getRecentLeaderboardMetadata().get().getId();
261263
Page<Indexed<UserWithScoreDto>> createdPage =
262264
leaderboardManager.getLeaderboardUsers(currentLeaderboardId, options, globalIndex);
263265

@@ -278,11 +280,13 @@ public ResponseEntity<ApiResponder<UserWithScoreDto>> getUserCurrentLeaderboardF
278280
final HttpServletRequest request, @PathVariable final String userId) {
279281
FakeLag.sleep(650);
280282

281-
Leaderboard leaderboardData = leaderboardRepository.getRecentLeaderboardMetadata();
283+
Optional<Leaderboard> leaderboardData = leaderboardRepository.getRecentLeaderboardMetadata();
282284

283285
// we do not support point of time in this endpoint currently
284286
UserWithScore user = userRepository.getUserWithScoreByIdAndLeaderboardId(
285-
userId, leaderboardData.getId(), UserFilterOptions.builder().build());
287+
userId,
288+
leaderboardData.get().getId(),
289+
UserFilterOptions.builder().build());
286290

287291
// if (user == null) {
288292
// return
@@ -336,7 +340,7 @@ public ResponseEntity<ApiResponder<Indexed<UserWithScoreDto>>> getUserCurrentLea
336340
AuthenticationObject authenticationObject = protector.validateSession(request);
337341
String userId = authenticationObject.getUser().getId();
338342

339-
Leaderboard leaderboardData = leaderboardRepository.getRecentLeaderboardMetadata();
343+
Optional<Leaderboard> leaderboardData = leaderboardRepository.getRecentLeaderboardMetadata();
340344

341345
if (leaderboardData == null) {
342346
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "No active leaderboard found.");
@@ -346,7 +350,9 @@ public ResponseEntity<ApiResponder<Indexed<UserWithScoreDto>>> getUserCurrentLea
346350

347351
if (!patina && !hunter && !nyu && !baruch && !rpi && !gwc && !sbu && !ccny && !columbia && !cornell && !bmcc) {
348352
// Use global ranking when no filters are applied
349-
userWithRank = leaderboardRepository.getGlobalRankedUserById(leaderboardData.getId(), userId);
353+
userWithRank = leaderboardRepository
354+
.getGlobalRankedUserById(leaderboardData.get().getId(), userId)
355+
.get();
350356
} else {
351357
// Use filtered ranking when filters are applied
352358
LeaderboardFilterOptions options = LeaderboardFilterOptions.builder()
@@ -362,7 +368,9 @@ public ResponseEntity<ApiResponder<Indexed<UserWithScoreDto>>> getUserCurrentLea
362368
.cornell(cornell)
363369
.bmcc(bmcc)
364370
.build();
365-
userWithRank = leaderboardRepository.getFilteredRankedUserById(leaderboardData.getId(), userId, options);
371+
userWithRank = leaderboardRepository
372+
.getFilteredRankedUserById(leaderboardData.get().getId(), userId, options)
373+
.get();
366374
}
367375

368376
if (userWithRank == null) {

src/main/java/org/patinanetwork/codebloom/common/components/DiscordClubManager.java

Lines changed: 21 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -79,15 +79,16 @@ private String buildTopUsersSection(final List<UserWithScore> users, final boole
7979
*/
8080
private void sendLeaderboardCompletedDiscordMessage(final DiscordClub club) {
8181
try {
82-
Leaderboard currentLeaderboard = leaderboardRepository.getRecentLeaderboardMetadata();
82+
Optional<Leaderboard> currentLeaderboard = leaderboardRepository.getRecentLeaderboardMetadata();
8383

8484
LeaderboardFilterOptions options = LeaderboardFilterGenerator.builderWithTag(club.getTag())
8585
.page(1)
8686
.pageSize(5)
8787
.build();
8888

89-
List<UserWithScore> users = LeaderboardUtils.filterUsersWithPoints(
90-
leaderboardRepository.getLeaderboardUsersById(currentLeaderboard.getId(), options));
89+
List<UserWithScore> users =
90+
LeaderboardUtils.filterUsersWithPoints(leaderboardRepository.getLeaderboardUsersById(
91+
currentLeaderboard.get().getId(), options));
9192

9293
String topUsersSection = buildTopUsersSection(users, true);
9394
String headerText = users.isEmpty()
@@ -115,7 +116,7 @@ private void sendLeaderboardCompletedDiscordMessage(final DiscordClub club) {
115116
topUsersSection,
116117
club.getName(),
117118
serverUrlUtils.getUrl(),
118-
currentLeaderboard.getId(),
119+
currentLeaderboard.get().getId(),
119120
club.getTag().name().toLowerCase(),
120121
serverUrlUtils.getUrl());
121122

@@ -132,7 +133,7 @@ private void sendLeaderboardCompletedDiscordMessage(final DiscordClub club) {
132133
.channelId(Long.valueOf(channelId.get()))
133134
.description(description)
134135
.title("🏆🏆🏆 %s - Final Leaderboard Score for %s"
135-
.formatted(currentLeaderboard.getName(), club.getName()))
136+
.formatted(currentLeaderboard.get().getName(), club.getName()))
136137
.footerText("Codebloom - LeetCode Leaderboard for %s".formatted(club.getName()))
137138
.footerIcon("%s/favicon.ico".formatted(serverUrlUtils.getUrl()))
138139
.color(new Color(69, 129, 103))
@@ -204,24 +205,29 @@ public MessageCreateData buildLeaderboardMessageForClub(String guildId, boolean
204205
DiscordClub club =
205206
discordClubRepository.getDiscordClubByGuildId(guildId).orElseThrow();
206207

207-
Leaderboard currentLeaderboard = leaderboardRepository.getRecentLeaderboardMetadata();
208+
Optional<Leaderboard> currentLeaderboard = leaderboardRepository.getRecentLeaderboardMetadata();
208209

209210
LeaderboardFilterOptions options = LeaderboardFilterGenerator.builderWithTag(club.getTag())
210211
.page(1)
211212
.pageSize(5)
212213
.build();
213214

214-
List<UserWithScore> users = LeaderboardUtils.filterUsersWithPoints(
215-
leaderboardRepository.getLeaderboardUsersById(currentLeaderboard.getId(), options));
215+
List<UserWithScore> users =
216+
LeaderboardUtils.filterUsersWithPoints(leaderboardRepository.getLeaderboardUsersById(
217+
currentLeaderboard.get().getId(), options));
216218

217-
LocalDateTime shouldExpireByTime =
218-
Optional.ofNullable(currentLeaderboard.getShouldExpireBy()).orElse(StandardizedLocalDateTime.now());
219+
Optional<LocalDateTime> shouldExpireByTime = currentLeaderboard.get().getShouldExpireBy();
219220

220-
Duration remaining = Duration.between(StandardizedLocalDateTime.now(), shouldExpireByTime);
221+
long daysLeft = 0;
222+
long hoursLeft = 0;
223+
long minutesLeft = 0;
221224

222-
long daysLeft = remaining.toDays();
223-
long hoursLeft = remaining.toHours() % 24;
224-
long minutesLeft = remaining.toMinutes() % 60;
225+
if (shouldExpireByTime.isPresent()) {
226+
Duration remaining = Duration.between(StandardizedLocalDateTime.now(), shouldExpireByTime.get());
227+
daysLeft = remaining.toDays();
228+
hoursLeft = remaining.toHours() % 24;
229+
minutesLeft = remaining.toMinutes() % 60;
230+
}
225231

226232
String topUsersSection = buildTopUsersSection(users, false);
227233
String headerText = "Here is %s on the LeetCode leaderboard for our very own members!"
@@ -259,7 +265,7 @@ public MessageCreateData buildLeaderboardMessageForClub(String guildId, boolean
259265

260266
MessageEmbed embed = new EmbedBuilder()
261267
.setTitle("%s - %s Leaderboard Update for %s"
262-
.formatted(currentLeaderboard.getName(), isWeekly ? "Weekly" : "", club.getName()))
268+
.formatted(currentLeaderboard.get().getName(), isWeekly ? "Weekly" : "", club.getName()))
263269
.setDescription(description)
264270
.setFooter(
265271
"Codebloom - LeetCode Leaderboard for %s".formatted(club.getName()),

src/main/java/org/patinanetwork/codebloom/common/components/LeaderboardManager.java

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package org.patinanetwork.codebloom.common.components;
22

33
import java.util.List;
4+
import java.util.Optional;
45
import lombok.extern.slf4j.Slf4j;
56
import org.patinanetwork.codebloom.common.db.models.achievements.Achievement;
67
import org.patinanetwork.codebloom.common.db.models.achievements.AchievementPlaceEnum;
@@ -49,9 +50,9 @@ private String calculatePlaceString(final int place) {
4950

5051
public void generateAchievementsForAllWinners() {
5152
log.info("generating achievements for all winners...");
52-
Leaderboard currentLeaderboard = leaderboardRepository.getRecentLeaderboardMetadata();
53+
Optional<Leaderboard> currentLeaderboard = leaderboardRepository.getRecentLeaderboardMetadata();
5354

54-
if (currentLeaderboard == null) {
55+
if (currentLeaderboard.isEmpty()) {
5556
return;
5657
}
5758

@@ -61,7 +62,7 @@ public void generateAchievementsForAllWinners() {
6162
for (var pair : filterOptsAndTags) {
6263
log.info("on leaderboard for {}", pair.getRight().getResolvedName());
6364
List<Indexed<UserWithScore>> users = leaderboardRepository.getRankedIndexedLeaderboardUsersById(
64-
currentLeaderboard.getId(), pair.getLeft());
65+
currentLeaderboard.get().getId(), pair.getLeft());
6566
List<UserWithScore> usersWithPoints = LeaderboardUtils.filterUsersWithPoints(
6667
users.stream().map(Indexed::getItem).toList());
6768
List<UserWithScore> winners = usersWithPoints.subList(0, maxWinners(usersWithPoints.size()));
@@ -77,35 +78,41 @@ public void generateAchievementsForAllWinners() {
7778
.leaderboard(pair.getRight())
7879
.title(String.format(
7980
"%s - %s - %s Place",
80-
currentLeaderboard.getName(), pair.getRight().getResolvedName(), placeString))
81+
currentLeaderboard.get().getName(),
82+
pair.getRight().getResolvedName(),
83+
placeString))
8184
.build();
8285
achievementRepository.createAchievement(achievement);
8386
}
8487
}
8588

8689
// handle global leaderboard
8790
List<Indexed<UserWithScore>> users = leaderboardRepository.getGlobalRankedIndexedLeaderboardUsersById(
88-
currentLeaderboard.getId(), LeaderboardFilterOptions.DEFAULT);
91+
currentLeaderboard.get().getId(), LeaderboardFilterOptions.DEFAULT);
8992
List<UserWithScore> usersWithPoints = LeaderboardUtils.filterUsersWithPoints(
9093
users.stream().map(Indexed::getItem).toList());
9194
List<UserWithScore> winners = usersWithPoints.subList(0, maxWinners(usersWithPoints.size()));
9295

9396
for (int i = 0; i < winners.size(); i++) {
9497
int place = i + 1;
95-
log.info("on leaderboard for {} for global winner #{}", currentLeaderboard.getName(), place);
98+
log.info(
99+
"on leaderboard for {} for global winner #{}",
100+
currentLeaderboard.get().getName(),
101+
place);
96102
String placeString = calculatePlaceString(place);
97103
UserWithScore user = winners.get(i);
98104
Achievement achievement = Achievement.builder()
99105
.userId(user.getId())
100106
.place(AchievementPlaceEnum.fromInteger(place))
101107
.leaderboard(null)
102-
.title(String.format("%s - %s Place", currentLeaderboard.getName(), placeString))
108+
.title(String.format(
109+
"%s - %s Place", currentLeaderboard.get().getName(), placeString))
103110
.build();
104111
achievementRepository.createAchievement(achievement);
105112
}
106113
}
107114

108-
public Leaderboard getLeaderboardMetadata(final String id) {
115+
public Optional<Leaderboard> getLeaderboardMetadata(final String id) {
109116
return leaderboardRepository.getLeaderboardMetadataById(id);
110117
}
111118

0 commit comments

Comments
 (0)