From 823ce84dc3cc9375a919c60ed71c2c6dd98b3410 Mon Sep 17 00:00:00 2001 From: Napster Date: Sun, 10 Dec 2023 14:44:46 +0100 Subject: [PATCH] Convert configuration to record --- .../space/npstr/baymax/HelpDeskListener.java | 39 +++--- .../java/space/npstr/baymax/Launcher.java | 20 ++-- .../java/space/npstr/baymax/ModelLoader.java | 12 +- .../config/ShardManagerConfiguration.java | 6 +- .../config/properties/BaymaxConfig.java | 111 ++++++------------ 5 files changed, 73 insertions(+), 115 deletions(-) diff --git a/src/main/java/space/npstr/baymax/HelpDeskListener.java b/src/main/java/space/npstr/baymax/HelpDeskListener.java index f317b53..2409c6d 100644 --- a/src/main/java/space/npstr/baymax/HelpDeskListener.java +++ b/src/main/java/space/npstr/baymax/HelpDeskListener.java @@ -20,6 +20,13 @@ import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import com.github.benmanes.caffeine.cache.RemovalCause; +import java.net.URI; +import java.time.Duration; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; import net.dv8tion.jda.api.entities.channel.middleman.MessageChannel; @@ -37,14 +44,6 @@ import space.npstr.baymax.helpdesk.Node; import space.npstr.baymax.helpdesk.exception.MalformedModelException; -import java.net.URI; -import java.time.Duration; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.TimeUnit; - /** * Created by napster on 05.09.18. */ @@ -81,8 +80,8 @@ public void onMessageReceived(MessageReceivedEvent event) { return; } - var helpDeskOpt = this.baymaxConfig.getHelpDesks().stream() - .filter(helpDesk -> helpDesk.getChannelId() == channel.getIdLong()) + var helpDeskOpt = this.baymaxConfig.helpDesks().stream() + .filter(helpDesk -> helpDesk.channelId() == channel.getIdLong()) .findAny(); if (helpDeskOpt.isEmpty()) { @@ -104,7 +103,7 @@ public void onMessageReceived(MessageReceivedEvent event) { var helpDesk = helpDeskOpt.get(); var userDialogues = this.helpDesksDialogues.computeIfAbsent( - helpDesk.getChannelId(), channelId -> this.createUserDialogueCache() + helpDesk.channelId(), channelId -> this.createUserDialogueCache() ); Member member = event.getMember(); if (member == null) { @@ -116,11 +115,11 @@ public void onMessageReceived(MessageReceivedEvent event) { if (content.contains("init")) { userDialogues.invalidateAll(); userDialogues.cleanUp(); - init(channel, helpDesk.getModelName(), helpDesk.getModelUri()); + init(channel, helpDesk.modelName(), helpDesk.modelUri()); return; } else if (content.contains("reload")) { try { - var reloadedModel = this.modelLoader.attemptReload(helpDesk.getModelName(), helpDesk.getModelUri()); + var reloadedModel = this.modelLoader.attemptReload(helpDesk.modelName(), helpDesk.modelUri()); userDialogues.invalidateAll(); userDialogues.cleanUp(); init(channel, reloadedModel); @@ -143,7 +142,7 @@ public void onMessageReceived(MessageReceivedEvent event) { userDialogues.get(event.getAuthor().getIdLong(), userId -> { - var model = this.modelLoader.getModel(helpDesk.getModelName(), helpDesk.getModelUri()); + var model = this.modelLoader.getModel(helpDesk.modelName(), helpDesk.modelUri()); return new UserDialogue(this.eventWaiter, model, event, this.restActions, this.temporaryRoleService); }); } @@ -155,17 +154,17 @@ public void onReady(ReadyEvent event) { //2. Post the root message ShardManager shardManager = Objects.requireNonNull(event.getJDA().getShardManager(), "Shard manager required"); - for (BaymaxConfig.HelpDesk helpDesk : this.baymaxConfig.getHelpDesks()) { - TextChannel channel = shardManager.getTextChannelById(helpDesk.getChannelId()); + for (BaymaxConfig.HelpDesk helpDesk : this.baymaxConfig.helpDesks()) { + TextChannel channel = shardManager.getTextChannelById(helpDesk.channelId()); if (channel == null) { - log.warn("Failed to find and setup configured help desk channel {}", helpDesk.getChannelId()); + log.warn("Failed to find and setup configured help desk channel {}", helpDesk.channelId()); return; } - init(channel, helpDesk.getModelName(), helpDesk.getModelUri()); + init(channel, helpDesk.modelName(), helpDesk.modelUri()); } } - private void init(TextChannel channel, String modelName, Optional modelUri) { + private void init(TextChannel channel, String modelName, @Nullable URI modelUri) { init(channel, this.modelLoader.getModel(modelName, modelUri)); } @@ -193,7 +192,7 @@ private void init(TextChannel channel, Map model) { private boolean isStaff(Member member) { return member.getRoles().stream() - .anyMatch(role -> this.baymaxConfig.getStaffRoleIds().contains(role.getIdLong())); + .anyMatch(role -> this.baymaxConfig.staffRoleIds().contains(role.getIdLong())); } private Cache createUserDialogueCache() { diff --git a/src/main/java/space/npstr/baymax/Launcher.java b/src/main/java/space/npstr/baymax/Launcher.java index 34c7575..ea71cdb 100644 --- a/src/main/java/space/npstr/baymax/Launcher.java +++ b/src/main/java/space/npstr/baymax/Launcher.java @@ -18,6 +18,13 @@ package space.npstr.baymax; import jakarta.annotation.PreDestroy; +import java.time.Instant; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; import net.dv8tion.jda.api.JDAInfo; import net.dv8tion.jda.api.sharding.ShardManager; import org.springframework.beans.factory.ObjectProvider; @@ -27,21 +34,18 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent; import org.springframework.boot.context.event.ApplicationFailedEvent; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import space.npstr.baymax.config.properties.BaymaxConfig; import space.npstr.baymax.info.AppInfo; import space.npstr.baymax.info.GitRepoState; -import java.time.Instant; -import java.time.ZoneId; -import java.time.format.DateTimeFormatter; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - /** * Created by napster on 05.09.18. */ @SpringBootApplication +@EnableConfigurationProperties({ + BaymaxConfig.class, +}) public class Launcher implements ApplicationRunner { private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(Launcher.class); diff --git a/src/main/java/space/npstr/baymax/ModelLoader.java b/src/main/java/space/npstr/baymax/ModelLoader.java index 3ee0a39..b6bb1f0 100644 --- a/src/main/java/space/npstr/baymax/ModelLoader.java +++ b/src/main/java/space/npstr/baymax/ModelLoader.java @@ -19,6 +19,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.lang.Nullable; import org.springframework.stereotype.Component; import space.npstr.baymax.helpdesk.ModelParser; import space.npstr.baymax.helpdesk.Node; @@ -36,7 +37,6 @@ import java.nio.file.Path; import java.util.Collections; import java.util.Map; -import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; /** @@ -58,7 +58,7 @@ public ModelLoader() throws IOException { this.tempDir.toFile().deleteOnExit(); } - public Map getModel(String name, Optional uri) { + public Map getModel(String name, @Nullable URI uri) { return this.models.computeIfAbsent(name, __ -> loadModel(name, uri)); } @@ -66,17 +66,17 @@ public Map getModel(String name, Optional uri) { * @throws RuntimeException if there is a general problem loading the model * @throws MalformedModelException if there is a problem parsing the model */ - public Map attemptReload(String name, Optional uri) { + public Map attemptReload(String name, @Nullable URI uri) { Map model = loadModel(name, uri); this.models.put(name, model); return model; } - private Map loadModel(String name, Optional uri) { + private Map loadModel(String name, @Nullable URI uri) { String rawModel; - if (uri.isPresent()) { + if (uri != null) { try { - rawModel = loadModelFromUrl(name, uri.get()); + rawModel = loadModelFromUrl(name, uri); } catch (Exception e) { throw new RuntimeException("Failed to load model" + name + " from url " + uri, e); } diff --git a/src/main/java/space/npstr/baymax/config/ShardManagerConfiguration.java b/src/main/java/space/npstr/baymax/config/ShardManagerConfiguration.java index 6502083..f357f8c 100644 --- a/src/main/java/space/npstr/baymax/config/ShardManagerConfiguration.java +++ b/src/main/java/space/npstr/baymax/config/ShardManagerConfiguration.java @@ -63,7 +63,7 @@ public ShardManager shardManager(BaymaxConfig baymaxConfig, OkHttpClient.Builder HelpDeskListener helpDeskListener) { DefaultShardManagerBuilder shardBuilder = DefaultShardManagerBuilder - .createDefault(baymaxConfig.getDiscordToken()) + .createDefault(baymaxConfig.discordToken()) .setChunkingFilter(ChunkingFilter.ALL) //we need to fetch members from the cache at several places .setMemberCachePolicy(MemberCachePolicy.ALL) .enableIntents( @@ -80,9 +80,9 @@ public ShardManager shardManager(BaymaxConfig baymaxConfig, OkHttpClient.Builder .setCallbackPool(jdaThreadPool, false) .disableCache(EnumSet.allOf(CacheFlag.class)); - String statusMessage = baymaxConfig.getStatusMessage(); + String statusMessage = baymaxConfig.statusMessage(); if (!ObjectUtils.isEmpty(statusMessage)) { - Activity.ActivityType activityType = Activity.ActivityType.fromKey(baymaxConfig.getStatusType()); + Activity.ActivityType activityType = Activity.ActivityType.fromKey(baymaxConfig.statusType()); Activity discordStatus = Activity.of(activityType, statusMessage); shardBuilder.setActivity(discordStatus); } diff --git a/src/main/java/space/npstr/baymax/config/properties/BaymaxConfig.java b/src/main/java/space/npstr/baymax/config/properties/BaymaxConfig.java index 7e64791..56c0fe8 100644 --- a/src/main/java/space/npstr/baymax/config/properties/BaymaxConfig.java +++ b/src/main/java/space/npstr/baymax/config/properties/BaymaxConfig.java @@ -17,96 +17,51 @@ package space.npstr.baymax.config.properties; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.stereotype.Component; - import java.net.URI; -import java.util.Collections; import java.util.List; -import java.util.Optional; import java.util.Set; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.lang.Nullable; /** * Created by napster on 05.09.18. */ -@Component @ConfigurationProperties("baymax") -public class BaymaxConfig { - - private String discordToken = ""; - private int statusType = 0; - private String statusMessage = ""; - private Set staffRoleIds = Collections.emptySet(); - private List helpDesks = Collections.emptyList(); - - public String getDiscordToken() { - return this.discordToken; - } - - public void setDiscordToken(String discordToken) { - this.discordToken = discordToken; - } - - public int getStatusType() { - return statusType; - } - - public void setStatusType(int statusType) { - this.statusType = statusType; - } - - public String getStatusMessage() { - return statusMessage; - } - - public void setStatusMessage(String statusMessage) { - this.statusMessage = statusMessage; - } - - public Set getStaffRoleIds() { - return this.staffRoleIds; - } - - public void setStaffRoleIds(Set staffRoleIds) { - this.staffRoleIds = staffRoleIds; - } - - public List getHelpDesks() { - return this.helpDesks; - } - - public void setHelpDesks(List helpDesks) { - this.helpDesks = helpDesks; - } - - public static class HelpDesk { - - private long channelId; - private String modelName = ""; - private Optional modelUri = Optional.empty(); - - public long getChannelId() { - return this.channelId; - } - - public void setChannelId(long channelId) { - this.channelId = channelId; - } - - public String getModelName() { - return this.modelName; +public record BaymaxConfig( + String discordToken, + int statusType, + @Nullable String statusMessage, + Set staffRoleIds, + List helpDesks +) { + + @SuppressWarnings("ConstantValue") + public BaymaxConfig { + if (discordToken == null || discordToken.isBlank()) { + throw new IllegalArgumentException("Discord token must not be blank"); } - - public void setModelName(String modelName) { - this.modelName = modelName; + if (staffRoleIds == null) { + staffRoleIds = Set.of(); } - - public Optional getModelUri() { - return modelUri; + if (helpDesks == null) { + helpDesks = List.of(); } + } - public void setModelUri(URI modelUri) { - this.modelUri = Optional.of(modelUri); + public record HelpDesk( + long channelId, + String modelName, + @Nullable URI modelUri + ) { + + @SuppressWarnings("ConstantValue") + public HelpDesk { + if (channelId <= 0) { + throw new IllegalArgumentException("Channel id must be positive"); + } + if (modelName == null || modelName.isBlank()) { + throw new IllegalArgumentException("Model name must not be blank"); + } } } }