From cfcbada10df2e521f5d44c407d70ff97e1ec72f6 Mon Sep 17 00:00:00 2001 From: Vankka Date: Tue, 27 Dec 2022 23:34:02 +0200 Subject: [PATCH] Remove optional usage from API --- .../com/discordsrv/api/DiscordSRVApi.java | 4 +- .../api/component/MinecraftComponent.java | 11 +-- .../discordsrv/api/discord/DiscordAPI.java | 36 +++---- .../discord/entity/guild/DiscordGuild.java | 10 +- .../entity/guild/DiscordGuildMember.java | 9 +- .../entity/interaction/command/Command.java | 20 ++-- .../interaction/command/CommandOption.java | 32 ++++-- .../component/ComponentIdentifier.java | 14 +-- .../interaction/component/impl/Button.java | 9 +- .../entity/message/DiscordMessageEmbed.java | 97 +++++++++---------- .../message/ReceivedDiscordMessage.java | 25 ++--- .../message/SendableDiscordMessage.java | 15 ++- .../impl/SendableDiscordMessageImpl.java | 13 +-- .../interaction/AbstractInteractionEvent.java | 13 ++- .../message/AbstractDiscordMessageEvent.java | 29 +++--- .../api/event/events/Cancellable.java | 14 ++- .../api/event/events/Processable.java | 12 +-- .../placeholder/PlaceholderLookupEvent.java | 8 +- .../api/player/IPlayerProvider.java | 10 +- .../com/discordsrv/api/profile/IProfile.java | 13 ++- .../api/profile/IProfileManager.java | 12 ++- .../component/PaperComponentHandle.java | 9 +- .../PlaceholderAPIIntegration.java | 21 ++-- .../bukkit/player/BukkitPlayerProvider.java | 17 ++-- .../bungee/player/BungeePlayerProvider.java | 6 +- .../discordsrv/common/AbstractDiscordSRV.java | 12 +-- .../common/channel/ChannelLockingModule.java | 2 +- .../common/channel/ChannelUpdaterModule.java | 2 +- .../command/subcommand/BroadcastCommand.java | 12 ++- .../renderer/DiscordSRVMinecraftRenderer.java | 20 ++-- .../common/component/util/ComponentUtil.java | 8 +- .../discordsrv/common/debug/DebugReport.java | 7 +- .../discord/api/DiscordAPIEventModule.java | 25 +++-- .../common/discord/api/DiscordAPIImpl.java | 79 ++++++++------- .../discord/api/DiscordCommandRegistry.java | 8 +- .../discord/api/entity/DiscordUserImpl.java | 2 +- .../api/entity/guild/DiscordGuildImpl.java | 13 +-- .../entity/guild/DiscordGuildMemberImpl.java | 6 +- .../message/ReceivedDiscordMessageImpl.java | 36 +++---- .../util/SendableDiscordMessageUtil.java | 6 +- .../common/event/util/EventUtil.java | 10 +- .../common/groupsync/GroupSyncModule.java | 15 +-- .../common/invite/DiscordInviteModule.java | 2 +- .../linking/impl/CachedLinkProvider.java | 2 +- .../discord/DiscordChatMessageModule.java | 4 +- .../DiscordMessageMirroringModule.java | 19 ++-- .../game/AbstractGameMessageModule.java | 2 +- .../com/discordsrv/common/player/IPlayer.java | 6 +- .../common/player/ServerPlayerProvider.java | 5 +- .../provider/AbstractPlayerProvider.java | 16 +-- .../player/provider/PlayerProvider.java | 13 ++- .../discordsrv/common/profile/Profile.java | 11 +-- .../common/profile/ProfileManager.java | 19 ++-- .../sponge/player/SpongePlayerProvider.java | 15 +-- .../player/VelocityPlayerProvider.java | 6 +- 55 files changed, 461 insertions(+), 381 deletions(-) diff --git a/api/src/main/java/com/discordsrv/api/DiscordSRVApi.java b/api/src/main/java/com/discordsrv/api/DiscordSRVApi.java index f5a42919..78ca559d 100644 --- a/api/src/main/java/com/discordsrv/api/DiscordSRVApi.java +++ b/api/src/main/java/com/discordsrv/api/DiscordSRVApi.java @@ -149,8 +149,8 @@ public interface DiscordSRVApi { * @see #discordConnectionDetails() discordConnectionDetails() to use specific GatewayIntents and CacheFlags * @see #jdaVersion() jdaVersion() to get the current jda version being used */ - @NotNull - Optional jda(); + @Nullable + JDA jda(); /** * Discord connection detail manager, specify {@link net.dv8tion.jda.api.requests.GatewayIntent}s and {@link net.dv8tion.jda.api.utils.cache.CacheFlag}s you need here. diff --git a/api/src/main/java/com/discordsrv/api/component/MinecraftComponent.java b/api/src/main/java/com/discordsrv/api/component/MinecraftComponent.java index d85b4849..a856c0a9 100644 --- a/api/src/main/java/com/discordsrv/api/component/MinecraftComponent.java +++ b/api/src/main/java/com/discordsrv/api/component/MinecraftComponent.java @@ -26,8 +26,7 @@ package com.discordsrv.api.component; import com.discordsrv.api.DiscordSRVApi; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; - -import java.util.Optional; +import org.jetbrains.annotations.Nullable; /** * A Minecraft json text component. Use {@link DiscordSRVApi#componentFactory()} to get an instance.
@@ -101,14 +100,14 @@ public interface MinecraftComponent { * * @return a {@link Adapter} for this component using the unrelocated adventure, {@code null} if not available */ - @NotNull + @Nullable @ApiStatus.NonExtendable - default Optional> unrelocatedAdapter() { + default Adapter unrelocatedAdapter() { MinecraftComponentAdapter adapter = MinecraftComponentAdapter.UNRELOCATED; if (adapter == null) { - return Optional.empty(); + return null; } - return Optional.of(adventureAdapter(adapter)); + return adventureAdapter(adapter); } /** diff --git a/api/src/main/java/com/discordsrv/api/discord/DiscordAPI.java b/api/src/main/java/com/discordsrv/api/discord/DiscordAPI.java index 47eed562..fbd1913d 100644 --- a/api/src/main/java/com/discordsrv/api/discord/DiscordAPI.java +++ b/api/src/main/java/com/discordsrv/api/discord/DiscordAPI.java @@ -29,8 +29,8 @@ import com.discordsrv.api.discord.entity.guild.DiscordGuild; import com.discordsrv.api.discord.entity.guild.DiscordRole; import com.discordsrv.api.discord.entity.interaction.command.Command; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import java.util.Optional; import java.util.concurrent.CompletableFuture; /** @@ -43,58 +43,58 @@ public interface DiscordAPI { * @param id the id for the message channel * @return the message channel */ - @NotNull - Optional getMessageChannelById(long id); + @Nullable + DiscordMessageChannel getMessageChannelById(long id); /** * Gets a Discord direct message channel by id, the provided entity should not be stored for long periods of time. * @param id the id for the direct message channel * @return the direct message channel */ - @NotNull - Optional getDirectMessageChannelById(long id); + @Nullable + DiscordDMChannel getDirectMessageChannelById(long id); /** * Gets a Discord news channel by id, the provided entity should not be stored for long periods of time. * @param id the id for the news channel * @return the news channel */ - @NotNull - Optional getNewsChannelById(long id); + @Nullable + DiscordNewsChannel getNewsChannelById(long id); /** * Gets a Discord text channel by id, the provided entity should not be stored for long periods of time. * @param id the id for the text channel * @return the text channel */ - @NotNull - Optional getTextChannelById(long id); + @Nullable + DiscordTextChannel getTextChannelById(long id); /** * Gets a Discord thread channel by id from the cache, the provided entity should not be stored for long periods of time. * @param id the id for the thread channel * @return the thread channel */ - @NotNull - Optional getCachedThreadChannelById(long id); + @Nullable + DiscordThreadChannel getCachedThreadChannelById(long id); /** * Gets a Discord server by id, the provided entity should not be stored for long periods of time. * @param id the id for the Discord server * @return the Discord server */ - @NotNull - Optional getGuildById(long id); + @Nullable + DiscordGuild getGuildById(long id); /** * Gets a Discord user by id, the provided entity should not be stored for long periods of time. - * This will always return an empty optional if {@link #isUserCachingEnabled()} returns {@code false}. + * This will always return {@code null} if {@link #isUserCachingEnabled()} returns {@code false}. * @param id the id for the Discord user * @return the Discord user * @see #isUserCachingEnabled() */ - @NotNull - Optional getUserById(long id); + @Nullable + DiscordUser getUserById(long id); /** * Looks up a Discord user by id from Discord, the provided entity should not be stored for long periods of time. @@ -115,8 +115,8 @@ public interface DiscordAPI { * @param id the id for the Discord role * @return the Discord role */ - @NotNull - Optional getRoleById(long id); + @Nullable + DiscordRole getRoleById(long id); /** * Registers a Discord command. diff --git a/api/src/main/java/com/discordsrv/api/discord/entity/guild/DiscordGuild.java b/api/src/main/java/com/discordsrv/api/discord/entity/guild/DiscordGuild.java index 4fa2bc43..4b79cbf9 100644 --- a/api/src/main/java/com/discordsrv/api/discord/entity/guild/DiscordGuild.java +++ b/api/src/main/java/com/discordsrv/api/discord/entity/guild/DiscordGuild.java @@ -28,9 +28,9 @@ import com.discordsrv.api.discord.entity.Snowflake; import com.discordsrv.api.placeholder.annotation.Placeholder; import net.dv8tion.jda.api.entities.Guild; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.List; -import java.util.Optional; import java.util.Set; /** @@ -58,8 +58,8 @@ public interface DiscordGuild extends JDAEntity, Snowflake { * @param id the id for the Discord guild member * @return the Discord guild member from the cache */ - @NotNull - Optional getMemberById(long id); + @Nullable + DiscordGuildMember getMemberById(long id); /** * Gets the members of this server that are in the cache. @@ -73,8 +73,8 @@ public interface DiscordGuild extends JDAEntity, Snowflake { * @param id the id for the Discord role * @return the Discord role from the cache */ - @NotNull - Optional getRoleById(long id); + @Nullable + DiscordRole getRoleById(long id); /** * Gets the roles in this Discord server. diff --git a/api/src/main/java/com/discordsrv/api/discord/entity/guild/DiscordGuildMember.java b/api/src/main/java/com/discordsrv/api/discord/entity/guild/DiscordGuildMember.java index b6a1e951..ef8aab03 100644 --- a/api/src/main/java/com/discordsrv/api/discord/entity/guild/DiscordGuildMember.java +++ b/api/src/main/java/com/discordsrv/api/discord/entity/guild/DiscordGuildMember.java @@ -30,9 +30,9 @@ import com.discordsrv.api.discord.entity.Mentionable; import com.discordsrv.api.placeholder.annotation.Placeholder; import net.dv8tion.jda.api.entities.Member; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.List; -import java.util.Optional; import java.util.concurrent.CompletableFuture; /** @@ -58,8 +58,8 @@ public interface DiscordGuildMember extends JDAEntity, Mentionable { * Gets the nickname of the Discord server member. * @return the nickname server member */ - @NotNull - Optional getNickname(); + @Nullable + String getNickname(); /** * Gets the roles of this Discord server member. @@ -96,7 +96,8 @@ public interface DiscordGuildMember extends JDAEntity, Mentionable { @Placeholder("user_effective_name") @NotNull default String getEffectiveName() { - return getNickname().orElseGet(() -> getUser().getUsername()); + String nickname = getNickname(); + return nickname != null ? nickname : getUser().getUsername(); } /** diff --git a/api/src/main/java/com/discordsrv/api/discord/entity/interaction/command/Command.java b/api/src/main/java/com/discordsrv/api/discord/entity/interaction/command/Command.java index 46c95382..4ffd72f1 100644 --- a/api/src/main/java/com/discordsrv/api/discord/entity/interaction/command/Command.java +++ b/api/src/main/java/com/discordsrv/api/discord/entity/interaction/command/Command.java @@ -141,9 +141,9 @@ public class Command implements JDAEntity { return id; } - @NotNull - public Optional getGuildId() { - return Optional.ofNullable(guildId); + @Nullable + public Long getGuildId() { + return guildId; } @NotNull @@ -194,19 +194,19 @@ public class Command implements JDAEntity { return defaultPermission; } - @NotNull + @Nullable @SuppressWarnings("unchecked") - public > Optional> getEventHandler() { + public > Consumer getEventHandler() { if (eventHandler == null) { - return Optional.empty(); + return null; } - return Optional.of((Consumer) eventHandler); + return (Consumer) eventHandler; } - @NotNull - public Optional> getAutoCompleteHandler() { - return Optional.ofNullable(autoCompleteHandler); + @Nullable + public Consumer getAutoCompleteHandler() { + return autoCompleteHandler; } @Override diff --git a/api/src/main/java/com/discordsrv/api/discord/entity/interaction/command/CommandOption.java b/api/src/main/java/com/discordsrv/api/discord/entity/interaction/command/CommandOption.java index 2a591018..00e0f909 100644 --- a/api/src/main/java/com/discordsrv/api/discord/entity/interaction/command/CommandOption.java +++ b/api/src/main/java/com/discordsrv/api/discord/entity/interaction/command/CommandOption.java @@ -115,14 +115,14 @@ public class CommandOption implements JDAEntity { return channelTypes; } - @NotNull - public Optional getMinValue() { - return Optional.ofNullable(minValue); + @Nullable + public Number getMinValue() { + return minValue; } - @NotNull - public Optional getMaxValue() { - return Optional.ofNullable(maxValue); + @Nullable + public Number getMaxValue() { + return maxValue; } @Override @@ -131,12 +131,24 @@ public class CommandOption implements JDAEntity { .setRequired(required) .setAutoComplete(autoComplete); if (type == Type.LONG) { - getMinValue().ifPresent(num -> data.setMinValue(num.longValue())); - getMaxValue().ifPresent(num -> data.setMaxValue(num.longValue())); + Number min = getMinValue(); + if (min != null) { + data.setMinValue(min.longValue()); + } + Number max = getMaxValue(); + if (max != null) { + data.setMinValue(max.longValue()); + } } if (type == Type.DOUBLE) { - getMinValue().ifPresent(num -> data.setMinValue(num.doubleValue())); - getMaxValue().ifPresent(num -> data.setMaxValue(num.doubleValue())); + Number min = getMinValue(); + if (min != null) { + data.setMinValue(min.doubleValue()); + } + Number max = getMaxValue(); + if (max != null) { + data.setMinValue(max.doubleValue()); + } } for (Map.Entry entry : choices.entrySet()) { String key = entry.getKey(); diff --git a/api/src/main/java/com/discordsrv/api/discord/entity/interaction/component/ComponentIdentifier.java b/api/src/main/java/com/discordsrv/api/discord/entity/interaction/component/ComponentIdentifier.java index 2b940d19..93ba9feb 100644 --- a/api/src/main/java/com/discordsrv/api/discord/entity/interaction/component/ComponentIdentifier.java +++ b/api/src/main/java/com/discordsrv/api/discord/entity/interaction/component/ComponentIdentifier.java @@ -25,9 +25,9 @@ package com.discordsrv.api.discord.entity.interaction.component; import org.intellij.lang.annotations.Subst; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.Objects; -import java.util.Optional; import java.util.regex.Pattern; /** @@ -62,23 +62,23 @@ public class ComponentIdentifier { return new ComponentIdentifier(extensionName, identifier); } - @NotNull - public static Optional parseFromDiscord(@NotNull String discordIdentifier) { + @Nullable + public static ComponentIdentifier parseFromDiscord(@NotNull String discordIdentifier) { if (!discordIdentifier.startsWith(ID_PREFIX)) { - return Optional.empty(); + return null; } discordIdentifier = discordIdentifier.substring(ID_PREFIX.length()); @Subst("Example:Test") String[] parts = discordIdentifier.split(Pattern.quote(ID_PREFIX)); if (parts.length != 2) { - return Optional.empty(); + return null; } try { - return Optional.of(of(parts[0], parts[1])); + return of(parts[0], parts[1]); } catch (IllegalStateException ignored) { - return Optional.empty(); + return null; } } diff --git a/api/src/main/java/com/discordsrv/api/discord/entity/interaction/component/impl/Button.java b/api/src/main/java/com/discordsrv/api/discord/entity/interaction/component/impl/Button.java index 6eb480ad..88794793 100644 --- a/api/src/main/java/com/discordsrv/api/discord/entity/interaction/component/impl/Button.java +++ b/api/src/main/java/com/discordsrv/api/discord/entity/interaction/component/impl/Button.java @@ -23,16 +23,15 @@ package com.discordsrv.api.discord.entity.interaction.component.impl; +import com.discordsrv.api.discord.entity.guild.DiscordCustomEmoji; import com.discordsrv.api.discord.entity.interaction.component.ComponentIdentifier; import com.discordsrv.api.discord.entity.interaction.component.MessageComponent; -import com.discordsrv.api.discord.entity.guild.DiscordCustomEmoji; import net.dv8tion.jda.api.entities.emoji.Emoji; import net.dv8tion.jda.api.interactions.components.ItemComponent; import net.dv8tion.jda.api.interactions.components.buttons.ButtonStyle; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Optional; import java.util.UUID; /** @@ -92,9 +91,9 @@ public class Button implements MessageComponent { return buttonStyle; } - @NotNull - public Optional getUrl() { - return buttonStyle == Style.LINK ? Optional.of(idOrUrl) : Optional.empty(); + @Nullable + public String getUrl() { + return buttonStyle == Style.LINK ? idOrUrl : null; } @NotNull diff --git a/api/src/main/java/com/discordsrv/api/discord/entity/message/DiscordMessageEmbed.java b/api/src/main/java/com/discordsrv/api/discord/entity/message/DiscordMessageEmbed.java index 91510962..a5168e1a 100644 --- a/api/src/main/java/com/discordsrv/api/discord/entity/message/DiscordMessageEmbed.java +++ b/api/src/main/java/com/discordsrv/api/discord/entity/message/DiscordMessageEmbed.java @@ -32,7 +32,6 @@ import org.jetbrains.annotations.Nullable; import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.List; -import java.util.Optional; /** * A Discord embed. @@ -102,39 +101,39 @@ public class DiscordMessageEmbed { this.footerImageUrl = footerImageUrl; } - @NotNull - public Optional getColor() { - return Optional.ofNullable(color); + @Nullable + public Color getColor() { + return color; } - @NotNull - public Optional getAuthorName() { - return Optional.ofNullable(authorName); + @Nullable + public String getAuthorName() { + return authorName; } - @NotNull - public Optional getAuthorUrl() { - return Optional.ofNullable(authorUrl); + @Nullable + public String getAuthorUrl() { + return authorUrl; } - @NotNull - public Optional getAuthorImageUrl() { - return Optional.ofNullable(authorImageUrl); + @Nullable + public String getAuthorImageUrl() { + return authorImageUrl; } - @NotNull - public Optional getTitle() { - return Optional.ofNullable(title); + @Nullable + public String getTitle() { + return title; } - @NotNull - public Optional getTitleUrl() { - return Optional.ofNullable(titleUrl); + @Nullable + public String getTitleUrl() { + return titleUrl; } - @NotNull - public Optional getDescription() { - return Optional.ofNullable(description); + @Nullable + public String getDescription() { + return description; } @NotNull @@ -142,29 +141,29 @@ public class DiscordMessageEmbed { return fields; } - @NotNull - public Optional getThumbnailUrl() { - return Optional.ofNullable(thumbnailUrl); + @Nullable + public String getThumbnailUrl() { + return thumbnailUrl; } - @NotNull - public Optional getImageUrl() { - return Optional.ofNullable(imageUrl); + @Nullable + public String getImageUrl() { + return imageUrl; } - @NotNull - public Optional getTimestamp() { - return Optional.ofNullable(timestamp); + @Nullable + public OffsetDateTime getTimestamp() { + return timestamp; } - @NotNull - public Optional getFooter() { - return Optional.ofNullable(footer); + @Nullable + public String getFooter() { + return footer; } - @NotNull - public Optional getFooterImageUrl() { - return Optional.ofNullable(footerImageUrl); + @Nullable + public String getFooterImageUrl() { + return footerImageUrl; } @NotNull @@ -254,19 +253,19 @@ public class DiscordMessageEmbed { } protected Builder(DiscordMessageEmbed embed) { - this.color = embed.getColor().orElse(null); - this.authorName = embed.getAuthorName().orElse(null); - this.authorUrl = embed.getAuthorUrl().orElse(null); - this.authorImageUrl = embed.getAuthorImageUrl().orElse(null); - this.title = embed.getTitle().orElse(null); - this.titleUrl = embed.getTitleUrl().orElse(null); - this.description = embed.getDescription().orElse(null); + this.color = embed.getColor(); + this.authorName = embed.getAuthorName(); + this.authorUrl = embed.getAuthorUrl(); + this.authorImageUrl = embed.getAuthorImageUrl(); + this.title = embed.getTitle(); + this.titleUrl = embed.getTitleUrl(); + this.description = embed.getDescription(); this.fields = new ArrayList<>(embed.getFields()); - this.thumbnailUrl = embed.getThumbnailUrl().orElse(null); - this.imageUrl = embed.getImageUrl().orElse(null); - this.timestamp = embed.getTimestamp().orElse(null); - this.footer = embed.getFooter().orElse(null); - this.footerImageUrl = embed.getFooterImageUrl().orElse(null); + this.thumbnailUrl = embed.getThumbnailUrl(); + this.imageUrl = embed.getImageUrl(); + this.timestamp = embed.getTimestamp(); + this.footer = embed.getFooter(); + this.footerImageUrl = embed.getFooterImageUrl(); } @Nullable diff --git a/api/src/main/java/com/discordsrv/api/discord/entity/message/ReceivedDiscordMessage.java b/api/src/main/java/com/discordsrv/api/discord/entity/message/ReceivedDiscordMessage.java index a87b15ae..ae9e5917 100644 --- a/api/src/main/java/com/discordsrv/api/discord/entity/message/ReceivedDiscordMessage.java +++ b/api/src/main/java/com/discordsrv/api/discord/entity/message/ReceivedDiscordMessage.java @@ -35,7 +35,6 @@ import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Unmodifiable; import java.util.List; -import java.util.Optional; import java.util.concurrent.CompletableFuture; /** @@ -104,38 +103,40 @@ public interface ReceivedDiscordMessage extends Snowflake { * Gets the messages this message is replying to. * @return the messages this message is replying to or a empty optional */ - @NotNull - Optional getReplyingTo(); + @Nullable + ReceivedDiscordMessage getReplyingTo(); /** * Gets the text channel the message was sent in. Not present if this message is a dm. * @return an optional potentially containing the text channel the message was sent in */ - @NotNull - Optional getTextChannel(); + @Nullable + DiscordTextChannel getTextChannel(); /** * Gets the dm channel the message was sent in. Not present if this message was sent in a server. * @return an optional potentially containing the dm channel the message was sent in */ - @NotNull - Optional getDMChannel(); + @Nullable + DiscordDMChannel getDMChannel(); /** * Gets the Discord server member that sent this message. * This is not present if the message was sent by a webhook. * @return an optional potentially containing the Discord server member that sent this message */ - @NotNull - Optional getMember(); + @Nullable + DiscordGuildMember getMember(); /** * Gets the Discord server the message was posted in. This is not present if the message was a dm. * @return an optional potentially containing the Discord server the message was posted in */ - @NotNull - default Optional getGuild() { - return getTextChannel().map(DiscordTextChannel::getGuild); + @Nullable + default DiscordGuild getGuild() { + DiscordTextChannel textChannel = getTextChannel(); + + return textChannel != null ? textChannel.getGuild() : null; } /** diff --git a/api/src/main/java/com/discordsrv/api/discord/entity/message/SendableDiscordMessage.java b/api/src/main/java/com/discordsrv/api/discord/entity/message/SendableDiscordMessage.java index 49b943e4..a1438337 100644 --- a/api/src/main/java/com/discordsrv/api/discord/entity/message/SendableDiscordMessage.java +++ b/api/src/main/java/com/discordsrv/api/discord/entity/message/SendableDiscordMessage.java @@ -32,7 +32,6 @@ import org.jetbrains.annotations.Unmodifiable; import java.util.Collection; import java.util.List; -import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.function.Supplier; @@ -58,8 +57,8 @@ public interface SendableDiscordMessage { * The raw content of the message. * @return the unmodified content of the message */ - @NotNull - Optional getContent(); + @Nullable + String getContent(); /** * Gets the embeds of the message. @@ -89,22 +88,22 @@ public interface SendableDiscordMessage { * Gets the webhook username. * @return the webhook username or {@code null} if this isn't a webhook message */ - @NotNull - Optional getWebhookUsername(); + @Nullable + String getWebhookUsername(); /** * Gets the webhook avatar url. * @return the webhook avatar url or {@code null} if no webhook avatar url is specified */ - @NotNull - Optional getWebhookAvatarUrl(); + @Nullable + String getWebhookAvatarUrl(); /** * Returns true if the {@link #getWebhookUsername() webhook username} is specified. * @return true if this is a webhook message */ default boolean isWebhookMessage() { - return getWebhookUsername().isPresent(); + return getWebhookUsername() != null; } @SuppressWarnings("UnusedReturnValue") // API diff --git a/api/src/main/java/com/discordsrv/api/discord/entity/message/impl/SendableDiscordMessageImpl.java b/api/src/main/java/com/discordsrv/api/discord/entity/message/impl/SendableDiscordMessageImpl.java index e34a352b..a88d2716 100644 --- a/api/src/main/java/com/discordsrv/api/discord/entity/message/impl/SendableDiscordMessageImpl.java +++ b/api/src/main/java/com/discordsrv/api/discord/entity/message/impl/SendableDiscordMessageImpl.java @@ -35,6 +35,7 @@ import com.discordsrv.api.placeholder.mapper.ResultMappers; import com.discordsrv.api.placeholder.util.Placeholders; import net.dv8tion.jda.api.entities.MessageEmbed; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.function.Function; @@ -67,8 +68,8 @@ public class SendableDiscordMessageImpl implements SendableDiscordMessage { } @Override - public @NotNull Optional getContent() { - return Optional.ofNullable(content); + public @Nullable String getContent() { + return content; } @Override @@ -88,13 +89,13 @@ public class SendableDiscordMessageImpl implements SendableDiscordMessage { } @Override - public @NotNull Optional getWebhookUsername() { - return Optional.ofNullable(webhookUsername); + public @Nullable String getWebhookUsername() { + return webhookUsername; } @Override - public @NotNull Optional getWebhookAvatarUrl() { - return Optional.ofNullable(webhookAvatarUrl); + public @Nullable String getWebhookAvatarUrl() { + return webhookAvatarUrl; } public static class BuilderImpl implements SendableDiscordMessage.Builder { diff --git a/api/src/main/java/com/discordsrv/api/discord/events/interaction/AbstractInteractionEvent.java b/api/src/main/java/com/discordsrv/api/discord/events/interaction/AbstractInteractionEvent.java index 24b78670..77529f37 100644 --- a/api/src/main/java/com/discordsrv/api/discord/events/interaction/AbstractInteractionEvent.java +++ b/api/src/main/java/com/discordsrv/api/discord/events/interaction/AbstractInteractionEvent.java @@ -31,8 +31,7 @@ import com.discordsrv.api.discord.entity.interaction.component.ComponentIdentifi import com.discordsrv.api.discord.events.AbstractDiscordEvent; import net.dv8tion.jda.api.events.interaction.GenericInteractionCreateEvent; import org.jetbrains.annotations.NotNull; - -import java.util.Optional; +import org.jetbrains.annotations.Nullable; public abstract class AbstractInteractionEvent extends AbstractDiscordEvent { @@ -64,13 +63,13 @@ public abstract class AbstractInteractionEvent getMember() { - return Optional.ofNullable(member); + @Nullable + public DiscordGuildMember getMember() { + return member; } - public Optional getGuild() { - return Optional.ofNullable(member).map(DiscordGuildMember::getGuild); + public DiscordGuild getGuild() { + return member != null ? member.getGuild() : null; } @NotNull diff --git a/api/src/main/java/com/discordsrv/api/discord/events/message/AbstractDiscordMessageEvent.java b/api/src/main/java/com/discordsrv/api/discord/events/message/AbstractDiscordMessageEvent.java index 147649ff..6e79fb01 100644 --- a/api/src/main/java/com/discordsrv/api/discord/events/message/AbstractDiscordMessageEvent.java +++ b/api/src/main/java/com/discordsrv/api/discord/events/message/AbstractDiscordMessageEvent.java @@ -30,8 +30,7 @@ import com.discordsrv.api.discord.entity.channel.DiscordThreadChannel; import com.discordsrv.api.discord.events.AbstractDiscordEvent; import net.dv8tion.jda.api.events.message.GenericMessageEvent; import org.jetbrains.annotations.NotNull; - -import java.util.Optional; +import org.jetbrains.annotations.Nullable; public abstract class AbstractDiscordMessageEvent extends AbstractDiscordEvent { @@ -43,7 +42,7 @@ public abstract class AbstractDiscordMessageEvent } public boolean isGuildMessage() { - return !getDMChannel().isPresent(); + return getDMChannel() == null; } /** @@ -51,25 +50,25 @@ public abstract class AbstractDiscordMessageEvent * This will not be present on messages from threads (see {@link #getThreadChannel()}). * @return an optional potentially containing a {@link DiscordTextChannel} */ - @NotNull - public Optional getTextChannel() { + @Nullable + public DiscordTextChannel getTextChannel() { return channel instanceof DiscordTextChannel - ? Optional.of((DiscordTextChannel) channel) - : Optional.empty(); + ? (DiscordTextChannel) channel + : null; } - @NotNull - public Optional getThreadChannel() { + @Nullable + public DiscordThreadChannel getThreadChannel() { return channel instanceof DiscordThreadChannel - ? Optional.of((DiscordThreadChannel) channel) - : Optional.empty(); + ? (DiscordThreadChannel) channel + : null; } - @NotNull - public Optional getDMChannel() { + @Nullable + public DiscordDMChannel getDMChannel() { return channel instanceof DiscordDMChannel - ? Optional.of((DiscordDMChannel) channel) - : Optional.empty(); + ? (DiscordDMChannel) channel + : null; } @NotNull diff --git a/api/src/main/java/com/discordsrv/api/event/events/Cancellable.java b/api/src/main/java/com/discordsrv/api/event/events/Cancellable.java index d44f9b56..a9ba1c5b 100644 --- a/api/src/main/java/com/discordsrv/api/event/events/Cancellable.java +++ b/api/src/main/java/com/discordsrv/api/event/events/Cancellable.java @@ -27,9 +27,7 @@ import com.discordsrv.api.event.bus.EventListener; import com.discordsrv.api.event.bus.Subscribe; import com.discordsrv.api.event.bus.internal.EventStateHolder; import org.jetbrains.annotations.ApiStatus; -import org.jetbrains.annotations.NotNull; - -import java.util.Optional; +import org.jetbrains.annotations.Nullable; /** * A {@link Event} that can be cancelled. @@ -54,19 +52,19 @@ public interface Cancellable extends Event { * Returns the {@link EventListener} that cancelled this event. * This is changed every time the event goes from not being cancelled to being cancelled. * - * @return the event listener that cancelled this event or an empty optional if it was cancelled before being passed to the {@link com.discordsrv.api.event.bus.EventBus} + * @return the event listener that cancelled this event or {@code null} if it was cancelled before being passed to the {@link com.discordsrv.api.event.bus.EventBus} * @throws IllegalStateException if the event isn't cancelled */ @ApiStatus.NonExtendable - @NotNull - default Optional whoCancelled() { + @Nullable + default EventListener whoCancelled() { EventListener listener = EventStateHolder.CANCELLED.get(); if (listener == null) { throw new IllegalStateException("Event is not cancelled"); } else if (listener == EventStateHolder.UNKNOWN_LISTENER) { - return Optional.empty(); + return null; } - return Optional.of(listener); + return listener; } } diff --git a/api/src/main/java/com/discordsrv/api/event/events/Processable.java b/api/src/main/java/com/discordsrv/api/event/events/Processable.java index 49273e8a..c6d07122 100644 --- a/api/src/main/java/com/discordsrv/api/event/events/Processable.java +++ b/api/src/main/java/com/discordsrv/api/event/events/Processable.java @@ -26,8 +26,7 @@ package com.discordsrv.api.event.events; import com.discordsrv.api.event.bus.EventListener; import com.discordsrv.api.event.bus.internal.EventStateHolder; import org.jetbrains.annotations.ApiStatus; - -import java.util.Optional; +import org.jetbrains.annotations.Nullable; /** * A {@link Event} that can be processed. @@ -49,18 +48,19 @@ public interface Processable extends Event { /** * Returns the {@link EventListener} that processed this event. * - * @return the event listener that processed this event or an empty optional if it was processed before being passed to the {@link com.discordsrv.api.event.bus.EventBus} + * @return the event listener that processed this event or {@code null} if it was processed before being passed to the {@link com.discordsrv.api.event.bus.EventBus} * @throws IllegalStateException if the event has not been processed */ @ApiStatus.NonExtendable - default Optional whoProcessed() { + @Nullable + default EventListener whoProcessed() { EventListener listener = EventStateHolder.PROCESSED.get(); if (listener == null) { throw new IllegalStateException("Event has not been processed"); } else if (listener == EventStateHolder.UNKNOWN_LISTENER) { - return Optional.empty(); + return null; } - return Optional.of(listener); + return listener; } } diff --git a/api/src/main/java/com/discordsrv/api/event/events/placeholder/PlaceholderLookupEvent.java b/api/src/main/java/com/discordsrv/api/event/events/placeholder/PlaceholderLookupEvent.java index f1f3ceb2..07ca0339 100644 --- a/api/src/main/java/com/discordsrv/api/event/events/placeholder/PlaceholderLookupEvent.java +++ b/api/src/main/java/com/discordsrv/api/event/events/placeholder/PlaceholderLookupEvent.java @@ -27,8 +27,8 @@ import com.discordsrv.api.event.events.Event; import com.discordsrv.api.event.events.Processable; import com.discordsrv.api.placeholder.PlaceholderLookupResult; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import java.util.Optional; import java.util.Set; public class PlaceholderLookupEvent implements Event, Processable { @@ -53,13 +53,13 @@ public class PlaceholderLookupEvent implements Event, Processable { } @SuppressWarnings("unchecked") - public Optional getContext(Class type) { + public @Nullable T getContext(Class type) { for (Object o : contexts) { if (type.isAssignableFrom(o.getClass())) { - return Optional.of((T) o); + return (T) o; } } - return Optional.empty(); + return null; } @Override diff --git a/api/src/main/java/com/discordsrv/api/player/IPlayerProvider.java b/api/src/main/java/com/discordsrv/api/player/IPlayerProvider.java index 98bdd1d1..e2483424 100644 --- a/api/src/main/java/com/discordsrv/api/player/IPlayerProvider.java +++ b/api/src/main/java/com/discordsrv/api/player/IPlayerProvider.java @@ -24,8 +24,8 @@ package com.discordsrv.api.player; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import java.util.Optional; import java.util.UUID; /** @@ -38,15 +38,15 @@ public interface IPlayerProvider { * @param player the uuid for the player * @return the {@link DiscordSRVPlayer} instance for the player, if available */ - @NotNull - Optional player(@NotNull UUID player); + @Nullable + DiscordSRVPlayer player(@NotNull UUID player); /** * Gets a player from the cache of online players. * @param username case-insensitive username for the player * @return the {@link DiscordSRVPlayer} instance for the player, if available */ - @NotNull - Optional player(@NotNull String username); + @Nullable + DiscordSRVPlayer player(@NotNull String username); } diff --git a/api/src/main/java/com/discordsrv/api/profile/IProfile.java b/api/src/main/java/com/discordsrv/api/profile/IProfile.java index b4de30e5..39419c61 100644 --- a/api/src/main/java/com/discordsrv/api/profile/IProfile.java +++ b/api/src/main/java/com/discordsrv/api/profile/IProfile.java @@ -23,21 +23,20 @@ package com.discordsrv.api.profile; -import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import java.util.Optional; import java.util.UUID; public interface IProfile { - @NotNull - Optional playerUUID(); + @Nullable + UUID playerUUID(); - @NotNull - Optional userId(); + @Nullable + Long userId(); default boolean isLinked() { - return playerUUID().isPresent() && userId().isPresent(); + return playerUUID() != null && userId() != null; } } diff --git a/api/src/main/java/com/discordsrv/api/profile/IProfileManager.java b/api/src/main/java/com/discordsrv/api/profile/IProfileManager.java index e35a5f96..8c5cc1f2 100644 --- a/api/src/main/java/com/discordsrv/api/profile/IProfileManager.java +++ b/api/src/main/java/com/discordsrv/api/profile/IProfileManager.java @@ -23,17 +23,23 @@ package com.discordsrv.api.profile; -import java.util.Optional; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + import java.util.UUID; import java.util.concurrent.CompletableFuture; public interface IProfileManager { + @NotNull CompletableFuture lookupProfile(UUID playerUUID); - Optional getProfile(UUID playerUUID); + @Nullable + IProfile getProfile(UUID playerUUID); + @NotNull CompletableFuture lookupProfile(long userId); - Optional getProfile(long userId); + @Nullable + IProfile getProfile(long userId); } diff --git a/bukkit/src/main/java/com/discordsrv/bukkit/component/PaperComponentHandle.java b/bukkit/src/main/java/com/discordsrv/bukkit/component/PaperComponentHandle.java index 39105bc6..0a415133 100644 --- a/bukkit/src/main/java/com/discordsrv/bukkit/component/PaperComponentHandle.java +++ b/bukkit/src/main/java/com/discordsrv/bukkit/component/PaperComponentHandle.java @@ -68,9 +68,12 @@ public class PaperComponentHandle { } catch (Throwable ignored) {} if (unrelocated != null) { MinecraftComponent component = discordSRV.componentFactory().empty(); - component.unrelocatedAdapter() - .orElseThrow(() -> new IllegalStateException("Unrelocated adventure unavailable")) - .setComponent(unrelocated); + MinecraftComponent.Adapter adapter = component.unrelocatedAdapter(); + if (adapter == null) { + throw new IllegalStateException("Unrelocated adventure unavailable"); + } + + adapter.setComponent(unrelocated); return component; } } diff --git a/bukkit/src/main/java/com/discordsrv/bukkit/integration/PlaceholderAPIIntegration.java b/bukkit/src/main/java/com/discordsrv/bukkit/integration/PlaceholderAPIIntegration.java index df3c35c8..343ad283 100644 --- a/bukkit/src/main/java/com/discordsrv/bukkit/integration/PlaceholderAPIIntegration.java +++ b/bukkit/src/main/java/com/discordsrv/bukkit/integration/PlaceholderAPIIntegration.java @@ -76,17 +76,21 @@ public class PlaceholderAPIIntegration extends PluginIntegration discordSRV.server().getPlayer(p.uniqueId())) - .orElse(null); + DiscordSRVPlayer srvPlayer = event.getContext(DiscordSRVPlayer.class); + Player player = srvPlayer != null ? discordSRV.server().getPlayer(srvPlayer.uniqueId()) : null; if (player != null) { setResult(event, placeholder, PlaceholderAPI.setPlaceholders(player, placeholder)); return; } - UUID uuid = event.getContext(IProfile.class) - .flatMap(IProfile::playerUUID) - .orElseGet(() -> event.getContext(IOfflinePlayer.class).map(IOfflinePlayer::uniqueId).orElse(null)); + IProfile profile = event.getContext(IProfile.class); + UUID uuid = profile != null ? profile.playerUUID() : null; + if (uuid == null) { + IOfflinePlayer offlinePlayer = event.getContext(IOfflinePlayer.class); + if (offlinePlayer != null) { + uuid = offlinePlayer.uniqueId(); + } + } OfflinePlayer offlinePlayer = uuid != null ? discordSRV.server().getOfflinePlayer(uuid) : null; setResult(event, placeholder, PlaceholderAPI.setPlaceholders(offlinePlayer, placeholder)); @@ -138,7 +142,10 @@ public class PlaceholderAPIIntegration extends PluginIntegration context; if (player != null) { context = new HashSet<>(2); - discordSRV.profileManager().getProfile(player.getUniqueId()).ifPresent(context::add); + IProfile profile = discordSRV.profileManager().getProfile(player.getUniqueId()); + if (profile != null) { + context.add(profile); + } if (player instanceof Player) { context.add(discordSRV.playerProvider().player((Player) player)); } else { diff --git a/bukkit/src/main/java/com/discordsrv/bukkit/player/BukkitPlayerProvider.java b/bukkit/src/main/java/com/discordsrv/bukkit/player/BukkitPlayerProvider.java index fba8ba61..9a0acae8 100644 --- a/bukkit/src/main/java/com/discordsrv/bukkit/player/BukkitPlayerProvider.java +++ b/bukkit/src/main/java/com/discordsrv/bukkit/player/BukkitPlayerProvider.java @@ -29,7 +29,6 @@ import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerLoginEvent; import org.bukkit.event.player.PlayerQuitEvent; -import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; @@ -67,30 +66,34 @@ public class BukkitPlayerProvider extends ServerPlayerProvider new IllegalStateException("Player not available")); + BukkitPlayer srvPlayer = player(player.getUniqueId()); + if (srvPlayer == null) { + throw new IllegalStateException("Player not available"); + } + return srvPlayer; } // IOfflinePlayer - private CompletableFuture> getFuture(Supplier provider) { + private CompletableFuture getFuture(Supplier provider) { return CompletableFuture.supplyAsync(() -> { OfflinePlayer offlinePlayer = provider.get(); if (offlinePlayer == null) { - return Optional.empty(); + return null; } - return Optional.of(new BukkitOfflinePlayer(discordSRV, offlinePlayer)); + return new BukkitOfflinePlayer(discordSRV, offlinePlayer); }, discordSRV.scheduler().executor()); } @Override - public CompletableFuture> offlinePlayer(UUID uuid) { + public CompletableFuture offlinePlayer(UUID uuid) { return getFuture(() -> discordSRV.server().getOfflinePlayer(uuid)); } @SuppressWarnings("deprecation") // Shut up, I know @Override - public CompletableFuture> offlinePlayer(String username) { + public CompletableFuture offlinePlayer(String username) { return getFuture(() -> discordSRV.server().getOfflinePlayer(username)); } diff --git a/bungee/src/main/java/com/discordsrv/bungee/player/BungeePlayerProvider.java b/bungee/src/main/java/com/discordsrv/bungee/player/BungeePlayerProvider.java index 060ad83e..fc102378 100644 --- a/bungee/src/main/java/com/discordsrv/bungee/player/BungeePlayerProvider.java +++ b/bungee/src/main/java/com/discordsrv/bungee/player/BungeePlayerProvider.java @@ -57,7 +57,11 @@ public class BungeePlayerProvider extends AbstractPlayerProvider new IllegalStateException("Player not available")); + BungeePlayer srvPlayer = player(player.getUniqueId()); + if (srvPlayer == null) { + throw new IllegalStateException("Player not available"); + } + return srvPlayer; } } diff --git a/common/src/main/java/com/discordsrv/common/AbstractDiscordSRV.java b/common/src/main/java/com/discordsrv/common/AbstractDiscordSRV.java index 516bdfca..f84c2765 100644 --- a/common/src/main/java/com/discordsrv/common/AbstractDiscordSRV.java +++ b/common/src/main/java/com/discordsrv/common/AbstractDiscordSRV.java @@ -41,7 +41,6 @@ import com.discordsrv.common.config.manager.MainConfigManager; import com.discordsrv.common.dependency.DiscordSRVDependencyManager; import com.discordsrv.common.discord.api.DiscordAPIEventModule; import com.discordsrv.common.discord.api.DiscordAPIImpl; -import com.discordsrv.common.discord.connection.DiscordConnectionManager; import com.discordsrv.common.discord.connection.jda.JDAConnectionManager; import com.discordsrv.common.discord.details.DiscordConnectionDetailsImpl; import com.discordsrv.common.event.bus.EventBusImpl; @@ -92,7 +91,6 @@ import java.lang.reflect.Constructor; import java.net.URL; import java.nio.file.Path; import java.util.Locale; -import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; @@ -272,9 +270,11 @@ public abstract class AbstractDiscordSRV jda() { - return Optional.ofNullable(discordConnectionManager) - .map(DiscordConnectionManager::instance); + public final @Nullable JDA jda() { + if (discordConnectionManager == null) { + return null; + } + return discordConnectionManager.instance(); } @Override @@ -688,7 +688,7 @@ public abstract class AbstractDiscordSRV { OrDefault shutdownConfig, boolean state ) { - JDA jda = discordSRV.jda().orElse(null); + JDA jda = discordSRV.jda(); if (jda == null) { return; } diff --git a/common/src/main/java/com/discordsrv/common/channel/ChannelUpdaterModule.java b/common/src/main/java/com/discordsrv/common/channel/ChannelUpdaterModule.java index d28f2ef0..70afae30 100644 --- a/common/src/main/java/com/discordsrv/common/channel/ChannelUpdaterModule.java +++ b/common/src/main/java/com/discordsrv/common/channel/ChannelUpdaterModule.java @@ -66,7 +66,7 @@ public class ChannelUpdaterModule extends AbstractModule { discordSRV.waitForStatus(DiscordSRV.Status.CONNECTED, 15, TimeUnit.SECONDS); } catch (InterruptedException ignored) {} - JDA jda = discordSRV.jda().orElse(null); + JDA jda = discordSRV.jda(); if (jda == null) { return; } diff --git a/common/src/main/java/com/discordsrv/common/command/game/command/subcommand/BroadcastCommand.java b/common/src/main/java/com/discordsrv/common/command/game/command/subcommand/BroadcastCommand.java index a55bc355..232f99f3 100644 --- a/common/src/main/java/com/discordsrv/common/command/game/command/subcommand/BroadcastCommand.java +++ b/common/src/main/java/com/discordsrv/common/command/game/command/subcommand/BroadcastCommand.java @@ -20,6 +20,7 @@ package com.discordsrv.common.command.game.command.subcommand; import com.discordsrv.api.component.MinecraftComponent; import com.discordsrv.api.discord.entity.channel.DiscordMessageChannel; +import com.discordsrv.api.discord.entity.channel.DiscordTextChannel; import com.discordsrv.api.discord.entity.channel.DiscordThreadChannel; import com.discordsrv.api.discord.entity.message.SendableDiscordMessage; import com.discordsrv.common.DiscordSRV; @@ -105,14 +106,21 @@ public abstract class BroadcastCommand implements GameCommandExecutor, GameComma List> futures = new ArrayList<>(); try { long id = Long.parseUnsignedLong(channel); - discordSRV.discordAPI().getMessageChannelById(id).ifPresent(channels::add); + + DiscordMessageChannel messageChannel = discordSRV.discordAPI().getMessageChannelById(id); + if (messageChannel != null) { + channels.add(messageChannel); + } } catch (IllegalArgumentException ignored) { OrDefault channelConfig = discordSRV.channelConfig().orDefault(null, channel); IChannelConfig config = channelConfig.get(cfg -> cfg instanceof IChannelConfig ? (IChannelConfig) cfg : null); if (config != null) { for (Long channelId : config.channelIds()) { - discordSRV.discordAPI().getTextChannelById(channelId).ifPresent(channels::add); + DiscordTextChannel textChannel = discordSRV.discordAPI().getTextChannelById(channelId); + if (textChannel != null) { + channels.add(textChannel); + } } discordSRV.discordAPI().findOrCreateThreads(channelConfig, config, channels::add, futures, false); diff --git a/common/src/main/java/com/discordsrv/common/component/renderer/DiscordSRVMinecraftRenderer.java b/common/src/main/java/com/discordsrv/common/component/renderer/DiscordSRVMinecraftRenderer.java index 3695cd6b..083c836f 100644 --- a/common/src/main/java/com/discordsrv/common/component/renderer/DiscordSRVMinecraftRenderer.java +++ b/common/src/main/java/com/discordsrv/common/component/renderer/DiscordSRVMinecraftRenderer.java @@ -29,6 +29,7 @@ import com.discordsrv.common.component.util.ComponentUtil; import com.discordsrv.common.config.main.channels.DiscordToMinecraftChatConfig; import com.discordsrv.common.function.OrDefault; import dev.vankka.mcdiscordreserializer.renderer.implementation.DefaultMinecraftRenderer; +import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.entities.channel.middleman.GuildChannel; import net.dv8tion.jda.api.utils.MiscUtil; import net.kyori.adventure.text.Component; @@ -77,9 +78,12 @@ public class DiscordSRVMinecraftRenderer extends DefaultMinecraftRenderer { return component.append(Component.text("<#" + id + ">")); } - GuildChannel guildChannel = discordSRV.jda() - .map(jda -> jda.getGuildChannelById(id)) - .orElse(null); + JDA jda = discordSRV.jda(); + if (jda == null) { + return Component.empty(); + } + + GuildChannel guildChannel = jda.getGuildChannelById(id); return component.append(ComponentUtil.fromAPI( discordSRV.componentFactory() @@ -96,17 +100,15 @@ public class DiscordSRVMinecraftRenderer extends DefaultMinecraftRenderer { DiscordToMinecraftChatConfig.Mentions.Format format = context != null ? context.config.map(cfg -> cfg.mentions).get(cfg -> cfg.user) : null; DiscordGuild guild = context != null - ? discordSRV.discordAPI() - .getGuildById(context.event.getGuild().getId()) - .orElse(null) + ? discordSRV.discordAPI().getGuildById(context.event.getGuild().getId()) : null; if (format == null || guild == null) { return component.append(Component.text("<@" + id + ">")); } long userId = MiscUtil.parseLong(id); - DiscordUser user = discordSRV.discordAPI().getUserById(userId).orElse(null); - DiscordGuildMember member = guild.getMemberById(userId).orElse(null); + DiscordUser user = discordSRV.discordAPI().getUserById(userId); + DiscordGuildMember member = guild.getMemberById(userId); GameTextBuilder builder = discordSRV.componentFactory() .textBuilder(user != null ? format.format : format.unknownFormat); @@ -133,7 +135,7 @@ public class DiscordSRVMinecraftRenderer extends DefaultMinecraftRenderer { } long roleId = MiscUtil.parseLong(id); - DiscordRole role = discordSRV.discordAPI().getRoleById(roleId).orElse(null); + DiscordRole role = discordSRV.discordAPI().getRoleById(roleId); GameTextBuilder builder = discordSRV.componentFactory() .textBuilder(role != null ? format.format : format.unknownFormat); diff --git a/common/src/main/java/com/discordsrv/common/component/util/ComponentUtil.java b/common/src/main/java/com/discordsrv/common/component/util/ComponentUtil.java index a5ebc3cb..8075251e 100644 --- a/common/src/main/java/com/discordsrv/common/component/util/ComponentUtil.java +++ b/common/src/main/java/com/discordsrv/common/component/util/ComponentUtil.java @@ -72,9 +72,11 @@ public final class ComponentUtil { public static Component fromUnrelocated(Object unrelocatedAdventure) { MinecraftComponentImpl component = MinecraftComponentImpl.empty(); - component.unrelocatedAdapter() - .orElseThrow(() -> new IllegalStateException("Could not get unrelocated adventure gson serializer")) - .setComponent(unrelocatedAdventure); + MinecraftComponent.Adapter adapter = component.unrelocatedAdapter(); + if (adapter == null) { + throw new IllegalStateException("Could not get unrelocated adventure gson serializer"); + } + adapter.setComponent(unrelocatedAdventure); return fromAPI(component); } diff --git a/common/src/main/java/com/discordsrv/common/debug/DebugReport.java b/common/src/main/java/com/discordsrv/common/debug/DebugReport.java index bcffaf2c..cd29a2c6 100644 --- a/common/src/main/java/com/discordsrv/common/debug/DebugReport.java +++ b/common/src/main/java/com/discordsrv/common/debug/DebugReport.java @@ -27,10 +27,10 @@ import com.discordsrv.common.paste.PasteService; import com.discordsrv.common.plugin.Plugin; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; +import net.dv8tion.jda.api.JDA; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; -import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.FileStore; @@ -92,7 +92,7 @@ public class DebugReport { public Path zip() throws Throwable { Path zipPath = discordSRV.dataDirectory().resolve("debug-" + System.currentTimeMillis() + ".zip"); - try (ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipPath.toFile()))) { + try (ZipOutputStream zipOutputStream = new ZipOutputStream(Files.newOutputStream(zipPath))) { for (DebugFile file : files) { zipOutputStream.putNextEntry(new ZipEntry(file.name())); @@ -123,7 +123,8 @@ public class DebugReport { values.put("gitRevision", discordSRV.gitRevision()); values.put("gitBranch", discordSRV.gitBranch()); values.put("status", discordSRV.status().name()); - values.put("jdaStatus", discordSRV.jda().map(jda -> jda.getStatus().name()).orElse("JDA null")); + JDA jda = discordSRV.jda(); + values.put("jdaStatus", jda != null ? jda.getStatus().name() : "JDA null"); values.put("platformLogger", discordSRV.platformLogger().getClass().getName()); values.put("onlineMode", discordSRV.onlineMode().name()); diff --git a/common/src/main/java/com/discordsrv/common/discord/api/DiscordAPIEventModule.java b/common/src/main/java/com/discordsrv/common/discord/api/DiscordAPIEventModule.java index 88478fae..c69858ed 100644 --- a/common/src/main/java/com/discordsrv/common/discord/api/DiscordAPIEventModule.java +++ b/common/src/main/java/com/discordsrv/common/discord/api/DiscordAPIEventModule.java @@ -58,6 +58,7 @@ import net.dv8tion.jda.api.interactions.commands.Command; import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.function.Consumer; import java.util.stream.Collectors; public class DiscordAPIEventModule extends AbstractModule { @@ -140,7 +141,10 @@ public class DiscordAPIEventModule extends AbstractModule { DiscordCommandAutoCompleteInteractionEvent autoComplete = new DiscordCommandAutoCompleteInteractionEvent( (CommandAutoCompleteInteractionEvent) event, command.getId(), user, guildMember, channel); discordSRV.eventBus().publish(autoComplete); - command.getAutoCompleteHandler().ifPresent(handler -> handler.accept(autoComplete)); + Consumer autoCompleteHandler = command.getAutoCompleteHandler(); + if (autoCompleteHandler != null) { + autoCompleteHandler.accept(autoComplete); + }; List choices = new ArrayList<>(); for (Map.Entry entry : autoComplete.getChoices().entrySet()) { @@ -180,7 +184,10 @@ public class DiscordAPIEventModule extends AbstractModule { ); newEvent = interactionEvent; - command.getEventHandler().ifPresent(handler -> handler.accept(interactionEvent)); + Consumer> eventHandler = command.getEventHandler(); + if (eventHandler != null) { + eventHandler.accept(interactionEvent); + } } else if (event instanceof UserContextInteractionEvent) { com.discordsrv.api.discord.entity.interaction.command.Command command = discordSRV.discordAPI() .getActiveCommand(guild, CommandType.MESSAGE, name).orElse(null); @@ -198,7 +205,10 @@ public class DiscordAPIEventModule extends AbstractModule { ); newEvent = interactionEvent; - command.getEventHandler().ifPresent(handler -> handler.accept(interactionEvent)); + Consumer> eventHandler = command.getEventHandler(); + if (eventHandler != null) { + eventHandler.accept(interactionEvent); + } } else if (event instanceof SlashCommandInteractionEvent) { com.discordsrv.api.discord.entity.interaction.command.Command command = discordSRV.discordAPI() .getActiveCommand(guild, CommandType.USER, name).orElse(null); @@ -216,11 +226,14 @@ public class DiscordAPIEventModule extends AbstractModule { ); newEvent = interactionEvent; - command.getEventHandler().ifPresent(handler -> handler.accept(interactionEvent)); + Consumer> eventHandler = command.getEventHandler(); + if (eventHandler != null) { + eventHandler.accept(interactionEvent); + } } } else if (event instanceof GenericComponentInteractionCreateEvent) { ComponentIdentifier identifier = ComponentIdentifier.parseFromDiscord( - ((GenericComponentInteractionCreateEvent) event).getComponentId()).orElse(null); + ((GenericComponentInteractionCreateEvent) event).getComponentId()); if (identifier == null) { return; } @@ -234,7 +247,7 @@ public class DiscordAPIEventModule extends AbstractModule { } } else if (event instanceof ModalInteractionEvent) { ComponentIdentifier identifier = ComponentIdentifier.parseFromDiscord( - ((ModalInteractionEvent) event).getModalId()).orElse(null); + ((ModalInteractionEvent) event).getModalId()); if (identifier == null) { return; } diff --git a/common/src/main/java/com/discordsrv/common/discord/api/DiscordAPIImpl.java b/common/src/main/java/com/discordsrv/common/discord/api/DiscordAPIImpl.java index ff49887e..6ddc98af 100644 --- a/common/src/main/java/com/discordsrv/common/discord/api/DiscordAPIImpl.java +++ b/common/src/main/java/com/discordsrv/common/discord/api/DiscordAPIImpl.java @@ -66,6 +66,7 @@ import java.util.Optional; import java.util.concurrent.*; import java.util.function.BiConsumer; import java.util.function.Consumer; +import java.util.function.Function; public class DiscordAPIImpl implements DiscordAPI { @@ -121,7 +122,7 @@ public class DiscordAPIImpl implements DiscordAPI { for (ThreadConfig threadConfig : threads) { long channelId = threadConfig.channelId; - DiscordTextChannel channel = getTextChannelById(channelId).orElse(null); + DiscordTextChannel channel = getTextChannelById(channelId); if (channel == null) { if (channelId > 0 && log) { discordSRV.logger().error("Unable to find channel with ID " + Long.toUnsignedString(channelId)); @@ -327,14 +328,14 @@ public class DiscordAPIImpl implements DiscordAPI { } @Override - public @NotNull Optional getMessageChannelById(long id) { - Optional textChannel = getTextChannelById(id); - if (textChannel.isPresent()) { + public @Nullable DiscordMessageChannel getMessageChannelById(long id) { + DiscordTextChannel textChannel = getTextChannelById(id); + if (textChannel != null) { return textChannel; } - Optional threadChannel = getCachedThreadChannelById(id); - if (threadChannel.isPresent()) { + DiscordThreadChannel threadChannel = getCachedThreadChannelById(id); + if (threadChannel != null) { return threadChannel; } @@ -355,11 +356,23 @@ public class DiscordAPIImpl implements DiscordAPI { } } + private T mapJDAEntity(Function get, Function map) { + JDA jda = discordSRV.jda(); + if (jda == null) { + return null; + } + + J entity = get.apply(jda); + if (entity == null) { + return null; + } + + return map.apply(entity); + } + @Override - public @NotNull Optional getDirectMessageChannelById(long id) { - return discordSRV.jda() - .map(jda -> jda.getPrivateChannelById(id)) - .map(this::getDirectMessageChannel); + public @Nullable DiscordDMChannel getDirectMessageChannelById(long id) { + return mapJDAEntity(jda -> jda.getPrivateChannelById(id), this::getDirectMessageChannel); } public DiscordDMChannelImpl getDirectMessageChannel(PrivateChannel jda) { @@ -367,8 +380,8 @@ public class DiscordAPIImpl implements DiscordAPI { } @Override - public @NotNull Optional getNewsChannelById(long id) { - return Optional.empty(); + public @Nullable DiscordNewsChannel getNewsChannelById(long id) { + return null; } public DiscordNewsChannelImpl getNewsChannel(NewsChannel jda) { @@ -376,10 +389,8 @@ public class DiscordAPIImpl implements DiscordAPI { } @Override - public @NotNull Optional getTextChannelById(long id) { - return discordSRV.jda() - .map(jda -> jda.getTextChannelById(id)) - .map(this::getTextChannel); + public @Nullable DiscordTextChannel getTextChannelById(long id) { + return mapJDAEntity(jda -> jda.getTextChannelById(id), this::getTextChannel); } public DiscordTextChannelImpl getTextChannel(TextChannel jda) { @@ -387,10 +398,8 @@ public class DiscordAPIImpl implements DiscordAPI { } @Override - public @NotNull Optional getCachedThreadChannelById(long id) { - return discordSRV.jda() - .map(jda -> jda.getThreadChannelById(id)) - .map(this::getThreadChannel); + public @Nullable DiscordThreadChannel getCachedThreadChannelById(long id) { + return mapJDAEntity(jda -> jda.getThreadChannelById(id), this::getThreadChannel); } public DiscordThreadChannelImpl getThreadChannel(ThreadChannel jda) { @@ -398,10 +407,8 @@ public class DiscordAPIImpl implements DiscordAPI { } @Override - public @NotNull Optional getGuildById(long id) { - return discordSRV.jda() - .map(jda -> jda.getGuildById(id)) - .map(this::getGuild); + public @Nullable DiscordGuild getGuildById(long id) { + return mapJDAEntity(jda -> jda.getGuildById(id), this::getGuild); } public DiscordGuildImpl getGuild(Guild jda) { @@ -413,10 +420,8 @@ public class DiscordAPIImpl implements DiscordAPI { } @Override - public @NotNull Optional getUserById(long id) { - return discordSRV.jda() - .map(jda -> jda.getUserById(id)) - .map(this::getUser); + public @Nullable DiscordUser getUserById(long id) { + return mapJDAEntity(jda -> jda.getUserById(id), this::getUser); } public DiscordUserImpl getUser(User jda) { @@ -425,14 +430,16 @@ public class DiscordAPIImpl implements DiscordAPI { @Override public @NotNull CompletableFuture retrieveUserById(long id) { - JDA jda = discordSRV.jda().orElse(null); + JDA jda = discordSRV.jda(); if (jda == null) { return notReady(); } - return jda.retrieveUserById(id) - .submit() - .thenApply(this::getUser); + return mapExceptions( + jda.retrieveUserById(id) + .submit() + .thenApply(this::getUser) + ); } @Override @@ -443,10 +450,8 @@ public class DiscordAPIImpl implements DiscordAPI { } @Override - public @NotNull Optional getRoleById(long id) { - return discordSRV.jda() - .map(jda -> jda.getRoleById(id)) - .map(this::getRole); + public @Nullable DiscordRole getRoleById(long id) { + return mapJDAEntity(jda -> jda.getRoleById(id), this::getRole); } public DiscordRoleImpl getRole(Role jda) { @@ -471,7 +476,7 @@ public class DiscordAPIImpl implements DiscordAPI { @Override public @NonNull CompletableFuture asyncLoad(@NonNull Long channelId, @NonNull Executor executor) { - JDA jda = discordSRV.jda().orElse(null); + JDA jda = discordSRV.jda(); if (jda == null) { return notReady(); } diff --git a/common/src/main/java/com/discordsrv/common/discord/api/DiscordCommandRegistry.java b/common/src/main/java/com/discordsrv/common/discord/api/DiscordCommandRegistry.java index 5e708896..6ae6f57e 100644 --- a/common/src/main/java/com/discordsrv/common/discord/api/DiscordCommandRegistry.java +++ b/common/src/main/java/com/discordsrv/common/discord/api/DiscordCommandRegistry.java @@ -60,8 +60,9 @@ public class DiscordCommandRegistry { public Command.RegistrationResult register(Command command, boolean temporary) { CommandType type = command.getType(); + Long guildId = command.getGuildId(); Registry registry = registries - .computeIfAbsent(command.getGuildId().orElse(GLOBAL_ID), key -> new EnumMap<>(CommandType.class)) + .computeIfAbsent(guildId != null ? guildId : GLOBAL_ID, key -> new EnumMap<>(CommandType.class)) .computeIfAbsent(type, key -> new Registry()); if (registry.contains(command)) { return Command.RegistrationResult.ALREADY_REGISTERED; @@ -78,8 +79,9 @@ public class DiscordCommandRegistry { } public void unregister(Command command) { + Long guildId = command.getGuildId(); Registry registry = registries - .computeIfAbsent(command.getGuildId().orElse(GLOBAL_ID), key -> Collections.emptyMap()) + .computeIfAbsent(guildId != null ? guildId : GLOBAL_ID, key -> Collections.emptyMap()) .get(command.getType()); if (registry != null) { @@ -95,7 +97,7 @@ public class DiscordCommandRegistry { } public void registerCommandsToDiscord() { - JDA jda = discordSRV.jda().orElse(null); + JDA jda = discordSRV.jda(); if (jda == null) { return; } diff --git a/common/src/main/java/com/discordsrv/common/discord/api/entity/DiscordUserImpl.java b/common/src/main/java/com/discordsrv/common/discord/api/entity/DiscordUserImpl.java index 9a2712db..43966725 100644 --- a/common/src/main/java/com/discordsrv/common/discord/api/entity/DiscordUserImpl.java +++ b/common/src/main/java/com/discordsrv/common/discord/api/entity/DiscordUserImpl.java @@ -78,7 +78,7 @@ public class DiscordUserImpl implements DiscordUser { @Override public CompletableFuture openPrivateChannel() { - JDA jda = discordSRV.jda().orElse(null); + JDA jda = discordSRV.jda(); if (jda == null) { return discordSRV.discordAPI().notReady(); } diff --git a/common/src/main/java/com/discordsrv/common/discord/api/entity/guild/DiscordGuildImpl.java b/common/src/main/java/com/discordsrv/common/discord/api/entity/guild/DiscordGuildImpl.java index 8906fb00..8e9acce3 100644 --- a/common/src/main/java/com/discordsrv/common/discord/api/entity/guild/DiscordGuildImpl.java +++ b/common/src/main/java/com/discordsrv/common/discord/api/entity/guild/DiscordGuildImpl.java @@ -26,6 +26,7 @@ import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Role; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.*; @@ -55,13 +56,13 @@ public class DiscordGuildImpl implements DiscordGuild { } @Override - public @NotNull Optional getMemberById(long id) { + public @Nullable DiscordGuildMember getMemberById(long id) { Member member = guild.getMemberById(id); if (member == null) { - return Optional.empty(); + return null; } - return Optional.of(discordSRV.discordAPI().getGuildMember(member)); + return discordSRV.discordAPI().getGuildMember(member); } @Override @@ -74,13 +75,13 @@ public class DiscordGuildImpl implements DiscordGuild { } @Override - public @NotNull Optional getRoleById(long id) { + public @Nullable DiscordRole getRoleById(long id) { Role role = guild.getRoleById(id); if (role == null) { - return Optional.empty(); + return null; } - return Optional.of(discordSRV.discordAPI().getRole(role)); + return discordSRV.discordAPI().getRole(role); } @Override diff --git a/common/src/main/java/com/discordsrv/common/discord/api/entity/guild/DiscordGuildMemberImpl.java b/common/src/main/java/com/discordsrv/common/discord/api/entity/guild/DiscordGuildMemberImpl.java index 1aac93f8..c1b6c2b6 100644 --- a/common/src/main/java/com/discordsrv/common/discord/api/entity/guild/DiscordGuildMemberImpl.java +++ b/common/src/main/java/com/discordsrv/common/discord/api/entity/guild/DiscordGuildMemberImpl.java @@ -32,10 +32,10 @@ import net.dv8tion.jda.api.entities.Role; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.TextColor; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; -import java.util.Optional; import java.util.concurrent.CompletableFuture; public class DiscordGuildMemberImpl implements DiscordGuildMember { @@ -72,8 +72,8 @@ public class DiscordGuildMemberImpl implements DiscordGuildMember { } @Override - public @NotNull Optional getNickname() { - return Optional.ofNullable(member.getNickname()); + public @Nullable String getNickname() { + return member.getNickname(); } @Override diff --git a/common/src/main/java/com/discordsrv/common/discord/api/entity/message/ReceivedDiscordMessageImpl.java b/common/src/main/java/com/discordsrv/common/discord/api/entity/message/ReceivedDiscordMessageImpl.java index 233b1848..a05972b3 100644 --- a/common/src/main/java/com/discordsrv/common/discord/api/entity/message/ReceivedDiscordMessageImpl.java +++ b/common/src/main/java/com/discordsrv/common/discord/api/entity/message/ReceivedDiscordMessageImpl.java @@ -29,6 +29,7 @@ import com.discordsrv.api.discord.entity.channel.DiscordDMChannel; import com.discordsrv.api.discord.entity.channel.DiscordMessageChannel; import com.discordsrv.api.discord.entity.channel.DiscordTextChannel; import com.discordsrv.api.discord.entity.channel.DiscordThreadChannel; +import com.discordsrv.api.discord.entity.guild.DiscordGuild; import com.discordsrv.api.discord.entity.guild.DiscordGuildMember; import com.discordsrv.api.discord.entity.message.DiscordMessageEmbed; import com.discordsrv.api.discord.entity.message.ReceivedDiscordMessage; @@ -47,11 +48,11 @@ import net.dv8tion.jda.api.entities.MessageEmbed; import net.dv8tion.jda.api.requests.ErrorResponse; import net.kyori.adventure.text.Component; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Unmodifiable; import java.util.ArrayList; import java.util.List; -import java.util.Optional; import java.util.concurrent.CompletableFuture; public class ReceivedDiscordMessageImpl implements ReceivedDiscordMessage { @@ -146,11 +147,11 @@ public class ReceivedDiscordMessageImpl implements ReceivedDiscordMessage { } DiscordMessageChannel channel = discordSRV.discordAPI().getMessageChannelById( - webhookMessage.getChannelId()).orElse(null); + webhookMessage.getChannelId()); DiscordUser user = discordSRV.discordAPI().getUserById( - webhookMessage.getAuthor().getId()).orElse(null); + webhookMessage.getAuthor().getId()); DiscordGuildMember member = channel instanceof DiscordTextChannel && user != null - ? ((DiscordTextChannel) channel).getGuild().getMemberById(user.getId()).orElse(null) : null; + ? ((DiscordTextChannel) channel).getGuild().getMemberById(user.getId()) : null; List attachments = new ArrayList<>(); for (ReadonlyAttachment attachment : webhookMessage.getAttachments()) { @@ -241,9 +242,10 @@ public class ReceivedDiscordMessageImpl implements ReceivedDiscordMessage { @Override public @NotNull String getJumpUrl() { + DiscordGuild guild = getGuild(); return String.format( Message.JUMP_URL, - getGuild().map(guild -> Long.toUnsignedString(guild.getId())).orElse("@me"), + guild != null ? Long.toUnsignedString(guild.getId()) : "@me", Long.toUnsignedString(getChannel().getId()), Long.toUnsignedString(id) ); @@ -260,22 +262,22 @@ public class ReceivedDiscordMessageImpl implements ReceivedDiscordMessage { } @Override - public @NotNull Optional getTextChannel() { + public @Nullable DiscordTextChannel getTextChannel() { return channel instanceof DiscordTextChannel - ? Optional.of((DiscordTextChannel) channel) - : Optional.empty(); + ? (DiscordTextChannel) channel + : null; } @Override - public @NotNull Optional getDMChannel() { + public @Nullable DiscordDMChannel getDMChannel() { return channel instanceof DiscordDMChannel - ? Optional.of((DiscordDMChannel) channel) - : Optional.empty(); + ? (DiscordDMChannel) channel + : null; } @Override - public @NotNull Optional getMember() { - return Optional.ofNullable(member); + public @Nullable DiscordGuildMember getMember() { + return member; } @Override @@ -289,13 +291,13 @@ public class ReceivedDiscordMessageImpl implements ReceivedDiscordMessage { } @Override - public @NotNull Optional getReplyingTo() { - return Optional.ofNullable(replyingTo); + public @Nullable ReceivedDiscordMessage getReplyingTo() { + return replyingTo; } @Override public @NotNull CompletableFuture delete() { - DiscordTextChannel textChannel = discordSRV.discordAPI().getTextChannelById(channelId).orElse(null); + DiscordTextChannel textChannel = discordSRV.discordAPI().getTextChannelById(channelId); if (textChannel == null) { return CompletableFutureUtil.failed(new RestErrorResponseException(ErrorResponse.UNKNOWN_CHANNEL)); } @@ -309,7 +311,7 @@ public class ReceivedDiscordMessageImpl implements ReceivedDiscordMessage { throw new IllegalArgumentException("Cannot edit a non-webhook message into a webhook message"); } - DiscordTextChannel textChannel = discordSRV.discordAPI().getTextChannelById(channelId).orElse(null); + DiscordTextChannel textChannel = discordSRV.discordAPI().getTextChannelById(channelId); if (textChannel == null) { return CompletableFutureUtil.failed(new RestErrorResponseException(ErrorResponse.UNKNOWN_CHANNEL)); } diff --git a/common/src/main/java/com/discordsrv/common/discord/api/entity/message/util/SendableDiscordMessageUtil.java b/common/src/main/java/com/discordsrv/common/discord/api/entity/message/util/SendableDiscordMessageUtil.java index 67a3b967..3134d061 100644 --- a/common/src/main/java/com/discordsrv/common/discord/api/entity/message/util/SendableDiscordMessageUtil.java +++ b/common/src/main/java/com/discordsrv/common/discord/api/entity/message/util/SendableDiscordMessageUtil.java @@ -63,7 +63,7 @@ public final class SendableDiscordMessageUtil { } return (T) builder - .setContent(message.getContent().orElse(null)) + .setContent(message.getContent()) .setEmbeds(embeds) .setAllowedMentions(allowedTypes) .mentionUsers(allowedUsers.stream().mapToLong(l -> l).toArray()) @@ -94,7 +94,7 @@ public final class SendableDiscordMessageUtil { public static WebhookMessageBuilder toWebhook(@NotNull SendableDiscordMessage message) { return WebhookMessageBuilder.fromJDA(null/*toJDA(message)*/) // TODO: lib update? lib replacement? - .setUsername(message.getWebhookUsername().orElse(null)) - .setAvatarUrl(message.getWebhookAvatarUrl().orElse(null)); + .setUsername(message.getWebhookUsername()) + .setAvatarUrl(message.getWebhookAvatarUrl()); } } diff --git a/common/src/main/java/com/discordsrv/common/event/util/EventUtil.java b/common/src/main/java/com/discordsrv/common/event/util/EventUtil.java index 3545b36d..402ed427 100644 --- a/common/src/main/java/com/discordsrv/common/event/util/EventUtil.java +++ b/common/src/main/java/com/discordsrv/common/event/util/EventUtil.java @@ -33,9 +33,8 @@ public final class EventUtil { return false; } - String whoProcessed = event.whoProcessed() - .map(EventListener::className) - .orElse("Unknown"); + EventListener processor = event.whoProcessed(); + String whoProcessed = processor != null ? processor.className() : "Unknown"; if (!whoProcessed.startsWith("com.discordsrv")) { logger.debug(event + " was handled by non-DiscordSRV handler: " + whoProcessed); } @@ -47,9 +46,8 @@ public final class EventUtil { return false; } - String whoCancelled = event.whoCancelled() - .map(EventListener::className) - .orElse("Unknown"); + EventListener canceller = event.whoCancelled(); + String whoCancelled = canceller != null ? canceller.className() : "Unknown"; logger.debug(event + " was cancelled by " + whoCancelled); return true; } diff --git a/common/src/main/java/com/discordsrv/common/groupsync/GroupSyncModule.java b/common/src/main/java/com/discordsrv/common/groupsync/GroupSyncModule.java index cc2e624c..378ff6ba 100644 --- a/common/src/main/java/com/discordsrv/common/groupsync/GroupSyncModule.java +++ b/common/src/main/java/com/discordsrv/common/groupsync/GroupSyncModule.java @@ -37,6 +37,7 @@ import com.discordsrv.common.logging.NamedLogger; import com.discordsrv.common.module.type.AbstractModule; import com.discordsrv.common.player.IPlayer; import com.discordsrv.common.player.event.PlayerConnectedEvent; +import com.discordsrv.common.profile.Profile; import com.github.benmanes.caffeine.cache.Cache; import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.Nullable; @@ -170,12 +171,12 @@ public class GroupSyncModule extends AbstractModule { private CompletableFuture lookupLinkedAccount(UUID player) { return discordSRV.profileManager().lookupProfile(player) - .thenApply(profile -> profile.userId().orElse(null)); + .thenApply(Profile::userId); } private CompletableFuture lookupLinkedAccount(long userId) { return discordSRV.profileManager().lookupProfile(userId) - .thenApply(profile -> profile.playerUUID().orElse(null)); + .thenApply(Profile::playerUUID); } // Permission data helper methods @@ -259,7 +260,7 @@ public class GroupSyncModule extends AbstractModule { } public Collection> resync(UUID player, long userId, GroupSyncCause cause) { - if (noPermissionProvider() || (!discordSRV.playerProvider().player(player).isPresent() && !supportsOffline())) { + if (noPermissionProvider() || (discordSRV.playerProvider().player(player) == null && !supportsOffline())) { return Collections.emptyList(); } @@ -292,12 +293,12 @@ public class GroupSyncModule extends AbstractModule { } private CompletableFuture resyncPair(GroupSyncConfig.PairConfig pair, UUID player, long userId) { - DiscordRole role = discordSRV.discordAPI().getRoleById(pair.roleId).orElse(null); + DiscordRole role = discordSRV.discordAPI().getRoleById(pair.roleId); if (role == null) { return CompletableFuture.completedFuture(GroupSyncResult.ROLE_DOESNT_EXIST); } - DiscordGuildMember member = role.getGuild().getMemberById(userId).orElse(null); + DiscordGuildMember member = role.getGuild().getMemberById(userId); if (member == null) { return CompletableFuture.completedFuture(GroupSyncResult.NOT_A_GUILD_MEMBER); } @@ -612,12 +613,12 @@ public class GroupSyncModule extends AbstractModule { private CompletableFuture modifyRoleState(long userId, GroupSyncConfig.PairConfig config, boolean remove) { long roleId = config.roleId; - DiscordRole role = discordSRV.discordAPI().getRoleById(roleId).orElse(null); + DiscordRole role = discordSRV.discordAPI().getRoleById(roleId); if (role == null) { return CompletableFuture.completedFuture(GroupSyncResult.ROLE_DOESNT_EXIST); } - DiscordGuildMember member = role.getGuild().getMemberById(userId).orElse(null); + DiscordGuildMember member = role.getGuild().getMemberById(userId); if (member == null) { return CompletableFuture.completedFuture(GroupSyncResult.NOT_A_GUILD_MEMBER); } diff --git a/common/src/main/java/com/discordsrv/common/invite/DiscordInviteModule.java b/common/src/main/java/com/discordsrv/common/invite/DiscordInviteModule.java index daa77b0f..921a1028 100644 --- a/common/src/main/java/com/discordsrv/common/invite/DiscordInviteModule.java +++ b/common/src/main/java/com/discordsrv/common/invite/DiscordInviteModule.java @@ -44,7 +44,7 @@ public class DiscordInviteModule extends AbstractModule { @Override public void reload() { - JDA jda = discordSRV.jda().orElse(null); + JDA jda = discordSRV.jda(); if (jda == null) { return; } diff --git a/common/src/main/java/com/discordsrv/common/linking/impl/CachedLinkProvider.java b/common/src/main/java/com/discordsrv/common/linking/impl/CachedLinkProvider.java index ef00d627..04a23e4b 100644 --- a/common/src/main/java/com/discordsrv/common/linking/impl/CachedLinkProvider.java +++ b/common/src/main/java/com/discordsrv/common/linking/impl/CachedLinkProvider.java @@ -63,7 +63,7 @@ public abstract class CachedLinkProvider implements LinkProvider { @NonNull Long oldValue, @NonNull Executor executor ) { - if (!discordSRV.playerProvider().player(key).isPresent()) { + if (discordSRV.playerProvider().player(key) == null) { // Don't keep players that aren't online in cache return CompletableFuture.completedFuture(null); } diff --git a/common/src/main/java/com/discordsrv/common/messageforwarding/discord/DiscordChatMessageModule.java b/common/src/main/java/com/discordsrv/common/messageforwarding/discord/DiscordChatMessageModule.java index f2e8686b..ad16f330 100644 --- a/common/src/main/java/com/discordsrv/common/messageforwarding/discord/DiscordChatMessageModule.java +++ b/common/src/main/java/com/discordsrv/common/messageforwarding/discord/DiscordChatMessageModule.java @@ -51,7 +51,7 @@ public class DiscordChatMessageModule extends AbstractModule { @Subscribe public void onDiscordMessageReceived(DiscordMessageReceiveEvent event) { if (!discordSRV.isReady() || event.getMessage().isFromSelf() - || !(event.getTextChannel().isPresent() || event.getThreadChannel().isPresent())) { + || !(event.getTextChannel() != null || event.getThreadChannel() != null)) { return; } @@ -84,7 +84,7 @@ public class DiscordChatMessageModule extends AbstractModule { DiscordMessageChannel channel = event.getChannel(); ReceivedDiscordMessage discordMessage = event.getDiscordMessage(); DiscordUser author = discordMessage.getAuthor(); - DiscordGuildMember member = discordMessage.getMember().orElse(null); + DiscordGuildMember member = discordMessage.getMember(); boolean webhookMessage = discordMessage.isWebhookMessage(); DiscordIgnoresConfig ignores = chatConfig.get(cfg -> cfg.ignores); diff --git a/common/src/main/java/com/discordsrv/common/messageforwarding/discord/DiscordMessageMirroringModule.java b/common/src/main/java/com/discordsrv/common/messageforwarding/discord/DiscordMessageMirroringModule.java index 0bb2dd98..9ddd80a0 100644 --- a/common/src/main/java/com/discordsrv/common/messageforwarding/discord/DiscordMessageMirroringModule.java +++ b/common/src/main/java/com/discordsrv/common/messageforwarding/discord/DiscordMessageMirroringModule.java @@ -94,7 +94,7 @@ public class DiscordMessageMirroringModule extends AbstractModule { } DiscordIgnoresConfig ignores = config.get(cfg -> cfg.ignores); - if (ignores != null && ignores.shouldBeIgnored(message.isWebhookMessage(), message.getAuthor(), message.getMember().orElse(null))) { + if (ignores != null && ignores.shouldBeIgnored(message.isWebhookMessage(), message.getAuthor(), message.getMember())) { continue; } @@ -143,11 +143,10 @@ public class DiscordMessageMirroringModule extends AbstractModule { List channelIds = iChannelConfig.channelIds(); if (channelIds != null) { for (Long channelId : channelIds) { - discordSRV.discordAPI().getTextChannelById(channelId).ifPresent(textChannel -> { - if (textChannel.getId() != channel.getId()) { - mirrorChannels.add(Pair.of(textChannel, config)); - } - }); + DiscordTextChannel textChannel = discordSRV.discordAPI().getTextChannelById(channelId); + if (textChannel != null && textChannel.getId() != channel.getId()) { + mirrorChannels.add(Pair.of(textChannel, config)); + } } } @@ -257,7 +256,7 @@ public class DiscordMessageMirroringModule extends AbstractModule { DiscordGuildMessageChannel destinationChannel, OrDefault config ) { - DiscordGuildMember member = message.getMember().orElse(null); + DiscordGuildMember member = message.getMember(); DiscordUser user = message.getAuthor(); String username = discordSRV.placeholderService().replacePlaceholders( config.get(cfg -> cfg.usernameFormat, "%user_effective_name% [M]"), @@ -267,8 +266,8 @@ public class DiscordMessageMirroringModule extends AbstractModule { username = username.substring(0, 32); } - ReceivedDiscordMessage replyMessage = message.getReplyingTo().orElse(null); - String content = message.getContent() + ReceivedDiscordMessage replyMessage = message.getReplyingTo(); + String content = Objects.requireNonNull(message.getContent()) .replace("[", "\\["); // Block markdown urls if (replyMessage != null) { @@ -399,7 +398,7 @@ public class DiscordMessageMirroringModule extends AbstractModule { } public DiscordGuildMessageChannel getMessageChannel(DiscordSRV discordSRV) { - DiscordTextChannel textChannel = discordSRV.discordAPI().getTextChannelById(channelId).orElse(null); + DiscordTextChannel textChannel = discordSRV.discordAPI().getTextChannelById(channelId); if (textChannel == null) { return null; } else if (threadId == -1) { diff --git a/common/src/main/java/com/discordsrv/common/messageforwarding/game/AbstractGameMessageModule.java b/common/src/main/java/com/discordsrv/common/messageforwarding/game/AbstractGameMessageModule.java index 5d446d3c..a1ddfd10 100644 --- a/common/src/main/java/com/discordsrv/common/messageforwarding/game/AbstractGameMessageModule.java +++ b/common/src/main/java/com/discordsrv/common/messageforwarding/game/AbstractGameMessageModule.java @@ -100,7 +100,7 @@ public abstract class AbstractGameMessageModule channelIds = channelConfig.channelIds(); if (channelIds != null) { for (Long channelId : channelConfig.channelIds()) { - DiscordTextChannel textChannel = discordSRV.discordAPI().getTextChannelById(channelId).orElse(null); + DiscordTextChannel textChannel = discordSRV.discordAPI().getTextChannelById(channelId); if (textChannel != null) { messageChannels.add(textChannel); } else if (channelId > 0) { diff --git a/common/src/main/java/com/discordsrv/common/player/IPlayer.java b/common/src/main/java/com/discordsrv/common/player/IPlayer.java index 993b11cf..6653755c 100644 --- a/common/src/main/java/com/discordsrv/common/player/IPlayer.java +++ b/common/src/main/java/com/discordsrv/common/player/IPlayer.java @@ -41,7 +41,11 @@ public interface IPlayer extends DiscordSRVPlayer, IOfflinePlayer, ICommandSende @ApiStatus.NonExtendable default Profile profile() { - return discordSRV().profileManager().getProfile(uniqueId()).orElseThrow(IllegalStateException::new); + Profile profile = discordSRV().profileManager().getProfile(uniqueId()); + if (profile == null) { + throw new IllegalStateException("Profile does not exist"); + } + return profile; } @NotNull diff --git a/common/src/main/java/com/discordsrv/common/player/ServerPlayerProvider.java b/common/src/main/java/com/discordsrv/common/player/ServerPlayerProvider.java index ad31c32c..6a3dbdb0 100644 --- a/common/src/main/java/com/discordsrv/common/player/ServerPlayerProvider.java +++ b/common/src/main/java/com/discordsrv/common/player/ServerPlayerProvider.java @@ -21,7 +21,6 @@ package com.discordsrv.common.player; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.player.provider.AbstractPlayerProvider; -import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; @@ -31,6 +30,6 @@ public abstract class ServerPlayerProvider> offlinePlayer(UUID uuid); - public abstract CompletableFuture> offlinePlayer(String username); + public abstract CompletableFuture offlinePlayer(UUID uuid); + public abstract CompletableFuture offlinePlayer(String username); } diff --git a/common/src/main/java/com/discordsrv/common/player/provider/AbstractPlayerProvider.java b/common/src/main/java/com/discordsrv/common/player/provider/AbstractPlayerProvider.java index dc5718a4..50590cf9 100644 --- a/common/src/main/java/com/discordsrv/common/player/provider/AbstractPlayerProvider.java +++ b/common/src/main/java/com/discordsrv/common/player/provider/AbstractPlayerProvider.java @@ -23,8 +23,12 @@ import com.discordsrv.common.player.IPlayer; import com.discordsrv.common.player.event.PlayerConnectedEvent; import com.discordsrv.common.player.event.PlayerDisconnectedEvent; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import java.util.*; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; @@ -55,18 +59,18 @@ public abstract class AbstractPlayerProvider player(@NotNull UUID uuid) { - return Optional.ofNullable(players.get(uuid)); + public final @Nullable T player(@NotNull UUID uuid) { + return players.get(uuid); } @Override - public final @NotNull Optional player(@NotNull String username) { + public final @Nullable T player(@NotNull String username) { for (T value : allPlayers) { if (value.username().equalsIgnoreCase(username)) { - return Optional.of(value); + return value; } } - return Optional.empty(); + return null; } @Override diff --git a/common/src/main/java/com/discordsrv/common/player/provider/PlayerProvider.java b/common/src/main/java/com/discordsrv/common/player/provider/PlayerProvider.java index cb25cb79..a8f3b9e0 100644 --- a/common/src/main/java/com/discordsrv/common/player/provider/PlayerProvider.java +++ b/common/src/main/java/com/discordsrv/common/player/provider/PlayerProvider.java @@ -18,29 +18,32 @@ package com.discordsrv.common.player.provider; +import com.discordsrv.api.player.DiscordSRVPlayer; import com.discordsrv.api.player.IPlayerProvider; import com.discordsrv.common.player.IPlayer; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.Collection; -import java.util.Optional; import java.util.UUID; public interface PlayerProvider extends IPlayerProvider { /** * Gets an online player by {@link UUID}. + * * @param uuid the uuid of the Player */ - @NotNull - Optional player(@NotNull UUID uuid); + @Nullable + DiscordSRVPlayer player(@NotNull UUID uuid); /** * Gets an online player by username. + * * @param username case-insensitive username for the player */ - @NotNull - Optional player(@NotNull String username); + @Nullable + DiscordSRVPlayer player(@NotNull String username); /** * Gets all online players. diff --git a/common/src/main/java/com/discordsrv/common/profile/Profile.java b/common/src/main/java/com/discordsrv/common/profile/Profile.java index f544a027..842e6a43 100644 --- a/common/src/main/java/com/discordsrv/common/profile/Profile.java +++ b/common/src/main/java/com/discordsrv/common/profile/Profile.java @@ -19,9 +19,8 @@ package com.discordsrv.common.profile; import com.discordsrv.api.profile.IProfile; -import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import java.util.Optional; import java.util.UUID; public class Profile implements IProfile { @@ -35,12 +34,12 @@ public class Profile implements IProfile { } @Override - public @NotNull Optional playerUUID() { - return Optional.ofNullable(playerUUID); + public @Nullable UUID playerUUID() { + return playerUUID; } @Override - public @NotNull Optional userId() { - return Optional.ofNullable(userId); + public @Nullable Long userId() { + return userId; } } diff --git a/common/src/main/java/com/discordsrv/common/profile/ProfileManager.java b/common/src/main/java/com/discordsrv/common/profile/ProfileManager.java index c9ba8a66..a4154597 100644 --- a/common/src/main/java/com/discordsrv/common/profile/ProfileManager.java +++ b/common/src/main/java/com/discordsrv/common/profile/ProfileManager.java @@ -21,9 +21,10 @@ package com.discordsrv.common.profile; import com.discordsrv.api.profile.IProfileManager; import com.discordsrv.common.DiscordSRV; import org.jetbrains.annotations.Blocking; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.Map; -import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; @@ -43,7 +44,7 @@ public class ProfileManager implements IProfileManager { Profile profile = lookupProfile(playerUUID).join(); profiles.put(playerUUID, profile); if (profile.isLinked()) { - discordUserMap.put(profile.userId().orElseThrow(AssertionError::new), profile); + discordUserMap.put(profile.userId(), profile); } } @@ -54,29 +55,29 @@ public class ProfileManager implements IProfileManager { } if (profile.isLinked()) { - discordUserMap.remove(profile.userId().orElseThrow(AssertionError::new)); + discordUserMap.remove(profile.userId()); } } @Override - public CompletableFuture lookupProfile(UUID playerUUID) { + public @NotNull CompletableFuture lookupProfile(UUID playerUUID) { return discordSRV.linkProvider().getUserId(playerUUID) .thenApply(opt -> new Profile(playerUUID, opt.orElse(null))); } @Override - public Optional getProfile(UUID playerUUID) { - return Optional.ofNullable(profiles.get(playerUUID)); + public @Nullable Profile getProfile(UUID playerUUID) { + return profiles.get(playerUUID); } @Override - public CompletableFuture lookupProfile(long userId) { + public @NotNull CompletableFuture lookupProfile(long userId) { return discordSRV.linkProvider().getPlayerUUID(userId) .thenApply(opt -> new Profile(opt.orElse(null), userId)); } @Override - public Optional getProfile(long userId) { - return Optional.ofNullable(discordUserMap.get(userId)); + public @Nullable Profile getProfile(long userId) { + return discordUserMap.get(userId); } } diff --git a/sponge/src/main/java/com/discordsrv/sponge/player/SpongePlayerProvider.java b/sponge/src/main/java/com/discordsrv/sponge/player/SpongePlayerProvider.java index c249bd6a..ed31bbc0 100644 --- a/sponge/src/main/java/com/discordsrv/sponge/player/SpongePlayerProvider.java +++ b/sponge/src/main/java/com/discordsrv/sponge/player/SpongePlayerProvider.java @@ -27,7 +27,6 @@ import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.Order; import org.spongepowered.api.event.network.ServerSideConnectionEvent; -import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; @@ -64,7 +63,11 @@ public class SpongePlayerProvider extends ServerPlayerProvider new IllegalStateException("Player not available")); + SpongePlayer srvPlayer = player(player.uniqueId()); + if (srvPlayer == null) { + throw new IllegalStateException("Player not available"); + } + return srvPlayer; } // IOfflinePlayer @@ -74,17 +77,17 @@ public class SpongePlayerProvider extends ServerPlayerProvider> offlinePlayer(UUID uuid) { + public CompletableFuture offlinePlayer(UUID uuid) { return discordSRV.game().server().userManager() .load(uuid) - .thenApply(optional -> optional.map(this::convert)); + .thenApply(optional -> optional.map(this::convert).orElse(null)); } @Override - public CompletableFuture> offlinePlayer(String username) { + public CompletableFuture offlinePlayer(String username) { return discordSRV.game().server().userManager() .load(username) - .thenApply(optional -> optional.map(this::convert)); + .thenApply(optional -> optional.map(this::convert).orElse(null)); } public IOfflinePlayer offlinePlayer(User user) { diff --git a/velocity/src/main/java/com/discordsrv/velocity/player/VelocityPlayerProvider.java b/velocity/src/main/java/com/discordsrv/velocity/player/VelocityPlayerProvider.java index ff1efa14..db15a1f6 100644 --- a/velocity/src/main/java/com/discordsrv/velocity/player/VelocityPlayerProvider.java +++ b/velocity/src/main/java/com/discordsrv/velocity/player/VelocityPlayerProvider.java @@ -57,6 +57,10 @@ public class VelocityPlayerProvider extends AbstractPlayerProvider new IllegalStateException("Player not available")); + VelocityPlayer srvPlayer = player(player.getUniqueId()); + if (srvPlayer == null) { + throw new IllegalStateException("Player not available"); + } + return srvPlayer; } }