Example usage for java.lang Long parseUnsignedLong

List of usage examples for java.lang Long parseUnsignedLong

Introduction

In this page you can find the example usage for java.lang Long parseUnsignedLong.

Prototype

public static long parseUnsignedLong(String s) throws NumberFormatException 

Source Link

Document

Parses the string argument as an unsigned decimal long .

Usage

From source file:sx.blah.discord.api.internal.DiscordUtils.java

/**
 * Converts a json {@link EmojiObject} to a {@link IEmoji}.
 *
 * @param guild The guild the emoji belongs to.
 * @param json The json object representing the emoji.
 * @return The converted emoji object.//from   w  w w  .jav  a  2  s.  com
 */
public static IEmoji getEmojiFromJSON(IGuild guild, EmojiObject json) {
    long id = Long.parseUnsignedLong(json.id);
    List<IRole> roles = Arrays.stream(json.roles).map(role -> guild.getRoleByID(Long.parseUnsignedLong(role)))
            .collect(Collectors.toList());

    EmojiImpl emoji = (EmojiImpl) guild.getEmojiByID(id);
    if (emoji != null) {
        emoji.setName(json.name);
        emoji.setRoles(roles);
        return emoji;
    }

    Cache<IRole> roleCache = new Cache<>((DiscordClientImpl) guild.getClient(), IRole.class);
    roleCache.putAll(roles);
    return new EmojiImpl(id, guild, json.name, roleCache, json.require_colons, json.managed, json.animated);
}

From source file:sx.blah.discord.api.internal.DiscordUtils.java

/**
 * Converts an array of json {@link MessageObject.ReactionObject}s to a list of {@link IReaction}s.
 *
 * @param message The message the reactions belong to.
 * @param json The json objects representing the reactions.
 * @return The converted reaction objects.
 */// w w w. j  av a2s  . co m
public static List<IReaction> getReactionsFromJSON(IMessage message, MessageObject.ReactionObject[] json) {
    List<IReaction> reactions = new CopyOnWriteArrayList<>();
    if (json != null)
        for (MessageObject.ReactionObject object : json) {
            long id = object.emoji.id == null ? 0 : Long.parseUnsignedLong(object.emoji.id);
            ReactionEmoji emoji = ReactionEmoji.of(object.emoji.name, id, object.emoji.animated);
            reactions.add(new Reaction(message, object.count, emoji));
        }

    return reactions;
}

From source file:sx.blah.discord.api.internal.DiscordUtils.java

/**
 * Converts a json {@link AuditLogObject} to a {@link AuditLog}.
 *
 * @param guild The guild the audit log belongs to.
 * @param json The json object representing the audit log.
 * @return The converted audit log object.
 *///from w  w w.  ja  v a  2s  . c  om
public static AuditLog getAuditLogFromJSON(IGuild guild, AuditLogObject json) {
    LongMap<IUser> users = Arrays.stream(json.users).map(u -> DiscordUtils.getUserFromJSON(guild.getShard(), u))
            .collect(LongMapCollector.toLongMap());

    LongMap<IWebhook> webhooks = Arrays.stream(json.webhooks).map(
            w -> DiscordUtils.getWebhookFromJSON(guild.getChannelByID(Long.parseUnsignedLong(w.channel_id)), w))
            .collect(LongMapCollector.toLongMap());

    LongMap<AuditLogEntry> entries = Arrays.stream(json.audit_log_entries)
            .map(e -> DiscordUtils.getAuditLogEntryFromJSON(guild, users, webhooks, e))
            .collect(LongMapCollector.toLongMap());

    return new AuditLog(entries);
}

From source file:sx.blah.discord.api.internal.DiscordUtils.java

/**
 * Converts a json {@link AuditLogEntry} to a {@link AuditLogEntry}.
 *
 * @param guild The guild the entry belongs to.
 * @param users The users of the parent audit log.
 * @param webhooks The webhooks of the parent audit log.
 * @param json The converted audit log entry object.
 * @return The converted audit log entry.
 */// www.  j  a  v  a 2 s . c o  m
public static AuditLogEntry getAuditLogEntryFromJSON(IGuild guild, LongMap<IUser> users,
        LongMap<IWebhook> webhooks, AuditLogEntryObject json) {
    long targetID = json.target_id == null ? 0 : Long.parseUnsignedLong(json.target_id);
    long id = Long.parseUnsignedLong(json.id);
    IUser user = users.get(Long.parseUnsignedLong(json.user_id));

    ChangeMap changes = json.changes == null ? new ChangeMap()
            : Arrays.stream(json.changes).collect(ChangeMap.Collector.toChangeMap());

    OptionMap options = new OptionMap(json.options);

    ActionType actionType = ActionType.fromRaw(json.action_type);
    switch (actionType) {
    case GUILD_UPDATE:
        return new DiscordObjectEntry<>(guild, id, user, changes, json.reason, actionType, options);
    case CHANNEL_CREATE:
    case CHANNEL_UPDATE:
    case CHANNEL_OVERWRITE_CREATE:
    case CHANNEL_OVERWRITE_UPDATE:
    case CHANNEL_OVERWRITE_DELETE:
        IChannel channel = guild.getChannelByID(targetID);
        if (channel == null)
            channel = guild.getVoiceChannelByID(targetID);

        if (channel == null) {
            return new TargetedEntry(id, user, changes, json.reason, actionType, options, targetID);
        }
        return new DiscordObjectEntry<>(channel, id, user, changes, json.reason, actionType, options);
    case MEMBER_KICK:
    case MEMBER_BAN_ADD:
    case MEMBER_BAN_REMOVE:
    case MEMBER_UPDATE:
    case MEMBER_ROLE_UPDATE:
    case MESSAGE_DELETE: // message delete target is the author of the message
        IUser target = users.get(targetID);

        if (target == null) {
            return new TargetedEntry(id, user, changes, json.reason, actionType, options, targetID);
        }
        return new DiscordObjectEntry<>(target, id, user, changes, json.reason, actionType, options);
    case ROLE_CREATE:
    case ROLE_UPDATE:
        IRole role = guild.getRoleByID(targetID);

        if (role == null) {
            return new TargetedEntry(id, user, changes, json.reason, actionType, options, targetID);
        }
        return new DiscordObjectEntry<>(role, id, user, changes, json.reason, actionType, options);
    case WEBHOOK_CREATE:
    case WEBHOOK_UPDATE:
        IWebhook webhook = webhooks.get(targetID);

        if (webhook == null) {
            return new TargetedEntry(id, user, changes, json.reason, actionType, options, targetID);
        }
        return new DiscordObjectEntry<>(webhook, id, user, changes, json.reason, actionType, options);
    case EMOJI_CREATE:
    case EMOJI_UPDATE:
        IEmoji emoji = guild.getEmojiByID(targetID);

        if (emoji == null) {
            return new TargetedEntry(id, user, changes, json.reason, actionType, options, targetID);
        }
        return new DiscordObjectEntry<>(emoji, id, user, changes, json.reason, actionType, options);
    case CHANNEL_DELETE:
    case ROLE_DELETE:
    case WEBHOOK_DELETE:
    case EMOJI_DELETE:
        return new TargetedEntry(id, user, changes, json.reason, actionType, options, targetID);
    case INVITE_CREATE:
    case INVITE_DELETE:
    case INVITE_UPDATE:
    case MEMBER_PRUNE:
        return new AuditLogEntry(id, user, changes, json.reason, actionType, options);
    }

    return null;
}

From source file:sx.blah.discord.api.internal.DiscordUtils.java

public static ICategory getCategoryFromJSON(IShard shard, IGuild guild, ChannelObject json) {
    Pair<Cache<PermissionOverride>, Cache<PermissionOverride>> permissionOverwrites = getPermissionOverwritesFromJSONs(
            (DiscordClientImpl) shard.getClient(), json.permission_overwrites);

    Category category = (Category) shard.getCategoryByID(Long.parseUnsignedLong(json.id));
    if (category != null) {
        category.setName(json.name);// w w w .j a  v a  2s .com
        category.setPosition(json.position);
        category.setNSFW(json.nsfw);
        category.userOverrides.clear();
        category.roleOverrides.clear();
        category.userOverrides.putAll(permissionOverwrites.getLeft());
        category.roleOverrides.putAll(permissionOverwrites.getRight());

    } else {
        category = new Category(shard, json.name, Long.parseUnsignedLong(json.id), guild, json.position,
                json.nsfw, permissionOverwrites.getLeft(), permissionOverwrites.getRight());
    }

    return category;
}

From source file:sx.blah.discord.api.internal.DispatchHandler.java

private void ready(ReadyResponse ready) {
    Discord4J.LOGGER.info(LogMarkers.WEBSOCKET, "Connected to Discord Gateway v{}. Receiving {} guilds.",
            ready.v, ready.guilds.length);

    ws.state = DiscordWS.State.READY;
    ws.hasReceivedReady = true; // Websocket received actual ready event
    if (client.ourUser == null)
        client.ourUser = DiscordUtils.getUserFromJSON(shard, ready.user);
    client.getDispatcher().dispatch(new LoginEvent(shard));

    new RequestBuilder(client).setAsync(true).doAction(() -> {
        ws.sessionId = ready.session_id;

        Set<UnavailableGuildObject> waitingGuilds = ConcurrentHashMap.newKeySet(ready.guilds.length);
        waitingGuilds.addAll(Arrays.asList(ready.guilds));

        final AtomicInteger loadedGuilds = new AtomicInteger(0);
        client.getDispatcher().waitFor((GuildCreateEvent e) -> {
            waitingGuilds.removeIf(g -> g.id.equals(e.getGuild().getStringID()));
            return loadedGuilds.incrementAndGet() >= ready.guilds.length;
        }, (long) Math.ceil(Math.sqrt(2 * ready.guilds.length)), TimeUnit.SECONDS);

        waitingGuilds.forEach(guild -> client.getDispatcher()
                .dispatch(new GuildUnavailableEvent(Long.parseUnsignedLong(guild.id))));
        return true;
    }).andThen(() -> {//from  www.  j  a v a2s.  c om
        if (this.shard.getInfo()[0] == 0) { // pms are only sent to shard 0
            for (ChannelObject pmObj : ready.private_channels) {
                IPrivateChannel pm = (IPrivateChannel) DiscordUtils.getChannelFromJSON(shard, null, pmObj);
                shard.privateChannels.put(pm);
            }
        }

        ws.isReady = true;
        client.getDispatcher().dispatch(new ShardReadyEvent(shard)); // All information for this shard has been received
        return true;
    }).execute();
}

From source file:sx.blah.discord.api.internal.DispatchHandler.java

private void messageCreate(MessageObject json) {
    boolean mentioned = json.mention_everyone;

    Channel channel = (Channel) client.getChannelByID(Long.parseUnsignedLong(json.channel_id));

    if (null != channel) {

        // check if our user is mentioned directly
        if (!mentioned) { //Not worth checking if already mentioned
            for (UserObject user : json.mentions) { //Check mention array for a mention
                if (client.getOurUser().getLongID() == Long.parseUnsignedLong(user.id)) {
                    mentioned = true;/*from  ww w  .java 2s.  c  om*/
                    break;
                }
            }
        }

        // check if our user is mentioned through role mentions
        if (!mentioned) { //Not worth checking if already mentioned
            for (String role : json.mention_roles) { //Check roles for a mention
                if (client.getOurUser().getRolesForGuild(channel.getGuild())
                        .contains(channel.getGuild().getRoleByID(Long.parseUnsignedLong(role)))) {
                    mentioned = true;
                    break;
                }
            }
        }

        IMessage message = DiscordUtils.getMessageFromJSON(channel, json);

        if (!channel.getMessageHistory().contains(message)) {
            Discord4J.LOGGER.debug(LogMarkers.MESSAGES, "Message from: {} ({}) in channel ID {}: {}",
                    message.getAuthor().getName(), json.author.id, json.channel_id, json.content);

            if (mentioned) {
                client.dispatcher.dispatch(new MentionEvent(message));
            }

            channel.addToCache(message);

            if (message.getAuthor().equals(client.getOurUser())) {
                client.dispatcher.dispatch(new MessageSendEvent(message));
                message.getChannel().setTypingStatus(false); //Messages being sent should stop the bot from typing
            } else {
                client.dispatcher.dispatch(new MessageReceivedEvent(message));
                if (!message.getEmbeds().isEmpty()) {
                    client.dispatcher.dispatch(new MessageEmbedEvent(null, message, new ArrayList<>()));
                }
            }
        }
    }
}

From source file:sx.blah.discord.api.internal.DispatchHandler.java

private void guildMemberAdd(GuildMemberAddEventResponse event) {
    long guildID = Long.parseUnsignedLong(event.guild_id);
    Guild guild = (Guild) client.getGuildByID(guildID);
    if (guild != null) {
        User user = (User) DiscordUtils.getUserFromGuildMemberResponse(guild,
                new MemberObject(event.user, event.roles));
        guild.users.put(user);//from  w  w w. j  a  v  a2s .  c o  m
        guild.setTotalMemberCount(guild.getTotalMemberCount() + 1);
        Instant timestamp = DiscordUtils.convertFromTimestamp(event.joined_at);
        Discord4J.LOGGER.debug(LogMarkers.EVENTS, "User \"{}\" joined guild \"{}\".", user.getName(),
                guild.getName());
        client.dispatcher.dispatch(new UserJoinEvent(guild, user, timestamp));
    }
}

From source file:sx.blah.discord.api.internal.DispatchHandler.java

private void guildMemberRemove(GuildMemberRemoveEventResponse event) {
    long guildID = Long.parseUnsignedLong(event.guild_id);
    Guild guild = (Guild) client.getGuildByID(guildID);
    if (guild != null) {
        User user = (User) guild.getUserByID(Long.parseUnsignedLong(event.user.id));
        if (user != null) {
            guild.users.remove(user);/*from w ww. ja  va  2s .c  om*/
            guild.joinTimes.remove(user);
            user.roles.remove(guild);
            guild.setTotalMemberCount(guild.getTotalMemberCount() - 1);
            Discord4J.LOGGER.debug(LogMarkers.EVENTS, "User \"{}\" has been removed from or left guild \"{}\".",
                    user.getName(), guild.getName());
            client.dispatcher.dispatch(new UserLeaveEvent(guild, user));
        }
    }
}

From source file:sx.blah.discord.api.internal.DispatchHandler.java

private void guildMemberUpdate(GuildMemberUpdateEventResponse event) {
    Guild guild = (Guild) client.getGuildByID(Long.parseUnsignedLong(event.guild_id));
    User user = (User) client.getUserByID(Long.parseUnsignedLong(event.user.id));

    if (guild != null && user != null) {
        List<IRole> oldRoles = user.getRolesForGuild(guild);
        boolean rolesChanged = oldRoles.size() != event.roles.length + 1;//Add one for the @everyone role
        if (!rolesChanged) {
            rolesChanged = oldRoles.stream().filter(role -> {
                if (role.equals(guild.getEveryoneRole()))
                    return false;

                for (String roleID : event.roles) {
                    if (role.getLongID() == Long.parseUnsignedLong(roleID)) {
                        return false;
                    }/*w  ww  . j  a  v  a 2s.com*/
                }

                return true;
            }).collect(Collectors.toList()).size() > 0;
        }

        if (rolesChanged) {
            user.roles.remove(guild);

            for (String role : event.roles)
                user.addRole(guild.getLongID(), guild.getRoleByID(Long.parseUnsignedLong(role)));

            user.addRole(guild.getLongID(), guild.getEveryoneRole());

            client.dispatcher
                    .dispatch(new UserRoleUpdateEvent(guild, user, oldRoles, user.getRolesForGuild(guild)));

            if (user.equals(client.getOurUser()))
                guild.loadWebhooks();
        }

        String oldNick = user.getNicknameForGuild(guild);
        if ((oldNick == null ^ event.nick == null) || (oldNick != null && !oldNick.equals(event.nick))
                || event.nick != null && !event.nick.equals(oldNick)) {
            user.addNick(guild.getLongID(), event.nick);
            client.dispatcher.dispatch(new NicknameChangedEvent(guild, user, oldNick, event.nick));
        }
    }
}