diff --git a/src/main/java/net/dv8tion/jda/api/utils/cache/CacheView.java b/src/main/java/net/dv8tion/jda/api/utils/cache/CacheView.java index 887b952280..fc24553f55 100644 --- a/src/main/java/net/dv8tion/jda/api/utils/cache/CacheView.java +++ b/src/main/java/net/dv8tion/jda/api/utils/cache/CacheView.java @@ -95,7 +95,7 @@ public interface CacheView extends Iterable * * @return {@link ClosableIterator} holding a read-lock on the data structure. * - * @since 4.0.0 + * @since 4.0.0 */ @Nonnull ClosableIterator lockedIterator(); @@ -110,7 +110,7 @@ public interface CacheView extends Iterable * @throws NullPointerException * If provided with null * - * @since 4.0.0 + * @since 4.0.0 */ default void forEachUnordered(@Nonnull final Consumer action) { @@ -140,7 +140,7 @@ default void forEachUnordered(@Nonnull final Consumer action) * * @return The resulting value after the action was performed * - * @since 4.0.0 + * @since 4.0.0 * * @see #acceptStream(Consumer) */ @@ -174,7 +174,7 @@ default R applyStream(@Nonnull Function, ? extends R> acti * @throws IllegalArgumentException * If the action is null * - * @since 4.0.0 + * @since 4.0.0 * * @see #applyStream(Function) */ @@ -449,9 +449,9 @@ static UnifiedMemberCacheView allMembers(@Nonnull Supplier extends AbstractCacheView { - public SimpleCacheView(@Nonnull Class type, @Nullable Function nameMapper) + public SimpleCacheView(@Nonnull Class type, @Nonnull T[] emptyArray, @Nullable Function nameMapper) { - super(type, nameMapper); + super(type, emptyArray, nameMapper); } } } diff --git a/src/main/java/net/dv8tion/jda/internal/JDAImpl.java b/src/main/java/net/dv8tion/jda/internal/JDAImpl.java index 77a56c3258..df69b4b167 100644 --- a/src/main/java/net/dv8tion/jda/internal/JDAImpl.java +++ b/src/main/java/net/dv8tion/jda/internal/JDAImpl.java @@ -106,12 +106,12 @@ public class JDAImpl implements JDA { public static final Logger LOG = JDALogger.getLog(JDA.class); - protected final SnowflakeCacheViewImpl userCache = new SnowflakeCacheViewImpl<>(User.class, User::getName); - protected final SnowflakeCacheViewImpl guildCache = new SnowflakeCacheViewImpl<>(Guild.class, Guild::getName); + protected final SnowflakeCacheViewImpl userCache = new SnowflakeCacheViewImpl<>(User.class, new User[0], User::getName); + protected final SnowflakeCacheViewImpl guildCache = new SnowflakeCacheViewImpl<>(Guild.class, new Guild[0], Guild::getName); protected final ChannelCacheViewImpl channelCache = new ChannelCacheViewImpl<>(Channel.class); protected final ArrayDeque privateChannelLRU = new ArrayDeque<>(); - protected final AbstractCacheView audioManagers = new CacheView.SimpleCacheView<>(AudioManager.class, m -> m.getGuild().getName()); + protected final AbstractCacheView audioManagers = new CacheView.SimpleCacheView<>(AudioManager.class, new AudioManager[0], m -> m.getGuild().getName()); protected final PresenceImpl presence; protected final Thread shutdownHook; @@ -139,7 +139,7 @@ public class JDAImpl implements JDA protected String gatewayUrl; protected ChunkingFilter chunkingFilter; - protected String clientId = null, requiredScopes = "bot"; + protected String clientId = null, requiredScopes = "bot"; protected ShardManager shardManager = null; protected MemberCachePolicy memberCachePolicy = MemberCachePolicy.ALL; @@ -230,7 +230,7 @@ public boolean cacheMember(Member member) try { return member.getUser().equals(getSelfUser()) // always cache self - || memberCachePolicy.cacheMember(member); // ask policy, should we cache? + || memberCachePolicy.cacheMember(member); // ask policy, should we cache? } catch (Exception e) { @@ -374,7 +374,8 @@ public void setToken(String token) public void setStatus(Status status) { - StatusChangeEvent event = MiscUtil.locked(statusLock, () -> { + StatusChangeEvent event = MiscUtil.locked(statusLock, () -> + { Status oldStatus = this.status.getAndSet(status); this.statusCondition.signalAll(); @@ -517,7 +518,7 @@ public JDA awaitStatus(@Nonnull Status status, @Nonnull Status... failOn) throws EnumSet endCondition = EnumSet.of(status, failOn); Status current = getStatus(); while (!current.isInit() // In case of disconnects during startup - || current.ordinal() < status.ordinal()) // If we missed the status (e.g. LOGGING_IN -> CONNECTED happened while waiting for lock) + || current.ordinal() < status.ordinal()) // If we missed the status (e.g. LOGGING_IN -> CONNECTED happened while waiting for lock) { if (current == Status.SHUTDOWN) throw new IllegalStateException("Was shutdown trying to await status.\nReason: " + shutdownReason); @@ -616,7 +617,7 @@ public List getMutualGuilds(@Nonnull UserSnowflake... users) public List getMutualGuilds(@Nonnull Collection users) { Checks.notNull(users, "users"); - for(UserSnowflake u : users) + for (UserSnowflake u : users) Checks.notNull(u, "All users"); return getGuilds().stream() .filter(guild -> users.stream().allMatch(guild::isMember)) @@ -629,7 +630,8 @@ public CacheRestAction retrieveUserById(long id) { return new DeferredRestAction<>(this, User.class, () -> isIntent(GatewayIntent.GUILD_MEMBERS) || isIntent(GatewayIntent.GUILD_PRESENCES) ? getUserById(id) : null, - () -> { + () -> + { if (id == getSelfUser().getIdLong()) return new CompletedRestAction<>(this, getSelfUser()); Route.CompiledRoute route = Route.Users.GET_USER.compile(Long.toUnsignedString(id)); @@ -757,7 +759,7 @@ public RestAction retrieveSticker(@Nonnull StickerSnowflake sticke Checks.notNull(sticker, "Sticker"); Route.CompiledRoute route = Route.Stickers.GET_STICKER.compile(sticker.getId()); return new RestActionImpl<>(this, route, - (response, request) -> entityBuilder.createRichSticker(response.getObject()) + (response, request) -> entityBuilder.createRichSticker(response.getObject()) ); } @@ -905,16 +907,18 @@ public CacheRestAction openPrivateChannelById(long userId) { if (selfUser != null && userId == selfUser.getIdLong()) throw new UnsupportedOperationException("Cannot open private channel with yourself!"); - return new DeferredRestAction<>(this, PrivateChannel.class, () -> { + return new DeferredRestAction<>(this, PrivateChannel.class, () -> + { User user = getUserById(userId); if (user instanceof UserImpl) return ((UserImpl) user).getPrivateChannel(); return null; - }, () -> { + }, () -> + { Route.CompiledRoute route = Route.Self.CREATE_PRIVATE_CHANNEL.compile(); DataObject body = DataObject.empty().put("recipient_id", userId); return new RestActionImpl<>(this, route, body, - (response, request) -> getEntityBuilder().createPrivateChannel(response.getObject())); + (response, request) -> getEntityBuilder().createPrivateChannel(response.getObject())); }); } @@ -986,7 +990,9 @@ public void shutdownInternals(ShutdownEvent event) { Runtime.getRuntime().removeShutdownHook(shutdownHook); } - catch (Exception ignored) {} + catch (Exception ignored) + { + } } // If the requester has been shutdown too, we can fire the shutdown event @@ -1015,9 +1021,9 @@ private void signalShutdown() private void closeAudioConnections() { getAudioManagerCache() - .stream() - .map(AudioManagerImpl.class::cast) - .forEach(m -> m.closeAudioConnection(ConnectionStatus.SHUTTING_DOWN)); + .stream() + .map(AudioManagerImpl.class::cast) + .forEach(m -> m.closeAudioConnection(ConnectionStatus.SHUTTING_DOWN)); } @Override @@ -1064,7 +1070,7 @@ public void addEventListener(@Nonnull Object... listeners) { Checks.noneNull(listeners, "listeners"); - for (Object listener: listeners) + for (Object listener : listeners) eventManager.register(listener); } @@ -1073,7 +1079,7 @@ public void removeEventListener(@Nonnull Object... listeners) { Checks.noneNull(listeners, "listeners"); - for (Object listener: listeners) + for (Object listener : listeners) eventManager.unregister(listener); } @@ -1100,11 +1106,11 @@ public RestAction> retrieveCommands(boolean withLocalizations) .withQueryParams("with_localizations", String.valueOf(withLocalizations)); return new RestActionImpl<>(this, route, - (response, request) -> - response.getArray() - .stream(DataArray::getObject) - .map(json -> new CommandImpl(this, null, json)) - .collect(Collectors.toList())); + (response, request) -> + response.getArray() + .stream(DataArray::getObject) + .map(json -> new CommandImpl(this, null, json)) + .collect(Collectors.toList())); } @Nonnull @@ -1157,11 +1163,11 @@ public RestAction> retrieveRoleConnectionMetadata() { Route.CompiledRoute route = Route.Applications.GET_ROLE_CONNECTION_METADATA.compile(getSelfUser().getApplicationId()); return new RestActionImpl<>(this, route, - (response, request) -> - response.getArray() - .stream(DataArray::getObject) - .map(RoleConnectionMetadata::fromData) - .collect(Helpers.toUnmodifiableList())); + (response, request) -> + response.getArray() + .stream(DataArray::getObject) + .map(RoleConnectionMetadata::fromData) + .collect(Helpers.toUnmodifiableList())); } @Nonnull @@ -1177,11 +1183,11 @@ public RestAction> updateRoleConnectionMetadata(@No RequestBody body = RequestBody.create(array.toJson(), Requester.MEDIA_TYPE_JSON); return new RestActionImpl<>(this, route, body, - (response, request) -> - response.getArray() - .stream(DataArray::getObject) - .map(RoleConnectionMetadata::fromData) - .collect(Helpers.toUnmodifiableList())); + (response, request) -> + response.getArray() + .stream(DataArray::getObject) + .map(RoleConnectionMetadata::fromData) + .collect(Helpers.toUnmodifiableList())); } @Nonnull diff --git a/src/main/java/net/dv8tion/jda/internal/entities/GuildImpl.java b/src/main/java/net/dv8tion/jda/internal/entities/GuildImpl.java index 4f2bcaf066..41a4349352 100644 --- a/src/main/java/net/dv8tion/jda/internal/entities/GuildImpl.java +++ b/src/main/java/net/dv8tion/jda/internal/entities/GuildImpl.java @@ -106,14 +106,14 @@ public class GuildImpl implements Guild private final long id; private final JDAImpl api; - private final SortedSnowflakeCacheViewImpl scheduledEventCache = new SortedSnowflakeCacheViewImpl<>(ScheduledEvent.class, ScheduledEvent::getName, Comparator.naturalOrder()); + private final SortedSnowflakeCacheViewImpl scheduledEventCache = new SortedSnowflakeCacheViewImpl<>(ScheduledEvent.class, new ScheduledEvent[0], ScheduledEvent::getName, Comparator.naturalOrder()); private final SortedChannelCacheViewImpl channelCache = new SortedChannelCacheViewImpl<>(GuildChannel.class); - private final SortedSnowflakeCacheViewImpl roleCache = new SortedSnowflakeCacheViewImpl<>(Role.class, Role::getName, Comparator.reverseOrder()); - private final SnowflakeCacheViewImpl emojicache = new SnowflakeCacheViewImpl<>(RichCustomEmoji.class, RichCustomEmoji::getName); - private final SnowflakeCacheViewImpl stickerCache = new SnowflakeCacheViewImpl<>(GuildSticker.class, GuildSticker::getName); + private final SortedSnowflakeCacheViewImpl roleCache = new SortedSnowflakeCacheViewImpl<>(Role.class, new Role[0], Role::getName, Comparator.reverseOrder()); + private final SnowflakeCacheViewImpl emojicache = new SnowflakeCacheViewImpl<>(RichCustomEmoji.class, new RichCustomEmoji[0], RichCustomEmoji::getName); + private final SnowflakeCacheViewImpl stickerCache = new SnowflakeCacheViewImpl<>(GuildSticker.class, new GuildSticker[0], GuildSticker::getName); private final MemberCacheViewImpl memberCache = new MemberCacheViewImpl(); private final CacheView.SimpleCacheView memberPresences; - private final SnowflakeCacheViewImpl voiceStateCache = new SnowflakeCacheViewImpl<>(GuildVoiceStateImpl.class, state -> state.getMember().getEffectiveName()); + private final SnowflakeCacheViewImpl voiceStateCache = new SnowflakeCacheViewImpl<>(GuildVoiceStateImpl.class, new GuildVoiceStateImpl[0], state -> state.getMember().getEffectiveName()); private CompletableFuture pendingRequestToSpeak; @@ -150,7 +150,7 @@ public GuildImpl(JDAImpl api, long id) this.id = id; this.api = api; if (api.getCacheFlags().stream().anyMatch(CacheFlag::isPresence)) - memberPresences = new CacheView.SimpleCacheView<>(MemberPresenceImpl.class, null); + memberPresences = new CacheView.SimpleCacheView<>(MemberPresenceImpl.class, new MemberPresenceImpl[0], null); else memberPresences = null; } @@ -193,7 +193,8 @@ public void invalidate() try (UnlockHook hook = userView.writeLock()) { long selfId = getJDA().getSelfUser().getIdLong(); - memberIds.forEach(memberId -> { + memberIds.forEach(memberId -> + { if (memberId == selfId) return true; // don't remove selfUser from cache userView.remove(memberId); @@ -304,9 +305,11 @@ public RestAction> retrieveIntegrationPrivilegesById( public RestAction retrieveCommandPrivileges() { Route.CompiledRoute route = Route.Interactions.GET_ALL_COMMAND_PERMISSIONS.compile(getJDA().getSelfUser().getApplicationId(), getId()); - return new RestActionImpl<>(getJDA(), route, (response, request) -> { + return new RestActionImpl<>(getJDA(), route, (response, request) -> + { Map> privileges = new HashMap<>(); - response.getArray().stream(DataArray::getObject).forEach(obj -> { + response.getArray().stream(DataArray::getObject).forEach(obj -> + { String id = obj.getString("id"); List list = Collections.unmodifiableList(parsePrivilegesList(obj)); privileges.put(id, list); @@ -508,7 +511,7 @@ public RestAction retrieveVanityInvite() JDAImpl api = getJDA(); Route.CompiledRoute route = Route.Guilds.GET_VANITY_URL.compile(getId()); return new RestActionImpl<>(api, route, - (response, request) -> new VanityInvite(vanityCode, response.getObject().getInt("uses"))); + (response, request) -> new VanityInvite(vanityCode, response.getObject().getInt("uses"))); } @Nullable @@ -551,9 +554,9 @@ public int getBoostCount() public List getBoosters() { return memberCache.applyStream((members) -> - members.filter(m -> m.getTimeBoosted() != null) - .sorted(Comparator.comparing(Member::getTimeBoosted)) - .collect(Helpers.toUnmodifiableList())); + members.filter(m -> m.getTimeBoosted() != null) + .sorted(Comparator.comparing(Member::getTimeBoosted)) + .collect(Helpers.toUnmodifiableList())); } @Override @@ -574,7 +577,8 @@ public RestAction retrieveMetaData() { Route.CompiledRoute route = Route.Guilds.GET_GUILD.compile(getId()); route = route.withQueryParams("with_counts", "true"); - return new RestActionImpl<>(getJDA(), route, (response, request) -> { + return new RestActionImpl<>(getJDA(), route, (response, request) -> + { DataObject json = response.getObject(); int memberLimit = json.getInt("max_members", 0); int presenceLimit = json.getInt("max_presences", 5000); @@ -876,9 +880,9 @@ public List getChannels(boolean includeHidden) if (includeHidden) { return channelCache.applyStream(stream -> - stream.filter(it -> !it.getType().isThread()) - .sorted() - .collect(Helpers.toUnmodifiableList()) + stream.filter(it -> !it.getType().isThread()) + .sorted() + .collect(Helpers.toUnmodifiableList()) ); } @@ -941,15 +945,17 @@ public RestAction retrieveEmojiById(@Nonnull String id) JDAImpl jda = getJDA(); return new DeferredRestAction<>(jda, RichCustomEmoji.class, - () -> { - RichCustomEmoji emoji = getEmojiById(id); - if (emoji != null) - { - if (emoji.getOwner() != null || !getSelfMember().hasPermission(Permission.MANAGE_GUILD_EXPRESSIONS)) - return emoji; - } - return null; - }, () -> { + () -> + { + RichCustomEmoji emoji = getEmojiById(id); + if (emoji != null) + { + if (emoji.getOwner() != null || !getSelfMember().hasPermission(Permission.MANAGE_GUILD_EXPRESSIONS)) + return emoji; + } + return null; + }, () -> + { Route.CompiledRoute route = Route.Emojis.GET_EMOJI.compile(getId(), id); return new AuditableRestActionImpl<>(jda, route, (response, request) -> { @@ -964,7 +970,8 @@ public RestAction retrieveEmojiById(@Nonnull String id) public RestAction> retrieveStickers() { Route.CompiledRoute route = Route.Stickers.GET_GUILD_STICKERS.compile(getId()); - return new RestActionImpl<>(getJDA(), route, (response, request) -> { + return new RestActionImpl<>(getJDA(), route, (response, request) -> + { DataArray array = response.getArray(); List stickers = new ArrayList<>(array.length()); EntityBuilder builder = api.getEntityBuilder(); @@ -993,7 +1000,8 @@ public RestAction retrieveSticker(@Nonnull StickerSnowflake sticke { Checks.notNull(sticker, "Sticker"); Route.CompiledRoute route = Route.Stickers.GET_GUILD_STICKER.compile(getId(), sticker.getId()); - return new RestActionImpl<>(getJDA(), route, (response, request) -> { + return new RestActionImpl<>(getJDA(), route, (response, request) -> + { DataObject object = response.getObject(); EntityBuilder builder = api.getEntityBuilder(); return (GuildSticker) builder.createRichSticker(object); @@ -1155,7 +1163,9 @@ public synchronized Task cancelRequestToSpeak() return new GatewayTask<>(future, () -> future.cancel(false)); } - return new GatewayTask<>(CompletableFuture.completedFuture(null), () -> {}); + return new GatewayTask<>(CompletableFuture.completedFuture(null), () -> + { + }); } @Nonnull @@ -1170,7 +1180,7 @@ public JDAImpl getJDA() public List getVoiceStates() { return this.voiceStateCache.applyStream(stream -> - stream.collect(Helpers.toUnmodifiableList()) + stream.collect(Helpers.toUnmodifiableList()) ); } @@ -1231,13 +1241,16 @@ public Task loadMembers(@Nonnull Consumer callback) if (isLoaded()) { memberCache.forEachUnordered(callback); - return new GatewayTask<>(CompletableFuture.completedFuture(null), () -> {}); + return new GatewayTask<>(CompletableFuture.completedFuture(null), () -> + { + }); } MemberChunkManager chunkManager = getJDA().getClient().getChunkManager(); boolean includePresences = getJDA().isIntent(GatewayIntent.GUILD_PRESENCES); MemberChunkManager.ChunkRequest handler = chunkManager.chunkGuild(this, includePresences, (last, list) -> list.forEach(callback)); - handler.exceptionally(ex -> { + handler.exceptionally(ex -> + { WebSocketClient.LOG.error("Encountered exception trying to handle member chunk response", ex); return null; }); @@ -1251,11 +1264,13 @@ public CacheRestAction retrieveMemberById(long id) JDAImpl jda = getJDA(); return new DeferredRestAction<>(jda, Member.class, () -> getMemberById(id), - () -> { + () -> + { if (id == jda.getSelfUser().getIdLong()) return new CompletedRestAction<>(jda, getSelfMember()); Route.CompiledRoute route = Route.Guilds.GET_MEMBER.compile(getId(), Long.toUnsignedString(id)); - return new RestActionImpl<>(jda, route, (resp, req) -> { + return new RestActionImpl<>(jda, route, (resp, req) -> + { MemberImpl member = jda.getEntityBuilder().createMember(this, resp.getObject()); jda.getEntityBuilder().updateMemberCache(member); return member; @@ -1272,18 +1287,22 @@ public Task> retrieveMembersByIds(boolean includePresence, @Nonnull "Cannot retrieve presences of members without GUILD_PRESENCES intent!"); if (ids.length == 0) - return new GatewayTask<>(CompletableFuture.completedFuture(Collections.emptyList()), () -> {}); + return new GatewayTask<>(CompletableFuture.completedFuture(Collections.emptyList()), () -> + { + }); Checks.check(ids.length <= 100, "You can only request 100 members at once"); MemberChunkManager chunkManager = api.getClient().getChunkManager(); List collect = new ArrayList<>(ids.length); CompletableFuture> result = new CompletableFuture<>(); - MemberChunkManager.ChunkRequest handle = chunkManager.chunkGuild(this, includePresence, ids, (last, list) -> { + MemberChunkManager.ChunkRequest handle = chunkManager.chunkGuild(this, includePresence, ids, (last, list) -> + { collect.addAll(list); if (last) result.complete(collect); }); - handle.exceptionally(ex -> { + handle.exceptionally(ex -> + { WebSocketClient.LOG.error("Encountered exception trying to handle member chunk response", ex); result.completeExceptionally(ex); return null; @@ -1304,13 +1323,15 @@ public Task> retrieveMembersByPrefix(@Nonnull String prefix, int li List collect = new ArrayList<>(limit); CompletableFuture> result = new CompletableFuture<>(); - MemberChunkManager.ChunkRequest handle = chunkManager.chunkGuild(this, prefix, limit, (last, list) -> { + MemberChunkManager.ChunkRequest handle = chunkManager.chunkGuild(this, prefix, limit, (last, list) -> + { collect.addAll(list); if (last) result.complete(collect); }); - handle.exceptionally(ex -> { + handle.exceptionally(ex -> + { WebSocketClient.LOG.error("Encountered exception trying to handle member chunk response", ex); result.completeExceptionally(ex); return null; @@ -1521,7 +1542,8 @@ public AuditableRestAction modifyNickname(@Nonnull Member member, String n } JDAImpl jda = getJDA(); - return new DeferredRestAction<>(jda, () -> { + return new DeferredRestAction<>(jda, () -> + { DataObject body = DataObject.empty().put("nick", nickname == null ? "" : nickname); Route.CompiledRoute route; @@ -1632,16 +1654,17 @@ public AuditableRestAction ban(@Nonnull Collection(getJDA(), route, body, (res, req) -> { + return new AuditableRestActionImpl<>(getJDA(), route, body, (res, req) -> + { DataObject responseBody = res.getObject(); List bannedUsers = responseBody.getArray("banned_users") - .stream(DataArray::getLong) - .map(UserSnowflake::fromId) - .collect(Collectors.toList()); + .stream(DataArray::getLong) + .map(UserSnowflake::fromId) + .collect(Collectors.toList()); List failedUsers = responseBody.getArray("failed_users") - .stream(DataArray::getLong) - .map(UserSnowflake::fromId) - .collect(Collectors.toList()); + .stream(DataArray::getLong) + .map(UserSnowflake::fromId) + .collect(Collectors.toList()); return new BulkBanResponse(bannedUsers, failedUsers); }); } @@ -1798,7 +1821,7 @@ public AuditableRestAction modifyMemberRoles(@Nonnull Member member, @Nonn }); Checks.check(!roles.contains(getPublicRole()), - "Cannot add the PublicRole of a Guild to a Member. All members have this role by default!"); + "Cannot add the PublicRole of a Guild to a Member. All members have this role by default!"); // Return an empty rest action if there were no changes final List memberRoles = member.getRoles(); @@ -1826,7 +1849,7 @@ public AuditableRestAction modifyMemberRoles(@Nonnull Member member, @Nonn } DataObject body = DataObject.empty() - .put("roles", roles.stream().map(Role::getId).collect(Collectors.toSet())); + .put("roles", roles.stream().map(Role::getId).collect(Collectors.toSet())); Route.CompiledRoute route = Route.Guilds.MODIFY_MEMBER.compile(getId(), member.getUser().getId()); return new AuditableRestActionImpl<>(getJDA(), route, body); @@ -1949,18 +1972,18 @@ public AuditableRestAction createSticker(@Nonnull String name, @No MediaType mediaType; switch (extension) { - case "apng": - case "png": - mediaType = Requester.MEDIA_TYPE_PNG; - break; - case "gif": - mediaType = Requester.MEDIA_TYPE_GIF; - break; - case "json": - mediaType = Requester.MEDIA_TYPE_JSON; - break; - default: - throw new IllegalArgumentException("Unsupported file extension: '." + extension + "', must be PNG, GIF, or JSON."); + case "apng": + case "png": + mediaType = Requester.MEDIA_TYPE_PNG; + break; + case "gif": + mediaType = Requester.MEDIA_TYPE_GIF; + break; + case "json": + mediaType = Requester.MEDIA_TYPE_JSON; + break; + default: + throw new IllegalArgumentException("Unsupported file extension: '." + extension + "', must be PNG, GIF, or JSON."); } // Add sticker metadata as form parts (because payload_json is broken) @@ -1975,7 +1998,7 @@ public AuditableRestAction createSticker(@Nonnull String name, @No MultipartBody body = builder.build(); Route.CompiledRoute route = Route.Stickers.CREATE_GUILD_STICKER.compile(getId()); return new AuditableRestActionImpl<>(api, route, body, - (response, request) -> (GuildSticker) api.getEntityBuilder().createRichSticker(response.getObject()) + (response, request) -> (GuildSticker) api.getEntityBuilder().createRichSticker(response.getObject()) ); } @@ -2058,13 +2081,13 @@ protected void checkPermission(Permission perm) protected void checkPosition(UserSnowflake user) { Member member = resolveMember(user); - if(member != null && !getSelfMember().canInteract(member)) + if (member != null && !getSelfMember().canInteract(member)) throw new HierarchyException("Can't modify a member with higher or equal highest role than yourself!"); } protected void checkPosition(Role role) { - if(!getSelfMember().canInteract(role)) + if (!getSelfMember().canInteract(role)) throw new HierarchyException("Can't modify a role with higher or equal highest role than yourself! Role: " + role.toString()); } @@ -2437,11 +2460,11 @@ public void handleVoiceStateUpdate(GuildVoiceStateImpl voiceState) public List getConnectedMembers(GuildChannel channel) { return this.voiceStateCache.applyStream(stream -> - stream - .filter(state -> channel.equals(state.getChannel())) - .map(GuildVoiceStateImpl::getMember) - .filter(Objects::nonNull) // sanity filter - .collect(Helpers.toUnmodifiableList()) + stream + .filter(state -> channel.equals(state.getChannel())) + .map(GuildVoiceStateImpl::getMember) + .filter(Objects::nonNull) // sanity filter + .collect(Helpers.toUnmodifiableList()) ); } diff --git a/src/main/java/net/dv8tion/jda/internal/entities/channel/concrete/ForumChannelImpl.java b/src/main/java/net/dv8tion/jda/internal/entities/channel/concrete/ForumChannelImpl.java index f0512965a2..3b257ec54d 100644 --- a/src/main/java/net/dv8tion/jda/internal/entities/channel/concrete/ForumChannelImpl.java +++ b/src/main/java/net/dv8tion/jda/internal/entities/channel/concrete/ForumChannelImpl.java @@ -43,12 +43,12 @@ import java.util.List; public class ForumChannelImpl extends AbstractGuildChannelImpl - implements ForumChannel, + implements ForumChannel, GuildChannelUnion, ForumChannelMixin { private final TLongObjectMap overrides = MiscUtil.newLongMap(); - private final SortedSnowflakeCacheViewImpl tagCache = new SortedSnowflakeCacheViewImpl<>(ForumTag.class, ForumTag::getName, Comparator.naturalOrder()); + private final SortedSnowflakeCacheViewImpl tagCache = new SortedSnowflakeCacheViewImpl<>(ForumTag.class, new ForumTag[0], ForumTag::getName, Comparator.naturalOrder()); private Emoji defaultReaction; private String topic; diff --git a/src/main/java/net/dv8tion/jda/internal/entities/channel/concrete/MediaChannelImpl.java b/src/main/java/net/dv8tion/jda/internal/entities/channel/concrete/MediaChannelImpl.java index eec54cb54b..528eee3d9c 100644 --- a/src/main/java/net/dv8tion/jda/internal/entities/channel/concrete/MediaChannelImpl.java +++ b/src/main/java/net/dv8tion/jda/internal/entities/channel/concrete/MediaChannelImpl.java @@ -43,12 +43,12 @@ import java.util.List; public class MediaChannelImpl extends AbstractGuildChannelImpl - implements MediaChannel, + implements MediaChannel, GuildChannelUnion, MediaChannelMixin { private final TLongObjectMap overrides = MiscUtil.newLongMap(); - private final SortedSnowflakeCacheViewImpl tagCache = new SortedSnowflakeCacheViewImpl<>(ForumTag.class, ForumTag::getName, Comparator.naturalOrder()); + private final SortedSnowflakeCacheViewImpl tagCache = new SortedSnowflakeCacheViewImpl<>(ForumTag.class, new ForumTag[0], ForumTag::getName, Comparator.naturalOrder()); private Emoji defaultReaction; private String topic; diff --git a/src/main/java/net/dv8tion/jda/internal/entities/channel/concrete/ThreadChannelImpl.java b/src/main/java/net/dv8tion/jda/internal/entities/channel/concrete/ThreadChannelImpl.java index dac8e00ec1..fe1ecd9e0d 100644 --- a/src/main/java/net/dv8tion/jda/internal/entities/channel/concrete/ThreadChannelImpl.java +++ b/src/main/java/net/dv8tion/jda/internal/entities/channel/concrete/ThreadChannelImpl.java @@ -61,7 +61,7 @@ public class ThreadChannelImpl extends AbstractGuildChannelImpl { private final ChannelType type; - private final CacheView.SimpleCacheView threadMembers = new CacheView.SimpleCacheView<>(ThreadMember.class, null); + private final CacheView.SimpleCacheView threadMembers = new CacheView.SimpleCacheView<>(ThreadMember.class, new ThreadMember[0], null); private TLongSet appliedTags = new TLongHashSet(ForumChannel.MAX_POST_TAGS); private AutoArchiveDuration autoArchiveDuration; @@ -224,10 +224,11 @@ public CacheRestAction retrieveThreadMemberById(long id) JDAImpl jda = (JDAImpl) getJDA(); return new DeferredRestAction<>(jda, ThreadMember.class, () -> getThreadMemberById(id), - () -> { + () -> + { Route.CompiledRoute route = Route.Channels.GET_THREAD_MEMBER.compile(getId(), Long.toUnsignedString(id)).withQueryParams("with_member", "true"); return new RestActionImpl<>(jda, route, (resp, req) -> - jda.getEntityBuilder().createThreadMember(getGuild(), this, resp.getObject())); + jda.getEntityBuilder().createThreadMember(getGuild(), this, resp.getObject())); }); } diff --git a/src/main/java/net/dv8tion/jda/internal/entities/channel/concrete/detached/DetachedForumChannelImpl.java b/src/main/java/net/dv8tion/jda/internal/entities/channel/concrete/detached/DetachedForumChannelImpl.java index 497a6bad7a..cc899b2e4a 100644 --- a/src/main/java/net/dv8tion/jda/internal/entities/channel/concrete/detached/DetachedForumChannelImpl.java +++ b/src/main/java/net/dv8tion/jda/internal/entities/channel/concrete/detached/DetachedForumChannelImpl.java @@ -41,14 +41,14 @@ import java.util.List; public class DetachedForumChannelImpl extends AbstractGuildChannelImpl - implements + implements ForumChannel, GuildChannelUnion, ForumChannelMixin, IInteractionPermissionMixin { private ChannelInteractionPermissions interactionPermissions; - private final SortedSnowflakeCacheViewImpl tagCache = new SortedSnowflakeCacheViewImpl<>(ForumTag.class, ForumTag::getName, Comparator.naturalOrder()); + private final SortedSnowflakeCacheViewImpl tagCache = new SortedSnowflakeCacheViewImpl<>(ForumTag.class, new ForumTag[0], ForumTag::getName, Comparator.naturalOrder()); private Emoji defaultReaction; private String topic; diff --git a/src/main/java/net/dv8tion/jda/internal/entities/channel/concrete/detached/DetachedMediaChannelImpl.java b/src/main/java/net/dv8tion/jda/internal/entities/channel/concrete/detached/DetachedMediaChannelImpl.java index f1448304be..0aa6dda2f0 100644 --- a/src/main/java/net/dv8tion/jda/internal/entities/channel/concrete/detached/DetachedMediaChannelImpl.java +++ b/src/main/java/net/dv8tion/jda/internal/entities/channel/concrete/detached/DetachedMediaChannelImpl.java @@ -48,7 +48,7 @@ public class DetachedMediaChannelImpl extends AbstractGuildChannelImpl { private ChannelInteractionPermissions interactionPermissions; - private final SortedSnowflakeCacheViewImpl tagCache = new SortedSnowflakeCacheViewImpl<>(ForumTag.class, ForumTag::getName, Comparator.naturalOrder()); + private final SortedSnowflakeCacheViewImpl tagCache = new SortedSnowflakeCacheViewImpl<>(ForumTag.class, new ForumTag[0], ForumTag::getName, Comparator.naturalOrder()); private Emoji defaultReaction; private String topic; diff --git a/src/main/java/net/dv8tion/jda/internal/utils/cache/AbstractCacheView.java b/src/main/java/net/dv8tion/jda/internal/utils/cache/AbstractCacheView.java index 8e0618fbf4..96a98088b0 100644 --- a/src/main/java/net/dv8tion/jda/internal/utils/cache/AbstractCacheView.java +++ b/src/main/java/net/dv8tion/jda/internal/utils/cache/AbstractCacheView.java @@ -28,7 +28,6 @@ import org.apache.commons.collections4.iterators.ObjectArrayIterator; import javax.annotation.Nonnull; -import java.lang.reflect.Array; import java.util.*; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.function.Consumer; @@ -44,11 +43,11 @@ public abstract class AbstractCacheView extends ReadWriteLockCache impleme protected final Class type; @SuppressWarnings("unchecked") - protected AbstractCacheView(Class type, Function nameMapper) + protected AbstractCacheView(Class type, T[] emptyArray, Function nameMapper) { this.nameMapper = nameMapper; this.type = type; - this.emptyArray = (T[]) Array.newInstance(type, 0); + this.emptyArray = emptyArray; } public void clear() diff --git a/src/main/java/net/dv8tion/jda/internal/utils/cache/MemberCacheViewImpl.java b/src/main/java/net/dv8tion/jda/internal/utils/cache/MemberCacheViewImpl.java index 403729d0b1..03d4d6de74 100644 --- a/src/main/java/net/dv8tion/jda/internal/utils/cache/MemberCacheViewImpl.java +++ b/src/main/java/net/dv8tion/jda/internal/utils/cache/MemberCacheViewImpl.java @@ -30,7 +30,7 @@ public class MemberCacheViewImpl extends SnowflakeCacheViewImpl implemen { public MemberCacheViewImpl() { - super(Member.class, Member::getEffectiveName); + super(Member.class, new Member[0], Member::getEffectiveName); } @Override diff --git a/src/main/java/net/dv8tion/jda/internal/utils/cache/SnowflakeCacheViewImpl.java b/src/main/java/net/dv8tion/jda/internal/utils/cache/SnowflakeCacheViewImpl.java index 4cb311fd57..e78dc7cc84 100644 --- a/src/main/java/net/dv8tion/jda/internal/utils/cache/SnowflakeCacheViewImpl.java +++ b/src/main/java/net/dv8tion/jda/internal/utils/cache/SnowflakeCacheViewImpl.java @@ -23,9 +23,9 @@ public class SnowflakeCacheViewImpl extends AbstractCacheView implements SnowflakeCacheView { - public SnowflakeCacheViewImpl(Class type, Function nameMapper) + public SnowflakeCacheViewImpl(Class type, T[] emptyArray, Function nameMapper) { - super(type, nameMapper); + super(type, emptyArray, nameMapper); } @Override diff --git a/src/main/java/net/dv8tion/jda/internal/utils/cache/SortedSnowflakeCacheViewImpl.java b/src/main/java/net/dv8tion/jda/internal/utils/cache/SortedSnowflakeCacheViewImpl.java index 4a6d7ce29c..07551a237a 100644 --- a/src/main/java/net/dv8tion/jda/internal/utils/cache/SortedSnowflakeCacheViewImpl.java +++ b/src/main/java/net/dv8tion/jda/internal/utils/cache/SortedSnowflakeCacheViewImpl.java @@ -34,14 +34,14 @@ public class SortedSnowflakeCacheViewImpl comparator; - public SortedSnowflakeCacheViewImpl(Class type, Comparator comparator) + public SortedSnowflakeCacheViewImpl(Class type, T[] emptyArray, Comparator comparator) { - this(type, null, comparator); + this(type, emptyArray, null, comparator); } - public SortedSnowflakeCacheViewImpl(Class type, Function nameMapper, Comparator comparator) + public SortedSnowflakeCacheViewImpl(Class type, T[] emptyArray, Function nameMapper, Comparator comparator) { - super(type, nameMapper); + super(type, emptyArray, nameMapper); this.comparator = comparator; } diff --git a/src/test/java/net/dv8tion/jda/test/restaction/pagination/PinnedMessagePaginationActionTest.java b/src/test/java/net/dv8tion/jda/test/restaction/pagination/PinnedMessagePaginationActionTest.java index b9483b9e37..fe836ad8cd 100644 --- a/src/test/java/net/dv8tion/jda/test/restaction/pagination/PinnedMessagePaginationActionTest.java +++ b/src/test/java/net/dv8tion/jda/test/restaction/pagination/PinnedMessagePaginationActionTest.java @@ -48,7 +48,7 @@ public class PinnedMessagePaginationActionTest extends IntegrationTest void setupMocks() { when(guild.getJDA()).thenReturn(jda); - when(jda.getUsersView()).thenReturn(new SnowflakeCacheViewImpl<>(User.class, User::getName)); + when(jda.getUsersView()).thenReturn(new SnowflakeCacheViewImpl<>(User.class, new User[0], User::getName)); channel = new TextChannelImpl(Constants.CHANNEL_ID, guild); } @@ -58,17 +58,17 @@ void testEmptyPaginationResponse() PinnedMessagePaginationActionImpl action = new PinnedMessagePaginationActionImpl(channel); assertThatRequestFrom(action) - .hasMethod(Method.GET) - .hasCompiledRoute("channels/" + Constants.CHANNEL_ID + "/messages/pins?limit=50") - .whenQueueCalled(); + .hasMethod(Method.GET) + .hasCompiledRoute("channels/" + Constants.CHANNEL_ID + "/messages/pins?limit=50") + .whenQueueCalled(); assertThat(captureListCallback(PinnedMessage.class, action, DataObject.empty().put("items", DataArray.empty()))) - .isEmpty(); + .isEmpty(); assertThatRequestFrom(action) - .hasMethod(Method.GET) - .hasCompiledRoute("channels/" + Constants.CHANNEL_ID + "/messages/pins?limit=50") - .whenQueueCalled(); + .hasMethod(Method.GET) + .hasCompiledRoute("channels/" + Constants.CHANNEL_ID + "/messages/pins?limit=50") + .whenQueueCalled(); } @Test @@ -83,38 +83,38 @@ void testFullResponseSetsBeforeOnNextUse() { timeStamp = timeStamp.plusSeconds(1); items.add(DataObject.empty() - .put("pinned_at", timeStamp) - .put("message", getTestMessage())); + .put("pinned_at", timeStamp) + .put("message", getTestMessage())); } OffsetDateTime lastTimestamp = timeStamp; assertThat(captureListCallback(PinnedMessage.class, action, DataObject.empty().put("items", items))) - .hasSize(50) - .last().matches(pinned -> pinned.getTimePinned().equals(lastTimestamp)); + .hasSize(50) + .last().matches(pinned -> pinned.getTimePinned().equals(lastTimestamp)); assertThatRequestFrom(action) - .hasMethod(Method.GET) - .hasQueryParams("limit", 50, "before", lastTimestamp) - .whenQueueCalled(); + .hasMethod(Method.GET) + .hasQueryParams("limit", 50, "before", lastTimestamp) + .whenQueueCalled(); } private DataObject getTestMessage() { return DataObject.empty() - .put("type", 0) - .put("id", randomSnowflake()) - .put("channel_id", Constants.CHANNEL_ID) - .put("content", "test content") - .put("embeds", DataArray.empty()) - .put("attachments", DataArray.empty()) - .put("components", DataArray.empty()) - .put("mentions", DataArray.empty()) - .put("mention_roles", DataArray.empty()) - .put("author", DataObject.empty() - .put("id", Constants.MINN_USER_ID) - .put("username", "minn") - .put("discriminator", "0") - .put("avatar", null)); + .put("type", 0) + .put("id", randomSnowflake()) + .put("channel_id", Constants.CHANNEL_ID) + .put("content", "test content") + .put("embeds", DataArray.empty()) + .put("attachments", DataArray.empty()) + .put("components", DataArray.empty()) + .put("mentions", DataArray.empty()) + .put("mention_roles", DataArray.empty()) + .put("author", DataObject.empty() + .put("id", Constants.MINN_USER_ID) + .put("username", "minn") + .put("discriminator", "0") + .put("avatar", null)); } }