gnu.trove.map.TLongObjectMap Java Examples

The following examples show how to use gnu.trove.map.TLongObjectMap. 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: FallingBlocksMatchModule.java    From PGM with GNU Affero General Public License v3.0 6 votes vote down vote up
private void disturb(long pos, BlockState blockState, @Nullable ParticipantState disturber) {
  FallingBlocksRule rule = this.ruleWithShortestDelay(blockState);
  if (rule != null) {
    long tick = match.getTick().tick + rule.delay;
    TLongObjectMap<ParticipantState> blockDisturbers = this.blockDisturbersByTick.get(tick);

    if (blockDisturbers == null) {
      blockDisturbers = new TLongObjectHashMap<>();
      this.blockDisturbersByTick.put(tick, blockDisturbers);
    }

    Block block = blockState.getBlock();
    if (!blockDisturbers.containsKey(pos)) {
      blockDisturbers.put(pos, disturber);
    }
  }
}
 
Example #2
Source File: MemberChunkManager.java    From JDA with Apache License 2.0 6 votes vote down vote up
private List<Member> toMembers(DataObject chunk)
{
    EntityBuilder builder = guild.getJDA().getEntityBuilder();
    DataArray memberArray = chunk.getArray("members");
    TLongObjectMap<DataObject> presences = chunk.optArray("presences").map(it ->
        builder.convertToUserMap(o -> o.getObject("user").getUnsignedLong("id"), it)
    ).orElseGet(TLongObjectHashMap::new);
    List<Member> collect = new ArrayList<>(memberArray.length());
    for (int i = 0; i < memberArray.length(); i++)
    {
        DataObject json = memberArray.getObject(i);
        long userId = json.getObject("user").getUnsignedLong("id");
        DataObject presence = presences.get(userId);
        MemberImpl member = builder.createMember(guild, json, null, presence);
        builder.updateMemberCache(member);
        collect.add(member);
    }
    return collect;
}
 
Example #3
Source File: WebSocketClient.java    From JDA with Apache License 2.0 6 votes vote down vote up
protected void updateAudioManagerReferences()
{
    AbstractCacheView<AudioManager> managerView = api.getAudioManagersView();
    try (UnlockHook hook = managerView.writeLock())
    {
        final TLongObjectMap<AudioManager> managerMap = managerView.getMap();
        if (managerMap.size() > 0)
            LOG.trace("Updating AudioManager references");

        for (TLongObjectIterator<AudioManager> it = managerMap.iterator(); it.hasNext(); )
        {
            it.advance();
            final long guildId = it.key();
            final AudioManagerImpl mng = (AudioManagerImpl) it.value();

            GuildImpl guild = (GuildImpl) api.getGuildById(guildId);
            if (guild == null)
            {
                //We no longer have access to the guild that this audio manager was for. Set the value to null.
                queuedAudioConnections.remove(guildId);
                mng.closeAudioConnection(ConnectionStatus.DISCONNECTED_REMOVED_DURING_RECONNECT);
                it.remove();
            }
        }
    }
}
 
Example #4
Source File: EntityBuilder.java    From JDA with Apache License 2.0 6 votes vote down vote up
private void createGuildEmotePass(GuildImpl guildObj, DataArray array)
{
    if (!getJDA().isCacheFlagSet(CacheFlag.EMOTE))
        return;
    SnowflakeCacheViewImpl<Emote> emoteView = guildObj.getEmotesView();
    try (UnlockHook hook = emoteView.writeLock())
    {
        TLongObjectMap<Emote> emoteMap = emoteView.getMap();
        for (int i = 0; i < array.length(); i++)
        {
            DataObject object = array.getObject(i);
            if (object.isNull("id"))
            {
                LOG.error("Received GUILD_CREATE with an emoji with a null ID. JSON: {}", object);
                continue;
            }
            final long emoteId = object.getLong("id");
            emoteMap.put(emoteId, createEmote(guildObj, object, false));
        }
    }
}
 
Example #5
Source File: FallingBlocksMatchModule.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Make any unsupported blocks fall that are disturbed for the current tick
 */
private void fallCheck() {
    this.visitsWorstTick = Math.max(this.visitsWorstTick, this.visitsThisTick);
    this.visitsThisTick = 0;

    World world = this.getMatch().getWorld();
    TLongObjectMap<ParticipantState> blockDisturbers = this.blockDisturbersByTick.remove(this.getMatch().getClock().now().tick);
    if(blockDisturbers == null) return;

    TLongSet supported = new TLongHashSet();
    TLongSet unsupported = new TLongHashSet();
    TLongObjectMap<ParticipantState> fallsByBreaker = new TLongObjectHashMap<>();

    try {
        while(!blockDisturbers.isEmpty()) {
            long pos = blockDisturbers.keySet().iterator().next();
            ParticipantState breaker = blockDisturbers.remove(pos);

            // Search down for the first block that can actually fall
            for(;;) {
                long below = neighborPos(pos, BlockFace.DOWN);
                if(!Materials.isColliding(blockAt(world, below).getType())) break;
                blockDisturbers.remove(pos); // Remove all the blocks we find along the way
                pos = below;
            }

            // Check if the block needs to fall, if it isn't already falling
            if(!fallsByBreaker.containsKey(pos) && !this.isSupported(pos, supported, unsupported)) {
                fallsByBreaker.put(pos, breaker);
            }
        }
    } catch(MaxSearchVisitsExceeded ex) {
        this.logError(ex);
    }

    for(TLongObjectIterator<ParticipantState> iter = fallsByBreaker.iterator(); iter.hasNext();) {
        iter.advance();
        this.fall(iter.key(), iter.value());
    }
}
 
Example #6
Source File: FallingBlocksMatchModule.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
private void disturb(long pos, BlockState blockState, @Nullable ParticipantState disturber) {
    FallingBlocksRule rule = this.ruleWithShortestDelay(blockState);
    if(rule != null) {
        long tick = this.getMatch().getClock().now().tick + rule.delay;
        TLongObjectMap<ParticipantState> blockDisturbers = this.blockDisturbersByTick.get(tick);

        if(blockDisturbers == null) {
            blockDisturbers = new TLongObjectHashMap<>();
            this.blockDisturbersByTick.put(tick, blockDisturbers);
        }

        Block block = blockState.getBlock();
        if(!blockDisturbers.containsKey(pos)) {
            blockDisturbers.put(pos, disturber);
        }
    }
}
 
Example #7
Source File: GuildSettingsUtils.java    From SkyBot with GNU Affero General Public License v3.0 6 votes vote down vote up
private static void loadVcAutoRoles(DatabaseAdapter adapter, TLongObjectMap<TLongLongMap> vcAutoRoleCache) {
    logger.info("Loading vc auto roles.");

    adapter.getVcAutoRoles((items) -> {

        items.forEach(
            (item) -> {
                final TLongLongMap cache = Optional.ofNullable(
                    vcAutoRoleCache.get(item.getGuildId())
                )
                    .orElseGet(
                        () -> {
                            vcAutoRoleCache.put(item.getGuildId(), new TLongLongHashMap()); // This returns the old value which was null
                            return vcAutoRoleCache.get(item.getGuildId());
                        }
                    );

                cache.put(item.getVoiceChannelId(), item.getRoleId());
            }
        );

        logger.info("Loaded " + items.size() + " vc auto roles.");

        return null;
    });
}
 
Example #8
Source File: GuildListener.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
private void handleVcAutoRole(Guild guild, Member member, VoiceChannel channel, boolean remove) {
    final Member self = guild.getSelfMember();
    final long guildId = guild.getIdLong();

    final TLongObjectMap<TLongLongMap> vcAutoRoleCache = variables.getVcAutoRoleCache();

    if (!vcAutoRoleCache.containsKey(guildId)) {
        return;
    }

    final TLongLongMap vcToRolePair = vcAutoRoleCache.get(guildId);

    if (vcToRolePair.get(channel.getIdLong()) > 0) {
        final Role role = guild.getRoleById(vcToRolePair.get(channel.getIdLong()));

        if (role != null && self.canInteract(member) && self.canInteract(role) && self.hasPermission(Permission.MANAGE_ROLES)) {
            if (remove) {
                guild
                    .removeRoleFromMember(member, role)
                    .reason("VC auto role removed")
                    .queue();
            } else {
                guild
                    .addRoleToMember(member, role)
                    .reason("VC auto role applied")
                    .queue();
            }
        }
    }
}
 
Example #9
Source File: VoiceChannelImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
public TLongObjectMap<Member> getConnectedMembersMap()
{
    connectedMembers.transformValues((member) -> {
        // Load real member instance from cache to provided up-to-date cache information
        Member real = getGuild().getMemberById(member.getIdLong());
        return real != null ? real : member;
    });
    return connectedMembers;
}
 
Example #10
Source File: EntityBuilder.java    From JDA with Apache License 2.0 5 votes vote down vote up
public TLongObjectMap<DataObject> convertToUserMap(ToLongFunction<DataObject> getId, DataArray array)
{
    TLongObjectMap<DataObject> map = new TLongObjectHashMap<>();
    for (int i = 0; i < array.length(); i++)
    {
        DataObject obj = array.getObject(i);
        long userId = getId.applyAsLong(obj);
        map.put(userId, obj);
    }
    return map;
}
 
Example #11
Source File: EventCache.java    From JDA with Apache License 2.0 5 votes vote down vote up
public synchronized void clear(Type type, long id)
{
    TLongObjectMap<List<CacheNode>> typeCache = this.eventCache.get(type);
    if (typeCache == null)
        return;

    List<CacheNode> events = typeCache.remove(id);
    if (events != null)
        LOG.debug("Clearing cache for type {} with ID {} (Size: {})", type, id, events.size());
}
 
Example #12
Source File: EventCache.java    From JDA with Apache License 2.0 5 votes vote down vote up
public synchronized void playbackCache(Type type, long triggerId)
{
    TLongObjectMap<List<CacheNode>> typeCache = this.eventCache.get(type);
    if (typeCache == null)
        return;

    List<CacheNode> items = typeCache.remove(triggerId);
    if (items != null && !items.isEmpty())
    {
        EventCache.LOG.debug("Replaying {} events from the EventCache for type {} with id: {}",
            items.size(), type, triggerId);
        for (CacheNode item : items)
            item.execute();
    }
}
 
Example #13
Source File: EventCache.java    From JDA with Apache License 2.0 5 votes vote down vote up
public synchronized void cache(Type type, long triggerId, long responseTotal, DataObject event, CacheConsumer handler)
{
    TLongObjectMap<List<CacheNode>> triggerCache =
            eventCache.computeIfAbsent(type, k -> new TLongObjectHashMap<>());

    List<CacheNode> items = triggerCache.get(triggerId);
    if (items == null)
    {
        items = new LinkedList<>();
        triggerCache.put(triggerId, items);
    }

    items.add(new CacheNode(responseTotal, event, handler));
}
 
Example #14
Source File: GuildMembersChunkHandler.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Override
protected Long handleInternally(DataObject content)
{
    final long guildId = content.getLong("guild_id");
    DataArray members = content.getArray("members");
    GuildImpl guild = (GuildImpl) getJDA().getGuildById(guildId);
    if (guild != null)
    {
        if (api.getClient().getChunkManager().handleChunk(guildId, content))
            return null;
        WebSocketClient.LOG.debug("Received member chunk for guild that is already in cache. GuildId: {} Count: {} Index: {}/{}",
                guildId, members.length(), content.getInt("chunk_index"), content.getInt("chunk_count"));
        // Chunk handling
        EntityBuilder builder = getJDA().getEntityBuilder();
        TLongObjectMap<DataObject> presences = content.optArray("presences").map(it ->
            builder.convertToUserMap(o -> o.getObject("user").getUnsignedLong("id"), it)
        ).orElseGet(TLongObjectHashMap::new);
        for (int i = 0; i < members.length(); i++)
        {
            DataObject object = members.getObject(i);
            long userId = object.getObject("user").getUnsignedLong("id");
            DataObject presence = presences.get(userId);
            MemberImpl member = builder.createMember(guild, object, null, presence);
            builder.updateMemberCache(member);
        }
        return null;
    }
    getJDA().getGuildSetupController().onMemberChunk(guildId, content);
    return null;
}
 
Example #15
Source File: ReadyHandler.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Override
protected Long handleInternally(DataObject content)
{
    EntityBuilder builder = getJDA().getEntityBuilder();

    DataArray guilds = content.getArray("guilds");
    //Make sure we don't have any duplicates here!
    TLongObjectMap<DataObject> distinctGuilds = new TLongObjectHashMap<>();
    for (int i = 0; i < guilds.length(); i++)
    {
        DataObject guild = guilds.getObject(i);
        long id = guild.getUnsignedLong("id");
        DataObject previous = distinctGuilds.put(id, guild);
        if (previous != null)
            WebSocketClient.LOG.warn("Found duplicate guild for id {} in ready payload", id);
    }

    DataObject selfJson = content.getObject("user");

    builder.createSelfUser(selfJson);
    if (getJDA().getGuildSetupController().setIncompleteCount(distinctGuilds.size()))
    {
        distinctGuilds.forEachEntry((id, guild) ->
        {
            getJDA().getGuildSetupController().onReady(id, guild);
            return true;
        });
    }

    handleReady(content);
    return null;
}
 
Example #16
Source File: AirUtils.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
private static void stopMusic(AudioUtils audioUtils, ShardManager manager) {
    final TLongObjectMap<GuildMusicManager> temp = new TLongObjectHashMap<>(audioUtils.getMusicManagers());

    for (final long key : temp.keys()) {
        final Guild guild = manager.getGuildById(key);

        if (guild != null) {
            stopMusic(guild, audioUtils);
        }
    }
}
 
Example #17
Source File: CommitCanvasN5Test.java    From paintera with GNU General Public License v2.0 5 votes vote down vote up
private static void writeAll(
		final N5Writer container,
		final String dataset,
		final CachedCellImg<UnsignedLongType, ?> canvas) throws IOException, UnableToPersistCanvas, UnableToUpdateLabelBlockLookup {
	final long numBlocks = Intervals.numElements(canvas.getCellGrid().getGridDimensions());
	final long[] blocks = new long[(int) numBlocks];
	Arrays.setAll(blocks, d -> d);

	final CommitCanvasN5 cc = new CommitCanvasN5(container, dataset);
	final List<TLongObjectMap<PersistCanvas.BlockDiff>> blockDiffs = cc.persistCanvas(canvas, blocks);
	if (cc.supportsLabelBlockLookupUpdate())
		cc.updateLabelBlockLookup(blockDiffs);
}
 
Example #18
Source File: LatestExchangeRates.java    From financisto with GNU General Public License v2.0 5 votes vote down vote up
@Override
public ExchangeRate getRate(Currency fromCurrency, Currency toCurrency) {
    if (fromCurrency.id == toCurrency.id) {
        return ExchangeRate.ONE;
    }
    TLongObjectMap<ExchangeRate> rateMap = getMapFor(fromCurrency.id);
    ExchangeRate rate = rateMap.get(toCurrency.id);
    if (rate == null) {
        rate = ExchangeRate.NA;
        rateMap.put(toCurrency.id, rate);
    }
    return rate;
}
 
Example #19
Source File: HistoryExchangeRates.java    From financisto with GNU General Public License v2.0 5 votes vote down vote up
private SortedSet<ExchangeRate> getSetFor(TLongObjectMap<SortedSet<ExchangeRate>> rates, long date) {
    SortedSet<ExchangeRate> s = rates.get(date);
    if (s == null) {
        s = new TreeSet<ExchangeRate>();
        rates.put(date, s);
    }
    return s;
}
 
Example #20
Source File: HistoryExchangeRates.java    From financisto with GNU General Public License v2.0 5 votes vote down vote up
private TLongObjectMap<SortedSet<ExchangeRate>> getMapFor(long fromCurrencyId) {
    TLongObjectMap<SortedSet<ExchangeRate>> m = rates.get(fromCurrencyId);
    if (m == null) {
        m = new TLongObjectHashMap<SortedSet<ExchangeRate>>();
        rates.put(fromCurrencyId, m);
    }
    return m;
}
 
Example #21
Source File: ShapeInterpolationMode.java    From paintera with GNU General Public License v2.0 5 votes vote down vote up
SectionInfo(
		final Mask<UnsignedLongType> mask,
		final AffineTransform3D globalTransform,
		final AffineTransform3D sourceToDisplayTransform,
		final Interval sourceBoundingBox,
		final TLongObjectMap<SelectedObjectInfo> selectedObjects)
{
	this.mask = mask;
	this.globalTransform = globalTransform;
	this.sourceToDisplayTransform = sourceToDisplayTransform;
	this.sourceBoundingBox = sourceBoundingBox;
	this.selectedObjects = selectedObjects;
}
 
Example #22
Source File: CommitCanvasN5.java    From paintera with GNU General Public License v2.0 5 votes vote down vote up
private static <T> T computeIfAbsent(final TLongObjectMap<T> map, final long key, final Supplier<T> fallback)
{
	T t = map.get(key);
	if (t == null)
	{
		t = fallback.get();
		map.put(key, t);
	}
	return t;
}
 
Example #23
Source File: LatestExchangeRates.java    From financisto with GNU General Public License v2.0 5 votes vote down vote up
private TLongObjectMap<ExchangeRate> getMapFor(long fromCurrencyId) {
    TLongObjectMap<ExchangeRate> m = rates.get(fromCurrencyId);
    if (m == null) {
        m = new TLongObjectHashMap<ExchangeRate>();
        rates.put(fromCurrencyId, m);
    }
    return m;
}
 
Example #24
Source File: PersistCanvas.java    From paintera with GNU General Public License v2.0 4 votes vote down vote up
default void updateLabelBlockLookup(final List<TLongObjectMap<BlockDiff>> blockDiffs) throws UnableToUpdateLabelBlockLookup
{
	throw new LabelBlockLookupUpdateNotSupported("");
}
 
Example #25
Source File: ChannelUpdateHandler.java    From JDA with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
private void applyPermissions(AbstractChannelImpl<?,?> channel, DataArray permOverwrites)
{
    TLongObjectMap<PermissionOverride> currentOverrides = new TLongObjectHashMap<>(channel.getOverrideMap());
    List<IPermissionHolder> changed = new ArrayList<>(currentOverrides.size());
    Guild guild = channel.getGuild();
    for (int i = 0; i < permOverwrites.length(); i++)
    {
        DataObject overrideJson = permOverwrites.getObject(i);
        long id = overrideJson.getUnsignedLong("id", 0);
        if (handlePermissionOverride(currentOverrides.remove(id), overrideJson, id, channel))
            addPermissionHolder(changed, guild, id);
    }

    currentOverrides.forEachValue(override -> {
        channel.getOverrideMap().remove(override.getIdLong());
        addPermissionHolder(changed, guild, override.getIdLong());
        api.handleEvent(
            new PermissionOverrideDeleteEvent(
                api, responseNumber,
                channel, override));
        return true;
    });

    if (changed.isEmpty())
        return;
    switch (channel.getType())
    {
    case CATEGORY:
        api.handleEvent(
            new CategoryUpdatePermissionsEvent(
                api, responseNumber,
                (Category) channel, changed));
        break;
    case STORE:
        api.handleEvent(
            new StoreChannelUpdatePermissionsEvent(
                api, responseNumber,
                (StoreChannel) channel, changed));
        break;
    case VOICE:
        api.handleEvent(
            new VoiceChannelUpdatePermissionsEvent(
                api, responseNumber,
                (VoiceChannel) channel, changed));
        break;
    case TEXT:
        api.handleEvent(
            new TextChannelUpdatePermissionsEvent(
                api, responseNumber,
                (TextChannel) channel, changed));
        break;
    }
}
 
Example #26
Source File: JDAImpl.java    From JDA with Apache License 2.0 4 votes vote down vote up
public TLongObjectMap<User> getFakeUserMap()
{
    return fakeUsers;
}
 
Example #27
Source File: JDAImpl.java    From JDA with Apache License 2.0 4 votes vote down vote up
public TLongObjectMap<PrivateChannel> getFakePrivateChannelMap()
{
    return fakePrivateChannels;
}
 
Example #28
Source File: AbstractCacheView.java    From JDA with Apache License 2.0 4 votes vote down vote up
public TLongObjectMap<T> getMap()
{
    if (!lock.writeLock().isHeldByCurrentThread())
        throw new IllegalStateException("Cannot access map directly without holding write lock!");
    return elements;
}
 
Example #29
Source File: AbstractChannelImpl.java    From JDA with Apache License 2.0 4 votes vote down vote up
public TLongObjectMap<PermissionOverride> getOverrideMap()
{
    return overrides;
}
 
Example #30
Source File: LatestExchangeRates.java    From financisto with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void addRate(ExchangeRate r) {
    TLongObjectMap<ExchangeRate> rateMap = getMapFor(r.fromCurrencyId);
    rateMap.put(r.toCurrencyId, r);
}