idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
30,800 | public static MessageBuilder fromMessage ( Message message ) { MessageBuilder builder = new MessageBuilder ( ) ; builder . getStringBuilder ( ) . append ( message . getContent ( ) ) ; if ( ! message . getEmbeds ( ) . isEmpty ( ) ) { builder . setEmbed ( message . getEmbeds ( ) . get ( 0 ) . toBuilder ( ) ) ; } for ( MessageAttachment attachment : message . getAttachments ( ) ) { builder . addAttachment ( attachment . getUrl ( ) ) ; } return builder ; } | Creates a message builder from a message . |
30,801 | public MessageBuilder appendCode ( String language , String code ) { delegate . appendCode ( language , code ) ; return this ; } | Appends code to the message . |
30,802 | public MessageBuilder append ( String message , MessageDecoration ... decorations ) { delegate . append ( message , decorations ) ; return this ; } | Appends a sting with or without decoration to the message . |
30,803 | public MessageBuilder addAttachment ( BufferedImage image , String fileName ) { delegate . addAttachment ( image , fileName ) ; return this ; } | Adds an attachment to the message . |
30,804 | public MessageBuilder addAttachmentAsSpoiler ( InputStream stream , String fileName ) { delegate . addAttachment ( stream , "SPOILER_" + fileName ) ; return this ; } | Adds an attachment to the message and marks it as spoiler . |
30,805 | public void addReaction ( Emoji emoji , boolean you ) { Optional < Reaction > reaction = reactions . stream ( ) . filter ( r -> emoji . equalsEmoji ( r . getEmoji ( ) ) ) . findAny ( ) ; reaction . ifPresent ( r -> ( ( ReactionImpl ) r ) . incrementCount ( you ) ) ; if ( ! reaction . isPresent ( ) ) { reactions . add ( new ReactionImpl ( this , emoji , 1 , you ) ) ; } } | Adds an emoji to the list of reactions . |
30,806 | public void removeReaction ( Emoji emoji , boolean you ) { Optional < Reaction > reaction = reactions . stream ( ) . filter ( r -> emoji . equalsEmoji ( r . getEmoji ( ) ) ) . findAny ( ) ; reaction . ifPresent ( r -> ( ( ReactionImpl ) r ) . decrementCount ( you ) ) ; reactions . removeIf ( r -> r . getCount ( ) <= 0 ) ; } | Removes an emoji from the list of reactions . |
30,807 | public static List < Class < ? > > getInterfaces ( Class < ? > clazz ) { return getInterfacesAsStream ( clazz ) . collect ( Collectors . toList ( ) ) ; } | Get all interfaces of the given class including extended interfaces and interfaces of all superclasses . If the given class is an interface it will be included in the result otherwise not . |
30,808 | public static Stream < Class < ? > > getInterfacesAsStream ( Class < ? > clazz ) { return getSuperclassesAsStream ( clazz , true ) . flatMap ( superClass -> Stream . concat ( superClass . isInterface ( ) ? Stream . of ( superClass ) : Stream . empty ( ) , Arrays . stream ( superClass . getInterfaces ( ) ) . flatMap ( ClassHelper :: getInterfacesAsStream ) ) ) . distinct ( ) ; } | Get a stream of all interfaces of the given class including extended interfaces and interfaces of all superclasses . If the given class is an interface it will be included in the result otherwise not . |
30,809 | public static List < Class < ? > > getSuperclasses ( Class < ? > clazz ) { return getSuperclassesAsStream ( clazz ) . collect ( Collectors . toList ( ) ) ; } | Get all superclasses of the given class . If the given class is an interface the result will be empty . The given class will not be included in the result . |
30,810 | public void clean ( ) { Instant minAge = Instant . now ( ) . minus ( storageTimeInSeconds , ChronoUnit . SECONDS ) ; synchronized ( messages ) { messages . removeIf ( messageRef -> Optional . ofNullable ( messageRef . get ( ) ) . map ( message -> ! message . isCachedForever ( ) && message . getCreationTimestamp ( ) . isBefore ( minAge ) ) . orElse ( true ) ) ; long foreverCachedAmount = messages . stream ( ) . map ( Reference :: get ) . filter ( Objects :: nonNull ) . filter ( Message :: isCachedForever ) . count ( ) ; messages . removeAll ( messages . stream ( ) . filter ( messageRef -> Optional . ofNullable ( messageRef . get ( ) ) . map ( message -> ! message . isCachedForever ( ) ) . orElse ( true ) ) . limit ( Math . max ( 0 , messages . size ( ) - capacity - foreverCachedAmount ) ) . collect ( Collectors . toList ( ) ) ) ; } } | Cleans the cache . |
30,811 | public List < FileContainer > getRequiredAttachments ( ) { List < FileContainer > requiredAttachments = new ArrayList < > ( ) ; if ( footerIconContainer != null ) { requiredAttachments . add ( footerIconContainer ) ; } if ( imageContainer != null ) { requiredAttachments . add ( imageContainer ) ; } if ( authorIconContainer != null ) { requiredAttachments . add ( authorIconContainer ) ; } if ( thumbnailContainer != null ) { requiredAttachments . add ( thumbnailContainer ) ; } return requiredAttachments ; } | Gets the required attachments for this embed . |
30,812 | public static Logger getLogger ( String name ) { AtomicBoolean logWarning = new AtomicBoolean ( false ) ; initialized . updateAndGet ( initialized -> { if ( ! initialized && ! ProviderUtil . hasProviders ( ) ) { noLogger . set ( true ) ; logWarning . set ( true ) ; } return true ; } ) ; if ( noLogger . get ( ) ) { return loggers . computeIfAbsent ( name , key -> { Level level = FallbackLoggerConfiguration . isTraceEnabled ( ) ? Level . TRACE : ( FallbackLoggerConfiguration . isDebugEnabled ( ) ? Level . DEBUG : Level . INFO ) ; Logger logger = new SimpleLogger ( name , level , true , false , true , true , "yyyy-MM-dd HH:mm:ss.SSSZ" , null , new PropertiesUtil ( new Properties ( ) ) , System . out ) ; if ( logWarning . get ( ) ) { logger . info ( "No Log4j2 compatible logger was found. Using default Javacord implementation!" ) ; } return new PrivacyProtectionLogger ( logger ) ; } ) ; } else { return new PrivacyProtectionLogger ( LogManager . getLogger ( name ) ) ; } } | Get or create a logger with the given name . |
30,813 | public static void setDebug ( boolean debug ) { FallbackLoggerConfiguration . debug . set ( debug ) ; if ( ! debug ) { trace . set ( false ) ; } } | Sets whether debug logging should be enabled . Disabling debug logging automatically disables trace logging too . |
30,814 | public static void setTrace ( boolean trace ) { FallbackLoggerConfiguration . trace . set ( trace ) ; if ( trace ) { debug . set ( true ) ; } } | Sets whether trace logging should be enabled . Enabling trace logging automatically enables debug logging too . |
30,815 | private void handleServerVoiceChannel ( JsonNode channelJson ) { long serverId = channelJson . get ( "guild_id" ) . asLong ( ) ; long channelId = channelJson . get ( "id" ) . asLong ( ) ; api . getPossiblyUnreadyServerById ( serverId ) . ifPresent ( server -> server . getVoiceChannelById ( channelId ) . ifPresent ( channel -> { dispatchServerChannelDeleteEvent ( channel ) ; ( ( ServerImpl ) server ) . removeChannelFromCache ( channel . getId ( ) ) ; } ) ) ; api . removeObjectListeners ( ServerVoiceChannel . class , channelId ) ; api . removeObjectListeners ( ServerChannel . class , channelId ) ; api . removeObjectListeners ( VoiceChannel . class , channelId ) ; api . removeObjectListeners ( Channel . class , channelId ) ; } | Handles server voice channel deletion . |
30,816 | private void handlePrivateChannel ( JsonNode channel ) { UserImpl recipient = ( UserImpl ) api . getOrCreateUser ( channel . get ( "recipients" ) . get ( 0 ) ) ; recipient . getPrivateChannel ( ) . ifPresent ( privateChannel -> { PrivateChannelDeleteEvent event = new PrivateChannelDeleteEventImpl ( privateChannel ) ; api . getEventDispatcher ( ) . dispatchPrivateChannelDeleteEvent ( api , privateChannel , recipient , event ) ; long channelId = privateChannel . getId ( ) ; api . removeObjectListeners ( PrivateChannel . class , channelId ) ; api . removeObjectListeners ( VoiceChannel . class , channelId ) ; api . removeObjectListeners ( TextChannel . class , channelId ) ; api . removeObjectListeners ( Channel . class , channelId ) ; api . forEachCachedMessageWhere ( msg -> msg . getChannel ( ) . getId ( ) == privateChannel . getId ( ) , msg -> api . removeMessageFromCache ( msg . getId ( ) ) ) ; recipient . setChannel ( null ) ; } ) ; } | Handles a private channel deletion . |
30,817 | private void handleGroupChannel ( JsonNode channel ) { long channelId = channel . get ( "id" ) . asLong ( ) ; api . getGroupChannelById ( channelId ) . ifPresent ( groupChannel -> { GroupChannelDeleteEvent event = new GroupChannelDeleteEventImpl ( groupChannel ) ; api . getEventDispatcher ( ) . dispatchGroupChannelDeleteEvent ( api , Collections . singleton ( groupChannel ) , groupChannel . getMembers ( ) , event ) ; api . removeObjectListeners ( GroupChannel . class , channelId ) ; api . removeObjectListeners ( VoiceChannel . class , channelId ) ; api . removeObjectListeners ( TextChannel . class , channelId ) ; api . removeObjectListeners ( Channel . class , channelId ) ; api . forEachCachedMessageWhere ( msg -> msg . getChannel ( ) . getId ( ) == groupChannel . getId ( ) , msg -> api . removeMessageFromCache ( msg . getId ( ) ) ) ; } ) ; } | Handles a group channel deletion . |
30,818 | private void dispatchServerChannelDeleteEvent ( ServerChannel channel ) { ServerChannelDeleteEvent event = new ServerChannelDeleteEventImpl ( channel ) ; api . getEventDispatcher ( ) . dispatchServerChannelDeleteEvent ( ( DispatchQueueSelector ) channel . getServer ( ) , channel . getServer ( ) , channel , event ) ; } | Dispatches a server channel delete event . |
30,819 | public CompletableFuture < byte [ ] > asByteArray ( DiscordApi api ) { CompletableFuture < byte [ ] > future = new CompletableFuture < > ( ) ; try { if ( fileAsByteArray != null ) { future . complete ( fileAsByteArray ) ; return future ; } if ( fileAsBufferedImage != null || fileAsFile != null || fileAsIcon != null || fileAsUrl != null || fileAsInputStream != null ) { asInputStream ( api ) . thenApply ( stream -> { try ( InputStream in = new BufferedInputStream ( stream ) ; ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ) { byte [ ] buf = new byte [ 1024 ] ; int n ; while ( - 1 != ( n = in . read ( buf ) ) ) { out . write ( buf , 0 , n ) ; } return out . toByteArray ( ) ; } catch ( IOException e ) { throw new CompletionException ( e ) ; } } ) . whenComplete ( ( bytes , throwable ) -> { if ( throwable != null ) { future . completeExceptionally ( throwable ) ; } else { future . complete ( bytes ) ; } } ) ; return future ; } future . completeExceptionally ( new IllegalStateException ( "No file variant is set" ) ) ; } catch ( Throwable t ) { future . completeExceptionally ( t ) ; } return future ; } | Gets the byte array for the file . |
30,820 | public CompletableFuture < InputStream > asInputStream ( DiscordApi api ) { CompletableFuture < InputStream > future = new CompletableFuture < > ( ) ; try { if ( fileAsBufferedImage != null ) { ByteArrayOutputStream os = new ByteArrayOutputStream ( ) ; ImageIO . write ( fileAsBufferedImage , getFileType ( ) , os ) ; future . complete ( new ByteArrayInputStream ( os . toByteArray ( ) ) ) ; return future ; } if ( fileAsFile != null ) { future . complete ( new FileInputStream ( fileAsFile ) ) ; return future ; } if ( fileAsIcon != null || fileAsUrl != null ) { URL url = fileAsUrl == null ? fileAsIcon . getUrl ( ) : fileAsUrl ; api . getThreadPool ( ) . getExecutorService ( ) . submit ( ( ) -> { try { logger . debug ( "Trying to download file from {}" , url ) ; HttpURLConnection conn = ( HttpURLConnection ) url . openConnection ( ) ; conn . setRequestMethod ( "GET" ) ; conn . setRequestProperty ( "Content-Type" , "application/json; charset=utf-8" ) ; conn . setRequestProperty ( "User-Agent" , Javacord . USER_AGENT ) ; future . complete ( conn . getInputStream ( ) ) ; logger . debug ( "Downloaded file from {} (content length: {})" , url , conn . getContentLength ( ) ) ; } catch ( Throwable t ) { future . completeExceptionally ( t ) ; } } ) ; return future ; } if ( fileAsByteArray != null ) { future . complete ( new ByteArrayInputStream ( fileAsByteArray ) ) ; return future ; } if ( fileAsInputStream != null ) { future . complete ( fileAsInputStream ) ; return future ; } future . completeExceptionally ( new IllegalStateException ( "No file variant is set" ) ) ; } catch ( Throwable t ) { future . completeExceptionally ( t ) ; } return future ; } | Gets the input stream for the file . |
30,821 | public < T extends Permissionable & DiscordEntity > ServerChannelUpdater addPermissionOverwrite ( T permissionable , Permissions permissions ) { delegate . addPermissionOverwrite ( permissionable , permissions ) ; return this ; } | Adds a permission overwrite for the given entity . |
30,822 | public PermissionsBuilder setState ( PermissionType type , PermissionState state ) { delegate . setState ( type , state ) ; return this ; } | Sets the new state of the given type . |
30,823 | public static UnicodeEmojiImpl fromString ( String emoji ) { return unicodeEmojis . computeIfAbsent ( emoji , key -> new UnicodeEmojiImpl ( emoji ) ) ; } | Gets a unicode emoji by its string representation . |
30,824 | public EmbedBuilder setFooter ( String text , InputStream icon ) { delegate . setFooter ( text , icon ) ; return this ; } | Sets the footer of the embed . This method assumes the file type is png ! |
30,825 | public EmbedBuilder addInlineField ( String name , String value ) { delegate . addField ( name , value , true ) ; return this ; } | Adds an inline field to the embed . |
30,826 | public EmbedBuilder addField ( String name , String value ) { delegate . addField ( name , value , false ) ; return this ; } | Adds a non - inline field to the embed . |
30,827 | public EmbedBuilder addField ( String name , String value , boolean inline ) { delegate . addField ( name , value , inline ) ; return this ; } | Adds a field to the embed . |
30,828 | public EmbedBuilder updateFields ( Predicate < EmbedField > predicate , Consumer < EditableEmbedField > updater ) { delegate . updateFields ( predicate , updater ) ; return this ; } | Updates all fields of the embed that satisfy the given predicate using the given updater . |
30,829 | public EmbedBuilder updateAllFields ( Consumer < EditableEmbedField > updater ) { delegate . updateFields ( field -> true , updater ) ; return this ; } | Updates all fields of the embed using the given updater . |
30,830 | private void handleResponse ( RestRequest < ? > request , RestRequestResult result , RatelimitBucket bucket , long responseTimestamp ) { if ( result == null || result . getResponse ( ) == null ) { return ; } Response response = result . getResponse ( ) ; boolean global = response . header ( "X-RateLimit-Global" , "false" ) . equalsIgnoreCase ( "true" ) ; int remaining = Integer . valueOf ( response . header ( "X-RateLimit-Remaining" , "1" ) ) ; long reset = request . getEndpoint ( ) . getHardcodedRatelimit ( ) . map ( ratelimit -> responseTimestamp + api . getTimeOffset ( ) + ratelimit ) . orElseGet ( ( ) -> Long . parseLong ( response . header ( "X-RateLimit-Reset" , "0" ) ) * 1000 ) ; if ( result . getResponse ( ) . code ( ) == 429 ) { int retryAfter = result . getJsonBody ( ) . isNull ( ) ? 0 : result . getJsonBody ( ) . get ( "retry_after" ) . asInt ( ) ; if ( global ) { logger . warn ( "Hit a global ratelimit! This means you were sending a very large " + "amount within a very short time frame." ) ; RatelimitBucket . setGlobalRatelimitResetTimestamp ( api , responseTimestamp + retryAfter ) ; } else { logger . debug ( "Received a 429 response from Discord! Recalculating time offset..." ) ; api . setTimeOffset ( null ) ; bucket . setRatelimitRemaining ( 0 ) ; bucket . setRatelimitResetTimestamp ( responseTimestamp + retryAfter ) ; } } else { CompletableFuture < RestRequestResult > requestResult = request . getResult ( ) ; if ( ! requestResult . isDone ( ) ) { requestResult . complete ( result ) ; } bucket . setRatelimitRemaining ( remaining ) ; bucket . setRatelimitResetTimestamp ( reset ) ; } } | Updates the ratelimit information and sets the result if the request was successful . |
30,831 | private void calculateOffset ( long currentTime , RestRequestResult result ) { if ( ( api . getTimeOffset ( ) != null ) || ( result == null ) || ( result . getResponse ( ) == null ) ) { return ; } synchronized ( api ) { if ( api . getTimeOffset ( ) == null ) { String date = result . getResponse ( ) . header ( "Date" ) ; if ( date != null ) { long discordTimestamp = OffsetDateTime . parse ( date , DateTimeFormatter . RFC_1123_DATE_TIME ) . toInstant ( ) . toEpochMilli ( ) ; api . setTimeOffset ( ( discordTimestamp - currentTime ) ) ; logger . debug ( "Calculated an offset of {} to the Discord time." , api :: getTimeOffset ) ; } } } } | Calculates the offset of the local time and discord s time . |
30,832 | public Optional < String > getMajorUrlParameter ( ) { if ( customMajorParam != null ) { return Optional . of ( customMajorParam ) ; } Optional < Integer > majorParameterPosition = endpoint . getMajorParameterPosition ( ) ; if ( ! majorParameterPosition . isPresent ( ) ) { return Optional . empty ( ) ; } if ( majorParameterPosition . get ( ) >= urlParameters . length ) { return Optional . empty ( ) ; } return Optional . of ( urlParameters [ majorParameterPosition . get ( ) ] ) ; } | Gets the major url parameter of this request . If an request has a major parameter it means that the ratelimits for this request are based on this parameter . |
30,833 | public RestRequest < T > addQueryParameter ( String key , String value ) { queryParameters . put ( key , value ) ; return this ; } | Adds a query parameter to the url . |
30,834 | public CompletableFuture < T > execute ( Function < RestRequestResult , T > function ) { api . getRatelimitManager ( ) . queueRequest ( this ) ; CompletableFuture < T > future = new CompletableFuture < > ( ) ; result . whenComplete ( ( result , throwable ) -> { if ( throwable != null ) { future . completeExceptionally ( throwable ) ; return ; } try { future . complete ( function . apply ( result ) ) ; } catch ( Throwable t ) { future . completeExceptionally ( t ) ; } } ) ; return future ; } | Executes the request . This will automatically retry if we hit a ratelimit . |
30,835 | public RestRequestInformation asRestRequestInformation ( ) { try { return new RestRequestInformationImpl ( api , new URL ( endpoint . getFullUrl ( urlParameters ) ) , queryParameters , headers , body ) ; } catch ( MalformedURLException e ) { throw new AssertionError ( e ) ; } } | Gets the information for this rest request . |
30,836 | private void handleChannelCategory ( JsonNode jsonChannel ) { long channelCategoryId = jsonChannel . get ( "id" ) . asLong ( ) ; api . getChannelCategoryById ( channelCategoryId ) . map ( ChannelCategoryImpl . class :: cast ) . ifPresent ( channel -> { boolean oldNsfwFlag = channel . isNsfw ( ) ; boolean newNsfwFlag = jsonChannel . get ( "nsfw" ) . asBoolean ( ) ; if ( oldNsfwFlag != newNsfwFlag ) { channel . setNsfwFlag ( newNsfwFlag ) ; ServerChannelChangeNsfwFlagEvent event = new ServerChannelChangeNsfwFlagEventImpl ( channel , newNsfwFlag , oldNsfwFlag ) ; api . getEventDispatcher ( ) . dispatchServerChannelChangeNsfwFlagEvent ( ( DispatchQueueSelector ) channel . getServer ( ) , channel , channel . getServer ( ) , null , event ) ; } } ) ; } | Handles a channel category update . |
30,837 | private void handleServerTextChannel ( JsonNode jsonChannel ) { long channelId = jsonChannel . get ( "id" ) . asLong ( ) ; api . getTextChannelById ( channelId ) . map ( c -> ( ( ServerTextChannelImpl ) c ) ) . ifPresent ( channel -> { String oldTopic = channel . getTopic ( ) ; String newTopic = jsonChannel . has ( "topic" ) && ! jsonChannel . get ( "topic" ) . isNull ( ) ? jsonChannel . get ( "topic" ) . asText ( ) : "" ; if ( ! oldTopic . equals ( newTopic ) ) { channel . setTopic ( newTopic ) ; ServerTextChannelChangeTopicEvent event = new ServerTextChannelChangeTopicEventImpl ( channel , newTopic , oldTopic ) ; api . getEventDispatcher ( ) . dispatchServerTextChannelChangeTopicEvent ( ( DispatchQueueSelector ) channel . getServer ( ) , channel . getServer ( ) , channel , event ) ; } boolean oldNsfwFlag = channel . isNsfw ( ) ; boolean newNsfwFlag = jsonChannel . get ( "nsfw" ) . asBoolean ( ) ; if ( oldNsfwFlag != newNsfwFlag ) { channel . setNsfwFlag ( newNsfwFlag ) ; ServerChannelChangeNsfwFlagEvent event = new ServerChannelChangeNsfwFlagEventImpl ( channel , newNsfwFlag , oldNsfwFlag ) ; api . getEventDispatcher ( ) . dispatchServerChannelChangeNsfwFlagEvent ( ( DispatchQueueSelector ) channel . getServer ( ) , null , channel . getServer ( ) , channel , event ) ; } int oldSlowmodeDelay = channel . getSlowmodeDelayInSeconds ( ) ; int newSlowmodeDelay = jsonChannel . get ( "rate_limit_per_user" ) . asInt ( 0 ) ; if ( oldSlowmodeDelay != newSlowmodeDelay ) { channel . setSlowmodeDelayInSeconds ( newSlowmodeDelay ) ; ServerTextChannelChangeSlowmodeEvent event = new ServerTextChannelChangeSlowmodeEventImpl ( channel , oldSlowmodeDelay , newSlowmodeDelay ) ; api . getEventDispatcher ( ) . dispatchServerTextChannelChangeSlowmodeEvent ( ( DispatchQueueSelector ) channel . getServer ( ) , channel . getServer ( ) , channel , event ) ; } } ) ; } | Handles a server text channel update . |
30,838 | private void handleServerVoiceChannel ( JsonNode jsonChannel ) { long channelId = jsonChannel . get ( "id" ) . asLong ( ) ; api . getServerVoiceChannelById ( channelId ) . map ( ServerVoiceChannelImpl . class :: cast ) . ifPresent ( channel -> { int oldBitrate = channel . getBitrate ( ) ; int newBitrate = jsonChannel . get ( "bitrate" ) . asInt ( ) ; if ( oldBitrate != newBitrate ) { channel . setBitrate ( newBitrate ) ; ServerVoiceChannelChangeBitrateEvent event = new ServerVoiceChannelChangeBitrateEventImpl ( channel , newBitrate , oldBitrate ) ; api . getEventDispatcher ( ) . dispatchServerVoiceChannelChangeBitrateEvent ( ( DispatchQueueSelector ) channel . getServer ( ) , channel . getServer ( ) , channel , event ) ; } int oldUserLimit = channel . getUserLimit ( ) . orElse ( 0 ) ; int newUserLimit = jsonChannel . get ( "user_limit" ) . asInt ( ) ; if ( oldUserLimit != newUserLimit ) { channel . setUserLimit ( newUserLimit ) ; ServerVoiceChannelChangeUserLimitEvent event = new ServerVoiceChannelChangeUserLimitEventImpl ( channel , newUserLimit , oldUserLimit ) ; api . getEventDispatcher ( ) . dispatchServerVoiceChannelChangeUserLimitEvent ( ( DispatchQueueSelector ) channel . getServer ( ) , channel . getServer ( ) , channel , event ) ; } } ) ; } | Handles a server voice channel update . |
30,839 | private void handleGroupChannel ( JsonNode jsonChannel ) { long channelId = jsonChannel . get ( "id" ) . asLong ( ) ; api . getGroupChannelById ( channelId ) . map ( GroupChannelImpl . class :: cast ) . ifPresent ( channel -> { String oldName = channel . getName ( ) . orElseThrow ( AssertionError :: new ) ; String newName = jsonChannel . get ( "name" ) . asText ( ) ; if ( ! Objects . equals ( oldName , newName ) ) { channel . setName ( newName ) ; GroupChannelChangeNameEvent event = new GroupChannelChangeNameEventImpl ( channel , newName , oldName ) ; api . getEventDispatcher ( ) . dispatchGroupChannelChangeNameEvent ( api , Collections . singleton ( channel ) , channel . getMembers ( ) , event ) ; } } ) ; } | Handles a group channel update . |
30,840 | private void dispatchServerChannelChangeOverwrittenPermissionsEvent ( ServerChannel channel , Permissions newPermissions , Permissions oldPermissions , DiscordEntity entity ) { if ( newPermissions . equals ( oldPermissions ) ) { return ; } ServerChannelChangeOverwrittenPermissionsEvent event = new ServerChannelChangeOverwrittenPermissionsEventImpl ( channel , newPermissions , oldPermissions , entity ) ; api . getEventDispatcher ( ) . dispatchServerChannelChangeOverwrittenPermissionsEvent ( ( DispatchQueueSelector ) channel . getServer ( ) , ( entity instanceof Role ) ? ( Role ) entity : null , channel . getServer ( ) , channel , ( entity instanceof User ) ? ( User ) entity : null , event ) ; } | Dispatches a ServerChannelChangeOverwrittenPermissionsEvent . |
30,841 | public void purgeCache ( ) { synchronized ( users ) { users . values ( ) . stream ( ) . map ( Reference :: get ) . filter ( Objects :: nonNull ) . map ( Cleanupable . class :: cast ) . forEach ( Cleanupable :: cleanup ) ; users . clear ( ) ; } userIdByRef . clear ( ) ; servers . values ( ) . stream ( ) . map ( Cleanupable . class :: cast ) . forEach ( Cleanupable :: cleanup ) ; servers . clear ( ) ; channels . values ( ) . stream ( ) . filter ( Cleanupable . class :: isInstance ) . map ( Cleanupable . class :: cast ) . forEach ( Cleanupable :: cleanup ) ; channels . clear ( ) ; unavailableServers . clear ( ) ; customEmojis . clear ( ) ; messages . clear ( ) ; messageIdByRef . clear ( ) ; timeOffset = null ; } | Purges all cached entities . This method is only meant to be called after receiving a READY packet . |
30,842 | public Collection < Server > getAllServers ( ) { ArrayList < Server > allServers = new ArrayList < > ( nonReadyServers . values ( ) ) ; allServers . addAll ( servers . values ( ) ) ; return Collections . unmodifiableList ( allServers ) ; } | Gets a collection with all servers including ready and not ready ones . |
30,843 | public Optional < Server > getPossiblyUnreadyServerById ( long id ) { if ( nonReadyServers . containsKey ( id ) ) { return Optional . ofNullable ( nonReadyServers . get ( id ) ) ; } return Optional . ofNullable ( servers . get ( id ) ) ; } | Gets a server by it s id including ready and not ready ones . |
30,844 | public void addServerToCache ( ServerImpl server ) { removeServerFromCache ( server . getId ( ) ) ; nonReadyServers . put ( server . getId ( ) , server ) ; server . addServerReadyConsumer ( s -> { nonReadyServers . remove ( s . getId ( ) ) ; removeUnavailableServerFromCache ( s . getId ( ) ) ; servers . put ( s . getId ( ) , s ) ; } ) ; } | Adds the given server to the cache . |
30,845 | public void removeServerFromCache ( long serverId ) { servers . computeIfPresent ( serverId , ( key , server ) -> { ( ( Cleanupable ) server ) . cleanup ( ) ; return null ; } ) ; nonReadyServers . computeIfPresent ( serverId , ( key , server ) -> { ( ( Cleanupable ) server ) . cleanup ( ) ; return null ; } ) ; } | Removes the given server from the cache . |
30,846 | public void addUserToCache ( User user ) { users . compute ( user . getId ( ) , ( key , value ) -> { Optional . ofNullable ( value ) . map ( Reference :: get ) . filter ( oldUser -> oldUser != user ) . map ( Cleanupable . class :: cast ) . ifPresent ( Cleanupable :: cleanup ) ; WeakReference < User > result = new WeakReference < > ( user , usersCleanupQueue ) ; userIdByRef . put ( result , key ) ; return result ; } ) ; } | Adds the given user to the cache . |
30,847 | public void addChannelToCache ( Channel channel ) { Channel oldChannel = channels . put ( channel . getId ( ) , channel ) ; if ( oldChannel != channel && oldChannel instanceof Cleanupable ) { ( ( Cleanupable ) oldChannel ) . cleanup ( ) ; } } | Adds a channel to the cache . |
30,848 | public void removeChannelFromCache ( long channelId ) { channels . computeIfPresent ( channelId , ( key , channel ) -> { if ( channel instanceof Cleanupable ) { ( ( Cleanupable ) channel ) . cleanup ( ) ; } return null ; } ) ; } | Removes a channel from the cache . |
30,849 | public User getOrCreateUser ( JsonNode data ) { long id = Long . parseLong ( data . get ( "id" ) . asText ( ) ) ; synchronized ( users ) { return getCachedUserById ( id ) . orElseGet ( ( ) -> { if ( ! data . has ( "username" ) ) { throw new IllegalStateException ( "Couldn't get or created user. Please inform the developer!" ) ; } return new UserImpl ( this , data ) ; } ) ; } } | Gets a user or creates a new one from the given data . |
30,850 | public KnownCustomEmoji getOrCreateKnownCustomEmoji ( Server server , JsonNode data ) { long id = Long . parseLong ( data . get ( "id" ) . asText ( ) ) ; return customEmojis . computeIfAbsent ( id , key -> new KnownCustomEmojiImpl ( this , server , data ) ) ; } | Gets or creates a new known custom emoji object . |
30,851 | public Message getOrCreateMessage ( TextChannel channel , JsonNode data ) { long id = Long . parseLong ( data . get ( "id" ) . asText ( ) ) ; synchronized ( messages ) { return getCachedMessageById ( id ) . orElseGet ( ( ) -> new MessageImpl ( this , channel , data ) ) ; } } | Gets or creates a new message object . |
30,852 | @ SuppressWarnings ( "unchecked" ) public < T extends ObjectAttachableListener > ListenerManager < T > addObjectListener ( Class < ? > objectClass , long objectId , Class < T > listenerClass , T listener ) { Map < ObjectAttachableListener , ListenerManagerImpl < ? extends ObjectAttachableListener > > listeners = objectListeners . computeIfAbsent ( objectClass , key -> new ConcurrentHashMap < > ( ) ) . computeIfAbsent ( objectId , key -> new ConcurrentHashMap < > ( ) ) . computeIfAbsent ( listenerClass , c -> Collections . synchronizedMap ( new LinkedHashMap < > ( ) ) ) ; return ( ListenerManager < T > ) listeners . computeIfAbsent ( listener , key -> new ListenerManagerImpl < > ( this , listener , listenerClass , objectClass , objectId ) ) ; } | Adds an object listener . Adding a listener multiple times to the same object will only add it once and return the same listener manager on each invocation . The order of invocation is according to first addition . |
30,853 | public < T extends ObjectAttachableListener > void removeObjectListener ( Class < ? > objectClass , long objectId , Class < T > listenerClass , T listener ) { synchronized ( objectListeners ) { if ( objectClass == null ) { return ; } Map < Long , Map < Class < ? extends ObjectAttachableListener > , Map < ObjectAttachableListener , ListenerManagerImpl < ? extends ObjectAttachableListener > > > > objectListener = objectListeners . get ( objectClass ) ; if ( objectListener == null ) { return ; } Map < Class < ? extends ObjectAttachableListener > , Map < ObjectAttachableListener , ListenerManagerImpl < ? extends ObjectAttachableListener > > > listeners = objectListener . get ( objectId ) ; if ( listeners == null ) { return ; } Map < ObjectAttachableListener , ListenerManagerImpl < ? extends ObjectAttachableListener > > classListeners = listeners . get ( listenerClass ) ; if ( classListeners == null ) { return ; } ListenerManagerImpl < ? extends ObjectAttachableListener > listenerManager = classListeners . get ( listener ) ; if ( listenerManager == null ) { return ; } classListeners . remove ( listener ) ; listenerManager . removed ( ) ; if ( classListeners . isEmpty ( ) ) { listeners . remove ( listenerClass ) ; if ( listeners . isEmpty ( ) ) { objectListener . remove ( objectId ) ; if ( objectListener . isEmpty ( ) ) { objectListeners . remove ( objectClass ) ; } } } } } | Removes an object listener . |
30,854 | public void removeObjectListeners ( Class < ? > objectClass , long objectId ) { if ( objectClass == null ) { return ; } synchronized ( objectListeners ) { Map < Long , Map < Class < ? extends ObjectAttachableListener > , Map < ObjectAttachableListener , ListenerManagerImpl < ? extends ObjectAttachableListener > > > > objects = objectListeners . get ( objectClass ) ; if ( objects == null ) { return ; } objects . computeIfPresent ( objectId , ( id , listeners ) -> { listeners . values ( ) . stream ( ) . flatMap ( map -> map . values ( ) . stream ( ) ) . forEach ( ListenerManagerImpl :: removed ) ; listeners . clear ( ) ; return null ; } ) ; if ( objects . isEmpty ( ) ) { objectListeners . remove ( objectClass ) ; } } } | Remove all listeners attached to an object . |
30,855 | @ SuppressWarnings ( "unchecked" ) public < T extends ObjectAttachableListener > List < T > getObjectListeners ( Class < ? > objectClass , long objectId , Class < T > listenerClass ) { return Collections . unmodifiableList ( ( List < T > ) Optional . ofNullable ( objectClass ) . map ( objectListeners :: get ) . map ( objectListener -> objectListener . get ( objectId ) ) . map ( listeners -> listeners . get ( listenerClass ) ) . map ( Map :: keySet ) . map ( ArrayList :: new ) . orElseGet ( ArrayList :: new ) ) ; } | Gets all object listeners of the given class . |
30,856 | private void updateActivity ( ActivityType type , String name , String streamingUrl ) { if ( name == null ) { activity = null ; } else if ( streamingUrl == null ) { activity = new ActivityImpl ( type , name , null ) ; } else { activity = new ActivityImpl ( type , name , streamingUrl ) ; } websocketAdapter . updateStatus ( ) ; } | Sets the current activity along with type and streaming Url . |
30,857 | public MessageSet getCachedMessagesWhere ( Predicate < Message > filter ) { synchronized ( messages ) { return messages . values ( ) . stream ( ) . map ( Reference :: get ) . filter ( Objects :: nonNull ) . filter ( filter ) . collect ( Collectors . toCollection ( MessageSetImpl :: new ) ) ; } } | Get messages from the cache that satisfy a given condition . |
30,858 | public void forEachCachedMessageWhere ( Predicate < Message > filter , Consumer < Message > action ) { synchronized ( messages ) { messages . values ( ) . stream ( ) . map ( Reference :: get ) . filter ( Objects :: nonNull ) . filter ( filter ) . forEach ( action ) ; } } | Execute a task for every message in cache that satisfied a given condition . |
30,859 | public int getTimeTillSpaceGetsAvailable ( ) { long globalRatelimitResetTimestamp = RatelimitBucket . globalRatelimitResetTimestamp . getOrDefault ( api . getToken ( ) , 0L ) ; long timestamp = System . currentTimeMillis ( ) + ( api . getTimeOffset ( ) == null ? 0 : api . getTimeOffset ( ) ) ; if ( ratelimitRemaining > 0 && ( globalRatelimitResetTimestamp - timestamp ) <= 0 ) { return 0 ; } return ( int ) ( Math . max ( ratelimitResetTimestamp , globalRatelimitResetTimestamp ) - timestamp ) ; } | Gets the time in seconds how long you have to wait till there s space in the bucket again . |
30,860 | private void handleChannelCategory ( JsonNode channel ) { long serverId = channel . get ( "guild_id" ) . asLong ( ) ; api . getPossiblyUnreadyServerById ( serverId ) . ifPresent ( server -> { ChannelCategory channelCategory = ( ( ServerImpl ) server ) . getOrCreateChannelCategory ( channel ) ; ServerChannelCreateEvent event = new ServerChannelCreateEventImpl ( channelCategory ) ; api . getEventDispatcher ( ) . dispatchServerChannelCreateEvent ( ( DispatchQueueSelector ) server , server , event ) ; } ) ; } | Handles channel category creation . |
30,861 | private void handleServerTextChannel ( JsonNode channel ) { long serverId = channel . get ( "guild_id" ) . asLong ( ) ; api . getPossiblyUnreadyServerById ( serverId ) . ifPresent ( server -> { ServerTextChannel textChannel = ( ( ServerImpl ) server ) . getOrCreateServerTextChannel ( channel ) ; ServerChannelCreateEvent event = new ServerChannelCreateEventImpl ( textChannel ) ; api . getEventDispatcher ( ) . dispatchServerChannelCreateEvent ( ( DispatchQueueSelector ) server , server , event ) ; } ) ; } | Handles server text channel creation . |
30,862 | private void handleServerVoiceChannel ( JsonNode channel ) { long serverId = channel . get ( "guild_id" ) . asLong ( ) ; api . getPossiblyUnreadyServerById ( serverId ) . ifPresent ( server -> { ServerVoiceChannel voiceChannel = ( ( ServerImpl ) server ) . getOrCreateServerVoiceChannel ( channel ) ; ServerChannelCreateEvent event = new ServerChannelCreateEventImpl ( voiceChannel ) ; api . getEventDispatcher ( ) . dispatchServerChannelCreateEvent ( ( DispatchQueueSelector ) server , server , event ) ; } ) ; } | Handles server voice channel creation . |
30,863 | private void handlePrivateChannel ( JsonNode channel ) { UserImpl recipient = ( UserImpl ) api . getOrCreateUser ( channel . get ( "recipients" ) . get ( 0 ) ) ; if ( ! recipient . getPrivateChannel ( ) . isPresent ( ) ) { PrivateChannel privateChannel = recipient . getOrCreateChannel ( channel ) ; PrivateChannelCreateEvent event = new PrivateChannelCreateEventImpl ( privateChannel ) ; api . getEventDispatcher ( ) . dispatchPrivateChannelCreateEvent ( api , recipient , event ) ; } } | Handles a private channel creation . |
30,864 | private void handleGroupChannel ( JsonNode channel ) { long channelId = channel . get ( "id" ) . asLong ( ) ; if ( ! api . getGroupChannelById ( channelId ) . isPresent ( ) ) { GroupChannel groupChannel = new GroupChannelImpl ( api , channel ) ; GroupChannelCreateEvent event = new GroupChannelCreateEventImpl ( groupChannel ) ; api . getEventDispatcher ( ) . dispatchGroupChannelCreateEvent ( api , groupChannel . getMembers ( ) , event ) ; } } | Handles a group channel creation . |
30,865 | public void addServerReadyConsumer ( Consumer < Server > consumer ) { synchronized ( readyConsumers ) { if ( ready ) { consumer . accept ( this ) ; } else { readyConsumers . add ( consumer ) ; } } } | Adds a consumer which will be informed once the server is ready . If the server is already ready it will immediately call the consumer otherwise it will be called from the websocket reading thread . |
30,866 | public Role getOrCreateRole ( JsonNode data ) { long id = Long . parseLong ( data . get ( "id" ) . asText ( ) ) ; synchronized ( this ) { return getRoleById ( id ) . orElseGet ( ( ) -> { Role role = new RoleImpl ( api , this , data ) ; this . roles . put ( role . getId ( ) , role ) ; return role ; } ) ; } } | Gets or create a new role . |
30,867 | public ChannelCategory getOrCreateChannelCategory ( JsonNode data ) { long id = Long . parseLong ( data . get ( "id" ) . asText ( ) ) ; ChannelType type = ChannelType . fromId ( data . get ( "type" ) . asInt ( ) ) ; synchronized ( this ) { if ( type == ChannelType . CHANNEL_CATEGORY ) { return getChannelCategoryById ( id ) . orElseGet ( ( ) -> new ChannelCategoryImpl ( api , this , data ) ) ; } } return null ; } | Gets or creates a channel category . |
30,868 | public ServerTextChannel getOrCreateServerTextChannel ( JsonNode data ) { long id = Long . parseLong ( data . get ( "id" ) . asText ( ) ) ; ChannelType type = ChannelType . fromId ( data . get ( "type" ) . asInt ( ) ) ; synchronized ( this ) { if ( type == ChannelType . SERVER_TEXT_CHANNEL || type == ChannelType . SERVER_NEWS_CHANNEL ) { return getTextChannelById ( id ) . orElseGet ( ( ) -> new ServerTextChannelImpl ( api , this , data ) ) ; } } return null ; } | Gets or creates a server text channel . |
30,869 | public ServerVoiceChannel getOrCreateServerVoiceChannel ( JsonNode data ) { long id = Long . parseLong ( data . get ( "id" ) . asText ( ) ) ; ChannelType type = ChannelType . fromId ( data . get ( "type" ) . asInt ( ) ) ; synchronized ( this ) { if ( type == ChannelType . SERVER_VOICE_CHANNEL ) { return getVoiceChannelById ( id ) . orElseGet ( ( ) -> new ServerVoiceChannelImpl ( api , this , data ) ) ; } } return null ; } | Gets or creates a server voice channel . |
30,870 | public void removeMember ( User user ) { long userId = user . getId ( ) ; members . remove ( userId ) ; nicknames . remove ( userId ) ; selfMuted . remove ( userId ) ; selfDeafened . remove ( userId ) ; muted . remove ( userId ) ; deafened . remove ( userId ) ; getRoles ( ) . forEach ( role -> ( ( RoleImpl ) role ) . removeUserFromCache ( user ) ) ; joinedAtTimestamps . remove ( userId ) ; } | Removes a member from the server . |
30,871 | public void addMember ( JsonNode member ) { User user = api . getOrCreateUser ( member . get ( "user" ) ) ; members . put ( user . getId ( ) , user ) ; if ( member . hasNonNull ( "nick" ) ) { nicknames . put ( user . getId ( ) , member . get ( "nick" ) . asText ( ) ) ; } if ( member . hasNonNull ( "mute" ) ) { setMuted ( user . getId ( ) , member . get ( "mute" ) . asBoolean ( ) ) ; } if ( member . hasNonNull ( "deaf" ) ) { setDeafened ( user . getId ( ) , member . get ( "deaf" ) . asBoolean ( ) ) ; } for ( JsonNode roleIds : member . get ( "roles" ) ) { long roleId = Long . parseLong ( roleIds . asText ( ) ) ; getRoleById ( roleId ) . map ( role -> ( ( RoleImpl ) role ) ) . ifPresent ( role -> role . addUserToCache ( user ) ) ; } joinedAtTimestamps . put ( user . getId ( ) , OffsetDateTime . parse ( member . get ( "joined_at" ) . asText ( ) ) . toInstant ( ) ) ; synchronized ( readyConsumers ) { if ( ! ready && members . size ( ) == getMemberCount ( ) ) { ready = true ; readyConsumers . forEach ( consumer -> consumer . accept ( this ) ) ; readyConsumers . clear ( ) ; } } } | Adds a member to the server . |
30,872 | public void setNickname ( User user , String nickname ) { nicknames . compute ( user . getId ( ) , ( key , value ) -> nickname ) ; } | Sets the nickname of the user . |
30,873 | public void setSelfMuted ( long userId , boolean muted ) { if ( muted ) { selfMuted . add ( userId ) ; } else { selfMuted . remove ( userId ) ; } } | Sets the self - muted state of the user with the given id . |
30,874 | public void setSelfDeafened ( long userId , boolean deafened ) { if ( deafened ) { selfDeafened . add ( userId ) ; } else { selfDeafened . remove ( userId ) ; } } | Sets the self - deafened state of the user with the given id . |
30,875 | public void setMuted ( long userId , boolean muted ) { if ( muted ) { this . muted . add ( userId ) ; } else { this . muted . remove ( userId ) ; } } | Sets the muted state of the user with the given id . |
30,876 | public void setDeafened ( long userId , boolean deafened ) { if ( deafened ) { this . deafened . add ( userId ) ; } else { this . deafened . remove ( userId ) ; } } | Sets the deafened state of the user with the given id . |
30,877 | private void dispatchEditEvent ( MessageEditEvent event ) { Optional < Server > optionalServer = event . getChannel ( ) . asServerChannel ( ) . map ( ServerChannel :: getServer ) ; api . getEventDispatcher ( ) . dispatchMessageEditEvent ( optionalServer . map ( DispatchQueueSelector . class :: cast ) . orElse ( api ) , event . getMessageId ( ) , optionalServer . orElse ( null ) , event . getChannel ( ) , event ) ; } | Dispatches an edit event . |
30,878 | public void addEntries ( JsonNode data ) { for ( JsonNode webhookJson : data . get ( "webhooks" ) ) { boolean alreadyAdded = involvedWebhooks . stream ( ) . anyMatch ( webhook -> webhook . getId ( ) == webhookJson . get ( "id" ) . asLong ( ) ) ; if ( ! alreadyAdded ) { involvedWebhooks . add ( new WebhookImpl ( api , webhookJson ) ) ; } } for ( JsonNode userJson : data . get ( "users" ) ) { boolean alreadyAdded = involvedUsers . stream ( ) . anyMatch ( user -> user . getId ( ) == userJson . get ( "id" ) . asLong ( ) ) ; if ( ! alreadyAdded ) { involvedUsers . add ( ( ( DiscordApiImpl ) api ) . getOrCreateUser ( userJson ) ) ; } } for ( JsonNode entry : data . get ( "audit_log_entries" ) ) { entries . add ( new AuditLogEntryImpl ( this , entry ) ) ; } } | Adds entries to the audit log . |
30,879 | public void handlePacket ( final JsonNode packet ) { if ( async ) { executorService . submit ( ( ) -> { try { handle ( packet ) ; } catch ( Throwable t ) { logger . warn ( "Couldn't handle packet of type {}. Please contact the developer! (packet: {})" , getType ( ) , packet , t ) ; } } ) ; } else { try { handle ( packet ) ; } catch ( Throwable t ) { logger . warn ( "Couldn't handle packet of type {}. Please contact the developer! (packet: {})" , getType ( ) , packet , t ) ; } } } | Handles the packet . |
30,880 | private static String getGateway ( DiscordApiImpl api ) { gatewayReadLock . lock ( ) ; if ( gateway == null ) { gatewayReadLock . unlock ( ) ; gatewayWriteLock . lock ( ) ; try { if ( gateway == null ) { gateway = new RestRequest < String > ( api , RestMethod . GET , RestEndpoint . GATEWAY ) . includeAuthorizationHeader ( false ) . execute ( result -> result . getJsonBody ( ) . get ( "url" ) . asText ( ) ) . join ( ) ; } gatewayReadLock . lock ( ) ; } finally { gatewayWriteLock . unlock ( ) ; } } try { return gateway ; } finally { gatewayReadLock . unlock ( ) ; } } | Gets the gateway used to connect . If no gateway was requested or set so far it will request one from Discord . |
30,881 | public static void setGateway ( String gateway ) { gatewayWriteLock . lock ( ) ; try { DiscordWebSocketAdapter . gateway = gateway ; } finally { gatewayWriteLock . unlock ( ) ; } } | Sets the gateway used to connect . |
30,882 | public void disconnect ( ) { reconnect = false ; websocket . get ( ) . sendClose ( WebSocketCloseReason . DISCONNECT . getNumericCloseCode ( ) ) ; api . getThreadPool ( ) . getDaemonScheduler ( ) . schedule ( ( ) -> heartbeatTimer . updateAndGet ( future -> { if ( future != null ) { future . cancel ( false ) ; } return null ; } ) , 1 , TimeUnit . MINUTES ) ; } | Disconnects from the websocket . |
30,883 | private void waitForIdentifyRateLimit ( ) { String token = api . getPrefixedToken ( ) ; connectionDelaySemaphorePerAccount . computeIfAbsent ( token , key -> new Semaphore ( 1 ) ) . acquireUninterruptibly ( ) ; for ( long delay = 5100 - ( System . currentTimeMillis ( ) - lastIdentificationPerAccount . getOrDefault ( token , 0L ) ) ; delay > 0 ; delay = 5100 - ( System . currentTimeMillis ( ) - lastIdentificationPerAccount . getOrDefault ( token , 0L ) ) ) { logger . debug ( "Delaying connecting by {}ms" , delay ) ; try { Thread . sleep ( delay ) ; } catch ( InterruptedException ignored ) { } } } | Identification is rate limited to once every 5 seconds so don t try to more often per account even in different instances . This method waits for the identification rate limit to be over then returns . |
30,884 | private Future < ? > startHeartbeat ( final WebSocket websocket , final int heartbeatInterval ) { heartbeatAckReceived . set ( true ) ; return api . getThreadPool ( ) . getScheduler ( ) . scheduleWithFixedDelay ( ( ) -> { try { if ( heartbeatAckReceived . getAndSet ( false ) ) { sendHeartbeat ( websocket ) ; logger . debug ( "Sent heartbeat (interval: {})" , heartbeatInterval ) ; } else { websocket . sendClose ( WebSocketCloseReason . HEARTBEAT_NOT_PROPERLY_ANSWERED . getNumericCloseCode ( ) , WebSocketCloseReason . HEARTBEAT_NOT_PROPERLY_ANSWERED . getCloseReason ( ) ) ; } } catch ( Throwable t ) { logger . error ( "Failed to send heartbeat or close web socket!" , t ) ; } } , 0 , heartbeatInterval , TimeUnit . MILLISECONDS ) ; } | Starts the heartbeat . |
30,885 | private void sendHeartbeat ( WebSocket websocket ) { ObjectNode heartbeatPacket = JsonNodeFactory . instance . objectNode ( ) ; heartbeatPacket . put ( "op" , GatewayOpcode . HEARTBEAT . getCode ( ) ) ; heartbeatPacket . put ( "d" , lastSeq ) ; WebSocketFrame heartbeatFrame = WebSocketFrame . createTextFrame ( heartbeatPacket . toString ( ) ) ; nextHeartbeatFrame . set ( heartbeatFrame ) ; websocket . sendFrame ( heartbeatFrame ) ; } | Sends the heartbeat . |
30,886 | private void sendResume ( WebSocket websocket ) { ObjectNode resumePacket = JsonNodeFactory . instance . objectNode ( ) . put ( "op" , GatewayOpcode . RESUME . getCode ( ) ) ; resumePacket . putObject ( "d" ) . put ( "token" , api . getPrefixedToken ( ) ) . put ( "session_id" , sessionId ) . put ( "seq" , lastSeq ) ; logger . debug ( "Sending resume packet" ) ; websocket . sendText ( resumePacket . toString ( ) ) ; } | Sends the resume packet . |
30,887 | private void sendIdentify ( WebSocket websocket ) { ObjectNode identifyPacket = JsonNodeFactory . instance . objectNode ( ) . put ( "op" , GatewayOpcode . IDENTIFY . getCode ( ) ) ; ObjectNode data = identifyPacket . putObject ( "d" ) ; String token = api . getPrefixedToken ( ) ; data . put ( "token" , token ) . put ( "compress" , true ) . put ( "large_threshold" , 250 ) . putObject ( "properties" ) . put ( "$os" , System . getProperty ( "os.name" ) ) . put ( "$browser" , "Javacord" ) . put ( "$device" , "Javacord" ) . put ( "$referrer" , "" ) . put ( "$referring_domain" , "" ) ; if ( api . getTotalShards ( ) > 1 ) { data . putArray ( "shard" ) . add ( api . getCurrentShard ( ) ) . add ( api . getTotalShards ( ) ) ; } synchronized ( identifyFrameListeners ) { websocket . removeListeners ( identifyFrameListeners ) ; identifyFrameListeners . clear ( ) ; } WebSocketFrame identifyFrame = WebSocketFrame . createTextFrame ( identifyPacket . toString ( ) ) ; lastSentFrameWasIdentify . set ( identifyFrame , false ) ; WebSocketAdapter identifyFrameListener = new WebSocketAdapter ( ) { public void onFrameSent ( WebSocket websocket , WebSocketFrame frame ) { if ( lastSentFrameWasIdentify . isMarked ( ) ) { if ( ! nextHeartbeatFrame . compareAndSet ( frame , null ) ) { lastSentFrameWasIdentify . set ( null , false ) ; websocket . removeListener ( this ) ; identifyFrameListeners . remove ( this ) ; } } else { if ( lastSentFrameWasIdentify . compareAndSet ( frame , null , false , true ) ) { lastIdentificationPerAccount . put ( token , System . currentTimeMillis ( ) ) ; connectionDelaySemaphorePerAccount . get ( token ) . release ( ) ; } } } } ; identifyFrameListeners . add ( identifyFrameListener ) ; websocket . addListener ( identifyFrameListener ) ; logger . debug ( "Sending identify packet" ) ; websocket . sendFrame ( identifyFrame ) ; } | Sends the identify packet . |
30,888 | public void sendVoiceStateUpdate ( Server server , ServerVoiceChannel channel , Boolean selfMuted , Boolean selfDeafened ) { ObjectNode updateVoiceStatePacket = JsonNodeFactory . instance . objectNode ( ) . put ( "op" , GatewayOpcode . VOICE_STATE_UPDATE . getCode ( ) ) ; if ( server == null ) { if ( channel == null ) { throw new IllegalArgumentException ( "Either server or channel must be given" ) ; } server = channel . getServer ( ) ; } User yourself = api . getYourself ( ) ; updateVoiceStatePacket . putObject ( "d" ) . put ( "guild_id" , server . getIdAsString ( ) ) . put ( "channel_id" , ( channel == null ) ? null : channel . getIdAsString ( ) ) . put ( "self_mute" , ( selfMuted == null ) ? server . isSelfMuted ( yourself ) : selfMuted ) . put ( "self_deaf" , ( selfDeafened == null ) ? server . isSelfDeafened ( yourself ) : selfDeafened ) ; logger . debug ( "Sending VOICE_STATE_UPDATE packet for channel {} on server {}" , channel , server ) ; websocket . get ( ) . sendText ( updateVoiceStatePacket . toString ( ) ) ; } | Sends the voice state update packet . |
30,889 | private void registerHandlers ( ) { addHandler ( new ReadyHandler ( api ) ) ; addHandler ( new ResumedHandler ( api ) ) ; addHandler ( new GuildBanAddHandler ( api ) ) ; addHandler ( new GuildBanRemoveHandler ( api ) ) ; addHandler ( new GuildCreateHandler ( api ) ) ; addHandler ( new GuildDeleteHandler ( api ) ) ; addHandler ( new GuildMembersChunkHandler ( api ) ) ; addHandler ( new GuildMemberAddHandler ( api ) ) ; addHandler ( new GuildMemberRemoveHandler ( api ) ) ; addHandler ( new GuildMemberUpdateHandler ( api ) ) ; addHandler ( new GuildUpdateHandler ( api ) ) ; addHandler ( new VoiceStateUpdateHandler ( api ) ) ; addHandler ( new GuildRoleCreateHandler ( api ) ) ; addHandler ( new GuildRoleDeleteHandler ( api ) ) ; addHandler ( new GuildRoleUpdateHandler ( api ) ) ; addHandler ( new GuildEmojisUpdateHandler ( api ) ) ; addHandler ( new ChannelCreateHandler ( api ) ) ; addHandler ( new ChannelDeleteHandler ( api ) ) ; addHandler ( new ChannelPinsUpdateHandler ( api ) ) ; addHandler ( new ChannelUpdateHandler ( api ) ) ; addHandler ( new WebhooksUpdateHandler ( api ) ) ; addHandler ( new PresencesReplaceHandler ( api ) ) ; addHandler ( new PresenceUpdateHandler ( api ) ) ; addHandler ( new TypingStartHandler ( api ) ) ; addHandler ( new UserUpdateHandler ( api ) ) ; addHandler ( new MessageCreateHandler ( api ) ) ; addHandler ( new MessageDeleteBulkHandler ( api ) ) ; addHandler ( new MessageDeleteHandler ( api ) ) ; addHandler ( new MessageUpdateHandler ( api ) ) ; addHandler ( new MessageReactionAddHandler ( api ) ) ; addHandler ( new MessageReactionRemoveAllHandler ( api ) ) ; addHandler ( new MessageReactionRemoveHandler ( api ) ) ; } | Registers all handlers . |
30,890 | public void updateStatus ( ) { Optional < Activity > activity = api . getActivity ( ) ; ObjectNode updateStatus = JsonNodeFactory . instance . objectNode ( ) . put ( "op" , GatewayOpcode . STATUS_UPDATE . getCode ( ) ) ; ObjectNode data = updateStatus . putObject ( "d" ) . put ( "status" , api . getStatus ( ) . getStatusString ( ) ) . put ( "afk" , false ) . putNull ( "since" ) ; ObjectNode activityJson = data . putObject ( "game" ) ; activityJson . put ( "name" , activity . isPresent ( ) ? activity . get ( ) . getName ( ) : null ) ; activityJson . put ( "type" , activity . map ( g -> g . getType ( ) . getId ( ) ) . orElse ( 0 ) ) ; activity . ifPresent ( g -> g . getStreamingUrl ( ) . ifPresent ( url -> activityJson . put ( "url" , url ) ) ) ; logger . debug ( "Updating status (content: {})" , updateStatus ) ; websocket . get ( ) . sendText ( updateStatus . toString ( ) ) ; } | Sends the update status packet . |
30,891 | public void queueRequestGuildMembers ( Server server ) { logger . debug ( "Queued {} for request guild members packet" , server ) ; requestGuildMembersQueue . add ( server . getId ( ) ) ; } | Adds a server id to be queued for the request guild members packet . |
30,892 | public static < T > Indexed < T > index ( long index , T value ) { return new Indexed < > ( index , value ) ; } | Combine an index and a value into an indexed value . |
30,893 | public static < S , O > Transition < S , O > to ( S newState , O ... outputs ) { return to ( newState , Stream . of ( outputs ) ) ; } | Create a transition to a new state with zero or more outputs . |
30,894 | public static < S , O > Transition < S , O > to ( S newState , Stream < O > outputs ) { return new Transition < > ( newState , outputs ) ; } | Create a transition to a new state with the given outputs . |
30,895 | public static < T , Y extends Comparable < Y > > Collector < T , ? , Optional < T > > maxBy ( Function < T , Y > projection ) { return maxBy ( projection , Comparable :: compareTo ) ; } | Find the item for which the supplied projection returns the maximum value . |
30,896 | public static < L , R , O > Stream < O > zip ( Stream < L > lefts , Stream < R > rights , BiFunction < L , R , O > combiner ) { return StreamSupport . stream ( ZippingSpliterator . zipping ( lefts . spliterator ( ) , rights . spliterator ( ) , combiner ) , false ) . onClose ( closerFor ( lefts , rights ) ) ; } | Zip together the left and right streams until either runs out of values . Each pair of values is combined into a single value using the supplied combiner function . |
30,897 | public static < L , M , R , O > Stream < O > zip ( Stream < L > lefts , Stream < M > middles , Stream < R > rights , TriFunction < L , M , R , O > combiner ) { return StreamSupport . stream ( TriZippingSpliterator . zipping ( lefts . spliterator ( ) , middles . spliterator ( ) , rights . spliterator ( ) , combiner ) , false ) . onClose ( closerFor ( lefts , middles , rights ) ) ; } | Zip together the left middle and right streams until any stream runs out of values . Each triple of values is combined into a single value using the supplied combiner function . |
30,898 | public static < T , O > Stream < O > zip ( List < Stream < T > > streams , Function < List < T > , O > combiner ) { List < Spliterator < T > > spliterators = streams . stream ( ) . map ( Stream :: spliterator ) . collect ( Collectors . toList ( ) ) ; return StreamSupport . stream ( ListZippingSpliterator . zipping ( spliterators , combiner ) , false ) . onClose ( closerFor ( streams ) ) ; } | Zip together a list of streams until one of them runs out of values . Each tuple of values is combined into a single value using the supplied combiner function . |
30,899 | public static < T > Stream < T > takeWhile ( Stream < T > source , Predicate < T > condition ) { return StreamSupport . stream ( TakeWhileSpliterator . over ( source . spliterator ( ) , condition ) , false ) . onClose ( source :: close ) ; } | Construct a stream which takes values from the source stream for as long as they meet the supplied condition and stops as soon as a value is encountered which does not meet the condition . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.