idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
30,700
public static < K , V , A > int occurrencesOfAttribute ( Map < K , V > map , Function < ? super V , ? extends A > function , A object ) { return Iterate . count ( map . values ( ) , Predicates . attributeEqual ( function , object ) ) ; }
Return the number of occurrences where object is equal to the specified attribute in the specified map .
30,701
public static < E , S extends SortedSet < E > > SynchronizedSortedSet < E > of ( S set ) { return new SynchronizedSortedSet < E > ( SortedSetAdapter . adapt ( set ) ) ; }
This method will take a MutableSortedSet and wrap it directly in a SynchronizedSortedSet . It will take any other non - GS - collection and first adapt it will a SortedSetAdapter and then return a SynchronizedSortedSet that wraps the adapter .
30,702
public static < E , S extends SortedSet < E > > MutableSortedSet < E > of ( S set , Object lock ) { return new SynchronizedSortedSet < E > ( SortedSetAdapter . adapt ( set ) , lock ) ; }
This method will take a MutableSortedSet and wrap it directly in a SynchronizedSortedSet . It will take any other non - GS - collection and first adapt it will a SortedSetAdapter and then return a SynchronizedSortedSet that wraps the adapter . Additionally a developer specifies which lock to use with the collection .
30,703
public static < E , S extends MutableSortedBag < E > > UnmodifiableSortedBag < E > of ( S bag ) { if ( bag == null ) { throw new IllegalArgumentException ( "cannot create an UnmodifiableSortedBag for null" ) ; } return new UnmodifiableSortedBag < E > ( bag ) ; }
This method will take a MutableSortedBag and wrap it directly in a UnmodifiableSortedBag .
30,704
public static < E , S extends Set < E > > SynchronizedMutableSet < E > of ( S set ) { return new SynchronizedMutableSet < E > ( SetAdapter . adapt ( set ) ) ; }
This method will take a MutableSet and wrap it directly in a SynchronizedMutableSet . It will take any other non - GS - collection and first adapt it will a SetAdapter and then return a SynchronizedMutableSet that wraps the adapter .
30,705
public static < K , V , M extends Map < K , V > > UnmodifiableMutableMap < K , V > of ( M map ) { if ( map == null ) { throw new IllegalArgumentException ( "cannot create a UnmodifiableMutableMap for null" ) ; } return new UnmodifiableMutableMap < K , V > ( MapAdapter . adapt ( map ) ) ; }
This method will take a MutableMap and wrap it directly in a UnmodifiableMutableMap . It will take any other non - GS - map and first adapt it will a MapAdapter and then return a UnmodifiableMutableMap that wraps the adapter .
30,706
public static < E , S extends SortedSet < E > > UnmodifiableSortedSet < E > of ( S set ) { if ( set == null ) { throw new IllegalArgumentException ( "cannot create an UnmodifiableSortedSet for null" ) ; } return new UnmodifiableSortedSet < E > ( SortedSetAdapter . adapt ( set ) ) ; }
This method will take a MutableSortedSet and wrap it directly in a UnmodifiableSortedSet . It will take any other non - GS - SortedSet and first adapt it will a SortedSetAdapter and then return a UnmodifiableSortedSet that wraps the adapter .
30,707
public static < E , S extends Set < E > > UnmodifiableMutableSet < E > of ( S set ) { if ( set == null ) { throw new IllegalArgumentException ( "cannot create an UnmodifiableMutableSet for null" ) ; } return new UnmodifiableMutableSet < E > ( SetAdapter . adapt ( set ) ) ; }
This method will take a MutableSet and wrap it directly in a UnmodifiableMutableSet . It will take any other non - GS - set and first adapt it will a SetAdapter and then return a UnmodifiableMutableSet that wraps the adapter .
30,708
public static < T > SerializableComparator < Pair < T , ? > > byFirstOfPair ( Comparator < ? super T > comparator ) { return new ByFirstOfPairComparator < T > ( comparator ) ; }
Creates a comparator for pairs by using an existing comparator that only compares the first element of the pair
30,709
public static < T > SerializableComparator < Pair < ? , T > > bySecondOfPair ( Comparator < ? super T > comparator ) { return new BySecondOfPairComparator < T > ( comparator ) ; }
Creates a comparator for pairs by using an existing comparator that only compares the second element of the pair
30,710
public static < T > void reverseForEach ( ArrayList < T > list , Procedure < ? super T > procedure ) { if ( ! list . isEmpty ( ) ) { ArrayListIterate . forEach ( list , list . size ( ) - 1 , 0 , procedure ) ; } }
Reverses over the List in reverse order executing the Procedure for each element
30,711
public static IntInterval oneToBy ( int count , int step ) { if ( count < 1 ) { throw new IllegalArgumentException ( "Only positive ranges allowed using oneToBy" ) ; } return IntInterval . fromToBy ( 1 , count , step ) ; }
Returns an IntInterval starting from 1 to the specified count value with a step value of step .
30,712
public static IntInterval fromTo ( int from , int to ) { if ( from <= to ) { return IntInterval . fromToBy ( from , to , 1 ) ; } return IntInterval . fromToBy ( from , to , - 1 ) ; }
Returns an IntInterval starting from the value from to the specified value to with a step value of 1 .
30,713
public static IntInterval evensFromTo ( int from , int to ) { if ( from % 2 != 0 ) { if ( from < to ) { from ++ ; } else { from -- ; } } if ( to % 2 != 0 ) { if ( to > from ) { to -- ; } else { to ++ ; } } return IntInterval . fromToBy ( from , to , to > from ? 2 : - 2 ) ; }
Returns an IntInterval representing the even values from the value from to the value to .
30,714
public static IntInterval oddsFromTo ( int from , int to ) { if ( from % 2 == 0 ) { if ( from < to ) { from ++ ; } else { from -- ; } } if ( to % 2 == 0 ) { if ( to > from ) { to -- ; } else { to ++ ; } } return IntInterval . fromToBy ( from , to , to > from ? 2 : - 2 ) ; }
Returns an IntInterval representing the odd values from the value from to the value to .
30,715
public static IntInterval fromToBy ( int from , int to , int stepBy ) { if ( stepBy == 0 ) { throw new IllegalArgumentException ( "Cannot use a step by of 0" ) ; } if ( from > to && stepBy > 0 || from < to && stepBy < 0 ) { throw new IllegalArgumentException ( "Step by is incorrect for the range" ) ; } return new IntInterval ( from , to , stepBy ) ; }
Returns an IntInterval for the range of integers inclusively between from and to with the specified stepBy value .
30,716
public < P1 , P2 > V putIfAbsentGetIfPresent ( K key , Function2 < K , V , K > keyTransformer , Function3 < P1 , P2 , K , V > factory , P1 param1 , P2 param2 ) { int hash = this . hash ( key ) ; Object [ ] currentArray = this . table ; V newValue = null ; boolean createdValue = false ; while ( true ) { int length = currentArray . length ; int index = ConcurrentHashMapUnsafe . indexFor ( hash , length ) ; Object o = ConcurrentHashMapUnsafe . arrayAt ( currentArray , index ) ; if ( o == RESIZED || o == RESIZING ) { currentArray = this . helpWithResizeWhileCurrentIndex ( currentArray , index ) ; } else { Entry < K , V > e = ( Entry < K , V > ) o ; while ( e != null ) { Object candidate = e . getKey ( ) ; if ( candidate . equals ( key ) ) { return e . getValue ( ) ; } e = e . getNext ( ) ; } if ( ! createdValue ) { createdValue = true ; newValue = factory . value ( param1 , param2 , key ) ; if ( newValue == null ) { return null ; } key = keyTransformer . value ( key , newValue ) ; } Entry < K , V > newEntry = new Entry < K , V > ( key , newValue , ( Entry < K , V > ) o ) ; if ( ConcurrentHashMapUnsafe . casArrayAt ( currentArray , index , o , newEntry ) ) { this . incrementSizeAndPossiblyResize ( currentArray , length , o ) ; return null ; } } } }
It puts an object into the map based on the key . It uses a copy of the key converted by transformer .
30,717
public static < E , RI extends RichIterable < E > > UnmodifiableRichIterable < E > of ( RI iterable ) { if ( iterable == null ) { throw new IllegalArgumentException ( "cannot create a UnmodifiableRichIterable for null" ) ; } return new UnmodifiableRichIterable < E > ( iterable ) ; }
This method will take a RichIterable and wrap it directly in a UnmodifiableRichIterable .
30,718
public static Predicates < Object > equal ( Object object ) { if ( object == null ) { return Predicates . isNull ( ) ; } return new EqualPredicate ( object ) ; }
Tests for equality .
30,719
public static < T extends Comparable < ? super T > > Predicates < T > betweenInclusive ( T from , T to ) { Predicates . failIfDifferentTypes ( from , to ) ; return new BetweenInclusive < T > ( from , to ) ; }
Creates a predicate which returns true if an object passed to accept method is within the range inclusive of the from and to values .
30,720
public static < T extends Comparable < ? super T > > Predicates < T > betweenExclusive ( T from , T to ) { Predicates . failIfDifferentTypes ( from , to ) ; return new BetweenExclusive < T > ( from , to ) ; }
Creates a predicate which returns true if an object passed to accept method is within the range exclusive of the from and to values .
30,721
public static < T extends Comparable < ? super T > > Predicates < T > betweenInclusiveFrom ( T from , T to ) { Predicates . failIfDifferentTypes ( from , to ) ; return new BetweenInclusiveFrom < T > ( from , to ) ; }
Creates a predicate which returns true if an object passed to accept method is within the range inclusive of the from and exclusive from the to value .
30,722
public static < T extends Comparable < ? super T > > Predicates < T > betweenInclusiveTo ( T from , T to ) { Predicates . failIfDifferentTypes ( from , to ) ; return new BetweenInclusiveTo < T > ( from , to ) ; }
Creates a predicate which returns true if an object passed to accept method is within the range exclusive of the from and inclusive of the to value .
30,723
public static Predicates < Object > in ( Iterable < ? > iterable ) { if ( iterable instanceof SetIterable < ? > ) { return new InSetIterablePredicate ( ( SetIterable < ? > ) iterable ) ; } if ( iterable instanceof Set < ? > ) { return new InSetPredicate ( ( Set < ? > ) iterable ) ; } if ( iterable instanceof Collection < ? > && ( ( Collection < ? > ) iterable ) . size ( ) <= SMALL_COLLECTION_THRESHOLD ) { return new InCollectionPredicate ( ( Collection < ? > ) iterable ) ; } return new InSetIterablePredicate ( UnifiedSet . newSet ( iterable ) ) ; }
Creates a predicate which returns true if an object passed to accept method is contained in the iterable .
30,724
public static < T > Predicates < T > attributeIn ( Function < ? super T , ? > function , Iterable < ? > iterable ) { return new AttributePredicate < T , Object > ( function , Predicates . in ( iterable ) ) ; }
Creates a predicate which returns true if an attribute selected from an object passed to accept method is contained in the iterable .
30,725
public static Predicates < Object > notIn ( Iterable < ? > iterable ) { if ( iterable instanceof SetIterable < ? > ) { return new NotInSetIterablePredicate ( ( SetIterable < ? > ) iterable ) ; } if ( iterable instanceof Set < ? > ) { return new NotInSetPredicate ( ( Set < ? > ) iterable ) ; } if ( iterable instanceof Collection < ? > && ( ( Collection < ? > ) iterable ) . size ( ) <= SMALL_COLLECTION_THRESHOLD ) { return new NotInCollectionPredicate ( ( Collection < ? > ) iterable ) ; } return new NotInSetIterablePredicate ( UnifiedSet . newSet ( iterable ) ) ; }
Creates a predicate which returns true if an object passed to accept method is not contained in the iterable .
30,726
public static < T > Predicates < T > attributeNotIn ( Function < ? super T , ? > function , Iterable < ? > iterable ) { return new AttributePredicate < T , Object > ( function , Predicates . notIn ( iterable ) ) ; }
Creates a predicate which returns true if an attribute selected from an object passed to accept method is not contained in the iterable .
30,727
public static < T > LazyIterable < T > adapt ( Iterable < T > iterable ) { return new LazyIterableAdapter < T > ( iterable ) ; }
Creates a deferred rich iterable for the specified iterable
30,728
public static < T > LazyIterable < T > select ( Iterable < T > iterable , Predicate < ? super T > predicate ) { return new SelectIterable < T > ( iterable , predicate ) ; }
Creates a deferred filtering iterable for the specified iterable
30,729
public static < T > LazyIterable < T > reject ( Iterable < T > iterable , Predicate < ? super T > predicate ) { return new RejectIterable < T > ( iterable , predicate ) ; }
Creates a deferred negative filtering iterable for the specified iterable
30,730
public static < T , V > LazyIterable < V > collect ( Iterable < T > iterable , Function < ? super T , ? extends V > function ) { return new CollectIterable < T , V > ( iterable , function ) ; }
Creates a deferred transforming iterable for the specified iterable
30,731
public static < T , V > LazyIterable < V > flatCollect ( Iterable < T > iterable , Function < ? super T , ? extends Iterable < V > > function ) { return new FlatCollectIterable < T , V > ( iterable , function ) ; }
Creates a deferred flattening iterable for the specified iterable
30,732
public static < T , V > LazyIterable < V > collectIf ( Iterable < T > iterable , Predicate < ? super T > predicate , Function < ? super T , ? extends V > function ) { return LazyIterate . select ( iterable , predicate ) . collect ( function ) ; }
Creates a deferred filtering and transforming iterable for the specified iterable
30,733
public static < T > LazyIterable < T > take ( Iterable < T > iterable , int count ) { return new TakeIterable < T > ( iterable , count ) ; }
Creates a deferred take iterable for the specified iterable using the specified count as the limit
30,734
public static < T > LazyIterable < T > drop ( Iterable < T > iterable , int count ) { return new DropIterable < T > ( iterable , count ) ; }
Creates a deferred drop iterable for the specified iterable using the specified count as the size to drop
30,735
public static < T > LazyIterable < T > distinct ( Iterable < T > iterable ) { return new DistinctIterable < T > ( iterable ) ; }
Creates a deferred distinct iterable for the specified iterable
30,736
public static < T > LazyIterable < T > concatenate ( Iterable < T > ... iterables ) { return CompositeIterable . with ( iterables ) ; }
Combines iterables into a deferred composite iterable
30,737
public static < T > LazyIterable < T > tap ( Iterable < T > iterable , Procedure < ? super T > procedure ) { return new TapIterable < T > ( iterable , procedure ) ; }
Creates a deferred tap iterable for the specified iterable .
30,738
public static < E , L extends List < E > > UnmodifiableMutableList < E > of ( L list ) { if ( list == null ) { throw new IllegalArgumentException ( "cannot create an UnmodifiableMutableList for null" ) ; } if ( list instanceof RandomAccess ) { return new RandomAccessUnmodifiableMutableList < E > ( RandomAccessListAdapter . adapt ( list ) ) ; } return new UnmodifiableMutableList < E > ( ListAdapter . adapt ( list ) ) ; }
This method will take a MutableList and wrap it directly in a UnmodifiableMutableList . It will take any other non - GS - list and first adapt it will a ListAdapter and then return a UnmodifiableMutableList that wraps the adapter .
30,739
public static < T , S extends MutableStack < T > > SynchronizedStack < T > of ( S stack ) { return new SynchronizedStack < T > ( stack ) ; }
This method will take a MutableStack and wrap it directly in a SynchronizedStack .
30,740
PrintStream getPrintStream ( ) { PrintStream result = ( PrintStream ) streams . get ( ) ; return ( ( result == null ) ? defaultPrintStream : result ) ; }
Returns this thread s PrintStream
30,741
private NailStats getOrCreateStatsFor ( Class nailClass ) { NailStats result ; synchronized ( allNailStats ) { String nailClassName = nailClass . getName ( ) ; result = allNailStats . get ( nailClassName ) ; if ( result == null ) { result = new NailStats ( nailClassName ) ; allNailStats . put ( nailClassName , result ) ; } } return result ; }
Returns the current NailStats object for the specified class creating a new one if necessary
30,742
public void shutdown ( ) { if ( shutdown . getAndSet ( true ) ) { return ; } try { serversocket . close ( ) ; } catch ( Throwable ex ) { LOG . log ( Level . WARNING , "Exception closing server socket on Nailgun server shutdown" , ex ) ; } }
Shuts down the server . The server will stop listening and its thread will finish . Any running nails will be allowed to finish .
30,743
public void run ( ) { originalSecurityManager = System . getSecurityManager ( ) ; System . setSecurityManager ( new NGSecurityManager ( originalSecurityManager ) ) ; if ( ! ( System . in instanceof ThreadLocalInputStream ) ) { System . setIn ( new ThreadLocalInputStream ( in ) ) ; } if ( ! ( System . out instanceof ThreadLocalPrintStream ) ) { System . setOut ( new ThreadLocalPrintStream ( out ) ) ; } if ( ! ( System . err instanceof ThreadLocalPrintStream ) ) { System . setErr ( new ThreadLocalPrintStream ( err ) ) ; } try { if ( listeningAddress . isInetAddress ( ) ) { if ( listeningAddress . getInetAddress ( ) == null ) { serversocket = new ServerSocket ( listeningAddress . getInetPort ( ) ) ; } else { serversocket = new ServerSocket ( listeningAddress . getInetPort ( ) , 0 , listeningAddress . getInetAddress ( ) ) ; } } else { if ( Platform . isWindows ( ) ) { boolean requireStrictLength = true ; serversocket = new NGWin32NamedPipeServerSocket ( listeningAddress . getLocalAddress ( ) , requireStrictLength ) ; } else { serversocket = new NGUnixDomainServerSocket ( listeningAddress . getLocalAddress ( ) ) ; } } String portDescription ; if ( listeningAddress . isInetAddress ( ) && listeningAddress . getInetPort ( ) == 0 ) { int runningPort = getPort ( ) ; while ( runningPort == 0 ) { try { Thread . sleep ( 50 ) ; } catch ( Throwable toIgnore ) { } runningPort = getPort ( ) ; } portDescription = ", port " + runningPort ; } else { portDescription = "" ; } running . set ( true ) ; out . println ( "NGServer " + NGConstants . VERSION + " started on " + listeningAddress . toString ( ) + portDescription + "." ) ; while ( ! shutdown . get ( ) ) { Socket socket = serversocket . accept ( ) ; sessionPool . take ( ) . run ( socket ) ; } } catch ( IOException ex ) { if ( ! shutdown . get ( ) ) { throw new RuntimeException ( ex ) ; } } try { sessionPool . shutdown ( ) ; } catch ( Throwable ex ) { LOG . log ( Level . WARNING , "Exception shutting down Nailgun server" , ex ) ; } System . setIn ( in ) ; System . setOut ( out ) ; System . setErr ( err ) ; System . setSecurityManager ( originalSecurityManager ) ; running . set ( false ) ; }
Listens for new connections and launches NGSession threads to process them .
30,744
public Set getAliases ( ) { Set result = new java . util . TreeSet ( ) ; synchronized ( aliases ) { result . addAll ( aliases . values ( ) ) ; } return ( result ) ; }
Returns a Set that is a snapshot of the Alias list . Modifications to this Set will not impact the AliasManager in any way .
30,745
private static String getVersion ( ) { Properties props = new Properties ( ) ; try ( InputStream is = NGConstants . class . getResourceAsStream ( "/META-INF/maven/com.facebook/nailgun-server/pom.properties" ) ) { props . load ( is ) ; } catch ( Throwable e ) { } return props . getProperty ( "version" , System . getProperty ( "nailgun.server.version" , "[UNKNOWN]" ) ) ; }
Loads the version number from a file generated by Maven .
30,746
InputStream getInputStream ( ) { InputStream result = ( InputStream ) streams . get ( ) ; return ( ( result == null ) ? defaultInputStream : result ) ; }
Returns this thread s InputStream
30,747
private static Set getCryptoImpls ( String serviceType ) { Set result = new TreeSet ( ) ; Provider [ ] providers = Security . getProviders ( ) ; for ( int i = 0 ; i < providers . length ; i ++ ) { Set keys = providers [ i ] . keySet ( ) ; for ( Object okey : providers [ i ] . keySet ( ) ) { String key = ( String ) okey ; key = key . split ( " " ) [ 0 ] ; if ( key . startsWith ( serviceType + "." ) ) { result . add ( key . substring ( serviceType . length ( ) + 1 ) ) ; } else if ( key . startsWith ( "Alg.Alias." + serviceType + "." ) ) { result . add ( key . substring ( serviceType . length ( ) + 11 ) ) ; } } } return result ; }
Provides a list of algorithms for the specified service ( which for our purposes is MessageDigest .
30,748
NGSession take ( ) { synchronized ( lock ) { if ( done ) { throw new UnsupportedOperationException ( "NGSession pool is shutting down" ) ; } NGSession session = idlePool . poll ( ) ; if ( session == null ) { session = instanceCreator . get ( ) ; session . start ( ) ; } workingPool . add ( session ) ; return session ; } }
Returns an NGSession from the pool or creates one if necessary
30,749
void give ( NGSession session ) { synchronized ( lock ) { if ( done ) { return ; } workingPool . remove ( session ) ; if ( idlePool . size ( ) < maxIdleSessions ) { idlePool . add ( session ) ; return ; } } session . shutdown ( ) ; }
Returns an NGSession to the pool . The pool may choose to shutdown the thread if idle pool is full .
30,750
void shutdown ( ) throws InterruptedException { List < NGSession > allSessions ; synchronized ( lock ) { done = true ; allSessions = Stream . concat ( workingPool . stream ( ) , idlePool . stream ( ) ) . collect ( Collectors . toList ( ) ) ; idlePool . clear ( ) ; workingPool . clear ( ) ; } for ( NGSession session : allSessions ) { session . shutdown ( ) ; } long start = System . nanoTime ( ) ; for ( NGSession session : allSessions ) { long timeout = NGConstants . SESSION_TERMINATION_TIMEOUT_MILLIS - TimeUnit . MILLISECONDS . convert ( System . nanoTime ( ) - start , TimeUnit . NANOSECONDS ) ; if ( timeout < 1 ) { timeout = 1 ; } session . join ( timeout ) ; if ( session . isAlive ( ) ) { throw new IllegalStateException ( "NGSession has not completed in " + NGConstants . SESSION_TERMINATION_TIMEOUT_MILLIS + " ms" ) ; } } }
Shuts down the pool . The function waits for running nails to finish .
30,751
CommandContext readCommandContext ( ) throws IOException { List < String > remoteArgs = new ArrayList ( ) ; Properties remoteEnv = new Properties ( ) ; String cwd = null ; String command = null ; while ( command == null ) { int bytesToRead = in . readInt ( ) ; byte chunkType = in . readByte ( ) ; byte [ ] b = new byte [ bytesToRead ] ; in . readFully ( b ) ; String line = new String ( b , "UTF-8" ) ; switch ( chunkType ) { case NGConstants . CHUNKTYPE_ARGUMENT : remoteArgs . add ( line ) ; break ; case NGConstants . CHUNKTYPE_ENVIRONMENT : int equalsIndex = line . indexOf ( '=' ) ; if ( equalsIndex > 0 ) { remoteEnv . setProperty ( line . substring ( 0 , equalsIndex ) , line . substring ( equalsIndex + 1 ) ) ; } break ; case NGConstants . CHUNKTYPE_COMMAND : command = line ; break ; case NGConstants . CHUNKTYPE_WORKINGDIRECTORY : cwd = line ; break ; default : } } startBackgroundReceive ( ) ; return new CommandContext ( command , cwd , remoteEnv , remoteArgs ) ; }
Get nail command context from the header and start reading for stdin and heartbeats
30,752
private void startBackgroundReceive ( ) { long futureTimeout = heartbeatTimeoutMillis + heartbeatTimeoutMillis / 10 ; orchestratorExecutor . submit ( ( ) -> { NGClientDisconnectReason reason = NGClientDisconnectReason . INTERNAL_ERROR ; try { LOG . log ( Level . FINE , "Orchestrator thread started" ) ; while ( true ) { Future < Byte > readFuture ; synchronized ( orchestratorEvent ) { if ( shutdown ) { break ; } readFuture = readExecutor . submit ( ( ) -> { try { return readChunk ( ) ; } catch ( IOException e ) { throw new ExecutionException ( e ) ; } } ) ; } byte chunkType = futureTimeout > 0 ? readFuture . get ( futureTimeout , TimeUnit . MILLISECONDS ) : readFuture . get ( ) ; if ( chunkType == NGConstants . CHUNKTYPE_HEARTBEAT ) { notifyHeartbeat ( ) ; } } } catch ( InterruptedException e ) { LOG . log ( Level . WARNING , "NGCommunicator orchestrator was interrupted" , e ) ; } catch ( ExecutionException e ) { Throwable cause = getCause ( e ) ; if ( cause instanceof EOFException ) { LOG . log ( Level . FINE , "Socket is disconnected" ) ; reason = NGClientDisconnectReason . SOCKET_ERROR ; } else if ( cause instanceof SocketTimeoutException ) { reason = NGClientDisconnectReason . SOCKET_TIMEOUT ; LOG . log ( Level . WARNING , "Nailgun client socket timed out after " + heartbeatTimeoutMillis + " ms" , cause ) ; } else { LOG . log ( Level . WARNING , "Nailgun client read future raised an exception" , cause ) ; } } catch ( TimeoutException e ) { reason = NGClientDisconnectReason . HEARTBEAT ; LOG . log ( Level . WARNING , "Nailgun client read future timed out after " + futureTimeout + " ms" , e ) ; } catch ( Throwable e ) { LOG . log ( Level . WARNING , "Nailgun orchestrator gets an exception " , e ) ; } LOG . log ( Level . FINE , "Nailgun client disconnected" ) ; clientConnected . set ( false ) ; setEof ( ) ; waitTerminationAndNotifyClients ( reason ) ; LOG . log ( Level . FINE , "Orchestrator thread finished" ) ; } ) ; }
Call this to move all reads like heartbeats and stdin to be performed by background thread . This method should only be called once as header data is read from the input stream .
30,753
void exit ( int exitCode ) { if ( isExited ) { return ; } try { stopIn ( ) ; } catch ( IOException ex ) { LOG . log ( Level . WARNING , "Unable to close socket for reading while sending final exit code" , ex ) ; } try ( PrintStream exit = new PrintStream ( new NGOutputStream ( this , NGConstants . CHUNKTYPE_EXIT ) ) ) { exit . println ( exitCode ) ; } isExited = true ; try { stopOut ( ) ; } catch ( IOException ex ) { LOG . log ( Level . WARNING , "Unable to close socket for writing while sending final exit code" , ex ) ; } }
Signal nail completion to the client . It will close communication socket afterwards so any read or write would result in an error This method is idempotent and need to be called only once . Any subsequent call will result in noop .
30,754
private void stopIn ( ) throws IOException { if ( inClosed ) { return ; } inClosed = true ; LOG . log ( Level . FINE , "Shutting down socket for input" ) ; setEof ( ) ; synchronized ( orchestratorEvent ) { shutdown = true ; orchestratorEvent . notifyAll ( ) ; } socket . shutdownInput ( ) ; }
Stop the thread reading stdin from the NailGun client
30,755
private void stopOut ( ) throws IOException { if ( outClosed ) { return ; } outClosed = true ; LOG . log ( Level . FINE , "Shutting down socket for output" ) ; socket . shutdownOutput ( ) ; }
Close socket for output and terminate connection any attempt to write anything to it after that will yield to IOException
30,756
public void close ( ) throws IOException { if ( closed ) { return ; } closed = true ; stopIn ( ) ; stopOut ( ) ; in . close ( ) ; out . close ( ) ; terminateExecutor ( readExecutor , "read" ) ; terminateExecutor ( orchestratorExecutor , "orchestrator" ) ; socket . close ( ) ; }
Closes communication socket gracefully
30,757
private byte readChunk ( ) throws IOException { try { return readChunkImpl ( ) ; } catch ( SocketException ex ) { synchronized ( orchestratorEvent ) { if ( shutdown ) { EOFException newException = new EOFException ( "NGCommunicator is shutting down" ) ; newException . initCause ( ex ) ; throw newException ; } } throw ex ; } }
Reads a NailGun chunk header from the underlying InputStream .
30,758
int receive ( byte [ ] b , int offset , int length ) throws IOException , InterruptedException { synchronized ( readLock ) { if ( remaining > 0 ) { int bytesToRead = Math . min ( remaining , length ) ; int result = stdin . read ( b , offset , bytesToRead ) ; remaining -= result ; return result ; } if ( eof ) { return - 1 ; } } sendSendInput ( ) ; synchronized ( readLock ) { if ( remaining == 0 && ! eof ) { readLock . wait ( ) ; } return receive ( b , offset , length ) ; } }
Read data from client s stdin . This function blocks till input is received from the client .
30,759
void send ( byte streamCode , byte [ ] b , int offset , int len ) throws IOException { synchronized ( writeLock ) { out . writeInt ( len ) ; out . writeByte ( streamCode ) ; out . write ( b , offset , len ) ; } out . flush ( ) ; }
Send data to the client
30,760
private void notifyHeartbeat ( ) { ArrayList < NGHeartbeatListener > listeners ; synchronized ( heartbeatListeners ) { if ( heartbeatListeners . isEmpty ( ) ) { return ; } listeners = new ArrayList < > ( heartbeatListeners ) ; } for ( NGHeartbeatListener listener : listeners ) { listener . heartbeatReceived ( ) ; } }
Calls heartbeatReceived method on all registered NGHeartbeatListeners .
30,761
public void run ( Socket socket ) { synchronized ( lock ) { nextSocket = socket ; lock . notify ( ) ; } Thread . yield ( ) ; }
Instructs this NGSession to process the specified socket after which this NGSession will return itself to the pool from which it came .
30,762
private Socket nextSocket ( ) { Socket result ; synchronized ( lock ) { result = nextSocket ; while ( ! done && result == null ) { try { lock . wait ( ) ; } catch ( InterruptedException e ) { done = true ; } result = nextSocket ; } nextSocket = null ; } if ( result != null ) { try { result . setSoTimeout ( this . heartbeatTimeoutMillis ) ; } catch ( SocketException e ) { return null ; } } return result ; }
Returns the next socket to process . This will block the NGSession thread until there s a socket to process or the NGSession has been shut down .
30,763
public void run ( ) { updateThreadName ( null ) ; LOG . log ( Level . FINE , "NGSession {0} is waiting for first client to connect" , instanceNumber ) ; Socket socket = nextSocket ( ) ; while ( socket != null ) { LOG . log ( Level . FINE , "NGSession {0} accepted new connection" , instanceNumber ) ; try ( NGCommunicator comm = communicatorCreator . get ( socket ) ) { runImpl ( comm , socket ) ; } catch ( Throwable t ) { LOG . log ( Level . WARNING , "Internal error in NGSession " + instanceNumber , t ) ; } LOG . log ( Level . FINEST , "NGSession {0} started cleanup" , instanceNumber ) ; if ( System . in instanceof ThreadLocalInputStream ) { ( ( ThreadLocalInputStream ) System . in ) . init ( null ) ; ( ( ThreadLocalPrintStream ) System . out ) . init ( null ) ; ( ( ThreadLocalPrintStream ) System . err ) . init ( null ) ; } LOG . log ( Level . FINE , "NGSession {0} is closing client socket" , instanceNumber ) ; try { socket . close ( ) ; } catch ( Throwable t ) { LOG . log ( Level . WARNING , "Internal error closing socket" , t ) ; } updateThreadName ( null ) ; sessionPool . give ( this ) ; socket = nextSocket ( ) ; } LOG . log ( Level . FINE , "NGSession {0} stopped" , instanceNumber ) ; }
The main NGSession loop . This gets the next socket to process runs the nail for the socket and loops until shut down .
30,764
public void onResume ( boolean retainedInstance ) { if ( mBlurredBackgroundView == null || retainedInstance ) { if ( mHoldingActivity . getWindow ( ) . getDecorView ( ) . isShown ( ) ) { mBluringTask = new BlurAsyncTask ( ) ; mBluringTask . execute ( ) ; } else { mHoldingActivity . getWindow ( ) . getDecorView ( ) . getViewTreeObserver ( ) . addOnPreDrawListener ( new ViewTreeObserver . OnPreDrawListener ( ) { public boolean onPreDraw ( ) { if ( mHoldingActivity != null ) { mHoldingActivity . getWindow ( ) . getDecorView ( ) . getViewTreeObserver ( ) . removeOnPreDrawListener ( this ) ; mBluringTask = new BlurAsyncTask ( ) ; mBluringTask . execute ( ) ; } return true ; } } ) ; } } }
Resume the engine .
30,765
private int getActionBarHeight ( ) { int actionBarHeight = 0 ; try { if ( mToolbar != null ) { actionBarHeight = mToolbar . getHeight ( ) ; } else if ( mHoldingActivity instanceof ActionBarActivity ) { ActionBar supportActionBar = ( ( ActionBarActivity ) mHoldingActivity ) . getSupportActionBar ( ) ; if ( supportActionBar != null ) { actionBarHeight = supportActionBar . getHeight ( ) ; } } else if ( mHoldingActivity instanceof AppCompatActivity ) { ActionBar supportActionBar = ( ( AppCompatActivity ) mHoldingActivity ) . getSupportActionBar ( ) ; if ( supportActionBar != null ) { actionBarHeight = supportActionBar . getHeight ( ) ; } } else if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . HONEYCOMB ) { android . app . ActionBar actionBar = mHoldingActivity . getActionBar ( ) ; if ( actionBar != null ) { actionBarHeight = actionBar . getHeight ( ) ; } } } catch ( NoClassDefFoundError e ) { if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . HONEYCOMB ) { android . app . ActionBar actionBar = mHoldingActivity . getActionBar ( ) ; if ( actionBar != null ) { actionBarHeight = actionBar . getHeight ( ) ; } } } return actionBarHeight ; }
Retrieve action bar height .
30,766
private int getStatusBarHeight ( ) { int result = 0 ; int resourceId = mHoldingActivity . getResources ( ) . getIdentifier ( "status_bar_height" , "dimen" , "android" ) ; if ( resourceId > 0 ) { result = mHoldingActivity . getResources ( ) . getDimensionPixelSize ( resourceId ) ; } return result ; }
retrieve status bar height in px
30,767
private int getNavigationBarOffset ( ) { int result = 0 ; Resources resources = mHoldingActivity . getResources ( ) ; if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . LOLLIPOP ) { int resourceId = resources . getIdentifier ( "navigation_bar_height" , "dimen" , "android" ) ; if ( resourceId > 0 ) { result = resources . getDimensionPixelSize ( resourceId ) ; } } return result ; }
Retrieve offset introduce by the navigation bar .
30,768
@ TargetApi ( Build . VERSION_CODES . KITKAT ) private boolean isStatusBarTranslucent ( ) { TypedValue typedValue = new TypedValue ( ) ; int [ ] attribute = new int [ ] { android . R . attr . windowTranslucentStatus } ; TypedArray array = mHoldingActivity . obtainStyledAttributes ( typedValue . resourceId , attribute ) ; boolean isStatusBarTranslucent = array . getBoolean ( 0 , false ) ; array . recycle ( ) ; return isStatusBarTranslucent ; }
Used to check if the status bar is translucent .
30,769
private void removeBlurredView ( ) { if ( mBlurredBackgroundView != null ) { ViewGroup parent = ( ViewGroup ) mBlurredBackgroundView . getParent ( ) ; if ( parent != null ) { parent . removeView ( mBlurredBackgroundView ) ; } mBlurredBackgroundView = null ; } }
Removed the blurred view from the view hierarchy .
30,770
public static Bitmap doBlur ( Bitmap sentBitmap , int radius , boolean canReuseInBitmap , Context context ) { Bitmap bitmap ; if ( canReuseInBitmap ) { bitmap = sentBitmap ; } else { bitmap = sentBitmap . copy ( sentBitmap . getConfig ( ) , true ) ; } if ( bitmap . getConfig ( ) == Bitmap . Config . RGB_565 ) { bitmap = convertRGB565toARGB888 ( bitmap ) ; } try { final RenderScript rs = RenderScript . create ( context ) ; final Allocation input = Allocation . createFromBitmap ( rs , bitmap , Allocation . MipmapControl . MIPMAP_NONE , Allocation . USAGE_SCRIPT ) ; final Allocation output = Allocation . createTyped ( rs , input . getType ( ) ) ; final ScriptIntrinsicBlur script = ScriptIntrinsicBlur . create ( rs , Element . U8_4 ( rs ) ) ; script . setRadius ( radius ) ; script . setInput ( input ) ; script . forEach ( output ) ; output . copyTo ( bitmap ) ; return bitmap ; } catch ( RSRuntimeException e ) { Log . e ( TAG , "RenderScript known error : https://code.google.com/p/android/issues/detail?id=71347 " + "continue with the FastBlur approach." ) ; } return null ; }
blur a given bitmap
30,771
private void setUpView ( ) { mBlurRadiusSeekbar . setOnSeekBarChangeListener ( new SeekBar . OnSeekBarChangeListener ( ) { public void onProgressChanged ( SeekBar seekBar , int progress , boolean fromUser ) { mBlurRadiusTextView . setText ( mBlurPrefix + progress ) ; } public void onStartTrackingTouch ( SeekBar seekBar ) { } public void onStopTrackingTouch ( SeekBar seekBar ) { } } ) ; mDownScaleFactorSeekbar . setOnSeekBarChangeListener ( new SeekBar . OnSeekBarChangeListener ( ) { public void onProgressChanged ( SeekBar seekBar , int progress , boolean fromUser ) { mDownScaleFactorTextView . setText ( mDownScalePrefix + progress ) ; } public void onStartTrackingTouch ( SeekBar seekBar ) { } public void onStopTrackingTouch ( SeekBar seekBar ) { } } ) ; mBlurPrefix = getString ( R . string . activity_sample_blur_radius ) ; mDownScalePrefix = getString ( R . string . activity_sample_down_scale_factor ) ; mBlurRadiusSeekbar . setProgress ( 8 ) ; mDownScaleFactorSeekbar . setProgress ( 4 ) ; }
Set up widgets .
30,772
private void checkRunningListenersAndStartIfPossible ( DispatchQueueSelector queueSelector ) { synchronized ( queuedListenerTasks ) { Queue < Runnable > queue = queueSelector == null ? null : queuedListenerTasks . get ( queueSelector ) ; if ( queue == null || queue . isEmpty ( ) ) { if ( queuedListenerTasks . get ( null ) . isEmpty ( ) ) { return ; } boolean moreObjectDependentTasks = queuedListenerTasks . entrySet ( ) . stream ( ) . filter ( entry -> ! entry . getValue ( ) . isEmpty ( ) ) . anyMatch ( entry -> entry . getKey ( ) != null ) ; if ( moreObjectDependentTasks || ! runningListeners . isEmpty ( ) ) { return ; } queueSelector = null ; queue = queuedListenerTasks . get ( null ) ; } DispatchQueueSelector finalQueueSelector = queueSelector ; Queue < Runnable > taskQueue = queue ; if ( ! queue . isEmpty ( ) && runningListeners . add ( finalQueueSelector ) ) { AtomicReference < Future < ? > > activeListener = new AtomicReference < > ( ) ; activeListener . set ( api . getThreadPool ( ) . getExecutorService ( ) . submit ( ( ) -> { if ( finalQueueSelector instanceof ServerImpl ) { Object serverReadyNotifier = new Object ( ) ; ( ( ServerImpl ) finalQueueSelector ) . addServerReadyConsumer ( s -> { synchronized ( serverReadyNotifier ) { serverReadyNotifier . notifyAll ( ) ; } } ) ; while ( ! ( ( ServerImpl ) finalQueueSelector ) . isReady ( ) ) { try { synchronized ( serverReadyNotifier ) { serverReadyNotifier . wait ( 5000 ) ; } } catch ( InterruptedException ignored ) { } } } activeListeners . put ( activeListener , new Object [ ] { System . nanoTime ( ) , finalQueueSelector } ) ; try { taskQueue . poll ( ) . run ( ) ; } catch ( Throwable t ) { logger . error ( "Unhandled exception in {}!" , ( ) -> getThreadType ( finalQueueSelector ) , ( ) -> t ) ; } activeListeners . remove ( activeListener ) ; runningListeners . remove ( finalQueueSelector ) ; synchronized ( queuedListenerTasks ) { queuedListenerTasks . notifyAll ( ) ; } checkRunningListenersAndStartIfPossible ( finalQueueSelector ) ; } ) ) ; } } }
Checks if there are listeners running for the given object and if not it takes one from the queue for the object and executes it .
30,773
private String getThreadType ( DispatchQueueSelector queueSelector ) { String threadType ; if ( queueSelector instanceof DiscordApi ) { threadType = "a global listener thread" ; } else if ( queueSelector == null ) { threadType = "a connection listener thread" ; } else { threadType = String . format ( "a listener thread for %s" , queueSelector ) ; } return threadType ; }
Gets the thread type used in log message for the given queue selector .
30,774
public ServerUpdater setNickname ( User user , String nickname ) { delegate . setNickname ( user , nickname ) ; return this ; }
Queues a user s nickname to be updated .
30,775
public ServerUpdater setVoiceChannel ( User user , ServerVoiceChannel channel ) { delegate . setVoiceChannel ( user , channel ) ; return this ; }
Queues a moving a user to a different voice channel .
30,776
public ServerUpdater addRoleToUser ( User user , Role role ) { delegate . addRoleToUser ( user , role ) ; return this ; }
Queues a role to be assigned to the user .
30,777
public ServerUpdater addRolesToUser ( User user , Collection < Role > roles ) { delegate . addRolesToUser ( user , roles ) ; return this ; }
Queues a collection of roles to be assigned to the user .
30,778
public ServerUpdater removeRoleFromUser ( User user , Role role ) { delegate . removeRoleFromUser ( user , role ) ; return this ; }
Queues a role to be removed from the user .
30,779
public ServerUpdater removeRolesFromUser ( User user , Collection < Role > roles ) { delegate . removeRolesFromUser ( user , roles ) ; return this ; }
Queues a collection of roles to be removed from the user .
30,780
private void populatePermissionOverwrites ( ) { if ( overwrittenUserPermissions == null ) { overwrittenUserPermissions = new HashMap < > ( ) ; overwrittenUserPermissions . putAll ( ( ( ServerChannelImpl ) channel ) . getInternalOverwrittenUserPermissions ( ) ) ; } if ( overwrittenRolePermissions == null ) { overwrittenRolePermissions = new HashMap < > ( ) ; overwrittenRolePermissions . putAll ( ( ( ServerChannelImpl ) channel ) . getInternalOverwrittenRolePermissions ( ) ) ; } }
Populates the maps which contain the permission overwrites .
30,781
public void setChannel ( PrivateChannel channel ) { if ( this . channel != channel ) { if ( this . channel != null ) { ( ( Cleanupable ) this . channel ) . cleanup ( ) ; } this . channel = channel ; } }
Sets the private channel with the user .
30,782
public PrivateChannel getOrCreateChannel ( JsonNode data ) { synchronized ( this ) { if ( channel != null ) { return channel ; } return new PrivateChannelImpl ( api , data ) ; } }
Gets or creates a new private channel .
30,783
public static Icon getAvatar ( DiscordApi api , String avatarHash , String discriminator , long userId ) { StringBuilder url = new StringBuilder ( "https://cdn.discordapp.com/" ) ; if ( avatarHash == null ) { url . append ( "embed/avatars/" ) . append ( Integer . parseInt ( discriminator ) % 5 ) . append ( ".png" ) ; } else { url . append ( "avatars/" ) . append ( userId ) . append ( '/' ) . append ( avatarHash ) . append ( avatarHash . startsWith ( "a_" ) ? ".gif" : ".png" ) ; } try { return new IconImpl ( api , new URL ( url . toString ( ) ) ) ; } catch ( MalformedURLException e ) { logger . warn ( "Seems like the url of the avatar is malformed! Please contact the developer!" , e ) ; return null ; } }
Gets the avatar for the given details .
30,784
private static CompletableFuture < MessageSet > getMessages ( TextChannel channel , int limit , long before , long after ) { CompletableFuture < MessageSet > future = new CompletableFuture < > ( ) ; channel . getApi ( ) . getThreadPool ( ) . getExecutorService ( ) . submit ( ( ) -> { try { int initialBatchSize = ( ( limit % 100 ) == 0 ) ? 100 : limit % 100 ; MessageSet initialMessages = requestAsMessages ( channel , initialBatchSize , before , after ) ; if ( ( limit <= 100 ) || initialMessages . isEmpty ( ) ) { future . complete ( initialMessages ) ; return ; } int remainingMessages = limit - initialBatchSize ; int steps = remainingMessages / 100 ; boolean older = ( before != - 1 ) || ( after == - 1 ) ; boolean newer = after != - 1 ; List < MessageSet > messageSets = new ArrayList < > ( ) ; MessageSet lastMessages = initialMessages ; messageSets . add ( lastMessages ) ; for ( int step = 0 ; step < steps ; ++ step ) { lastMessages = requestAsMessages ( channel , 100 , lastMessages . getOldestMessage ( ) . filter ( message -> older ) . map ( DiscordEntity :: getId ) . orElse ( - 1L ) , lastMessages . getNewestMessage ( ) . filter ( message -> newer ) . map ( DiscordEntity :: getId ) . orElse ( - 1L ) ) ; if ( lastMessages . isEmpty ( ) ) { break ; } messageSets . add ( lastMessages ) ; } future . complete ( new MessageSetImpl ( messageSets . stream ( ) . flatMap ( Collection :: stream ) . collect ( Collectors . toList ( ) ) ) ) ; } catch ( Throwable t ) { future . completeExceptionally ( t ) ; } } ) ; return future ; }
Gets up to a given amount of messages in the given channel .
30,785
private static Stream < Message > getMessagesAsStream ( TextChannel channel , long before , long after ) { return StreamSupport . stream ( Spliterators . spliteratorUnknownSize ( new Iterator < Message > ( ) { private final DiscordApiImpl api = ( ( DiscordApiImpl ) channel . getApi ( ) ) ; private final boolean older = ( before != - 1 ) || ( after == - 1 ) ; private final boolean newer = after != - 1 ; private long referenceMessageId = older ? before : after ; private final List < JsonNode > messageJsons = Collections . synchronizedList ( new ArrayList < > ( ) ) ; private void ensureMessagesAvailable ( ) { if ( messageJsons . isEmpty ( ) ) { synchronized ( messageJsons ) { if ( messageJsons . isEmpty ( ) ) { messageJsons . addAll ( requestAsSortedJsonNodes ( channel , 100 , older ? referenceMessageId : - 1 , newer ? referenceMessageId : - 1 , older ) ) ; if ( ! messageJsons . isEmpty ( ) ) { referenceMessageId = messageJsons . get ( messageJsons . size ( ) - 1 ) . get ( "id" ) . asLong ( ) ; } } } } } public boolean hasNext ( ) { ensureMessagesAvailable ( ) ; return ! messageJsons . isEmpty ( ) ; } public Message next ( ) { ensureMessagesAvailable ( ) ; return api . getOrCreateMessage ( channel , messageJsons . remove ( 0 ) ) ; } } , Spliterator . ORDERED | Spliterator . DISTINCT | Spliterator . NONNULL | Spliterator . CONCURRENT ) , false ) ; }
Gets a stream of messages in the given channel sorted from newest to oldest .
30,786
public static CompletableFuture < MessageSet > getMessagesBefore ( TextChannel channel , int limit , long before ) { return getMessages ( channel , limit , before , - 1 ) ; }
Gets up to a given amount of messages in the given channel before a given message in any channel .
30,787
public static CompletableFuture < MessageSet > getMessagesBeforeUntil ( TextChannel channel , Predicate < Message > condition , long before ) { return getMessagesUntil ( channel , condition , before , - 1 ) ; }
Gets messages in the given channel before a given message in any channel until one that meets the given condition is found . If no message matches the condition an empty set is returned .
30,788
public static CompletableFuture < MessageSet > getMessagesBeforeWhile ( TextChannel channel , Predicate < Message > condition , long before ) { return getMessagesWhile ( channel , condition , before , - 1 ) ; }
Gets messages in the given channel before a given message in any channel while they meet the given condition . If the first message does not match the condition an empty set is returned .
30,789
public static CompletableFuture < MessageSet > getMessagesAfter ( TextChannel channel , int limit , long after ) { return getMessages ( channel , limit , - 1 , after ) ; }
Gets up to a given amount of messages in the given channel after a given message in any channel .
30,790
public static CompletableFuture < MessageSet > getMessagesAround ( TextChannel channel , int limit , long around ) { CompletableFuture < MessageSet > future = new CompletableFuture < > ( ) ; channel . getApi ( ) . getThreadPool ( ) . getExecutorService ( ) . submit ( ( ) -> { try { int halfLimit = limit / 2 ; MessageSet newerMessages = getMessagesAfter ( channel , halfLimit , around ) . join ( ) ; MessageSet olderMessages = getMessagesBefore ( channel , halfLimit + 1 , around + 1 ) . join ( ) ; if ( olderMessages . getNewestMessage ( ) . map ( DiscordEntity :: getId ) . map ( id -> id != around ) . orElse ( false ) ) { olderMessages = olderMessages . tailSet ( olderMessages . getOldestMessage ( ) . orElseThrow ( AssertionError :: new ) , false ) ; } Collection < Message > messages = Stream . of ( olderMessages , newerMessages ) . flatMap ( Collection :: stream ) . collect ( Collectors . toList ( ) ) ; future . complete ( new MessageSetImpl ( messages ) ) ; } catch ( Throwable t ) { future . completeExceptionally ( t ) ; } } ) ; return future ; }
Gets up to a given amount of messages in the given channel around a given message in any channel . The given message will be part of the result in addition to the messages around if it was sent in the given channel and does not count towards the limit . Half of the messages will be older than the given message and half of the messages will be newer . If there aren t enough older or newer messages the actual amount of messages will be less than the given limit . It s also not guaranteed to be perfectly balanced .
30,791
public static CompletableFuture < MessageSet > getMessagesAroundUntil ( TextChannel channel , Predicate < Message > condition , long around ) { CompletableFuture < MessageSet > future = new CompletableFuture < > ( ) ; channel . getApi ( ) . getThreadPool ( ) . getExecutorService ( ) . submit ( ( ) -> { try { List < Message > messages = new ArrayList < > ( ) ; Optional < Message > untilMessage = getMessagesAroundAsStream ( channel , around ) . peek ( messages :: add ) . filter ( condition ) . findFirst ( ) ; future . complete ( new MessageSetImpl ( untilMessage . map ( message -> messages ) . orElse ( Collections . emptyList ( ) ) ) ) ; } catch ( Throwable t ) { future . completeExceptionally ( t ) ; } } ) ; return future ; }
Gets messages in the given channel around a given message in any channel until one that meets the given condition is found . If no message matches the condition an empty set is returned . The given message will be part of the result in addition to the messages around if it was sent in the given channel and is matched against the condition and will abort retrieval . Half of the messages will be older than the given message and half of the messages will be newer . If there aren t enough older or newer messages the halves will not be same - sized . It s also not guaranteed to be perfectly balanced .
30,792
public static CompletableFuture < MessageSet > getMessagesAroundWhile ( TextChannel channel , Predicate < Message > condition , long around ) { CompletableFuture < MessageSet > future = new CompletableFuture < > ( ) ; channel . getApi ( ) . getThreadPool ( ) . getExecutorService ( ) . submit ( ( ) -> { try { List < Message > messages = new ArrayList < > ( ) ; Optional < Message > untilMessage = getMessagesAroundAsStream ( channel , around ) . peek ( messages :: add ) . filter ( condition . negate ( ) ) . findFirst ( ) ; untilMessage . ifPresent ( messages :: remove ) ; future . complete ( new MessageSetImpl ( messages ) ) ; } catch ( Throwable t ) { future . completeExceptionally ( t ) ; } } ) ; return future ; }
Gets messages in the given channel around a given message in any channel while they meet the given condition . If the first message does not match the condition an empty set is returned . The given message will be part of the result in addition to the messages around if it was sent in the given channel and is matched against the condition and will abort retrieval . Half of the messages will be older than the given message and half of the messages will be newer . If there aren t enough older or newer messages the halves will not be same - sized . It s also not guaranteed to be perfectly balanced .
30,793
public static CompletableFuture < MessageSet > getMessagesBetween ( TextChannel channel , long from , long to ) { CompletableFuture < MessageSet > future = new CompletableFuture < > ( ) ; channel . getApi ( ) . getThreadPool ( ) . getExecutorService ( ) . submit ( ( ) -> { try { future . complete ( new MessageSetImpl ( getMessagesBetweenAsStream ( channel , from , to ) . collect ( Collectors . toList ( ) ) ) ) ; } catch ( Throwable t ) { future . completeExceptionally ( t ) ; } } ) ; return future ; }
Gets all messages in the given channel between the first given message in any channel and the second given message in any channel excluding the boundaries . Gets up to a given amount of messages in the given channel before a given message in any channel .
30,794
public static Stream < Message > getMessagesBetweenAsStream ( TextChannel channel , long from , long to ) { long before = Math . max ( from , to ) ; long after = Math . min ( from , to ) ; Stream < Message > messages = getMessagesAsStream ( channel , - 1 , after ) . filter ( message -> message . getId ( ) < before ) ; return ( from == after ) ? messages : messages . sorted ( Comparator . reverseOrder ( ) ) ; }
Gets all messages in the given channel between the first given message in any channel and the second given message in any channel excluding the boundaries sorted from first given message to the second given message .
30,795
private static List < JsonNode > requestAsSortedJsonNodes ( TextChannel channel , int limit , long before , long after , boolean reversed ) { List < JsonNode > messageJsonNodes = requestAsJsonNodes ( channel , limit , before , after ) ; Comparator < JsonNode > idComparator = Comparator . comparingLong ( jsonNode -> jsonNode . get ( "id" ) . asLong ( ) ) ; messageJsonNodes . sort ( reversed ? idComparator . reversed ( ) : idComparator ) ; return messageJsonNodes ; }
Requests the messages from Discord sorted by their id .
30,796
public SSLSocketFactory createSslSocketFactory ( ) { try { SSLContext sslContext = SSLContext . getInstance ( "TLS" ) ; sslContext . init ( null , new TrustManager [ ] { this } , null ) ; return sslContext . getSocketFactory ( ) ; } catch ( NoSuchAlgorithmException | KeyManagementException e ) { throw new AssertionError ( e ) ; } }
Creates a new SSL socket factory that generates SSL sockets that trust all certificates unconditionally .
30,797
@ SuppressWarnings ( "unchecked" ) private void prepareListeners ( ) { if ( preparedListeners != null && preparedUnspecifiedListeners != null ) { return ; } preparedListeners = new ConcurrentHashMap < > ( ) ; Stream < Class < ? extends GloballyAttachableListener > > eventTypes = Stream . concat ( listeners . keySet ( ) . stream ( ) , Stream . concat ( listenerSuppliers . keySet ( ) . stream ( ) , listenerFunctions . keySet ( ) . stream ( ) ) ) . distinct ( ) ; eventTypes . forEach ( type -> { ArrayList < Function < DiscordApi , GloballyAttachableListener > > typeListenerFunctions = new ArrayList < > ( ) ; listeners . getOrDefault ( type , Collections . emptyList ( ) ) . forEach ( listener -> typeListenerFunctions . add ( api -> listener ) ) ; listenerSuppliers . getOrDefault ( type , Collections . emptyList ( ) ) . forEach ( supplier -> typeListenerFunctions . add ( api -> supplier . get ( ) ) ) ; listenerFunctions . getOrDefault ( type , Collections . emptyList ( ) ) . forEach ( function -> typeListenerFunctions . add ( ( Function < DiscordApi , GloballyAttachableListener > ) function ) ) ; preparedListeners . put ( type , typeListenerFunctions ) ; } ) ; preparedUnspecifiedListeners = new CopyOnWriteArrayList < > ( unspecifiedListenerFunctions ) ; unspecifiedListenerSuppliers . forEach ( supplier -> preparedUnspecifiedListeners . add ( ( api ) -> supplier . get ( ) ) ) ; unspecifiedListeners . forEach ( listener -> preparedUnspecifiedListeners . add ( ( api ) -> listener ) ) ; }
Compile pre - registered listeners into proper collections for DiscordApi creation .
30,798
private Optional < Icon > getSplash ( String splashHash ) { if ( splashHash == null ) { return Optional . empty ( ) ; } try { return Optional . of ( new IconImpl ( getApi ( ) , new URL ( "https://cdn.discordapp.com/splashs/" + getServer ( ) . getIdAsString ( ) + "/" + splashHash + ".png" ) ) ) ; } catch ( MalformedURLException e ) { logger . warn ( "Seems like the url of the splash is malformed! Please contact the developer!" , e ) ; return Optional . empty ( ) ; } }
Gets the splash for the given hash .
30,799
public void shutdown ( ) { executorService . shutdown ( ) ; scheduler . shutdown ( ) ; daemonScheduler . shutdown ( ) ; executorServiceSingleThreads . values ( ) . forEach ( ExecutorService :: shutdown ) ; }
Shutdowns the thread pool . This method is called automatically after disconnecting .