Skip to content

Commit 08c09de

Browse files
committed
use Spring JDBC for custom tags
1 parent 4242744 commit 08c09de

File tree

8 files changed

+148
-157
lines changed

8 files changed

+148
-157
lines changed

src/main/java/net/javadiscord/javabot/systems/staff_commands/tags/CustomTagManager.java

Lines changed: 22 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package net.javadiscord.javabot.systems.staff_commands.tags;
22

33
import com.dynxsty.dih4jda.util.AutoCompleteUtils;
4+
5+
import lombok.RequiredArgsConstructor;
46
import lombok.extern.slf4j.Slf4j;
57
import net.dv8tion.jda.api.JDA;
68
import net.dv8tion.jda.api.entities.Guild;
@@ -13,10 +15,10 @@
1315
import net.javadiscord.javabot.systems.staff_commands.tags.model.CustomTag;
1416
import org.jetbrains.annotations.Contract;
1517
import org.jetbrains.annotations.NotNull;
18+
import org.springframework.dao.DataAccessException;
1619
import org.springframework.stereotype.Service;
1720

1821
import javax.sql.DataSource;
19-
import java.sql.Connection;
2022
import java.sql.SQLException;
2123
import java.util.*;
2224
import java.util.stream.Collectors;
@@ -27,6 +29,7 @@
2729
*/
2830
@Slf4j
2931
@Service
32+
@RequiredArgsConstructor
3033
public class CustomTagManager {
3134
private static final Map<Long, Set<CustomTag>> LOADED_TAGS;
3235

@@ -35,15 +38,7 @@ public class CustomTagManager {
3538
}
3639

3740
private final DataSource dataSource;
38-
39-
/**
40-
* The constructor of this class.
41-
*
42-
* @param dataSource The {@link DataSource} which is used to make connections to the database.
43-
*/
44-
public CustomTagManager(@NotNull DataSource dataSource) {
45-
this.dataSource = dataSource;
46-
}
41+
private final CustomTagRepository customTagRepository;
4742

4843
/**
4944
* Cleans the given String by removing all whitespaces and slashes, so it can be used for custom tags.
@@ -130,11 +125,8 @@ public void init(JDA jda) throws SQLException {
130125
* @throws SQLException If an error occurs.
131126
*/
132127
@Contract("_ -> new")
133-
private @NotNull Set<CustomTag> getCustomTags(long guildId) throws SQLException {
134-
try (Connection con = dataSource.getConnection()) {
135-
CustomTagRepository repo = new CustomTagRepository(con);
136-
return new HashSet<>(repo.getCustomTagsByGuildId(guildId));
137-
}
128+
private @NotNull Set<CustomTag> getCustomTags(long guildId) throws DataAccessException {
129+
return new HashSet<>(customTagRepository.getCustomTagsByGuildId(guildId));
138130
}
139131

140132
/**
@@ -168,18 +160,15 @@ public Optional<CustomTag> getByName(long guildId, String name) {
168160
* @return Whether the command was successfully created/added.
169161
* @throws SQLException If an error occurs.
170162
*/
171-
public boolean addCommand(@NotNull Guild guild, @NotNull CustomTag tag) throws SQLException {
163+
public boolean addCommand(@NotNull Guild guild, @NotNull CustomTag tag) throws DataAccessException {
172164
if (doesTagExist(guild.getIdLong(), tag.getName())) {
173165
return false;
174166
}
175-
try (Connection con = dataSource.getConnection()) {
176-
CustomTagRepository repo = new CustomTagRepository(con);
177-
Set<CustomTag> tags = new HashSet<>(LOADED_TAGS.get(guild.getIdLong()));
178-
tags.add(tag);
179-
LOADED_TAGS.put(guild.getIdLong(), tags);
180-
log.info("Created Custom Tag in guild \"{}\": {}", guild.getName(), tag.getName());
181-
return repo.insert(tag) != null;
182-
}
167+
Set<CustomTag> tags = new HashSet<>(LOADED_TAGS.get(guild.getIdLong()));
168+
tags.add(tag);
169+
LOADED_TAGS.put(guild.getIdLong(), tags);
170+
log.info("Created Custom Tag in guild \"{}\": {}", guild.getName(), tag.getName());
171+
return customTagRepository.insert(tag) != null;
183172
}
184173

185174
/**
@@ -190,16 +179,13 @@ public boolean addCommand(@NotNull Guild guild, @NotNull CustomTag tag) throws S
190179
* @return Whether the command was successfully deleted.
191180
* @throws SQLException If an error occurs.
192181
*/
193-
public boolean removeCommand(long guildId, @NotNull CustomTag tag) throws SQLException {
182+
public boolean removeCommand(long guildId, @NotNull CustomTag tag) throws DataAccessException {
194183
if (!doesTagExist(guildId, tag.getName())) {
195184
return false;
196185
}
197-
try (Connection con = dataSource.getConnection()) {
198-
CustomTagRepository repo = new CustomTagRepository(con);
199-
repo.delete(tag);
200-
LOADED_TAGS.put(guildId, new HashSet<>(getCustomTags(guildId)));
201-
log.info("Deleted Custom Tag in guild \"{}\": {}", guildId, tag);
202-
}
186+
customTagRepository.delete(tag);
187+
LOADED_TAGS.put(guildId, new HashSet<>(getCustomTags(guildId)));
188+
log.info("Deleted Custom Tag in guild \"{}\": {}", guildId, tag);
203189
return true;
204190
}
205191

@@ -212,17 +198,14 @@ public boolean removeCommand(long guildId, @NotNull CustomTag tag) throws SQLExc
212198
* @return Whether the command was successfully edited.
213199
* @throws SQLException If an error occurs.
214200
*/
215-
public boolean editCommand(long guildId, @NotNull CustomTag old, @NotNull CustomTag update) throws SQLException {
201+
public boolean editCommand(long guildId, @NotNull CustomTag old, @NotNull CustomTag update) throws DataAccessException {
216202
if (!doesTagExist(guildId, old.getName())) {
217203
return false;
218204
}
219-
try (Connection con = dataSource.getConnection()) {
220-
CustomTagRepository repo = new CustomTagRepository(con);
221-
repo.edit(old, update);
222-
LOADED_TAGS.put(guildId, new HashSet<>(getCustomTags(guildId)));
223-
log.info("Edited Custom Tag in guild \"{}\": {} -> {}", guildId, old, update);
224-
return true;
225-
}
205+
customTagRepository.edit(old, update);
206+
LOADED_TAGS.put(guildId, new HashSet<>(getCustomTags(guildId)));
207+
log.info("Edited Custom Tag in guild \"{}\": {} -> {}", guildId, old, update);
208+
return true;
226209
}
227210

228211
/**

src/main/java/net/javadiscord/javabot/systems/staff_commands/tags/commands/CreateCustomTagSubcommand.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,8 @@
2222
import net.javadiscord.javabot.util.ExceptionLogger;
2323
import net.javadiscord.javabot.util.Responses;
2424
import org.jetbrains.annotations.NotNull;
25+
import org.springframework.dao.DataAccessException;
2526

26-
import java.sql.SQLException;
2727
import java.time.Instant;
2828
import java.util.List;
2929

@@ -124,7 +124,7 @@ public void handleModal(@NotNull ModalInteractionEvent event, @NotNull List<Moda
124124
} else {
125125
Responses.error(event.getHook(), "Could not create Custom Tag. Please try again.").queue();
126126
}
127-
} catch (SQLException e) {
127+
} catch (DataAccessException e) {
128128
ExceptionLogger.capture(e);
129129
Responses.error(event.getHook(), "An unexpected error occurred. Please try again.").queue();
130130
}

src/main/java/net/javadiscord/javabot/systems/staff_commands/tags/commands/DeleteCustomTagSubcommand.java

Lines changed: 24 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -12,33 +12,38 @@
1212
import net.dv8tion.jda.api.interactions.commands.build.SubcommandData;
1313
import net.dv8tion.jda.api.requests.restaction.interactions.ReplyCallbackAction;
1414
import net.javadiscord.javabot.data.config.BotConfig;
15-
import net.javadiscord.javabot.data.h2db.DbHelper;
1615
import net.javadiscord.javabot.systems.staff_commands.tags.CustomTagManager;
1716
import net.javadiscord.javabot.systems.staff_commands.tags.dao.CustomTagRepository;
1817
import net.javadiscord.javabot.systems.staff_commands.tags.model.CustomTag;
18+
import net.javadiscord.javabot.util.ExceptionLogger;
1919
import net.javadiscord.javabot.util.Responses;
2020
import org.jetbrains.annotations.NotNull;
21+
import org.springframework.dao.DataAccessException;
2122

2223
import java.time.Instant;
2324
import java.util.Optional;
25+
import java.util.concurrent.ExecutorService;
2426

2527
/**
2628
* <h3>This class represents the /tag-admin delete command.</h3>
2729
*/
2830
public class DeleteCustomTagSubcommand extends TagsSubcommand implements AutoCompletable {
2931
private final CustomTagManager customTagManager;
30-
private final DbHelper dbHelper;
32+
private final ExecutorService asyncPool;
33+
private final CustomTagRepository customTagRepository;
3134

3235
/**
3336
* The constructor of this class, which sets the corresponding {@link SubcommandData}.
3437
* @param customTagManager The {@link CustomTagManager}
3538
* @param botConfig The main configuration of the bot
36-
* @param dbHelper An object managing databse operations
39+
* @param asyncPool The main thread pool for asynchronous operations
40+
* @param customTagRepository Dao object that represents the CUSTOM_COMMANDS SQL Table.
3741
*/
38-
public DeleteCustomTagSubcommand(CustomTagManager customTagManager, BotConfig botConfig, DbHelper dbHelper) {
42+
public DeleteCustomTagSubcommand(CustomTagManager customTagManager, BotConfig botConfig, ExecutorService asyncPool, CustomTagRepository customTagRepository) {
3943
super(botConfig);
4044
this.customTagManager = customTagManager;
41-
this.dbHelper = dbHelper;
45+
this.asyncPool = asyncPool;
46+
this.customTagRepository = customTagRepository;
4247
setSubcommandData(new SubcommandData("delete", "Deletes a single Custom Tag.")
4348
.addOption(OptionType.STRING, "name", "The tag's name.", true, true)
4449
);
@@ -51,17 +56,21 @@ public ReplyCallbackAction handleCustomTagsSubcommand(@NotNull SlashCommandInter
5156
return Responses.replyMissingArguments(event);
5257
}
5358
String tagName = CustomTagManager.cleanString(nameMapping.getAsString());
54-
dbHelper.doDaoAction(CustomTagRepository::new, dao -> {
55-
Optional<CustomTag> tagOptional = dao.findByName(event.getGuild().getIdLong(), tagName);
56-
if (tagOptional.isEmpty()) {
57-
Responses.error(event.getHook(), "Could not find Custom Tag with name `%s`.", tagName).queue();
58-
return;
59+
asyncPool.execute(()->{
60+
try {
61+
Optional<CustomTag> tagOptional = customTagRepository.findByName(event.getGuild().getIdLong(), tagName);
62+
if (tagOptional.isEmpty()) {
63+
Responses.error(event.getHook(), "Could not find Custom Tag with name `%s`.", tagName).queue();
64+
return;
65+
}
66+
if (customTagManager.removeCommand(event.getGuild().getIdLong(), tagOptional.get())) {
67+
event.getHook().sendMessageEmbeds(buildDeleteCommandEmbed(event.getMember(), tagOptional.get())).queue();
68+
return;
69+
}
70+
Responses.error(event.getHook(), "Could not delete Custom Tag. Please try again.").queue();
71+
} catch (DataAccessException e) {
72+
ExceptionLogger.capture(e, DeleteCustomTagSubcommand.class.getSimpleName());
5973
}
60-
if (customTagManager.removeCommand(event.getGuild().getIdLong(), tagOptional.get())) {
61-
event.getHook().sendMessageEmbeds(buildDeleteCommandEmbed(event.getMember(), tagOptional.get())).queue();
62-
return;
63-
}
64-
Responses.error(event.getHook(), "Could not delete Custom Tag. Please try again.").queue();
6574
});
6675
return event.deferReply(true);
6776
}

src/main/java/net/javadiscord/javabot/systems/staff_commands/tags/commands/EditCustomTagSubcommand.java

Lines changed: 24 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -20,37 +20,42 @@
2020
import net.dv8tion.jda.api.interactions.modals.ModalMapping;
2121
import net.dv8tion.jda.api.requests.restaction.interactions.InteractionCallbackAction;
2222
import net.javadiscord.javabot.data.config.BotConfig;
23-
import net.javadiscord.javabot.data.h2db.DbHelper;
2423
import net.javadiscord.javabot.systems.AutoDetectableComponentHandler;
2524
import net.javadiscord.javabot.systems.staff_commands.tags.CustomTagManager;
2625
import net.javadiscord.javabot.systems.staff_commands.tags.dao.CustomTagRepository;
2726
import net.javadiscord.javabot.systems.staff_commands.tags.model.CustomTag;
27+
import net.javadiscord.javabot.util.ExceptionLogger;
2828
import net.javadiscord.javabot.util.Responses;
2929
import org.jetbrains.annotations.NotNull;
30+
import org.springframework.dao.DataAccessException;
3031

3132
import java.time.Instant;
3233
import java.util.List;
3334
import java.util.Optional;
3435
import java.util.Set;
36+
import java.util.concurrent.ExecutorService;
3537

3638
/**
3739
* <h3>This class represents the /tag-admin edit command.</h3>
3840
*/
3941
@AutoDetectableComponentHandler("tag-edit")
4042
public class EditCustomTagSubcommand extends TagsSubcommand implements AutoCompletable, ModalHandler {
4143
private final CustomTagManager customTagManager;
42-
private final DbHelper dbHelper;
44+
private final ExecutorService asyncPool;
45+
private final CustomTagRepository customTagRepository;
4346

4447
/**
4548
* The constructor of this class, which sets the corresponding {@link SubcommandData}.
4649
* @param customTagManager The {@link CustomTagManager}
4750
* @param botConfig The main configuration of the bot
48-
* @param dbHelper An object managing databse operations
51+
* @param asyncPool The main thread pool for asynchronous operations
52+
* @param customTagRepository Dao object that represents the CUSTOM_COMMANDS SQL Table.
4953
*/
50-
public EditCustomTagSubcommand(CustomTagManager customTagManager, BotConfig botConfig, DbHelper dbHelper) {
54+
public EditCustomTagSubcommand(CustomTagManager customTagManager, BotConfig botConfig, CustomTagRepository customTagRepository, ExecutorService asyncPool) {
5155
super(botConfig);
5256
this.customTagManager = customTagManager;
53-
this.dbHelper = dbHelper;
57+
this.asyncPool = asyncPool;
58+
this.customTagRepository = customTagRepository;
5459
setSubcommandData(new SubcommandData("edit", "Edits a single Custom Tag.")
5560
.addOption(OptionType.STRING, "name", "The tag's name.", true, true)
5661
);
@@ -151,17 +156,21 @@ public void handleModal(@NotNull ModalInteractionEvent event, @NotNull List<Moda
151156
update.setEmbed(Boolean.parseBoolean(embedMapping.getAsString()));
152157

153158
event.deferReply(true).queue();
154-
dbHelper.doDaoAction(CustomTagRepository::new, dao -> {
155-
Optional<CustomTag> tagOptional = dao.findByName(event.getGuild().getIdLong(), update.getName());
156-
if (tagOptional.isEmpty()) {
157-
Responses.error(event.getHook(), "Could not find Custom Tag with name `/%s`.", update.getName()).queue();
158-
return;
159+
asyncPool.execute(()->{
160+
try {
161+
Optional<CustomTag> tagOptional = customTagRepository.findByName(event.getGuild().getIdLong(), update.getName());
162+
if (tagOptional.isEmpty()) {
163+
Responses.error(event.getHook(), "Could not find Custom Tag with name `/%s`.", update.getName()).queue();
164+
return;
165+
}
166+
if (customTagManager.editCommand(event.getGuild().getIdLong(), tagOptional.get(), update)) {
167+
event.getHook().sendMessageEmbeds(buildEditTagEmbed(event.getMember(), update)).queue();
168+
return;
169+
}
170+
Responses.error(event.getHook(), "Could not edit Custom Command. Please try again.").queue();
171+
} catch (DataAccessException e) {
172+
ExceptionLogger.capture(e, EditCustomTagSubcommand.class.getSimpleName());
159173
}
160-
if (customTagManager.editCommand(event.getGuild().getIdLong(), tagOptional.get(), update)) {
161-
event.getHook().sendMessageEmbeds(buildEditTagEmbed(event.getMember(), update)).queue();
162-
return;
163-
}
164-
Responses.error(event.getHook(), "Could not edit Custom Command. Please try again.").queue();
165174
});
166175
}
167176
}

src/main/java/net/javadiscord/javabot/systems/staff_commands/tags/commands/TagListSubcommand.java

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,40 +5,49 @@
55
import net.dv8tion.jda.api.requests.restaction.interactions.ReplyCallbackAction;
66
import net.dv8tion.jda.api.utils.MarkdownUtil;
77
import net.javadiscord.javabot.data.config.BotConfig;
8-
import net.javadiscord.javabot.data.h2db.DbHelper;
98
import net.javadiscord.javabot.systems.staff_commands.tags.dao.CustomTagRepository;
109
import net.javadiscord.javabot.systems.staff_commands.tags.model.CustomTag;
10+
import net.javadiscord.javabot.util.ExceptionLogger;
1111
import net.javadiscord.javabot.util.Responses;
1212
import org.jetbrains.annotations.NotNull;
13+
import org.springframework.dao.DataAccessException;
1314

1415
import java.util.List;
16+
import java.util.concurrent.ExecutorService;
1517
import java.util.stream.Collectors;
1618

1719
/**
1820
* <h3>This class represents the /tags command.</h3>
1921
*/
2022
public class TagListSubcommand extends TagsSubcommand {
21-
private final DbHelper dbHelper;
23+
private final ExecutorService asyncPool;
24+
private final CustomTagRepository customTagRepository;
2225

2326
/**
2427
* The constructor of this class, which sets the corresponding {@link net.dv8tion.jda.api.interactions.commands.build.SlashCommandData}.
2528
* @param botConfig The main configuration of the bot
26-
* @param dbHelper An object managing databse operations
29+
* @param asyncPool The main thread pool for asynchronous operations
30+
* @param customTagRepository Dao object that represents the CUSTOM_COMMANDS SQL Table.
2731
*/
28-
public TagListSubcommand(BotConfig botConfig, DbHelper dbHelper) {
32+
public TagListSubcommand(BotConfig botConfig, ExecutorService asyncPool, CustomTagRepository customTagRepository) {
2933
super(botConfig);
30-
this.dbHelper = dbHelper;
34+
this.asyncPool = asyncPool;
35+
this.customTagRepository = customTagRepository;
3136
setSubcommandData(new SubcommandData("list", "Lists all custom tags"));
3237
setRequiredStaff(false);
3338
}
3439

3540
@Override
3641
public ReplyCallbackAction handleCustomTagsSubcommand(@NotNull SlashCommandInteractionEvent event) {
37-
dbHelper.doDaoAction(CustomTagRepository::new, dao -> {
38-
List<CustomTag> tags = dao.getCustomTagsByGuildId(event.getGuild().getIdLong());
39-
String tagList = tags.stream().map(CustomTag::getName).map(MarkdownUtil::monospace).collect(Collectors.joining(", "));
40-
Responses.info(event.getHook(), "Custom Tag List",
41-
String.format(tagList.length() > 0 ? tagList : "No Custom Tags created yet.")).queue();
42+
asyncPool.execute(()->{
43+
try {
44+
List<CustomTag> tags = customTagRepository.getCustomTagsByGuildId(event.getGuild().getIdLong());
45+
String tagList = tags.stream().map(CustomTag::getName).map(MarkdownUtil::monospace).collect(Collectors.joining(", "));
46+
Responses.info(event.getHook(), "Custom Tag List",
47+
String.format(tagList.length() > 0 ? tagList : "No Custom Tags created yet.")).queue();
48+
} catch (DataAccessException e) {
49+
ExceptionLogger.capture(e, TagListSubcommand.class.getSimpleName());
50+
}
4251
});
4352
return event.deferReply(false);
4453
}

src/main/java/net/javadiscord/javabot/systems/staff_commands/tags/commands/TagsAdminCommand.java

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
11
package net.javadiscord.javabot.systems.staff_commands.tags.commands;
22

3+
import java.util.concurrent.ExecutorService;
4+
35
import com.dynxsty.dih4jda.interactions.commands.SlashCommand;
46
import net.dv8tion.jda.api.interactions.commands.build.Commands;
57
import net.javadiscord.javabot.data.config.BotConfig;
68
import net.javadiscord.javabot.data.h2db.DbHelper;
79
import net.javadiscord.javabot.systems.moderation.CommandModerationPermissions;
810
import net.javadiscord.javabot.systems.staff_commands.tags.CustomTagManager;
11+
import net.javadiscord.javabot.systems.staff_commands.tags.dao.CustomTagRepository;
912

1013
/**
1114
* Represents the `/tag-admin` command. This holds administrative commands for managing "Custom Tags".
@@ -17,9 +20,11 @@ public class TagsAdminCommand extends SlashCommand implements CommandModerationP
1720
* @param tagManager The {@link CustomTagManager}
1821
* @param botConfig The main configuration of the bot
1922
* @param dbHelper An object managing databse operations
23+
* @param asyncPool The main thread pool for asynchronous operations
24+
* @param customTagRepository Dao object that represents the CUSTOM_COMMANDS SQL Table.
2025
*/
21-
public TagsAdminCommand(CustomTagManager tagManager, BotConfig botConfig, DbHelper dbHelper) {
26+
public TagsAdminCommand(CustomTagManager tagManager, BotConfig botConfig, DbHelper dbHelper, ExecutorService asyncPool, CustomTagRepository customTagRepository) {
2227
setModerationSlashCommandData(Commands.slash("tag-admin", "Administrative commands for managing \"Custom Tags\"."));
23-
addSubcommands(new CreateCustomTagSubcommand(tagManager, botConfig), new DeleteCustomTagSubcommand(tagManager, botConfig, dbHelper), new EditCustomTagSubcommand(tagManager, botConfig, dbHelper));
28+
addSubcommands(new CreateCustomTagSubcommand(tagManager, botConfig), new DeleteCustomTagSubcommand(tagManager, botConfig, asyncPool, customTagRepository), new EditCustomTagSubcommand(tagManager, botConfig, customTagRepository, asyncPool));
2429
}
2530
}

0 commit comments

Comments
 (0)