Java Code Examples for net.dv8tion.jda.api.utils.MiscUtil#locked()

The following examples show how to use net.dv8tion.jda.api.utils.MiscUtil#locked() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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 9
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 10
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 11
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 12
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 13
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 14
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 15
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 16
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 17
Source File: MemberChunkManager.java    From JDA with Apache License 2.0 4 votes vote down vote up
public void cancelRequest(ChunkRequest request)
{
    MiscUtil.locked(lock, () -> {
        requests.remove(request.nonce);
    });
}
 
Example 18
Source File: MemberChunkManager.java    From JDA with Apache License 2.0 4 votes vote down vote up
public void clear()
{
    MiscUtil.locked(lock, requests::clear);
}
 
Example 19
Source File: BotRateLimiter.java    From JDA with Apache License 2.0 4 votes vote down vote up
@Override
public void run()
{
    log.trace("Bucket {} is running {} requests", bucketId, requests.size());
    while (!requests.isEmpty())
    {
        Long rateLimit = getRateLimit();
        if (rateLimit > 0L)
        {
            // We need to backoff since we ran out of remaining uses or hit the global rate limit
            log.debug("Backing off {} ms for bucket {}", rateLimit, bucketId);
            break;
        }

        Request request = requests.removeFirst();
        if (request.isSkipped())
            continue;
        if (isUnlimited())
        {
            boolean shouldSkip = MiscUtil.locked(bucketLock, () -> {
                // Attempt moving request to correct bucket if it has been created
                Bucket bucket = getBucket(request.getRoute(), true);
                if (bucket != this)
                {
                    bucket.enqueue(request);
                    runBucket(bucket);
                    return true;
                }
                return false;
            });
            if (shouldSkip) continue;
        }

        try
        {
            rateLimit = requester.execute(request);
            if (rateLimit != null)
                retry(request); // this means we hit a hard rate limit (429) so the request needs to be retried
        }
        catch (Throwable ex)
        {
            log.error("Encountered exception trying to execute request", ex);
            if (ex instanceof Error)
                throw (Error) ex;
            break;
        }
    }

    backoff();
}
 
Example 20
Source File: VoiceServerUpdateHandler.java    From JDA with Apache License 2.0 4 votes vote down vote up
@Override
protected Long handleInternally(DataObject content)
{
    final long guildId = content.getLong("guild_id");
    if (getJDA().getGuildSetupController().isLocked(guildId))
        return guildId;
    Guild guild = getJDA().getGuildById(guildId);
    if (guild == null)
        throw new IllegalArgumentException("Attempted to start audio connection with Guild that doesn't exist!");

    getJDA().getDirectAudioController().update(guild, guild.getSelfMember().getVoiceState().getChannel());

    if (content.isNull("endpoint"))
    {
        //Discord did not provide an endpoint yet, we are to wait until discord has resources to provide
        // an endpoint, which will result in them sending another VOICE_SERVER_UPDATE which we will handle
        // to actually connect to the audio server.
        return null;
    }

    //Strip the port from the endpoint.
    String endpoint = content.getString("endpoint").replace(":80", "");
    String token = content.getString("token");
    String sessionId = guild.getSelfMember().getVoiceState().getSessionId();
    if (sessionId == null)
        throw new IllegalArgumentException("Attempted to create audio connection without having a session ID. Did VOICE_STATE_UPDATED fail?");

    VoiceDispatchInterceptor voiceInterceptor = getJDA().getVoiceInterceptor();
    if (voiceInterceptor != null)
    {
        voiceInterceptor.onVoiceServerUpdate(new VoiceDispatchInterceptor.VoiceServerUpdate(guild, endpoint, token, sessionId, allContent));
        return null;
    }

    AudioManagerImpl audioManager = (AudioManagerImpl) getJDA().getAudioManagersView().get(guildId);
    if (audioManager == null)
    {
        WebSocketClient.LOG.debug(
            "Received a VOICE_SERVER_UPDATE but JDA is not currently connected nor attempted to connect " +
            "to a VoiceChannel. Assuming that this is caused by another client running on this account. " +
            "Ignoring the event.");
        return null;
    }

    MiscUtil.locked(audioManager.CONNECTION_LOCK, () ->
    {
        //Synchronized to prevent attempts to close while setting up initial objects.
        VoiceChannel target = guild.getSelfMember().getVoiceState().getChannel();
        if (target == null)
        {
            WebSocketClient.LOG.warn("Ignoring VOICE_SERVER_UPDATE for unknown channel");
            return;
        }

        AudioConnection connection = new AudioConnection(audioManager, endpoint, sessionId, token, target);
        audioManager.setAudioConnection(connection);
        connection.startConnection();
    });
    return null;
}