Skip to content

Commit 2d70d10

Browse files
Replaced static field in Bot.java with static accessors
1 parent a2f8cb4 commit 2d70d10

File tree

81 files changed

+288
-240
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

81 files changed

+288
-240
lines changed

src/main/java/net/javadiscord/javabot/Bot.java

Lines changed: 83 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -60,48 +60,21 @@
6060
@Slf4j
6161
public class Bot {
6262

63-
/**
64-
* The set of configuration properties that this bot uses.
65-
*/
66-
public static BotConfig config;
63+
private static BotConfig config;
6764

68-
/**
69-
* An instance of {@link AutoMod}.
70-
*/
71-
public static AutoMod autoMod;
65+
private static AutoMod autoMod;
7266

73-
/**
74-
* A reference to the Bot's {@link DIH4JDA}.
75-
*/
76-
public static DIH4JDA dih4jda;
67+
private static DIH4JDA dih4jda;
7768

78-
/**
79-
* The Bots {@link MessageCache}, which handles logging of deleted and edited messages.
80-
*/
81-
public static MessageCache messageCache;
69+
private static MessageCache messageCache;
8270

83-
/**
84-
* A reference to the Bot's {@link ServerLockManager}.
85-
*/
86-
public static ServerLockManager serverLockManager;
71+
private static ServerLockManager serverLockManager;
8772

88-
/**
89-
* A static reference to the {@link CustomTagManager} which handles and loads all registered Custom Commands.
90-
*/
91-
public static CustomTagManager customTagManager;
73+
private static CustomTagManager customTagManager;
9274

93-
/**
94-
* A reference to the data source that provides access to the relational
95-
* database that this bot users for certain parts of the application. Use
96-
* this to obtain a connection and perform transactions.
97-
*/
98-
public static HikariDataSource dataSource;
75+
private static HikariDataSource dataSource;
9976

100-
/**
101-
* A general-purpose thread pool that can be used by the bot to execute
102-
* tasks outside the main event processing thread.
103-
*/
104-
public static ScheduledExecutorService asyncPool;
77+
private static ScheduledExecutorService asyncPool;
10578

10679
private Bot() {
10780
}
@@ -211,5 +184,80 @@ private static void addComponentHandler(@NotNull DIH4JDA dih4jda) {
211184
List.of("qotw-submission-select"), new SubmissionInteractionManager()
212185
));
213186
}
187+
188+
/**
189+
* The set of configuration properties that this bot uses.
190+
*
191+
* @return The {@link BotConfig} which was set in {@link Bot#main(String[])}.
192+
*/
193+
public static BotConfig getConfig() {
194+
return config;
195+
}
196+
197+
/**
198+
* A static reference to the bots' {@link AutoMod} instance.
199+
*
200+
* @return The {@link AutoMod} instance which was created in {@link Bot#main(String[])}.
201+
*/
202+
public static AutoMod getAutoMod() {
203+
return autoMod;
204+
}
205+
206+
/**
207+
* A static reference to the bots' {@link DIH4JDA} instance.
208+
*
209+
* @return The {@link DIH4JDA} instance which was set in {@link Bot#main(String[])}.
210+
*/
211+
public static DIH4JDA getDIH4JDA() {
212+
return dih4jda;
213+
}
214+
215+
/**
216+
* The bots' {@link MessageCache}, which handles logging of deleted and edited messages.
217+
*
218+
* @return The {@link MessageCache} which was initialized in {@link Bot#main(String[])}.
219+
*/
220+
public static MessageCache getMessageCache() {
221+
return messageCache;
222+
}
223+
224+
/**
225+
* A reference to the bots' {@link ServerLockManager}.
226+
*
227+
* @return The {@link ServerLockManager} which was created in {@link Bot#main(String[])}.
228+
*/
229+
public static ServerLockManager getServerLockManager() {
230+
return serverLockManager;
231+
}
232+
233+
/**
234+
* A static reference to the {@link CustomTagManager} which handles and loads all registered Custom Commands.
235+
*
236+
* @return The {@link CustomTagManager} which was created in {@link Bot#main(String[])}.
237+
*/
238+
public static CustomTagManager getCustomTagManager() {
239+
return customTagManager;
240+
}
241+
242+
/**
243+
* A reference to the data source that provides access to the relational
244+
* database that this bot users for certain parts of the application. Use
245+
* this to obtain a connection and perform transactions.
246+
*
247+
* @return The {@link HikariDataSource} which was initialized in {@link Bot#main(String[])}.
248+
*/
249+
public static HikariDataSource getDataSource() {
250+
return dataSource;
251+
}
252+
253+
/**
254+
* A general-purpose thread pool that can be used by the bot to execute
255+
* tasks outside the main event processing thread.
256+
*
257+
* @return The {@link ScheduledExecutorService} which was set in {@link Bot#main(String[])}.
258+
*/
259+
public static ScheduledExecutorService getAsyncPool() {
260+
return asyncPool;
261+
}
214262
}
215263

src/main/java/net/javadiscord/javabot/data/h2db/DbActions.java

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ private DbActions() {
2525
* @throws SQLException If an error occurs.
2626
*/
2727
public static void doAction(@NotNull ConnectionConsumer consumer) throws SQLException {
28-
try (Connection c = Bot.dataSource.getConnection()) {
28+
try (Connection c = Bot.getDataSource().getConnection()) {
2929
consumer.consume(c);
3030
}
3131
}
@@ -39,7 +39,7 @@ public static void doAction(@NotNull ConnectionConsumer consumer) throws SQLExce
3939
* @throws SQLException If an error occurs.
4040
*/
4141
public static <T> T map(@NotNull ConnectionFunction<T> function) throws SQLException {
42-
try (Connection c = Bot.dataSource.getConnection()) {
42+
try (Connection c = Bot.getDataSource().getConnection()) {
4343
return function.apply(c);
4444
}
4545
}
@@ -55,7 +55,7 @@ public static <T> T map(@NotNull ConnectionFunction<T> function) throws SQLExcep
5555
* @throws SQLException If an error occurs.
5656
*/
5757
public static <T> T mapQuery(@NotNull String query, @NotNull StatementModifier modifier, @NotNull ResultSetMapper<T> mapper) throws SQLException {
58-
try (Connection c = Bot.dataSource.getConnection(); PreparedStatement stmt = c.prepareStatement(query)) {
58+
try (Connection c = Bot.getDataSource().getConnection(); PreparedStatement stmt = c.prepareStatement(query)) {
5959
modifier.modify(stmt);
6060
ResultSet rs = stmt.executeQuery();
6161
return mapper.map(rs);
@@ -73,7 +73,7 @@ public static <T> T mapQuery(@NotNull String query, @NotNull StatementModifier m
7373
*/
7474
public static <T> @NotNull CompletableFuture<T> mapQueryAsync(@NotNull String query, @NotNull StatementModifier modifier, @NotNull ResultSetMapper<T> mapper) {
7575
CompletableFuture<T> cf = new CompletableFuture<>();
76-
Bot.asyncPool.submit(() -> {
76+
Bot.getAsyncPool().submit(() -> {
7777
try {
7878
cf.complete(mapQuery(query, modifier, mapper));
7979
} catch (SQLException e) {
@@ -93,7 +93,7 @@ public static <T> T mapQuery(@NotNull String query, @NotNull StatementModifier m
9393
* @return The column value.
9494
*/
9595
public static long count(@NotNull String query, @NotNull StatementModifier modifier) {
96-
try (Connection c = Bot.dataSource.getConnection(); PreparedStatement stmt = c.prepareStatement(query)) {
96+
try (Connection c = Bot.getDataSource().getConnection(); PreparedStatement stmt = c.prepareStatement(query)) {
9797
modifier.modify(stmt);
9898
ResultSet rs = stmt.executeQuery();
9999
if (!rs.next()) return 0;
@@ -113,7 +113,7 @@ public static long count(@NotNull String query, @NotNull StatementModifier modif
113113
*/
114114
public static long count(@NotNull String query) {
115115
try (
116-
Connection conn = Bot.dataSource.getConnection();
116+
Connection conn = Bot.getDataSource().getConnection();
117117
Statement stmt = conn.createStatement()
118118
) {
119119
ResultSet rs = stmt.executeQuery(query);
@@ -151,7 +151,7 @@ public static long countf(@NotNull String queryFormat, @NotNull Object... args)
151151
* @throws SQLException If an error occurs.
152152
*/
153153
public static int update(@NotNull String query, Object @NotNull ... params) throws SQLException {
154-
try (Connection c = Bot.dataSource.getConnection(); PreparedStatement stmt = c.prepareStatement(query)) {
154+
try (Connection c = Bot.getDataSource().getConnection(); PreparedStatement stmt = c.prepareStatement(query)) {
155155
int i = 1;
156156
for (Object param : params) {
157157
stmt.setObject(i++, param);
@@ -168,8 +168,8 @@ public static int update(@NotNull String query, Object @NotNull ... params) thro
168168
*/
169169
public static @NotNull CompletableFuture<Void> doAsyncAction(ConnectionConsumer consumer) {
170170
CompletableFuture<Void> future = new CompletableFuture<>();
171-
Bot.asyncPool.submit(() -> {
172-
try (Connection c = Bot.dataSource.getConnection()) {
171+
Bot.getAsyncPool().submit(() -> {
172+
try (Connection c = Bot.getDataSource().getConnection()) {
173173
consumer.consume(c);
174174
future.complete(null);
175175
} catch (SQLException e) {
@@ -192,8 +192,8 @@ public static int update(@NotNull String query, Object @NotNull ... params) thro
192192
*/
193193
public static <T> @NotNull CompletableFuture<Void> doAsyncDaoAction(Function<Connection, T> daoConstructor, DaoConsumer<T> consumer) {
194194
CompletableFuture<Void> future = new CompletableFuture<>();
195-
Bot.asyncPool.submit(() -> {
196-
try (Connection c = Bot.dataSource.getConnection()) {
195+
Bot.getAsyncPool().submit(() -> {
196+
try (Connection c = Bot.getDataSource().getConnection()) {
197197
T dao = daoConstructor.apply(c);
198198
consumer.consume(dao);
199199
future.complete(null);
@@ -214,8 +214,8 @@ public static int update(@NotNull String query, Object @NotNull ... params) thro
214214
*/
215215
public static <T> @NotNull CompletableFuture<T> mapAsync(ConnectionFunction<T> function) {
216216
CompletableFuture<T> future = new CompletableFuture<>();
217-
Bot.asyncPool.submit(() -> {
218-
try (Connection c = Bot.dataSource.getConnection()) {
217+
Bot.getAsyncPool().submit(() -> {
218+
try (Connection c = Bot.getDataSource().getConnection()) {
219219
future.complete(function.apply(c));
220220
} catch (SQLException e) {
221221
ExceptionLogger.capture(e, DbActions.class.getSimpleName());
@@ -254,7 +254,7 @@ public static <T> Optional<T> fetchSingleEntity(String query, StatementModifier
254254
* @return The logical size, in bytes.
255255
*/
256256
public static int getLogicalSize(String table) {
257-
try (Connection c = Bot.dataSource.getConnection(); PreparedStatement stmt = c.prepareStatement("CALL DISK_SPACE_USED(?)")) {
257+
try (Connection c = Bot.getDataSource().getConnection(); PreparedStatement stmt = c.prepareStatement("CALL DISK_SPACE_USED(?)")) {
258258
stmt.setString(1, table);
259259
ResultSet rs = stmt.executeQuery();
260260
if (rs.next()) {

src/main/java/net/javadiscord/javabot/data/h2db/DbHelper.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -81,8 +81,8 @@ private DbHelper() {
8181
* @param consumer The consumer that will use a connection.
8282
*/
8383
public static void doDbAction(ConnectionConsumer consumer) {
84-
Bot.asyncPool.submit(() -> {
85-
try (Connection c = Bot.dataSource.getConnection()) {
84+
Bot.getAsyncPool().submit(() -> {
85+
try (Connection c = Bot.getDataSource().getConnection()) {
8686
consumer.consume(c);
8787
} catch (SQLException e) {
8888
ExceptionLogger.capture(e, DbHelper.class.getSimpleName());
@@ -100,8 +100,8 @@ public static void doDbAction(ConnectionConsumer consumer) {
100100
* @param <T> The type of data access object. Usually some kind of repository.
101101
*/
102102
public static <T> void doDaoAction(Function<Connection, T> daoConstructor, DaoConsumer<T> consumer) {
103-
Bot.asyncPool.submit(() -> {
104-
try (Connection c = Bot.dataSource.getConnection()) {
103+
Bot.getAsyncPool().submit(() -> {
104+
try (Connection c = Bot.getDataSource().getConnection()) {
105105
T dao = daoConstructor.apply(c);
106106
consumer.consume(dao);
107107
} catch (SQLException e) {

src/main/java/net/javadiscord/javabot/data/h2db/commands/DbAdminCommand.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,6 @@ public DbAdminCommand() {
2929
addSubcommandGroups(Map.of(
3030
new SubcommandGroupData("message-cache", "Administrative tools for managing the Message Cache."), Set.of(new MessageCacheInfoSubcommand())
3131
));
32-
requireUsers(Bot.config.getSystems().getAdminConfig().getAdminUsers());
32+
requireUsers(Bot.getConfig().getSystems().getAdminConfig().getAdminUsers());
3333
}
3434
}

src/main/java/net/javadiscord/javabot/data/h2db/commands/ExportSchemaSubcommand.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,16 +30,16 @@ public class ExportSchemaSubcommand extends SlashCommand.Subcommand {
3030
public ExportSchemaSubcommand() {
3131
setSubcommandData(new SubcommandData("export-schema", "(ADMIN ONLY) Exports the bot's schema.")
3232
.addOption(OptionType.BOOLEAN, "include-data", "Should data be included in the export?"));
33-
requireUsers(Bot.config.getSystems().getAdminConfig().getAdminUsers());
33+
requireUsers(Bot.getConfig().getSystems().getAdminConfig().getAdminUsers());
3434
requirePermissions(Permission.MANAGE_SERVER);
3535
}
3636

3737
@Override
3838
public void execute(SlashCommandInteractionEvent event) {
3939
boolean includeData = event.getOption("include-data", false, OptionMapping::getAsBoolean);
4040
event.deferReply(false).queue();
41-
Bot.asyncPool.submit(() -> {
42-
try (Connection con = Bot.dataSource.getConnection()) {
41+
Bot.getAsyncPool().submit(() -> {
42+
try (Connection con = Bot.getDataSource().getConnection()) {
4343
PreparedStatement stmt = con.prepareStatement(String.format("SCRIPT %s TO '%s';", includeData ? "" : "NODATA", SCHEMA_FILE));
4444
boolean success = stmt.execute();
4545
if (!success) {

src/main/java/net/javadiscord/javabot/data/h2db/commands/ExportTableSubcommand.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ public ExportTableSubcommand() {
4444
.addChoice("Starboard", "STARBOARD")
4545
.addChoice("Warns", "WARN"),
4646
new OptionData(OptionType.BOOLEAN, "include-data", "Should data be included in the export?")));
47-
requireUsers(Bot.config.getSystems().getAdminConfig().getAdminUsers());
47+
requireUsers(Bot.getConfig().getSystems().getAdminConfig().getAdminUsers());
4848
requirePermissions(Permission.MANAGE_SERVER);
4949
}
5050

@@ -57,8 +57,8 @@ public void execute(SlashCommandInteractionEvent event) {
5757
return;
5858
}
5959
event.deferReply(false).queue();
60-
Bot.asyncPool.submit(() -> {
61-
try (Connection con = Bot.dataSource.getConnection()) {
60+
Bot.getAsyncPool().submit(() -> {
61+
try (Connection con = Bot.getDataSource().getConnection()) {
6262
PreparedStatement stmt = con.prepareStatement(String.format("SCRIPT %s TO '%s' TABLE %s;", includeData ? "COLUMNS" : "NODATA", TABLE_FILE, tableOption.getAsString()));
6363
boolean success = stmt.execute();
6464
if (!success) {

src/main/java/net/javadiscord/javabot/data/h2db/commands/MessageCacheInfoSubcommand.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,13 +21,13 @@ public class MessageCacheInfoSubcommand extends SlashCommand.Subcommand {
2121
*/
2222
public MessageCacheInfoSubcommand() {
2323
setSubcommandData(new SubcommandData("info", "Displays some info about the Message Cache."));
24-
requireUsers(Bot.config.getSystems().getAdminConfig().getAdminUsers());
24+
requireUsers(Bot.getConfig().getSystems().getAdminConfig().getAdminUsers());
2525
requirePermissions(Permission.MANAGE_SERVER);
2626
}
2727

2828
@Override
2929
public void execute(SlashCommandInteractionEvent event) {
30-
event.replyEmbeds(buildInfoEmbed(Bot.config.get(event.getGuild()), event.getUser())).queue();
30+
event.replyEmbeds(buildInfoEmbed(Bot.getConfig().get(event.getGuild()), event.getUser())).queue();
3131
}
3232

3333
private MessageEmbed buildInfoEmbed(GuildConfig config, User author) {
@@ -38,8 +38,8 @@ private MessageEmbed buildInfoEmbed(GuildConfig config, User author) {
3838
.setTitle("Message Cache Info")
3939
.setColor(Responses.Type.DEFAULT.getColor())
4040
.addField("Table Size", DbActions.getLogicalSize("message_cache") + " bytes", false)
41-
.addField("Message Count", String.valueOf(Bot.messageCache.messageCount), true)
42-
.addField("Cached (Memory)", String.format("%s/%s (%.2f%%)", Bot.messageCache.cache.size(), maxMessages, ((float) Bot.messageCache.cache.size() / maxMessages) * 100), true)
41+
.addField("Message Count", String.valueOf(Bot.getMessageCache().messageCount), true)
42+
.addField("Cached (Memory)", String.format("%s/%s (%.2f%%)", Bot.getMessageCache().cache.size(), maxMessages, ((float) Bot.getMessageCache().cache.size() / maxMessages) * 100), true)
4343
.addField("Cached (Database)", String.format("%s/%s (%.2f%%)", messages, maxMessages, ((float) messages / maxMessages) * 100), true)
4444
.build();
4545
}

src/main/java/net/javadiscord/javabot/data/h2db/commands/MigrateSubcommand.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ public class MigrateSubcommand extends SlashCommand.Subcommand implements AutoCo
4646
public MigrateSubcommand() {
4747
setSubcommandData(new SubcommandData("migrate", "(ADMIN ONLY) Run a single database migration")
4848
.addOption(OptionType.STRING, "name", "The migration's filename", true, true));
49-
requireUsers(Bot.config.getSystems().getAdminConfig().getAdminUsers());
49+
requireUsers(Bot.getConfig().getSystems().getAdminConfig().getAdminUsers());
5050
requirePermissions(Permission.MANAGE_SERVER);
5151
}
5252

@@ -87,8 +87,8 @@ public void execute(@NotNull SlashCommandInteractionEvent event) {
8787
return;
8888
}
8989
event.deferReply().queue();
90-
Bot.asyncPool.submit(() -> {
91-
try (Connection con = Bot.dataSource.getConnection()) {
90+
Bot.getAsyncPool().submit(() -> {
91+
try (Connection con = Bot.getDataSource().getConnection()) {
9292
for (int i = 0; i < statements.length; i++) {
9393
if (statements[i].isBlank()) {
9494
event.getHook().sendMessage("Skipping statement " + (i + 1) + "; it is blank.").queue();

src/main/java/net/javadiscord/javabot/data/h2db/commands/MigrationsListSubcommand.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ public class MigrationsListSubcommand extends SlashCommand.Subcommand {
2828
*/
2929
public MigrationsListSubcommand() {
3030
setSubcommandData(new SubcommandData("migrations-list", "(ADMIN ONLY) Shows a list with all available database migrations."));
31-
requireUsers(Bot.config.getSystems().getAdminConfig().getAdminUsers());
31+
requireUsers(Bot.getConfig().getSystems().getAdminConfig().getAdminUsers());
3232
requirePermissions(Permission.MANAGE_SERVER);
3333
}
3434

src/main/java/net/javadiscord/javabot/data/h2db/commands/QuickMigrateSubcommand.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ public class QuickMigrateSubcommand extends SlashCommand.Subcommand implements M
3333
*/
3434
public QuickMigrateSubcommand() {
3535
setSubcommandData(new SubcommandData("quick-migrate", "(ADMIN ONLY) Run a single quick database migration"));
36-
requireUsers(Bot.config.getSystems().getAdminConfig().getAdminUsers());
36+
requireUsers(Bot.getConfig().getSystems().getAdminConfig().getAdminUsers());
3737
requirePermissions(Permission.MANAGE_SERVER);
3838
}
3939

@@ -61,9 +61,9 @@ public void handleModal(@NotNull ModalInteractionEvent event, List<ModalMapping>
6161
Responses.error(event.getHook(), "The provided migration does not contain any statements. Please remove or edit it before running again.").queue();
6262
return;
6363
}
64-
Bot.asyncPool.submit(() -> {
64+
Bot.getAsyncPool().submit(() -> {
6565
TextChannel channel = event.getChannel().asTextChannel();
66-
try (Connection con = Bot.dataSource.getConnection()) {
66+
try (Connection con = Bot.getDataSource().getConnection()) {
6767
for (int i = 0; i < statements.length; i++) {
6868
if (statements[i].isBlank()) {
6969
channel.sendMessage("Skipping statement " + (i + 1) + "; it is blank.").queue();

0 commit comments

Comments
 (0)