Skip to content

Commit 67041fd

Browse files
committed
fix fix
1 parent 07e06c0 commit 67041fd

File tree

8 files changed

+62
-79
lines changed

8 files changed

+62
-79
lines changed

src/main/java/net/discordjug/javabot/SpringConfig.java

Lines changed: 0 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,7 @@
44
import java.util.Collection;
55
import java.util.concurrent.Executors;
66
import java.util.concurrent.ScheduledExecutorService;
7-
import java.util.regex.Pattern;
87

9-
import com.google.gson.Gson;
10-
import com.google.gson.GsonBuilder;
11-
import net.discordjug.javabot.data.config.PatternTypeAdapter;
128
import org.springframework.context.ApplicationContext;
139
import org.springframework.context.annotation.Bean;
1410
import org.springframework.context.annotation.Configuration;
@@ -94,13 +90,4 @@ BotConfig botConfig() {
9490
}
9591
return botConfig;
9692
}
97-
98-
@Bean
99-
Gson gson() {
100-
return new GsonBuilder()
101-
.serializeNulls()
102-
.setPrettyPrinting()
103-
.registerTypeAdapter(Pattern.class, new PatternTypeAdapter())
104-
.create();
105-
}
10693
}

src/main/java/net/discordjug/javabot/data/config/BotConfig.java

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
11
package net.discordjug.javabot.data.config;
22

3-
import com.google.gson.Gson;
4-
import com.google.gson.GsonBuilder;
53
import com.google.gson.JsonSyntaxException;
64
import lombok.extern.slf4j.Slf4j;
75
import net.discordjug.javabot.util.ExceptionLogger;
6+
import net.discordjug.javabot.util.GsonUtils;
87
import net.dv8tion.jda.api.entities.Guild;
98

109
import org.jetbrains.annotations.NotNull;
@@ -64,11 +63,10 @@ public BotConfig(Path dir) {
6463
}
6564
}
6665
this.guilds = new ConcurrentHashMap<>();
67-
Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
6866
Path systemsFile = dir.resolve(SYSTEMS_FILE);
6967
if (Files.exists(systemsFile)) {
7068
try (BufferedReader reader = Files.newBufferedReader(systemsFile)) {
71-
this.systemsConfig = gson.fromJson(reader, SystemsConfig.class);
69+
this.systemsConfig = GsonUtils.fromJson(reader, SystemsConfig.class);
7270
log.info("Loaded systems config from {}", systemsFile);
7371
} catch (JsonSyntaxException e) {
7472
ExceptionLogger.capture(e, getClass().getSimpleName());
@@ -133,10 +131,9 @@ public SystemsConfig getSystems() {
133131
* Flushes all configuration to the disk.
134132
*/
135133
public void flush() {
136-
Gson gson = new GsonBuilder().serializeNulls().setPrettyPrinting().create();
137134
Path systemsFile = this.dir.resolve(SYSTEMS_FILE);
138135
try (BufferedWriter writer = Files.newBufferedWriter(systemsFile)) {
139-
gson.toJson(this.systemsConfig, writer);
136+
GsonUtils.toJson(this.systemsConfig, writer);
140137
writer.flush();
141138
} catch (IOException e) {
142139
ExceptionLogger.capture(e, getClass().getSimpleName());

src/main/java/net/discordjug/javabot/data/config/GuildConfig.java

Lines changed: 6 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
11
package net.discordjug.javabot.data.config;
22

3-
import com.google.gson.Gson;
4-
import com.google.gson.GsonBuilder;
53
import com.google.gson.JsonSyntaxException;
64
import lombok.Data;
75
import lombok.extern.slf4j.Slf4j;
86
import net.discordjug.javabot.data.config.guild.*;
97
import net.discordjug.javabot.util.ExceptionLogger;
8+
import net.discordjug.javabot.util.GsonUtils;
109
import net.discordjug.javabot.util.Pair;
1110
import net.dv8tion.jda.api.entities.Guild;
1211

@@ -20,7 +19,6 @@
2019
import java.nio.file.Path;
2120
import java.util.List;
2221
import java.util.Optional;
23-
import java.util.regex.Pattern;
2422

2523
/**
2624
* A collection of guild-specific configuration items, each of which represents
@@ -71,13 +69,10 @@ public GuildConfig(Guild guild, Path file) {
7169
* @throws UncheckedIOException if an IO error occurs.
7270
*/
7371
public static GuildConfig loadOrCreate(Guild guild, Path file) {
74-
Gson gson = new GsonBuilder()
75-
.registerTypeAdapter(Pattern.class, new PatternTypeAdapter())
76-
.create();
7772
GuildConfig config;
7873
if (Files.exists(file)) {
7974
try (BufferedReader reader = Files.newBufferedReader(file)) {
80-
config = gson.fromJson(reader, GuildConfig.class);
75+
config = GsonUtils.fromJson(reader, GuildConfig.class);
8176
config.setFile(file);
8277
config.setGuild(guild);
8378
log.info("Loaded config from {}", file);
@@ -118,13 +113,8 @@ private void setGuild(Guild guild) {
118113
* Saves this config to its file path.
119114
*/
120115
public synchronized void flush() {
121-
Gson gson = new GsonBuilder()
122-
.serializeNulls()
123-
.setPrettyPrinting()
124-
.registerTypeAdapter(Pattern.class, new PatternTypeAdapter())
125-
.create();
126116
try (BufferedWriter writer = Files.newBufferedWriter(this.file)) {
127-
gson.toJson(this, writer);
117+
GsonUtils.toJson(this, writer);
128118
writer.flush();
129119
} catch (IOException e) {
130120
ExceptionLogger.capture(e, getClass().getSimpleName());
@@ -167,9 +157,9 @@ public void set(String propertyName, String value) throws UnknownPropertyExcepti
167157
Optional<Pair<Field, Object>> result = ReflectionUtils.resolveField(propertyName, this);
168158
result.ifPresent(pair -> {
169159
try {
170-
Field updatedField = ReflectionUtils.set(pair.first(), pair.second(), value);
171-
if (updatedField.get(pair.second()) instanceof GuildConfigItem) {
172-
((GuildConfigItem) updatedField.get(pair.second())).setGuildConfig(this);
160+
Object updatedField = ReflectionUtils.set(pair.first(), pair.second(), value);
161+
if (updatedField instanceof GuildConfigItem item) {
162+
item.setGuildConfig(this);
173163
}
174164
this.flush();
175165
} catch (IllegalAccessException e) {

src/main/java/net/discordjug/javabot/data/config/ReflectionUtils.java

Lines changed: 6 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
package net.discordjug.javabot.data.config;
22

3-
import com.google.gson.Gson;
4-
import com.google.gson.GsonBuilder;
53
import lombok.extern.slf4j.Slf4j;
64
import net.discordjug.javabot.util.ExceptionLogger;
5+
import net.discordjug.javabot.util.GsonUtils;
76
import net.discordjug.javabot.util.Pair;
87

98
import org.jetbrains.annotations.NotNull;
@@ -16,32 +15,13 @@
1615
import java.util.Map;
1716
import java.util.Optional;
1817
import java.util.function.Function;
19-
import java.util.regex.Pattern;
2018

2119
/**
2220
* Utility class for resolving JSON files.
2321
*/
2422
@Slf4j
2523
public class ReflectionUtils {
2624
private static final Map<Class<?>, Function<String, Object>> propertyTypeParsers = new HashMap<>();
27-
private static final Gson gson = new GsonBuilder()
28-
.serializeNulls()
29-
.setPrettyPrinting()
30-
.registerTypeAdapter(Pattern.class, new PatternTypeAdapter())
31-
.create();
32-
33-
static {
34-
propertyTypeParsers.put(Integer.class, Integer::parseInt);
35-
propertyTypeParsers.put(int.class, Integer::parseInt);
36-
propertyTypeParsers.put(Long.class, Long::parseLong);
37-
propertyTypeParsers.put(long.class, Long::parseLong);
38-
propertyTypeParsers.put(Float.class, Float::parseFloat);
39-
propertyTypeParsers.put(float.class, Float::parseFloat);
40-
propertyTypeParsers.put(Double.class, Double::parseDouble);
41-
propertyTypeParsers.put(double.class, Double::parseDouble);
42-
propertyTypeParsers.put(Boolean.class, Boolean::parseBoolean);
43-
propertyTypeParsers.put(String.class, s -> s);
44-
}
4525

4626
private ReflectionUtils() {
4727
}
@@ -134,11 +114,12 @@ private static Field findDeclaredField(Class<?> cl, String name) throws NoSuchFi
134114
* @param field The field to set.
135115
* @param parent The object whose property value to set.
136116
* @param s The string representation of the value.
137-
* @return Returns the edited {@link Field}.
117+
* @return Returns the new value.
138118
* @throws IllegalAccessException If the field cannot be set.
139119
*/
140-
public static Field set(@NotNull Field field, @NotNull Object parent, @NotNull String s) throws IllegalAccessException {
141-
field.set(parent, gson.fromJson(s, field.getType()));
142-
return field;
120+
public static Object set(@NotNull Field field, @NotNull Object parent, @NotNull String s) throws IllegalAccessException {
121+
Object value = GsonUtils.fromJson(s, field.getType());
122+
field.set(parent, value);
123+
return value;
143124
}
144125
}

src/main/java/net/discordjug/javabot/listener/filter/MessageRuleFilter.java

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@
1313
import java.util.List;
1414
import java.util.stream.Collectors;
1515

16-
import com.google.gson.Gson;
1716
import lombok.RequiredArgsConstructor;
1817
import net.discordjug.javabot.data.config.BotConfig;
1918
import net.discordjug.javabot.data.config.guild.MessageRule;
@@ -23,6 +22,7 @@
2322
import net.discordjug.javabot.data.h2db.message_cache.model.CachedMessage;
2423
import net.discordjug.javabot.util.Checks;
2524
import net.discordjug.javabot.util.ExceptionLogger;
25+
import net.discordjug.javabot.util.GsonUtils;
2626
import net.dv8tion.jda.api.EmbedBuilder;
2727
import net.dv8tion.jda.api.entities.Message.Attachment;
2828
import net.dv8tion.jda.api.entities.Message;
@@ -38,7 +38,6 @@ public class MessageRuleFilter implements MessageFilter {
3838

3939
private final BotConfig botConfig;
4040
private final MessageCache messageCache;
41-
private final Gson gson;
4241

4342
@Override
4443
public MessageModificationStatus processMessage(MessageContent content) {
@@ -76,7 +75,7 @@ private void log(MessageContent content, MessageRule ruleToExecute, ModerationCo
7675
content.event().getMessage().getAuthor(),
7776
CachedMessage.of(content.event().getMessage()), "Message content")
7877
.setTitle("Message rule triggered")
79-
.addField("Rule description", "```\n" + gson.toJson(ruleToExecute) + "\n```", false);
78+
.addField("Rule description", "```\n" + GsonUtils.toJson(ruleToExecute) + "\n```", false);
8079
if (!content.attachments().isEmpty()) {
8180
embed.addField("Attachment hashes", computeAttachmentDescription(content.attachments()), false);
8281
}

src/main/java/net/discordjug/javabot/systems/configuration/GetConfigSubcommand.java

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
package net.discordjug.javabot.systems.configuration;
22

3-
import com.google.gson.Gson;
43
import net.discordjug.javabot.data.config.BotConfig;
54
import net.discordjug.javabot.data.config.GuildConfig;
65
import net.discordjug.javabot.data.config.UnknownPropertyException;
6+
import net.discordjug.javabot.util.GsonUtils;
77
import net.discordjug.javabot.util.Responses;
88
import net.dv8tion.jda.api.events.interaction.command.CommandAutoCompleteInteractionEvent;
99
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
@@ -20,20 +20,15 @@
2020
* Subcommand that allows staff-members to get a single property variable from the guild config.
2121
*/
2222
public class GetConfigSubcommand extends ConfigSubcommand implements AutoCompletable {
23-
24-
private final Gson gson;
25-
2623
/**
2724
* The constructor of this class, which sets the corresponding {@link SubcommandData}.
2825
* @param botConfig The main configuration of the bot
29-
* @param gson Mapper used for displaying config as json
3026
*/
31-
public GetConfigSubcommand(BotConfig botConfig, Gson gson) {
27+
public GetConfigSubcommand(BotConfig botConfig) {
3228
super(botConfig);
3329
setCommandData(new SubcommandData("get", "Get the current value of a configuration property.")
3430
.addOption(OptionType.STRING, "property", "The name of a property.", true, true)
3531
);
36-
this.gson = gson;
3732
}
3833

3934
@Override
@@ -44,7 +39,7 @@ public ReplyCallbackAction handleConfigSubcommand(@Nonnull SlashCommandInteracti
4439
}
4540
String property = propertyOption.getAsString().trim();
4641
Object value = config.resolve(property);
47-
String json = gson.toJson(value);
42+
String json = GsonUtils.toJson(value);
4843
return Responses.info(event, "Configuration Property", "The value of the property `%s` is:\n```\n%s\n```", property, json);
4944
}
5045

src/main/java/net/discordjug/javabot/systems/configuration/SetConfigSubcommand.java

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
package net.discordjug.javabot.systems.configuration;
22

3-
import com.google.gson.Gson;
43
import net.discordjug.javabot.annotations.AutoDetectableComponentHandler;
54
import net.discordjug.javabot.data.config.BotConfig;
65
import net.discordjug.javabot.data.config.GuildConfig;
76
import net.discordjug.javabot.data.config.UnknownPropertyException;
7+
import net.discordjug.javabot.util.GsonUtils;
88
import net.discordjug.javabot.util.Responses;
99
import net.dv8tion.jda.api.components.label.Label;
1010
import net.dv8tion.jda.api.components.textinput.TextInput;
@@ -32,21 +32,16 @@
3232
*/
3333
@AutoDetectableComponentHandler("config-set")
3434
public class SetConfigSubcommand extends ConfigSubcommand implements ModalHandler, AutoCompletable {
35-
36-
private final Gson gson;
37-
3835
/**
3936
* The constructor of this class, which sets the corresponding {@link SubcommandData}.
4037
* @param botConfig The main configuration of the bot
41-
* @param gson Mapper used for displaying config as json
4238
*/
43-
public SetConfigSubcommand(BotConfig botConfig, Gson gson) {
39+
public SetConfigSubcommand(BotConfig botConfig) {
4440
super(botConfig);
4541
setCommandData(new SubcommandData("set", "Sets the value of a configuration property.")
4642
.addOption(OptionType.STRING, "property", "The name of a property.", true, true)
4743
.addOption(OptionType.STRING, "value", "The value to set for the property.", false)
4844
);
49-
this.gson = gson;
5045
}
5146

5247
@Override
@@ -63,7 +58,7 @@ public InteractionCallbackAction<?> handleConfigSubcommand(@Nonnull SlashCommand
6358
if (resolved == null) {
6459
return Responses.error(event, "Config `%s` not found", property);
6560
}
66-
String json = gson.toJson(resolved);
61+
String json = GsonUtils.toJson(resolved);
6762
return event.replyModal(
6863
Modal.create(ComponentIdBuilder.build("config-set", property), "Change configuration value")
6964
.addComponents(Label.of("new value", TextInput.create("value", TextInputStyle.PARAGRAPH)
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package net.discordjug.javabot.util;
2+
3+
import com.google.gson.Gson;
4+
import com.google.gson.GsonBuilder;
5+
import net.discordjug.javabot.data.config.PatternTypeAdapter;
6+
7+
import java.io.Reader;
8+
import java.io.Writer;
9+
import java.util.regex.Pattern;
10+
11+
/**
12+
* Utility class that contains several methods for using Gson.
13+
*/
14+
public class GsonUtils {
15+
16+
private static final Gson gson = new GsonBuilder()
17+
.serializeNulls()
18+
.setPrettyPrinting()
19+
.registerTypeAdapter(Pattern.class, new PatternTypeAdapter())
20+
.enableComplexMapKeySerialization()
21+
.create();
22+
23+
public static <T> T fromJson(String json, Class<T> type) {
24+
return gson.fromJson(json, type);
25+
}
26+
27+
public static <T> T fromJson(Reader json, Class<T> type) {
28+
return gson.fromJson(json, type);
29+
}
30+
31+
public static String toJson(Object object) {
32+
return gson.toJson(object);
33+
}
34+
35+
public static void toJson(Object object, Writer writer) {
36+
gson.toJson(object, writer);
37+
}
38+
39+
}

0 commit comments

Comments
 (0)