net.dv8tion.jda.api.utils.MiscUtil Java Examples

The following examples show how to use net.dv8tion.jda.api.utils.MiscUtil. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MemberChunkManager.java    From JDA with Apache License 2.0 6 votes vote down vote up
public boolean handleChunk(long guildId, DataObject response)
{
    return MiscUtil.locked(lock, () -> {
        String nonce = response.getString("nonce", null);
        if (nonce == null || nonce.isEmpty())
            return false;
        long key = Long.parseLong(nonce);
        ChunkRequest request = requests.get(key);
        if (request == null)
            return false;

        boolean lastChunk = isLastChunk(response);
        request.handleChunk(lastChunk, response);
        if (lastChunk || request.isCancelled())
        {
            requests.remove(key);
            request.complete(null);
        }
        return true;
    });
}
 
Example #2
Source File: GuildImpl.java    From JDA with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public GuildManager getManager()
{
    GuildManager mng = manager;
    if (mng == null)
    {
        mng = MiscUtil.locked(mngLock, () ->
        {
            if (manager == null)
                manager = new GuildManagerImpl(this);
            return manager;
        });
    }
    return mng;
}
 
Example #3
Source File: SelfUserImpl.java    From JDA with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public AccountManager getManager()
{
    AccountManager mng = manager;
    if (mng == null)
    {
        mng = MiscUtil.locked(mngLock, () ->
        {
            if (manager == null)
                manager = new AccountManagerImpl(this);
            return manager;
        });
    }
    return mng;
}
 
Example #4
Source File: RoleImpl.java    From JDA with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public RoleManager getManager()
{
    RoleManager mng = manager;
    if (mng == null)
    {
        mng = MiscUtil.locked(mngLock, () ->
        {
            if (manager == null)
                manager = new RoleManagerImpl(this);
            return manager;
        });
    }
    return mng;
}
 
Example #5
Source File: FakeUser.java    From SkyBot with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void formatTo(Formatter formatter, int flags, int width, int precision) {
    final boolean alt = (flags & FormattableFlags.ALTERNATE) == FormattableFlags.ALTERNATE;
    final boolean upper = (flags & FormattableFlags.UPPERCASE) == FormattableFlags.UPPERCASE;
    final boolean leftJustified = (flags & FormattableFlags.LEFT_JUSTIFY) == FormattableFlags.LEFT_JUSTIFY;

    String out;
    if (!alt) {
        out = getAsMention();
    } else if (upper) {
        out = getAsTag().toUpperCase();
    } else {
        out = getAsTag();
    }

    MiscUtil.appendTo(formatter, width, precision, leftJustified, out);
}
 
Example #6
Source File: PermissionOverrideImpl.java    From JDA with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public PermissionOverrideAction getManager()
{
    if (!getGuild().getSelfMember().hasPermission(getChannel(), Permission.MANAGE_PERMISSIONS))
        throw new InsufficientPermissionException(getChannel(), Permission.MANAGE_PERMISSIONS);
    PermissionOverrideAction mng = manager;
    if (mng == null)
    {
        mng = MiscUtil.locked(mngLock, () ->
        {
            if (manager == null)
                manager = new PermissionOverrideActionImpl(this).setOverride(false);
            return manager;
        });
    }
    return mng.reset();
}
 
Example #7
Source File: AbstractChannelImpl.java    From JDA with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public ChannelManager getManager()
{
    ChannelManager mng = manager;
    if (mng == null)
    {
        mng = MiscUtil.locked(mngLock, () ->
        {
            if (manager == null)
                manager = new ChannelManagerImpl(this);
            return manager;
        });
    }
    return mng;
}
 
Example #8
Source File: WebhookImpl.java    From JDA with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public WebhookManager getManager()
{
    WebhookManager mng = manager;
    if (mng == null)
    {
        mng = MiscUtil.locked(mngLock, () ->
        {
            if (manager == null)
                manager = new WebhookManagerImpl(this);
            return manager;
        });
    }
    return mng;
}
 
Example #9
Source File: UserImpl.java    From JDA with Apache License 2.0 6 votes vote down vote up
@Override
public void formatTo(Formatter formatter, int flags, int width, int precision)
{
    boolean alt = (flags & FormattableFlags.ALTERNATE) == FormattableFlags.ALTERNATE;
    boolean upper = (flags & FormattableFlags.UPPERCASE) == FormattableFlags.UPPERCASE;
    boolean leftJustified = (flags & FormattableFlags.LEFT_JUSTIFY) == FormattableFlags.LEFT_JUSTIFY;

    String out;
    if (!alt)
        out = getAsMention();
    else if (upper)
        out = getAsTag().toUpperCase();
    else
        out = getAsTag();

    MiscUtil.appendTo(formatter, width, precision, leftJustified, out);
}
 
Example #10
Source File: EmoteImpl.java    From JDA with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public EmoteManager getManager()
{
    EmoteManager m = manager;
    if (m == null)
    {
        m = MiscUtil.locked(mngLock, () ->
        {
            if (manager == null)
                manager = new EmoteManagerImpl(this);
            return manager;
        });
    }
    return m;
}
 
Example #11
Source File: BotRateLimiter.java    From JDA with Apache License 2.0 6 votes vote down vote up
@Override
public int cancelRequests()
{
    return MiscUtil.locked(bucketLock, () -> {
        // Empty buckets will be removed by the cleanup worker, which also checks for rate limit parameters
        AtomicInteger count = new AtomicInteger(0);
        buckets.values()
            .stream()
            .map(Bucket::getRequests)
            .flatMap(Collection::stream)
            .filter(request -> !request.isPriority() && !request.isCancelled())
            .forEach(request -> {
                request.cancel();
                count.incrementAndGet();
            });

        int cancelled = count.get();
        if (cancelled == 1)
            RateLimiter.log.warn("Cancelled 1 request!");
        else if (cancelled > 1)
            RateLimiter.log.warn("Cancelled {} requests!", cancelled);
        return cancelled;
    });
}
 
Example #12
Source File: BotRateLimiter.java    From JDA with Apache License 2.0 6 votes vote down vote up
@Contract("_,true->!null")
private Bucket getBucket(Route.CompiledRoute route, boolean create)
{
    return MiscUtil.locked(bucketLock, () ->
    {
        // Retrieve the hash via the route
        String hash = getRouteHash(route.getBaseRoute());
        // Get or create a bucket for the hash + major parameters
        String bucketId = hash + ":" + route.getMajorParameters();
        Bucket bucket = this.buckets.get(bucketId);
        if (bucket == null && create)
            this.buckets.put(bucketId, bucket = new Bucket(bucketId));

        return bucket;
    });
}
 
Example #13
Source File: BotRateLimiter.java    From JDA with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean stop()
{
    return MiscUtil.locked(bucketLock, () -> {
        if (isStopped)
            return false;
        super.stop();
        if (cleanupWorker != null)
            cleanupWorker.cancel(false);
        cleanup();
        int size = buckets.size();
        if (!isShutdown && size > 0) // Tell user about active buckets so they don't get confused by the longer shutdown
        {
            int average = (int) Math.ceil(
                    buckets.values().stream()
                        .map(Bucket::getRequests)
                        .mapToInt(Collection::size)
                        .average().orElse(0)
            );

            log.info("Waiting for {} bucket(s) to finish. Average queue size of {} requests", size, average);
        }
        // No more requests to process?
        return size < 1;
    });
}
 
Example #14
Source File: BotRateLimiter.java    From JDA with Apache License 2.0 5 votes vote down vote up
private void cleanup()
{
    // This will remove buckets that are no longer needed every 30 seconds to avoid memory leakage
    // We will keep the hashes in memory since they are very limited (by the amount of possible routes)
    MiscUtil.locked(bucketLock, () -> {
        int size = buckets.size();
        Iterator<Map.Entry<String, Bucket>> entries = buckets.entrySet().iterator();

        while (entries.hasNext())
        {
            Map.Entry<String, Bucket> entry = entries.next();
            String key = entry.getKey();
            Bucket bucket = entry.getValue();
            // Remove cancelled requests
            bucket.requests.removeIf(Request::isSkipped);

            // Check if the bucket is empty
            if (bucket.isUnlimited() && bucket.requests.isEmpty())
                entries.remove(); // remove unlimited if requests are empty
            // If the requests of the bucket are drained and the reset is expired the bucket has no valuable information
            else if (bucket.requests.isEmpty() && bucket.reset <= getNow())
                entries.remove();
        }
        // Log how many buckets were removed
        size -= buckets.size();
        if (size > 0)
            log.debug("Removed {} expired buckets", size);
    });
}
 
Example #15
Source File: BotRateLimiter.java    From JDA with Apache License 2.0 5 votes vote down vote up
private void backoff()
{
    // Schedule backoff if requests are not done
    MiscUtil.locked(bucketLock, () -> {
        rateLimitQueue.remove(this);
        if (!requests.isEmpty())
            runBucket(this);
        else if (isStopped)
            buckets.remove(bucketId);
        if (isStopped && buckets.isEmpty())
            requester.getJDA().shutdownRequester();
    });
}
 
Example #16
Source File: TextChannelImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public RestAction<Void> deleteMessagesByIds(@Nonnull Collection<String> messageIds)
{
    checkPermission(Permission.MESSAGE_MANAGE, "Must have MESSAGE_MANAGE in order to bulk delete messages in this channel regardless of author.");
    if (messageIds.size() < 2 || messageIds.size() > 100)
        throw new IllegalArgumentException("Must provide at least 2 or at most 100 messages to be deleted.");

    long twoWeeksAgo = TimeUtil.getDiscordTimestamp((System.currentTimeMillis() - (14 * 24 * 60 * 60 * 1000)));
    for (String id : messageIds)
        Checks.check(MiscUtil.parseSnowflake(id) > twoWeeksAgo, "Message Id provided was older than 2 weeks. Id: " + id);

    return deleteMessages0(messageIds);
}
 
Example #17
Source File: ReceivedMessage.java    From JDA with Apache License 2.0 5 votes vote down vote up
private Emote matchEmote(Matcher m)
{
    long emoteId = MiscUtil.parseSnowflake(m.group(2));
    String name = m.group(1);
    boolean animated = m.group(0).startsWith("<a:");
    Emote emote = getJDA().getEmoteById(emoteId);
    if (emote == null)
        emote = new EmoteImpl(emoteId, api).setName(name).setAnimated(animated);
    return emote;
}
 
Example #18
Source File: ReceivedMessage.java    From JDA with Apache License 2.0 5 votes vote down vote up
private Role matchRole(Matcher matcher)
{
    long roleId = MiscUtil.parseSnowflake(matcher.group(1));
    if (!mentionedRoles.contains(roleId))
        return null;
    if (getChannelType().isGuild())
        return getGuild().getRoleById(roleId);
    else
        return getJDA().getRoleById(roleId);
}
 
Example #19
Source File: BotRateLimiter.java    From JDA with Apache License 2.0 5 votes vote down vote up
private void runBucket(Bucket bucket)
{
    if (isShutdown)
        return;
    // Schedule a new bucket worker if no worker is running
    MiscUtil.locked(bucketLock, () ->
        rateLimitQueue.computeIfAbsent(bucket,
            (k) -> getScheduler().schedule(bucket, bucket.getRateLimit(), TimeUnit.MILLISECONDS)));
}
 
Example #20
Source File: ReceivedMessage.java    From JDA with Apache License 2.0 5 votes vote down vote up
private User matchUser(Matcher matcher)
{
    long userId = MiscUtil.parseSnowflake(matcher.group(1));
    if (!mentionedUsers.contains(userId))
        return null;
    User user = getJDA().getUserById(userId);
    if (user == null)
        user = api.getFakeUserMap().get(userId);
    if (user == null && userMentions != null)
        user = userMentions.stream().filter(it -> it.getIdLong() == userId).findFirst().orElse(null);
    return user;
}
 
Example #21
Source File: BotRateLimiter.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Override
protected Long handleResponse(Route.CompiledRoute route, okhttp3.Response response)
{
    return MiscUtil.locked(bucketLock, () -> {
        long rateLimit = updateBucket(route, response).getRateLimit();
        if (response.code() == 429)
            return rateLimit;
        else
            return null;
    });
}
 
Example #22
Source File: IMentionable.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Override
default void formatTo(Formatter formatter, int flags, int width, int precision)
{
    boolean leftJustified = (flags & FormattableFlags.LEFT_JUSTIFY) == FormattableFlags.LEFT_JUSTIFY;
    boolean upper = (flags & FormattableFlags.UPPERCASE) == FormattableFlags.UPPERCASE;
    String out = upper ? getAsMention().toUpperCase(formatter.locale()) : getAsMention();

    MiscUtil.appendTo(formatter, width, precision, leftJustified, out);
}
 
Example #23
Source File: BotRateLimiter.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("rawtypes")
protected void queueRequest(Request request)
{
    // Create bucket and enqueue request
    MiscUtil.locked(bucketLock, () -> {
        Bucket bucket = getBucket(request.getRoute(), true);
        bucket.enqueue(request);
        runBucket(bucket);
    });
}
 
Example #24
Source File: AudioManagerImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
public void closeAudioConnection(ConnectionStatus reason)
{
    MiscUtil.locked(CONNECTION_LOCK, () ->
    {
        if (audioConnection != null)
            this.audioConnection.close(reason);
        else if (reason != ConnectionStatus.DISCONNECTED_REMOVED_FROM_GUILD)
            getJDA().getDirectAudioController().disconnect(getGuild());
        this.audioConnection = null;
    });
}
 
Example #25
Source File: MessageChannel.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Override
default void formatTo(Formatter formatter, int flags, int width, int precision)
{
    boolean leftJustified = (flags & FormattableFlags.LEFT_JUSTIFY) == FormattableFlags.LEFT_JUSTIFY;
    boolean upper = (flags & FormattableFlags.UPPERCASE) == FormattableFlags.UPPERCASE;
    boolean alt = (flags & FormattableFlags.ALTERNATE) == FormattableFlags.ALTERNATE;
    String out;

    out = upper ?  getName().toUpperCase(formatter.locale()) : getName();
    if (alt)
        out = "#" + out;

    MiscUtil.appendTo(formatter, width, precision, leftJustified, out);
}
 
Example #26
Source File: MemberChunkManager.java    From JDA with Apache License 2.0 5 votes vote down vote up
private void init()
{
    MiscUtil.locked(lock, () -> {
        if (timeoutHandle == null)
            timeoutHandle = client.getJDA().getGatewayPool().scheduleAtFixedRate(new TimeoutHandler(), 5, 5, TimeUnit.SECONDS);
    });
}
 
Example #27
Source File: DefaultShardManager.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Override
public Guild getGuildById(long id)
{
    int shardId = MiscUtil.getShardForGuild(id, getShardsTotal());
    JDA shard = this.getShardById(shardId);
    return shard == null ? null : shard.getGuildById(id);
}
 
Example #28
Source File: MemberChunkManager.java    From JDA with Apache License 2.0 5 votes vote down vote up
private void makeRequest(ChunkRequest request)
{
    MiscUtil.locked(lock, () -> {
        requests.put(request.nonce, request);
        sendChunkRequest(request.getRequest());
    });
}
 
Example #29
Source File: MemberChunkManager.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Override
public void run()
{
    MiscUtil.locked(lock, () ->
    {
        requests.forEachValue(request -> {
            if (request.getAge() > MAX_CHUNK_AGE)
                request.completeExceptionally(new TimeoutException());
            return true;
        });
        requests.valueCollection().removeIf(ChunkRequest::isDone);
    });
}
 
Example #30
Source File: TextChannel.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Override
default void formatTo(Formatter formatter, int flags, int width, int precision)
{
    boolean leftJustified = (flags & FormattableFlags.LEFT_JUSTIFY) == FormattableFlags.LEFT_JUSTIFY;
    boolean upper = (flags & FormattableFlags.UPPERCASE) == FormattableFlags.UPPERCASE;
    boolean alt = (flags & FormattableFlags.ALTERNATE) == FormattableFlags.ALTERNATE;
    String out;

    if (alt)
        out = "#" + (upper ? getName().toUpperCase(formatter.locale()) : getName());
    else
        out = getAsMention();

    MiscUtil.appendTo(formatter, width, precision, leftJustified, out);
}