Skip to content

Commit 4242744

Browse files
committed
use Spring JDBC for QOTW repositories
1 parent 0efa241 commit 4242744

27 files changed

+532
-540
lines changed

src/main/java/net/javadiscord/javabot/systems/notification/NotificationService.java

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,13 @@
99
import net.javadiscord.javabot.data.config.BotConfig;
1010
import net.javadiscord.javabot.data.h2db.DbHelper;
1111
import net.javadiscord.javabot.systems.qotw.QOTWPointsService;
12+
import net.javadiscord.javabot.systems.qotw.submissions.dao.QOTWSubmissionRepository;
1213

1314
import org.jetbrains.annotations.Contract;
1415
import org.jetbrains.annotations.NotNull;
1516
import org.springframework.stereotype.Service;
1617

18+
import java.util.concurrent.ExecutorService;
1719
import java.util.function.Function;
1820

1921
/**
@@ -25,6 +27,8 @@ public class NotificationService {
2527
private final QOTWPointsService qotwPointsService;
2628
private final BotConfig botConfig;
2729
private final DbHelper dbHelper;
30+
private final ExecutorService asyncPool;
31+
private final QOTWSubmissionRepository qotwSubmissionRepository;
2832

2933
@Contract("_ -> new")
3034
public @NotNull GuildNotificationService withGuild(Guild guild) {
@@ -37,11 +41,11 @@ public class NotificationService {
3741
}
3842

3943
public @NotNull QOTWGuildNotificationService withQOTW(Guild guild) {
40-
return new QOTWGuildNotificationService(this, guild, dbHelper);
44+
return new QOTWGuildNotificationService(this, guild, asyncPool, qotwSubmissionRepository);
4145
}
4246

4347
public @NotNull QOTWNotificationService withQOTW(Guild guild, User user) {
44-
return new QOTWNotificationService(this, qotwPointsService, user, guild, botConfig.getSystems(), dbHelper);
48+
return new QOTWNotificationService(this, qotwPointsService, user, guild, botConfig.getSystems(), asyncPool, qotwSubmissionRepository);
4549
}
4650

4751
/**

src/main/java/net/javadiscord/javabot/systems/notification/QOTWGuildNotificationService.java

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,18 @@
88
import net.dv8tion.jda.api.entities.MessageEmbed;
99
import net.dv8tion.jda.api.entities.ThreadChannel;
1010
import net.dv8tion.jda.api.entities.User;
11-
import net.javadiscord.javabot.data.h2db.DbHelper;
1211
import net.javadiscord.javabot.systems.qotw.submissions.SubmissionStatus;
1312
import net.javadiscord.javabot.systems.qotw.submissions.dao.QOTWSubmissionRepository;
1413
import net.javadiscord.javabot.systems.qotw.submissions.model.QOTWSubmission;
14+
import net.javadiscord.javabot.util.ExceptionLogger;
15+
1516
import org.jetbrains.annotations.NotNull;
17+
import org.springframework.dao.DataAccessException;
1618

1719
import javax.annotation.Nullable;
1820
import java.time.Instant;
1921
import java.util.Optional;
22+
import java.util.concurrent.ExecutorService;
2023

2124
/**
2225
* Handles all sorts of guild qotw notifications.
@@ -29,7 +32,8 @@ public class QOTWGuildNotificationService {
2932
*/
3033
protected final NotificationService notificationService;
3134
private final Guild guild;
32-
private final DbHelper dbHelper;
35+
private final ExecutorService asyncPool;
36+
private final QOTWSubmissionRepository qotwSubmissionRepository;
3337

3438
/**
3539
* Sends the executed action, performed on a QOTW submission thread, to the {@link Guild}s log channel.
@@ -40,12 +44,16 @@ public class QOTWGuildNotificationService {
4044
* @param reasons The reasons for taking this action.
4145
*/
4246
public void sendSubmissionActionNotification(User reviewedBy, ThreadChannel submissionThread, SubmissionStatus status, @Nullable String... reasons) {
43-
dbHelper.doDaoAction(QOTWSubmissionRepository::new, dao -> {
44-
Optional<QOTWSubmission> submissionOptional = dao.getSubmissionByThreadId(submissionThread.getIdLong());
45-
submissionOptional.ifPresent(submission -> guild.getJDA().retrieveUserById(submission.getAuthorId()).queue(author -> {
46-
notificationService.withGuild(guild).sendToModerationLog(c -> c.sendMessageEmbeds(buildSubmissionActionEmbed(author, submissionThread, reviewedBy, status, reasons)));
47-
log.info("{} {} {}'s QOTW Submission{}", reviewedBy.getAsTag(), status.name().toLowerCase(), author.getAsTag(), reasons != null ? " for: " + String.join(", ", reasons) : ".");
48-
}));
47+
asyncPool.execute(()->{
48+
try {
49+
Optional<QOTWSubmission> submissionOptional = qotwSubmissionRepository.getSubmissionByThreadId(submissionThread.getIdLong());
50+
submissionOptional.ifPresent(submission -> guild.getJDA().retrieveUserById(submission.getAuthorId()).queue(author -> {
51+
notificationService.withGuild(guild).sendToModerationLog(c -> c.sendMessageEmbeds(buildSubmissionActionEmbed(author, submissionThread, reviewedBy, status, reasons)));
52+
log.info("{} {} {}'s QOTW Submission{}", reviewedBy.getAsTag(), status.name().toLowerCase(), author.getAsTag(), reasons != null ? " for: " + String.join(", ", reasons) : ".");
53+
}));
54+
}catch (DataAccessException e) {
55+
ExceptionLogger.capture(e, QOTWGuildNotificationService.class.getSimpleName());
56+
}
4957
});
5058
}
5159

src/main/java/net/javadiscord/javabot/systems/notification/QOTWNotificationService.java

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,16 @@
66
import net.dv8tion.jda.api.entities.MessageEmbed;
77
import net.dv8tion.jda.api.entities.User;
88
import net.javadiscord.javabot.data.config.SystemsConfig;
9-
import net.javadiscord.javabot.data.h2db.DbHelper;
109
import net.javadiscord.javabot.systems.qotw.QOTWPointsService;
1110
import net.javadiscord.javabot.systems.qotw.model.QOTWAccount;
11+
import net.javadiscord.javabot.systems.qotw.submissions.dao.QOTWSubmissionRepository;
1212
import net.javadiscord.javabot.util.Responses;
1313
import org.jetbrains.annotations.NotNull;
14+
import org.springframework.dao.DataAccessException;
1415

1516
import javax.annotation.Nonnull;
16-
import java.sql.SQLException;
1717
import java.time.Instant;
18+
import java.util.concurrent.ExecutorService;
1819

1920
/**
2021
* An extension of {@link QOTWGuildNotificationService} which also handles user qotw
@@ -27,14 +28,14 @@ public final class QOTWNotificationService extends QOTWGuildNotificationService
2728
private final QOTWAccount account;
2829
private final SystemsConfig systemsConfig;
2930

30-
QOTWNotificationService(NotificationService notificationService, QOTWPointsService pointsService,@NotNull User user, Guild guild, SystemsConfig systemsConfig, DbHelper dbHelper) {
31-
super(notificationService, guild, dbHelper);
31+
QOTWNotificationService(NotificationService notificationService, QOTWPointsService pointsService,@NotNull User user, Guild guild, SystemsConfig systemsConfig, ExecutorService asyncPool, QOTWSubmissionRepository qotwSubmissionRepository) {
32+
super(notificationService, guild, asyncPool, qotwSubmissionRepository);
3233
this.user = user;
3334
this.guild = guild;
3435
QOTWAccount account;
3536
try {
3637
account = pointsService.getOrCreateAccount(user.getIdLong());
37-
} catch (SQLException e) {
38+
} catch (DataAccessException e) {
3839
log.error("Could not find Account with user Id: {}", user.getIdLong(), e);
3940
account = null;
4041
}

src/main/java/net/javadiscord/javabot/systems/qotw/QOTWCloseSubmissionsJob.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ public class QOTWCloseSubmissionsJob {
3636
private final NotificationService notificationService;
3737
private final BotConfig botConfig;
3838
private final DbHelper dbHelper;
39+
private final QOTWSubmissionRepository qotwSubmissionRepository;
3940

4041
/**
4142
* disable the Submission button.
@@ -57,10 +58,9 @@ public void execute() throws SQLException {
5758
message.editMessageComponents(ActionRow.of(Button.secondary("qotw-submission:closed", "Submissions closed").asDisabled())).queue();
5859
for (ThreadChannel thread : qotwConfig.getSubmissionChannel().getThreadChannels()) {
5960
try (Connection con = dbHelper.getDataSource().getConnection()) {
60-
QOTWSubmissionRepository repo = new QOTWSubmissionRepository(con);
61-
Optional<QOTWSubmission> optionalSubmission = repo.getSubmissionByThreadId(thread.getIdLong());
61+
Optional<QOTWSubmission> optionalSubmission = qotwSubmissionRepository.getSubmissionByThreadId(thread.getIdLong());
6262
if (optionalSubmission.isEmpty()) continue;
63-
new SubmissionControlsManager(botConfig.get(guild), dbHelper, optionalSubmission.get(), pointsService, notificationService).sendControls();
63+
new SubmissionControlsManager(botConfig.get(guild), optionalSubmission.get(), pointsService, notificationService).sendControls();
6464
} catch (SQLException e) {
6565
ExceptionLogger.capture(e, getClass().getSimpleName());
6666
throw e;

src/main/java/net/javadiscord/javabot/systems/qotw/QOTWJob.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ public class QOTWJob {
4141
private final NotificationService notificationService;
4242
private final BotConfig botConfig;
4343
private final DataSource dataSource;
44+
private final QuestionQueueRepository questionQueueRepository;
4445

4546
/**
4647
* Posts a new question to the QOTW channel.
@@ -56,8 +57,7 @@ public void execute() throws SQLException {
5657
GuildConfig config = botConfig.get(guild);
5758
if (config.getModerationConfig().getLogChannel() == null) continue;
5859
try (Connection c = dataSource.getConnection()) {
59-
QuestionQueueRepository repo = new QuestionQueueRepository(c);
60-
Optional<QOTWQuestion> nextQuestion = repo.getNextQuestion(guild.getIdLong());
60+
Optional<QOTWQuestion> nextQuestion = questionQueueRepository.getNextQuestion(guild.getIdLong());
6161
if (nextQuestion.isEmpty()) {
6262
notificationService.withGuild(guild).sendToModerationLog(m -> m.sendMessageFormat("Warning! %s No available next question for QOTW!", config.getQotwConfig().getQOTWReviewRole().getAsMention()));
6363
} else {
@@ -68,15 +68,15 @@ public void execute() throws SQLException {
6868
.putRolePermissionOverride(guild.getIdLong(), Set.of(Permission.VIEW_CHANNEL, Permission.MESSAGE_SEND_IN_THREADS), Collections.singleton(Permission.MESSAGE_SEND))
6969
.queue();
7070
if (question.getQuestionNumber() == null) {
71-
question.setQuestionNumber(repo.getNextQuestionNumber());
71+
question.setQuestionNumber(questionQueueRepository.getNextQuestionNumber());
7272
}
7373
NewsChannel questionChannel = qotw.getQuestionChannel();
7474
if (questionChannel == null) continue;
7575
questionChannel.sendMessage(qotw.getQOTWRole().getAsMention())
7676
.setEmbeds(this.buildQuestionEmbed(question))
7777
.setActionRows(ActionRow.of(Button.success("qotw-submission:submit:" + question.getQuestionNumber(), "Submit your Answer")))
7878
.queue(msg -> questionChannel.crosspostMessageById(msg.getIdLong()).queue());
79-
repo.markUsed(question);
79+
questionQueueRepository.markUsed(question);
8080
}
8181
} catch (SQLException e) {
8282
ExceptionLogger.capture(e, getClass().getSimpleName());

src/main/java/net/javadiscord/javabot/systems/qotw/QOTWPointsService.java

Lines changed: 27 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,10 @@
88
import net.javadiscord.javabot.util.ExceptionLogger;
99
import net.javadiscord.javabot.util.Pair;
1010

11-
import javax.sql.DataSource;
12-
11+
import org.springframework.dao.DataAccessException;
1312
import org.springframework.stereotype.Service;
13+
import org.springframework.transaction.annotation.Transactional;
1414

15-
import java.sql.Connection;
16-
import java.sql.SQLException;
1715
import java.util.List;
1816
import java.util.Optional;
1917

@@ -23,7 +21,7 @@
2321
@RequiredArgsConstructor
2422
@Service
2523
public class QOTWPointsService {
26-
private final DataSource dataSource;
24+
private final QuestionPointsRepository pointsRepository;
2725

2826
/**
2927
* Creates a new QOTW Account if none exists.
@@ -32,23 +30,19 @@ public class QOTWPointsService {
3230
* @return An {@link QOTWAccount} object.
3331
* @throws SQLException If an error occurs.
3432
*/
35-
public QOTWAccount getOrCreateAccount(long userId) throws SQLException {
33+
@Transactional
34+
public QOTWAccount getOrCreateAccount(long userId) throws DataAccessException {
3635
QOTWAccount account;
37-
try (Connection con = this.dataSource.getConnection()) {
38-
con.setAutoCommit(false);
39-
QuestionPointsRepository repo = new QuestionPointsRepository(con);
40-
Optional<QOTWAccount> optional = repo.getByUserId(userId);
41-
if (optional.isPresent()) {
42-
account = optional.get();
43-
} else {
44-
account = new QOTWAccount();
45-
account.setUserId(userId);
46-
account.setPoints(0);
47-
repo.insert(account);
48-
}
49-
con.commit();
50-
return account;
36+
Optional<QOTWAccount> optional = pointsRepository.getByUserId(userId);
37+
if (optional.isPresent()) {
38+
account = optional.get();
39+
} else {
40+
account = new QOTWAccount();
41+
account.setUserId(userId);
42+
account.setPoints(0);
43+
pointsRepository.insert(account);
5144
}
45+
return account;
5246
}
5347

5448
/**
@@ -58,14 +52,13 @@ public QOTWAccount getOrCreateAccount(long userId) throws SQLException {
5852
* @return The QOTW-Rank as an integer.
5953
*/
6054
public int getQOTWRank(long userId) {
61-
try (Connection con = dataSource.getConnection()) {
62-
QuestionPointsRepository repo = new QuestionPointsRepository(con);
63-
List<QOTWAccount> accounts = repo.sortByPoints();
55+
try{
56+
List<QOTWAccount> accounts = pointsRepository.sortByPoints();
6457
return accounts.stream()
6558
.map(QOTWAccount::getUserId)
6659
.toList()
6760
.indexOf(userId) + 1;
68-
} catch (SQLException e) {
61+
} catch (DataAccessException e) {
6962
ExceptionLogger.capture(e, getClass().getSimpleName());
7063
return -1;
7164
}
@@ -80,7 +73,7 @@ public int getQOTWRank(long userId) {
8073
public long getPoints(long userId) {
8174
try {
8275
return getOrCreateAccount(userId).getPoints();
83-
} catch (SQLException e) {
76+
} catch (DataAccessException e) {
8477
ExceptionLogger.capture(e, getClass().getSimpleName());
8578
return -1;
8679
}
@@ -94,15 +87,14 @@ public long getPoints(long userId) {
9487
* @return A {@link List} with the top member ids.
9588
*/
9689
public List<Pair<QOTWAccount, Member>> getTopMembers(int n, Guild guild) {
97-
try (Connection con = dataSource.getConnection()) {
98-
QuestionPointsRepository repo = new QuestionPointsRepository(con);
99-
List<QOTWAccount> accounts = repo.sortByPoints();
90+
try {
91+
List<QOTWAccount> accounts = pointsRepository.sortByPoints();
10092
return accounts.stream()
10193
.map(s -> new Pair<>(s, guild.getMemberById(s.getUserId())))
10294
.filter(p -> p.second() != null)
10395
.limit(n)
10496
.toList();
105-
} catch (SQLException e) {
97+
} catch (DataAccessException e) {
10698
ExceptionLogger.capture(e, getClass().getSimpleName());
10799
return List.of();
108100
}
@@ -116,10 +108,9 @@ public List<Pair<QOTWAccount, Member>> getTopMembers(int n, Guild guild) {
116108
* @return An unmodifiable {@link List} of {@link QOTWAccount}s.
117109
*/
118110
public List<QOTWAccount> getTopAccounts(int amount, int page) {
119-
try (Connection con = dataSource.getConnection()) {
120-
QuestionPointsRepository repo = new QuestionPointsRepository(con);
121-
return repo.getTopAccounts(page, amount);
122-
} catch (SQLException e) {
111+
try {
112+
return pointsRepository.getTopAccounts(page, amount);
113+
} catch (DataAccessException e) {
123114
ExceptionLogger.capture(e, getClass().getSimpleName());
124115
return List.of();
125116
}
@@ -132,16 +123,15 @@ public List<QOTWAccount> getTopAccounts(int amount, int page) {
132123
* @return The total points after the update.
133124
*/
134125
public long increment(long userId) {
135-
try (Connection con = dataSource.getConnection()) {
136-
QuestionPointsRepository repo = new QuestionPointsRepository(con);
126+
try {
137127
QOTWAccount account = getOrCreateAccount(userId);
138128
account.setPoints(account.getPoints() + 1);
139-
if (repo.update(account)) {
129+
if (pointsRepository.update(account)) {
140130
return account.getPoints();
141131
} else {
142132
return 0;
143133
}
144-
} catch (SQLException e) {
134+
} catch (DataAccessException e) {
145135
ExceptionLogger.capture(e, getClass().getSimpleName());
146136
return 0;
147137
}

src/main/java/net/javadiscord/javabot/systems/qotw/QOTWReminderJob.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ public class QOTWReminderJob {
2929
private final NotificationService notificationService;
3030
private final BotConfig botConfig;
3131
private final DataSource dataSource;
32+
private final QuestionQueueRepository questionQueueRepository;
3233

3334
/**
3435
* Checks that there's a question in the QOTW queue ready for posting soon.
@@ -39,8 +40,7 @@ public void execute() throws SQLException {
3940
for (Guild guild : jda.getGuilds()) {
4041
ModerationConfig config = botConfig.get(guild).getModerationConfig();
4142
try (Connection c = dataSource.getConnection()) {
42-
QuestionQueueRepository repo = new QuestionQueueRepository(c);
43-
Optional<QOTWQuestion> q = repo.getNextQuestion(guild.getIdLong());
43+
Optional<QOTWQuestion> q = questionQueueRepository.getNextQuestion(guild.getIdLong());
4444
if (q.isEmpty()) {
4545
notificationService.withGuild(guild).sendToModerationLog(m -> m.sendMessageFormat(
4646
"Warning! %s There's no Question of the Week in the queue. Please add one before it's time to post!",

src/main/java/net/javadiscord/javabot/systems/qotw/QOTWUserReminderJob.java

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@
66
import net.javadiscord.javabot.data.config.BotConfig;
77
import net.javadiscord.javabot.data.config.guild.QOTWConfig;
88
import net.javadiscord.javabot.data.h2db.DbHelper;
9+
import net.javadiscord.javabot.systems.qotw.dao.QuestionQueueRepository;
910
import net.javadiscord.javabot.systems.qotw.submissions.SubmissionManager;
11+
import net.javadiscord.javabot.systems.qotw.submissions.dao.QOTWSubmissionRepository;
1012
import net.javadiscord.javabot.systems.qotw.submissions.model.QOTWSubmission;
1113
import net.javadiscord.javabot.systems.user_preferences.UserPreferenceService;
1214
import net.javadiscord.javabot.systems.user_preferences.model.Preference;
@@ -29,6 +31,8 @@ public class QOTWUserReminderJob {
2931
private final UserPreferenceService userPreferenceService;
3032
private final BotConfig botConfig;
3133
private final DbHelper dbHelper;
34+
private final QOTWSubmissionRepository qotwSubmissionRepository;
35+
private final QuestionQueueRepository questionQueueRepository;
3236

3337
/**
3438
* Checks that there's a question in the QOTW queue ready for posting soon.
@@ -37,7 +41,7 @@ public class QOTWUserReminderJob {
3741
public void execute() {
3842
for (Guild guild : jda.getGuilds()) {
3943
QOTWConfig config = botConfig.get(guild).getQotwConfig();
40-
List<QOTWSubmission> submissions = new SubmissionManager(config, dbHelper).getActiveSubmissionThreads(guild.getIdLong());
44+
List<QOTWSubmission> submissions = new SubmissionManager(config, dbHelper, qotwSubmissionRepository, questionQueueRepository).getActiveSubmissionThreads(guild.getIdLong());
4145
for (QOTWSubmission submission : submissions) {
4246
UserPreference preference = userPreferenceService.getOrCreate(submission.getAuthorId(), Preference.QOTW_REMINDER);
4347
if (preference.isEnabled()) {

0 commit comments

Comments
 (0)