Skip to content

Commit 07e06c0

Browse files
committed
add setting and getting config in json format
1 parent 41197ab commit 07e06c0

File tree

7 files changed

+50
-21
lines changed

7 files changed

+50
-21
lines changed

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,8 +68,8 @@ public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
6868
for(Class<?> cl : getClass().getClassLoader().loadClass("sun.font.FontConfigManager").getDeclaredClasses()) {
6969
hints.jni().registerType(cl, MemberCategory.ACCESS_DECLARED_FIELDS, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS);
7070
}
71-
} catch (ClassNotFoundException e) {
72-
throw new RuntimeException(e);
71+
} catch (ClassNotFoundException _) {
72+
// FontConfigManager is only supported on Linux
7373
}
7474

7575
for (Class<?> cl : WebhookEmbed.class.getClasses()) {

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

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

9+
import com.google.gson.Gson;
10+
import com.google.gson.GsonBuilder;
11+
import net.discordjug.javabot.data.config.PatternTypeAdapter;
812
import org.springframework.context.ApplicationContext;
913
import org.springframework.context.annotation.Bean;
1014
import org.springframework.context.annotation.Configuration;
@@ -90,4 +94,13 @@ BotConfig botConfig() {
9094
}
9195
return botConfig;
9296
}
97+
98+
@Bean
99+
Gson gson() {
100+
return new GsonBuilder()
101+
.serializeNulls()
102+
.setPrettyPrinting()
103+
.registerTypeAdapter(Pattern.class, new PatternTypeAdapter())
104+
.create();
105+
}
93106
}

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,10 @@ public void set(String propertyName, String value) throws UnknownPropertyExcepti
167167
Optional<Pair<Field, Object>> result = ReflectionUtils.resolveField(propertyName, this);
168168
result.ifPresent(pair -> {
169169
try {
170-
ReflectionUtils.set(pair.first(), pair.second(), value);
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);
173+
}
171174
this.flush();
172175
} catch (IllegalAccessException e) {
173176
ExceptionLogger.capture(e, getClass().getSimpleName());

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

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

3+
import com.google.gson.Gson;
4+
import com.google.gson.GsonBuilder;
35
import lombok.extern.slf4j.Slf4j;
46
import net.discordjug.javabot.util.ExceptionLogger;
57
import net.discordjug.javabot.util.Pair;
@@ -14,13 +16,19 @@
1416
import java.util.Map;
1517
import java.util.Optional;
1618
import java.util.function.Function;
19+
import java.util.regex.Pattern;
1720

1821
/**
1922
* Utility class for resolving JSON files.
2023
*/
2124
@Slf4j
2225
public class ReflectionUtils {
2326
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();
2432

2533
static {
2634
propertyTypeParsers.put(Integer.class, Integer::parseInt);
@@ -126,13 +134,11 @@ private static Field findDeclaredField(Class<?> cl, String name) throws NoSuchFi
126134
* @param field The field to set.
127135
* @param parent The object whose property value to set.
128136
* @param s The string representation of the value.
137+
* @return Returns the edited {@link Field}.
129138
* @throws IllegalAccessException If the field cannot be set.
130139
*/
131-
public static void set(@NotNull Field field, @NotNull Object parent, @NotNull String s) throws IllegalAccessException {
132-
Function<String, Object> parser = propertyTypeParsers.get(field.getType());
133-
if (parser == null) {
134-
throw new IllegalArgumentException("No supported property type parser for the type " + field.getType().getSimpleName());
135-
}
136-
field.set(parent, parser.apply(s));
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;
137143
}
138144
}

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

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,11 @@
1111
import java.time.Duration;
1212
import java.util.Base64;
1313
import java.util.List;
14-
import java.util.regex.Pattern;
1514
import java.util.stream.Collectors;
1615

1716
import com.google.gson.Gson;
18-
import com.google.gson.GsonBuilder;
1917
import lombok.RequiredArgsConstructor;
2018
import net.discordjug.javabot.data.config.BotConfig;
21-
import net.discordjug.javabot.data.config.PatternTypeAdapter;
2219
import net.discordjug.javabot.data.config.guild.MessageRule;
2320
import net.discordjug.javabot.data.config.guild.MessageRule.MessageAction;
2421
import net.discordjug.javabot.data.config.guild.ModerationConfig;
@@ -41,6 +38,7 @@ public class MessageRuleFilter implements MessageFilter {
4138

4239
private final BotConfig botConfig;
4340
private final MessageCache messageCache;
41+
private final Gson gson;
4442

4543
@Override
4644
public MessageModificationStatus processMessage(MessageContent content) {
@@ -73,11 +71,6 @@ public MessageModificationStatus processMessage(MessageContent content) {
7371
}
7472

7573
private void log(MessageContent content, MessageRule ruleToExecute, ModerationConfig moderationConfig) {
76-
Gson gson = new GsonBuilder()
77-
.serializeNulls()
78-
.setPrettyPrinting()
79-
.registerTypeAdapter(Pattern.class, new PatternTypeAdapter())
80-
.create();
8174
EmbedBuilder embed = messageCache.buildMessageCacheEmbed(
8275
content.event().getMessage().getChannel(),
8376
content.event().getMessage().getAuthor(),

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

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

3+
import com.google.gson.Gson;
34
import net.discordjug.javabot.data.config.BotConfig;
45
import net.discordjug.javabot.data.config.GuildConfig;
56
import net.discordjug.javabot.data.config.UnknownPropertyException;
@@ -19,15 +20,20 @@
1920
* Subcommand that allows staff-members to get a single property variable from the guild config.
2021
*/
2122
public class GetConfigSubcommand extends ConfigSubcommand implements AutoCompletable {
23+
24+
private final Gson gson;
25+
2226
/**
2327
* The constructor of this class, which sets the corresponding {@link SubcommandData}.
2428
* @param botConfig The main configuration of the bot
29+
* @param gson Mapper used for displaying config as json
2530
*/
26-
public GetConfigSubcommand(BotConfig botConfig) {
31+
public GetConfigSubcommand(BotConfig botConfig, Gson gson) {
2732
super(botConfig);
2833
setCommandData(new SubcommandData("get", "Get the current value of a configuration property.")
2934
.addOption(OptionType.STRING, "property", "The name of a property.", true, true)
3035
);
36+
this.gson = gson;
3137
}
3238

3339
@Override
@@ -38,7 +44,8 @@ public ReplyCallbackAction handleConfigSubcommand(@Nonnull SlashCommandInteracti
3844
}
3945
String property = propertyOption.getAsString().trim();
4046
Object value = config.resolve(property);
41-
return Responses.info(event, "Configuration Property", "The value of the property `%s` is:\n```\n%s\n```", property, value);
47+
String json = gson.toJson(value);
48+
return Responses.info(event, "Configuration Property", "The value of the property `%s` is:\n```\n%s\n```", property, json);
4249
}
4350

4451
@Override

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

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

3+
import com.google.gson.Gson;
34
import net.discordjug.javabot.annotations.AutoDetectableComponentHandler;
45
import net.discordjug.javabot.data.config.BotConfig;
56
import net.discordjug.javabot.data.config.GuildConfig;
@@ -31,16 +32,21 @@
3132
*/
3233
@AutoDetectableComponentHandler("config-set")
3334
public class SetConfigSubcommand extends ConfigSubcommand implements ModalHandler, AutoCompletable {
35+
36+
private final Gson gson;
37+
3438
/**
3539
* The constructor of this class, which sets the corresponding {@link SubcommandData}.
3640
* @param botConfig The main configuration of the bot
41+
* @param gson Mapper used for displaying config as json
3742
*/
38-
public SetConfigSubcommand(BotConfig botConfig) {
43+
public SetConfigSubcommand(BotConfig botConfig, Gson gson) {
3944
super(botConfig);
4045
setCommandData(new SubcommandData("set", "Sets the value of a configuration property.")
4146
.addOption(OptionType.STRING, "property", "The name of a property.", true, true)
4247
.addOption(OptionType.STRING, "value", "The value to set for the property.", false)
4348
);
49+
this.gson = gson;
4450
}
4551

4652
@Override
@@ -57,10 +63,11 @@ public InteractionCallbackAction<?> handleConfigSubcommand(@Nonnull SlashCommand
5763
if (resolved == null) {
5864
return Responses.error(event, "Config `%s` not found", property);
5965
}
66+
String json = gson.toJson(resolved);
6067
return event.replyModal(
6168
Modal.create(ComponentIdBuilder.build("config-set", property), "Change configuration value")
6269
.addComponents(Label.of("new value", TextInput.create("value", TextInputStyle.PARAGRAPH)
63-
.setValue(String.valueOf(resolved))
70+
.setValue(json)
6471
.build()))
6572
.build());
6673
}

0 commit comments

Comments
 (0)