Remove optional usage from API

This commit is contained in:
Vankka 2022-12-27 23:34:02 +02:00
parent 29f48944d3
commit cfcbada10d
No known key found for this signature in database
GPG Key ID: 6E50CB7A29B96AD0
55 changed files with 461 additions and 381 deletions

View File

@ -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> 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.

View File

@ -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.<br/>
@ -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<Adapter<Object>> unrelocatedAdapter() {
default Adapter<Object> unrelocatedAdapter() {
MinecraftComponentAdapter<Object> adapter = MinecraftComponentAdapter.UNRELOCATED;
if (adapter == null) {
return Optional.empty();
return null;
}
return Optional.of(adventureAdapter(adapter));
return adventureAdapter(adapter);
}
/**

View File

@ -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<? extends DiscordMessageChannel> 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<DiscordDMChannel> 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<DiscordNewsChannel> 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<DiscordTextChannel> 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<DiscordThreadChannel> 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<DiscordGuild> 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<DiscordUser> 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<DiscordRole> getRoleById(long id);
@Nullable
DiscordRole getRoleById(long id);
/**
* Registers a Discord command.

View File

@ -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<Guild>, Snowflake {
* @param id the id for the Discord guild member
* @return the Discord guild member from the cache
*/
@NotNull
Optional<DiscordGuildMember> 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<Guild>, Snowflake {
* @param id the id for the Discord role
* @return the Discord role from the cache
*/
@NotNull
Optional<DiscordRole> getRoleById(long id);
@Nullable
DiscordRole getRoleById(long id);
/**
* Gets the roles in this Discord server.

View File

@ -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<Member>, Mentionable {
* Gets the nickname of the Discord server member.
* @return the nickname server member
*/
@NotNull
Optional<String> getNickname();
@Nullable
String getNickname();
/**
* Gets the roles of this Discord server member.
@ -96,7 +96,8 @@ public interface DiscordGuildMember extends JDAEntity<Member>, Mentionable {
@Placeholder("user_effective_name")
@NotNull
default String getEffectiveName() {
return getNickname().orElseGet(() -> getUser().getUsername());
String nickname = getNickname();
return nickname != null ? nickname : getUser().getUsername();
}
/**

View File

@ -141,9 +141,9 @@ public class Command implements JDAEntity<CommandData> {
return id;
}
@NotNull
public Optional<Long> getGuildId() {
return Optional.ofNullable(guildId);
@Nullable
public Long getGuildId() {
return guildId;
}
@NotNull
@ -194,19 +194,19 @@ public class Command implements JDAEntity<CommandData> {
return defaultPermission;
}
@NotNull
@Nullable
@SuppressWarnings("unchecked")
public <T extends AbstractCommandInteractionEvent<?>> Optional<Consumer<T>> getEventHandler() {
public <T extends AbstractCommandInteractionEvent<?>> Consumer<T> getEventHandler() {
if (eventHandler == null) {
return Optional.empty();
return null;
}
return Optional.of((Consumer<T>) eventHandler);
return (Consumer<T>) eventHandler;
}
@NotNull
public Optional<Consumer<DiscordCommandAutoCompleteInteractionEvent>> getAutoCompleteHandler() {
return Optional.ofNullable(autoCompleteHandler);
@Nullable
public Consumer<DiscordCommandAutoCompleteInteractionEvent> getAutoCompleteHandler() {
return autoCompleteHandler;
}
@Override

View File

@ -115,14 +115,14 @@ public class CommandOption implements JDAEntity<OptionData> {
return channelTypes;
}
@NotNull
public Optional<Number> getMinValue() {
return Optional.ofNullable(minValue);
@Nullable
public Number getMinValue() {
return minValue;
}
@NotNull
public Optional<Number> getMaxValue() {
return Optional.ofNullable(maxValue);
@Nullable
public Number getMaxValue() {
return maxValue;
}
@Override
@ -131,12 +131,24 @@ public class CommandOption implements JDAEntity<OptionData> {
.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<String, Object> entry : choices.entrySet()) {
String key = entry.getKey();

View File

@ -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<ComponentIdentifier> 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;
}
}

View File

@ -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<String> getUrl() {
return buttonStyle == Style.LINK ? Optional.of(idOrUrl) : Optional.empty();
@Nullable
public String getUrl() {
return buttonStyle == Style.LINK ? idOrUrl : null;
}
@NotNull

View File

@ -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<Color> getColor() {
return Optional.ofNullable(color);
@Nullable
public Color getColor() {
return color;
}
@NotNull
public Optional<String> getAuthorName() {
return Optional.ofNullable(authorName);
@Nullable
public String getAuthorName() {
return authorName;
}
@NotNull
public Optional<String> getAuthorUrl() {
return Optional.ofNullable(authorUrl);
@Nullable
public String getAuthorUrl() {
return authorUrl;
}
@NotNull
public Optional<String> getAuthorImageUrl() {
return Optional.ofNullable(authorImageUrl);
@Nullable
public String getAuthorImageUrl() {
return authorImageUrl;
}
@NotNull
public Optional<String> getTitle() {
return Optional.ofNullable(title);
@Nullable
public String getTitle() {
return title;
}
@NotNull
public Optional<String> getTitleUrl() {
return Optional.ofNullable(titleUrl);
@Nullable
public String getTitleUrl() {
return titleUrl;
}
@NotNull
public Optional<String> getDescription() {
return Optional.ofNullable(description);
@Nullable
public String getDescription() {
return description;
}
@NotNull
@ -142,29 +141,29 @@ public class DiscordMessageEmbed {
return fields;
}
@NotNull
public Optional<String> getThumbnailUrl() {
return Optional.ofNullable(thumbnailUrl);
@Nullable
public String getThumbnailUrl() {
return thumbnailUrl;
}
@NotNull
public Optional<String> getImageUrl() {
return Optional.ofNullable(imageUrl);
@Nullable
public String getImageUrl() {
return imageUrl;
}
@NotNull
public Optional<OffsetDateTime> getTimestamp() {
return Optional.ofNullable(timestamp);
@Nullable
public OffsetDateTime getTimestamp() {
return timestamp;
}
@NotNull
public Optional<String> getFooter() {
return Optional.ofNullable(footer);
@Nullable
public String getFooter() {
return footer;
}
@NotNull
public Optional<String> 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

View File

@ -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<ReceivedDiscordMessage> 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<DiscordTextChannel> 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<DiscordDMChannel> 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<DiscordGuildMember> 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<DiscordGuild> getGuild() {
return getTextChannel().map(DiscordTextChannel::getGuild);
@Nullable
default DiscordGuild getGuild() {
DiscordTextChannel textChannel = getTextChannel();
return textChannel != null ? textChannel.getGuild() : null;
}
/**

View File

@ -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<String> 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<String> 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<String> 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

View File

@ -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<String> 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<String> getWebhookUsername() {
return Optional.ofNullable(webhookUsername);
public @Nullable String getWebhookUsername() {
return webhookUsername;
}
@Override
public @NotNull Optional<String> getWebhookAvatarUrl() {
return Optional.ofNullable(webhookAvatarUrl);
public @Nullable String getWebhookAvatarUrl() {
return webhookAvatarUrl;
}
public static class BuilderImpl implements SendableDiscordMessage.Builder {

View File

@ -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<T extends GenericInteractionCreateEvent> extends AbstractDiscordEvent<T> {
@ -64,13 +63,13 @@ public abstract class AbstractInteractionEvent<T extends GenericInteractionCreat
return user;
}
@NotNull
public Optional<DiscordGuildMember> getMember() {
return Optional.ofNullable(member);
@Nullable
public DiscordGuildMember getMember() {
return member;
}
public Optional<DiscordGuild> getGuild() {
return Optional.ofNullable(member).map(DiscordGuildMember::getGuild);
public DiscordGuild getGuild() {
return member != null ? member.getGuild() : null;
}
@NotNull

View File

@ -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<T extends GenericMessageEvent> extends AbstractDiscordEvent<T> {
@ -43,7 +42,7 @@ public abstract class AbstractDiscordMessageEvent<T extends GenericMessageEvent>
}
public boolean isGuildMessage() {
return !getDMChannel().isPresent();
return getDMChannel() == null;
}
/**
@ -51,25 +50,25 @@ public abstract class AbstractDiscordMessageEvent<T extends GenericMessageEvent>
* This will not be present on messages from threads (see {@link #getThreadChannel()}).
* @return an optional potentially containing a {@link DiscordTextChannel}
*/
@NotNull
public Optional<DiscordTextChannel> getTextChannel() {
@Nullable
public DiscordTextChannel getTextChannel() {
return channel instanceof DiscordTextChannel
? Optional.of((DiscordTextChannel) channel)
: Optional.empty();
? (DiscordTextChannel) channel
: null;
}
@NotNull
public Optional<DiscordThreadChannel> getThreadChannel() {
@Nullable
public DiscordThreadChannel getThreadChannel() {
return channel instanceof DiscordThreadChannel
? Optional.of((DiscordThreadChannel) channel)
: Optional.empty();
? (DiscordThreadChannel) channel
: null;
}
@NotNull
public Optional<DiscordDMChannel> getDMChannel() {
@Nullable
public DiscordDMChannel getDMChannel() {
return channel instanceof DiscordDMChannel
? Optional.of((DiscordDMChannel) channel)
: Optional.empty();
? (DiscordDMChannel) channel
: null;
}
@NotNull

View File

@ -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<EventListener> 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;
}
}

View File

@ -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<EventListener> 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;
}
}

View File

@ -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 <T> Optional<T> getContext(Class<T> type) {
public <T> @Nullable T getContext(Class<T> type) {
for (Object o : contexts) {
if (type.isAssignableFrom(o.getClass())) {
return Optional.of((T) o);
return (T) o;
}
}
return Optional.empty();
return null;
}
@Override

View File

@ -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<? extends DiscordSRVPlayer> 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<? extends DiscordSRVPlayer> player(@NotNull String username);
@Nullable
DiscordSRVPlayer player(@NotNull String username);
}

View File

@ -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<UUID> playerUUID();
@Nullable
UUID playerUUID();
@NotNull
Optional<Long> userId();
@Nullable
Long userId();
default boolean isLinked() {
return playerUUID().isPresent() && userId().isPresent();
return playerUUID() != null && userId() != null;
}
}

View File

@ -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<? extends IProfile> lookupProfile(UUID playerUUID);
Optional<? extends IProfile> getProfile(UUID playerUUID);
@Nullable
IProfile getProfile(UUID playerUUID);
@NotNull
CompletableFuture<? extends IProfile> lookupProfile(long userId);
Optional<? extends IProfile> getProfile(long userId);
@Nullable
IProfile getProfile(long userId);
}

View File

@ -68,9 +68,12 @@ public class PaperComponentHandle<T> {
} catch (Throwable ignored) {}
if (unrelocated != null) {
MinecraftComponent component = discordSRV.componentFactory().empty();
component.unrelocatedAdapter()
.orElseThrow(() -> new IllegalStateException("Unrelocated adventure unavailable"))
.setComponent(unrelocated);
MinecraftComponent.Adapter<Object> adapter = component.unrelocatedAdapter();
if (adapter == null) {
throw new IllegalStateException("Unrelocated adventure unavailable");
}
adapter.setComponent(unrelocated);
return component;
}
}

View File

@ -76,17 +76,21 @@ public class PlaceholderAPIIntegration extends PluginIntegration<BukkitDiscordSR
}
placeholder = "%" + placeholder + "%";
Player player = event.getContext(DiscordSRVPlayer.class)
.map(p -> 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<BukkitDiscordSR
Set<Object> 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 {

View File

@ -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<BukkitPlayer, Buk
}
public BukkitPlayer player(Player player) {
return player(player.getUniqueId()).orElseThrow(() -> new IllegalStateException("Player not available"));
BukkitPlayer srvPlayer = player(player.getUniqueId());
if (srvPlayer == null) {
throw new IllegalStateException("Player not available");
}
return srvPlayer;
}
// IOfflinePlayer
private CompletableFuture<Optional<IOfflinePlayer>> getFuture(Supplier<OfflinePlayer> provider) {
private CompletableFuture<IOfflinePlayer> getFuture(Supplier<OfflinePlayer> 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<Optional<IOfflinePlayer>> offlinePlayer(UUID uuid) {
public CompletableFuture<IOfflinePlayer> offlinePlayer(UUID uuid) {
return getFuture(() -> discordSRV.server().getOfflinePlayer(uuid));
}
@SuppressWarnings("deprecation") // Shut up, I know
@Override
public CompletableFuture<Optional<IOfflinePlayer>> offlinePlayer(String username) {
public CompletableFuture<IOfflinePlayer> offlinePlayer(String username) {
return getFuture(() -> discordSRV.server().getOfflinePlayer(username));
}

View File

@ -57,7 +57,11 @@ public class BungeePlayerProvider extends AbstractPlayerProvider<BungeePlayer, B
}
public BungeePlayer player(ProxiedPlayer player) {
return player(player.getUniqueId()).orElseThrow(() -> new IllegalStateException("Player not available"));
BungeePlayer srvPlayer = player(player.getUniqueId());
if (srvPlayer == null) {
throw new IllegalStateException("Player not available");
}
return srvPlayer;
}
}

View File

@ -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<B extends IBootstrap, C extends MainCon
}
@Override
public final @NotNull Optional<JDA> 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<B extends IBootstrap, C extends MainCon
if (!initial) {
waitForStatus(Status.CONNECTED, 20, TimeUnit.SECONDS);
} else {
JDA jda = jda().orElse(null);
JDA jda = jda();
if (jda != null) {
try {
jda.awaitReady();

View File

@ -87,7 +87,7 @@ public class ChannelLockingModule extends AbstractModule<DiscordSRV> {
OrDefault<ChannelLockingConfig.Channels> shutdownConfig,
boolean state
) {
JDA jda = discordSRV.jda().orElse(null);
JDA jda = discordSRV.jda();
if (jda == null) {
return;
}

View File

@ -66,7 +66,7 @@ public class ChannelUpdaterModule extends AbstractModule<DiscordSRV> {
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;
}

View File

@ -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<CompletableFuture<DiscordThreadChannel>> 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<BaseChannelConfig> 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);

View File

@ -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);

View File

@ -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<Object> adapter = component.unrelocatedAdapter();
if (adapter == null) {
throw new IllegalStateException("Could not get unrelocated adventure gson serializer");
}
adapter.setComponent(unrelocatedAdventure);
return fromAPI(component);
}

View File

@ -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());

View File

@ -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<DiscordSRV> {
@ -140,7 +141,10 @@ public class DiscordAPIEventModule extends AbstractModule<DiscordSRV> {
DiscordCommandAutoCompleteInteractionEvent autoComplete = new DiscordCommandAutoCompleteInteractionEvent(
(CommandAutoCompleteInteractionEvent) event, command.getId(), user, guildMember, channel);
discordSRV.eventBus().publish(autoComplete);
command.getAutoCompleteHandler().ifPresent(handler -> handler.accept(autoComplete));
Consumer<DiscordCommandAutoCompleteInteractionEvent> autoCompleteHandler = command.getAutoCompleteHandler();
if (autoCompleteHandler != null) {
autoCompleteHandler.accept(autoComplete);
};
List<Command.Choice> choices = new ArrayList<>();
for (Map.Entry<String, Object> entry : autoComplete.getChoices().entrySet()) {
@ -180,7 +184,10 @@ public class DiscordAPIEventModule extends AbstractModule<DiscordSRV> {
);
newEvent = interactionEvent;
command.getEventHandler().ifPresent(handler -> handler.accept(interactionEvent));
Consumer<AbstractCommandInteractionEvent<?>> 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<DiscordSRV> {
);
newEvent = interactionEvent;
command.getEventHandler().ifPresent(handler -> handler.accept(interactionEvent));
Consumer<AbstractCommandInteractionEvent<?>> 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<DiscordSRV> {
);
newEvent = interactionEvent;
command.getEventHandler().ifPresent(handler -> handler.accept(interactionEvent));
Consumer<AbstractCommandInteractionEvent<?>> 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<DiscordSRV> {
}
} else if (event instanceof ModalInteractionEvent) {
ComponentIdentifier identifier = ComponentIdentifier.parseFromDiscord(
((ModalInteractionEvent) event).getModalId()).orElse(null);
((ModalInteractionEvent) event).getModalId());
if (identifier == null) {
return;
}

View File

@ -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<? extends DiscordMessageChannel> getMessageChannelById(long id) {
Optional<DiscordTextChannel> textChannel = getTextChannelById(id);
if (textChannel.isPresent()) {
public @Nullable DiscordMessageChannel getMessageChannelById(long id) {
DiscordTextChannel textChannel = getTextChannelById(id);
if (textChannel != null) {
return textChannel;
}
Optional<DiscordThreadChannel> 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, J> T mapJDAEntity(Function<JDA, J> get, Function<J, T> 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<DiscordDMChannel> 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<DiscordNewsChannel> 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<DiscordTextChannel> 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<DiscordThreadChannel> 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<DiscordGuild> 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<DiscordUser> 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<DiscordUser> 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<DiscordRole> 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<WebhookClient> asyncLoad(@NonNull Long channelId, @NonNull Executor executor) {
JDA jda = discordSRV.jda().orElse(null);
JDA jda = discordSRV.jda();
if (jda == null) {
return notReady();
}

View File

@ -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;
}

View File

@ -78,7 +78,7 @@ public class DiscordUserImpl implements DiscordUser {
@Override
public CompletableFuture<DiscordDMChannel> openPrivateChannel() {
JDA jda = discordSRV.jda().orElse(null);
JDA jda = discordSRV.jda();
if (jda == null) {
return discordSRV.discordAPI().notReady();
}

View File

@ -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<DiscordGuildMember> 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<DiscordRole> 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

View File

@ -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<String> getNickname() {
return Optional.ofNullable(member.getNickname());
public @Nullable String getNickname() {
return member.getNickname();
}
@Override

View File

@ -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<Attachment> 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<DiscordTextChannel> getTextChannel() {
public @Nullable DiscordTextChannel getTextChannel() {
return channel instanceof DiscordTextChannel
? Optional.of((DiscordTextChannel) channel)
: Optional.empty();
? (DiscordTextChannel) channel
: null;
}
@Override
public @NotNull Optional<DiscordDMChannel> getDMChannel() {
public @Nullable DiscordDMChannel getDMChannel() {
return channel instanceof DiscordDMChannel
? Optional.of((DiscordDMChannel) channel)
: Optional.empty();
? (DiscordDMChannel) channel
: null;
}
@Override
public @NotNull Optional<DiscordGuildMember> 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<ReceivedDiscordMessage> getReplyingTo() {
return Optional.ofNullable(replyingTo);
public @Nullable ReceivedDiscordMessage getReplyingTo() {
return replyingTo;
}
@Override
public @NotNull CompletableFuture<Void> 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));
}

View File

@ -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());
}
}

View File

@ -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;
}

View File

@ -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<DiscordSRV> {
private CompletableFuture<Long> lookupLinkedAccount(UUID player) {
return discordSRV.profileManager().lookupProfile(player)
.thenApply(profile -> profile.userId().orElse(null));
.thenApply(Profile::userId);
}
private CompletableFuture<UUID> 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<DiscordSRV> {
}
public Collection<CompletableFuture<GroupSyncResult>> 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<DiscordSRV> {
}
private CompletableFuture<GroupSyncResult> 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<DiscordSRV> {
private CompletableFuture<GroupSyncResult> 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);
}

View File

@ -44,7 +44,7 @@ public class DiscordInviteModule extends AbstractModule<DiscordSRV> {
@Override
public void reload() {
JDA jda = discordSRV.jda().orElse(null);
JDA jda = discordSRV.jda();
if (jda == null) {
return;
}

View File

@ -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);
}

View File

@ -51,7 +51,7 @@ public class DiscordChatMessageModule extends AbstractModule<DiscordSRV> {
@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<DiscordSRV> {
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);

View File

@ -94,7 +94,7 @@ public class DiscordMessageMirroringModule extends AbstractModule<DiscordSRV> {
}
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<DiscordSRV> {
List<Long> 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<DiscordSRV> {
DiscordGuildMessageChannel destinationChannel,
OrDefault<MirroringConfig> 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<DiscordSRV> {
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<DiscordSRV> {
}
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) {

View File

@ -100,7 +100,7 @@ public abstract class AbstractGameMessageModule<T extends IMessageConfig, E exte
List<Long> 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) {

View File

@ -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

View File

@ -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<T extends IPlayer, DT extends Discord
super(discordSRV);
}
public abstract CompletableFuture<Optional<IOfflinePlayer>> offlinePlayer(UUID uuid);
public abstract CompletableFuture<Optional<IOfflinePlayer>> offlinePlayer(String username);
public abstract CompletableFuture<IOfflinePlayer> offlinePlayer(UUID uuid);
public abstract CompletableFuture<IOfflinePlayer> offlinePlayer(String username);
}

View File

@ -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<T extends IPlayer, DT extends Disco
}
@Override
public final @NotNull Optional<T> 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<T> 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

View File

@ -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<T extends IPlayer> extends IPlayerProvider {
/**
* Gets an online player by {@link UUID}.
*
* @param uuid the uuid of the Player
*/
@NotNull
Optional<T> 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<T> player(@NotNull String username);
@Nullable
DiscordSRVPlayer player(@NotNull String username);
/**
* Gets all online players.

View File

@ -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<UUID> playerUUID() {
return Optional.ofNullable(playerUUID);
public @Nullable UUID playerUUID() {
return playerUUID;
}
@Override
public @NotNull Optional<Long> userId() {
return Optional.ofNullable(userId);
public @Nullable Long userId() {
return userId;
}
}

View File

@ -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<Profile> lookupProfile(UUID playerUUID) {
public @NotNull CompletableFuture<Profile> lookupProfile(UUID playerUUID) {
return discordSRV.linkProvider().getUserId(playerUUID)
.thenApply(opt -> new Profile(playerUUID, opt.orElse(null)));
}
@Override
public Optional<Profile> getProfile(UUID playerUUID) {
return Optional.ofNullable(profiles.get(playerUUID));
public @Nullable Profile getProfile(UUID playerUUID) {
return profiles.get(playerUUID);
}
@Override
public CompletableFuture<Profile> lookupProfile(long userId) {
public @NotNull CompletableFuture<Profile> lookupProfile(long userId) {
return discordSRV.linkProvider().getPlayerUUID(userId)
.thenApply(opt -> new Profile(opt.orElse(null), userId));
}
@Override
public Optional<Profile> getProfile(long userId) {
return Optional.ofNullable(discordUserMap.get(userId));
public @Nullable Profile getProfile(long userId) {
return discordUserMap.get(userId);
}
}

View File

@ -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<SpongePlayer, Spo
}
public SpongePlayer player(ServerPlayer player) {
return player(player.uniqueId()).orElseThrow(() -> 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<SpongePlayer, Spo
}
@Override
public CompletableFuture<Optional<IOfflinePlayer>> offlinePlayer(UUID uuid) {
public CompletableFuture<IOfflinePlayer> 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<Optional<IOfflinePlayer>> offlinePlayer(String username) {
public CompletableFuture<IOfflinePlayer> 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) {

View File

@ -57,6 +57,10 @@ public class VelocityPlayerProvider extends AbstractPlayerProvider<VelocityPlaye
}
public VelocityPlayer player(Player player) {
return player(player.getUniqueId()).orElseThrow(() -> new IllegalStateException("Player not available"));
VelocityPlayer srvPlayer = player(player.getUniqueId());
if (srvPlayer == null) {
throw new IllegalStateException("Player not available");
}
return srvPlayer;
}
}