idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
20,200
private void unicast ( SwimMember member , ImmutableMember update ) { bootstrapService . getUnicastService ( ) . unicast ( member . address ( ) , MEMBERSHIP_GOSSIP , SERIALIZER . encode ( Lists . newArrayList ( update ) ) ) ; }
Unicasts the given update to the given member .
20,201
private void gossip ( ) { checkFailures ( ) ; checkMetadata ( ) ; if ( ! updates . isEmpty ( ) ) { List < ImmutableMember > updates = Lists . newArrayList ( this . updates . values ( ) ) ; this . updates . clear ( ) ; gossip ( updates ) ; } }
Gossips pending updates to the cluster .
20,202
private void gossip ( Collection < ImmutableMember > updates ) { List < SwimMember > members = Lists . newArrayList ( randomMembers ) ; if ( ! members . isEmpty ( ) ) { Collections . shuffle ( members ) ; for ( int i = 0 ; i < Math . min ( members . size ( ) , config . getGossipFanout ( ) ) ; i ++ ) { gossip ( members . get ( i ) , updates ) ; } } }
Gossips this node s pending updates with a random set of peers .
20,203
private void gossip ( SwimMember member , Collection < ImmutableMember > updates ) { LOGGER . trace ( "{} - Gossipping updates {} to {}" , localMember . id ( ) , updates , member ) ; bootstrapService . getUnicastService ( ) . unicast ( member . address ( ) , MEMBERSHIP_GOSSIP , SERIALIZER . encode ( updates ) ) ; }
Gossips this node s pending updates with the given peer .
20,204
private void registerHandlers ( ) { bootstrapService . getMessagingService ( ) . registerHandler ( MEMBERSHIP_SYNC , syncHandler , swimScheduler ) ; bootstrapService . getMessagingService ( ) . registerHandler ( MEMBERSHIP_PROBE , probeHandler , swimScheduler ) ; bootstrapService . getMessagingService ( ) . registerHandler ( MEMBERSHIP_PROBE_REQUEST , probeRequestHandler ) ; bootstrapService . getUnicastService ( ) . addListener ( MEMBERSHIP_GOSSIP , gossipListener , swimScheduler ) ; }
Registers message handlers for the SWIM protocol .
20,205
private void unregisterHandlers ( ) { bootstrapService . getMessagingService ( ) . unregisterHandler ( MEMBERSHIP_SYNC ) ; bootstrapService . getMessagingService ( ) . unregisterHandler ( MEMBERSHIP_PROBE ) ; bootstrapService . getMessagingService ( ) . unregisterHandler ( MEMBERSHIP_PROBE_REQUEST ) ; bootstrapService . getUnicastService ( ) . removeListener ( MEMBERSHIP_GOSSIP , gossipListener ) ; }
Unregisters handlers for the SWIM protocol .
20,206
public CompletableFuture < Map < Long , Integer > > holderStatus ( ) { return getProxyClient ( ) . applyBy ( name ( ) , service -> service . holderStatus ( ) ) ; }
Query all permit holders . For debugging only .
20,207
private void recordHeartbeat ( RaftMemberContext member , long timestamp ) { raft . checkThread ( ) ; member . setHeartbeatTime ( timestamp ) ; member . setResponseTime ( System . currentTimeMillis ( ) ) ; long heartbeatTime = computeHeartbeatTime ( ) ; long currentTimestamp = System . currentTimeMillis ( ) ; Iterator < TimestampedFuture < Long > > iterator = heartbeatFutures . iterator ( ) ; while ( iterator . hasNext ( ) ) { TimestampedFuture < Long > future = iterator . next ( ) ; if ( future . timestamp < heartbeatTime ) { future . complete ( null ) ; iterator . remove ( ) ; } else if ( currentTimestamp - future . timestamp > electionTimeout ) { future . completeExceptionally ( new RaftException . ProtocolException ( "Failed to reach consensus" ) ) ; iterator . remove ( ) ; } else { break ; } } if ( ! heartbeatFutures . isEmpty ( ) ) { sendHeartbeats ( ) ; } }
Records a completed heartbeat to the given member .
20,208
private void failHeartbeat ( ) { raft . checkThread ( ) ; long currentTimestamp = System . currentTimeMillis ( ) ; Iterator < TimestampedFuture < Long > > iterator = heartbeatFutures . iterator ( ) ; while ( iterator . hasNext ( ) ) { TimestampedFuture < Long > future = iterator . next ( ) ; if ( currentTimestamp - future . timestamp > electionTimeout ) { future . completeExceptionally ( new RaftException . ProtocolException ( "Failed to reach consensus" ) ) ; iterator . remove ( ) ; } } }
Records a failed heartbeat .
20,209
private void completeCommits ( long previousCommitIndex , long commitIndex ) { for ( long i = previousCommitIndex + 1 ; i <= commitIndex ; i ++ ) { CompletableFuture < Long > future = appendFutures . remove ( i ) ; if ( future != null ) { future . complete ( i ) ; } } }
Completes append entries attempts up to the given index .
20,210
public CompletableFuture < Void > snapshot ( ) { return Futures . allOf ( config . getMembers ( ) . stream ( ) . map ( MemberId :: from ) . map ( id -> communicationService . send ( snapshotSubject , null , id , SNAPSHOT_TIMEOUT ) ) . collect ( Collectors . toList ( ) ) ) . thenApply ( v -> null ) ; }
Takes snapshots of all Raft partitions .
20,211
private CompletableFuture < Void > handleSnapshot ( ) { return Futures . allOf ( partitions . values ( ) . stream ( ) . map ( partition -> partition . snapshot ( ) ) . collect ( Collectors . toList ( ) ) ) . thenApply ( v -> null ) ; }
Handles a snapshot request from a peer .
20,212
private void onChange ( String key , byte [ ] oldValue , byte [ ] newValue ) { listeners . forEach ( id -> getSession ( id ) . accept ( client -> client . onChange ( key , oldValue , newValue ) ) ) ; }
Sends a change event to listeners .
20,213
public void openSession ( PrimaryBackupSession session ) { sessions . put ( session . sessionId ( ) . id ( ) , session ) ; listeners . forEach ( l -> l . onOpen ( session ) ) ; }
Adds a session to the sessions list .
20,214
public void expireSession ( PrimaryBackupSession session ) { if ( sessions . remove ( session . sessionId ( ) . id ( ) ) != null ) { session . expire ( ) ; listeners . forEach ( l -> l . onExpire ( session ) ) ; } }
Expires and removes a session from the sessions list .
20,215
public void closeSession ( PrimaryBackupSession session ) { if ( sessions . remove ( session . sessionId ( ) . id ( ) ) != null ) { session . close ( ) ; listeners . forEach ( l -> l . onClose ( session ) ) ; } }
Closes and removes a session from the sessions list .
20,216
private void initialize ( long index ) { currentSegment = journal . getSegment ( index ) ; currentSegment . acquire ( ) ; currentReader = currentSegment . createReader ( ) ; long nextIndex = getNextIndex ( ) ; while ( index > nextIndex && hasNext ( ) ) { next ( ) ; nextIndex = getNextIndex ( ) ; } }
Initializes the reader to the given index .
20,217
private void rewind ( long index ) { if ( currentSegment . index ( ) >= index ) { JournalSegment < E > segment = journal . getSegment ( index - 1 ) ; if ( segment != null ) { currentReader . close ( ) ; currentSegment . release ( ) ; currentSegment = segment ; currentSegment . acquire ( ) ; currentReader = currentSegment . createReader ( ) ; } } currentReader . reset ( index ) ; previousEntry = currentReader . getCurrentEntry ( ) ; }
Rewinds the journal to the given index .
20,218
public static OperationResult succeeded ( long index , long eventIndex , byte [ ] result ) { return new OperationResult ( index , eventIndex , null , result ) ; }
Returns a successful operation result .
20,219
public static OperationResult failed ( long index , long eventIndex , Throwable error ) { return new OperationResult ( index , eventIndex , error , null ) ; }
Returns a failed operation result .
20,220
public synchronized < U > Versioned < U > map ( Function < V , U > transformer ) { return new Versioned < > ( value != null ? transformer . apply ( value ) : null , version , creationTime ) ; }
Maps this instance into another after transforming its value while retaining the same version and creationTime .
20,221
public static < U > U valueOrElse ( Versioned < U > versioned , U defaultValue ) { return versioned == null ? defaultValue : versioned . value ( ) ; }
Returns the value of the specified Versioned object if non - null or else returns a default value .
20,222
String eventSubject ( long sessionId ) { if ( prefix == null ) { return String . format ( "event-%d" , sessionId ) ; } else { return String . format ( "%s-event-%d" , prefix , sessionId ) ; } }
Returns the event subject for the given session .
20,223
@ SuppressWarnings ( "unchecked" ) public Class < ? extends TypedConfig < ? > > getConcreteClass ( AtomixRegistry registry , String typeName ) { ConfiguredType type = registry . getType ( typeClass , typeName ) ; if ( type == null ) { return null ; } return ( Class < ? extends TypedConfig < ? > > ) type . newConfig ( ) . getClass ( ) ; }
Returns the concrete configuration class .
20,224
private void scheduleRebalance ( ) { if ( rebalanceTimer != null ) { rebalanceTimer . cancel ( ) ; } rebalanceTimer = getScheduler ( ) . schedule ( REBALANCE_DURATION , this :: rebalance ) ; }
Schedules rebalancing of primaries .
20,225
private void rebalance ( ) { boolean rebalanced = false ; for ( ElectionState election : elections . values ( ) ) { int primaryCount = election . countPrimaries ( election . primary ) ; int minCandidateCount = 0 ; for ( Registration candidate : election . registrations ) { if ( minCandidateCount == 0 ) { minCandidateCount = election . countPrimaries ( candidate ) ; } else { minCandidateCount = Math . min ( minCandidateCount , election . countPrimaries ( candidate ) ) ; } } if ( minCandidateCount < primaryCount ) { for ( Registration candidate : election . registrations ) { if ( election . countPrimaries ( candidate ) < primaryCount ) { PrimaryTerm oldTerm = election . term ( ) ; elections . put ( election . partitionId , election . transfer ( candidate . member ( ) ) ) ; PrimaryTerm newTerm = term ( election . partitionId ) ; if ( ! Objects . equals ( oldTerm , newTerm ) ) { notifyTermChange ( election . partitionId , newTerm ) ; rebalanced = true ; } } } } } if ( rebalanced ) { scheduleRebalance ( ) ; } }
Periodically rebalances primaries .
20,226
public Snapshot getCurrentSnapshot ( ) { Map . Entry < Long , Snapshot > entry = snapshots . lastEntry ( ) ; return entry != null ? entry . getValue ( ) : null ; }
Returns the current snapshot .
20,227
private Collection < Snapshot > loadSnapshots ( ) { storage . directory ( ) . mkdirs ( ) ; List < Snapshot > snapshots = new ArrayList < > ( ) ; for ( File file : storage . directory ( ) . listFiles ( File :: isFile ) ) { if ( SnapshotFile . isSnapshotFile ( file ) ) { SnapshotFile snapshotFile = new SnapshotFile ( file ) ; SnapshotDescriptor descriptor = new SnapshotDescriptor ( FileBuffer . allocate ( file , SnapshotDescriptor . BYTES ) ) ; if ( descriptor . isLocked ( ) ) { log . debug ( "Loaded disk snapshot: {} ({})" , descriptor . index ( ) , snapshotFile . file ( ) . getName ( ) ) ; snapshots . add ( new FileSnapshot ( snapshotFile , descriptor , this ) ) ; descriptor . close ( ) ; } else { log . debug ( "Deleting partial snapshot: {} ({})" , descriptor . index ( ) , snapshotFile . file ( ) . getName ( ) ) ; descriptor . close ( ) ; descriptor . delete ( ) ; } } } return snapshots ; }
Loads all available snapshots from disk .
20,228
public Snapshot newTemporarySnapshot ( long index , WallClockTimestamp timestamp ) { SnapshotDescriptor descriptor = SnapshotDescriptor . builder ( ) . withIndex ( index ) . withTimestamp ( timestamp . unixTimestamp ( ) ) . build ( ) ; return newSnapshot ( descriptor , StorageLevel . MEMORY ) ; }
Creates a temporary in - memory snapshot .
20,229
public CompletableFuture < Void > snapshot ( ) { RaftPartitionServer server = this . server ; if ( server != null ) { return server . snapshot ( ) ; } return CompletableFuture . completedFuture ( null ) ; }
Takes a snapshot of the partition .
20,230
CompletableFuture < Partition > open ( PartitionMetadata metadata , PartitionManagementService managementService ) { this . partition = metadata ; this . client = createClient ( managementService ) ; if ( partition . members ( ) . contains ( managementService . getMembershipService ( ) . getLocalMember ( ) . id ( ) ) ) { server = createServer ( managementService ) ; return server . start ( ) . thenCompose ( v -> client . start ( ) ) . thenApply ( v -> null ) ; } return client . start ( ) . thenApply ( v -> this ) ; }
Opens the partition .
20,231
CompletableFuture < Void > update ( PartitionMetadata metadata , PartitionManagementService managementService ) { if ( server == null && metadata . members ( ) . contains ( managementService . getMembershipService ( ) . getLocalMember ( ) . id ( ) ) ) { server = createServer ( managementService ) ; return server . join ( metadata . members ( ) ) ; } else if ( server != null && ! metadata . members ( ) . contains ( managementService . getMembershipService ( ) . getLocalMember ( ) . id ( ) ) ) { return server . leave ( ) . thenRun ( ( ) -> server = null ) ; } return CompletableFuture . completedFuture ( null ) ; }
Updates the partition with the given metadata .
20,232
CompletableFuture < Void > close ( ) { return closeClient ( ) . exceptionally ( v -> null ) . thenCompose ( v -> closeServer ( ) ) . exceptionally ( v -> null ) ; }
Closes the partition .
20,233
protected RaftPartitionServer createServer ( PartitionManagementService managementService ) { return new RaftPartitionServer ( this , config , managementService . getMembershipService ( ) . getLocalMember ( ) . id ( ) , managementService . getMembershipService ( ) , managementService . getMessagingService ( ) , managementService . getPrimitiveTypes ( ) , threadContextFactory ) ; }
Creates a Raft server .
20,234
private RaftPartitionClient createClient ( PartitionManagementService managementService ) { return new RaftPartitionClient ( this , managementService . getMembershipService ( ) . getLocalMember ( ) . id ( ) , new RaftClientCommunicator ( name ( ) , Serializer . using ( RaftNamespaces . RAFT_PROTOCOL ) , managementService . getMessagingService ( ) ) , threadContextFactory ) ; }
Creates a Raft client .
20,235
public CompletableFuture < Void > delete ( ) { return server . stop ( ) . thenCompose ( v -> client . stop ( ) ) . thenRun ( ( ) -> { if ( server != null ) { server . delete ( ) ; } } ) ; }
Deletes the partition .
20,236
public void setCommandSequence ( long sequence ) { for ( long i = commandSequence + 1 ; i <= sequence ; i ++ ) { commandSequence = i ; List < Runnable > queries = this . sequenceQueries . remove ( commandSequence ) ; if ( queries != null ) { for ( Runnable query : queries ) { query . run ( ) ; } } } }
Sets the session operation sequence number .
20,237
public void setLastApplied ( long index ) { for ( long i = lastApplied + 1 ; i <= index ; i ++ ) { lastApplied = i ; List < Runnable > queries = this . indexQueries . remove ( lastApplied ) ; if ( queries != null ) { for ( Runnable query : queries ) { query . run ( ) ; } } } }
Sets the session index .
20,238
public void registerSequenceQuery ( long sequence , Runnable query ) { List < Runnable > queries = this . sequenceQueries . computeIfAbsent ( sequence , v -> new LinkedList < Runnable > ( ) ) ; queries . add ( query ) ; }
Registers a causal session query .
20,239
public void registerIndexQuery ( long index , Runnable query ) { List < Runnable > queries = this . indexQueries . computeIfAbsent ( index , v -> new LinkedList < > ( ) ) ; queries . add ( query ) ; }
Registers a session index query .
20,240
public Collection < PendingCommand > clearCommands ( ) { Collection < PendingCommand > commands = Lists . newArrayList ( pendingCommands . values ( ) ) ; pendingCommands . clear ( ) ; return commands ; }
Clears and returns all pending commands .
20,241
public long getLastCompleted ( ) { EventHolder event = events . peek ( ) ; if ( event != null && event . eventIndex > completeIndex ) { return event . eventIndex - 1 ; } return lastApplied ; }
Returns the index of the highest event acked for the session .
20,242
private void clearEvents ( long index ) { if ( index > completeIndex ) { EventHolder event = events . peek ( ) ; while ( event != null && event . eventIndex <= index ) { events . remove ( ) ; completeIndex = event . eventIndex ; event = events . peek ( ) ; } completeIndex = index ; } }
Clears events up to the given sequence .
20,243
private void sendEvents ( EventHolder event ) { if ( server . isLeader ( ) ) { eventExecutor . execute ( ( ) -> { PublishRequest request = PublishRequest . builder ( ) . withSession ( sessionId ( ) . id ( ) ) . withEventIndex ( event . eventIndex ) . withPreviousIndex ( event . previousIndex ) . withEvents ( event . events ) . build ( ) ; log . trace ( "Sending {}" , request ) ; protocol . publish ( memberId ( ) , request ) ; } ) ; } }
Sends an event to the session .
20,244
public void open ( ) { setState ( State . OPEN ) ; protocol . registerResetListener ( sessionId ( ) , request -> resendEvents ( request . index ( ) ) , server . getServiceManager ( ) . executor ( ) ) ; }
Opens the session .
20,245
private synchronized void onStateChange ( PartitionId partitionId , PrimitiveState state ) { states . put ( partitionId , state ) ; switch ( state ) { case CONNECTED : if ( this . state != PrimitiveState . CONNECTED && ! states . containsValue ( PrimitiveState . SUSPENDED ) && ! states . containsValue ( PrimitiveState . CLOSED ) ) { this . state = PrimitiveState . CONNECTED ; stateChangeListeners . forEach ( l -> l . accept ( PrimitiveState . CONNECTED ) ) ; } break ; case SUSPENDED : if ( this . state == PrimitiveState . CONNECTED ) { this . state = PrimitiveState . SUSPENDED ; stateChangeListeners . forEach ( l -> l . accept ( PrimitiveState . SUSPENDED ) ) ; } break ; case CLOSED : if ( this . state != PrimitiveState . CLOSED ) { this . state = PrimitiveState . CLOSED ; stateChangeListeners . forEach ( l -> l . accept ( PrimitiveState . CLOSED ) ) ; } break ; } }
Handles a partition proxy state change .
20,246
public boolean isNewerThan ( MapValue other ) { if ( other == null ) { return true ; } return this . timestamp . isNewerThan ( other . timestamp ) ; }
Tests if this value is newer than the specified MapValue .
20,247
private CompletableFuture < T > orderedFuture ( ) { if ( ! complete ) { synchronized ( orderedFutures ) { if ( ! complete ) { CompletableFuture < T > future = new CompletableFuture < > ( ) ; orderedFutures . add ( future ) ; return future ; } } } if ( error == null ) { return CompletableFuture . completedFuture ( result ) ; } else { return Futures . exceptionalFuture ( error ) ; } }
Adds a new ordered future .
20,248
private void complete ( T result , Throwable error ) { synchronized ( orderedFutures ) { this . result = result ; this . error = error ; this . complete = true ; if ( error == null ) { for ( CompletableFuture < T > future : orderedFutures ) { future . complete ( result ) ; } } else { for ( CompletableFuture < T > future : orderedFutures ) { future . completeExceptionally ( error ) ; } } orderedFutures . clear ( ) ; } }
Completes futures in FIFO order .
20,249
public CompletableFuture < byte [ ] > invoke ( PrimitiveOperation operation ) { CompletableFuture < byte [ ] > future = new CompletableFuture < > ( ) ; switch ( operation . id ( ) . type ( ) ) { case COMMAND : context . execute ( ( ) -> invokeCommand ( operation , future ) ) ; break ; case QUERY : context . execute ( ( ) -> invokeQuery ( operation , future ) ) ; break ; default : throw new IllegalArgumentException ( "Unknown operation type " + operation . id ( ) . type ( ) ) ; } return future ; }
Submits a operation to the cluster .
20,250
public MemberSelector createSelector ( CommunicationStrategy selectionStrategy ) { MemberSelector selector = new MemberSelector ( leader , members , selectionStrategy , this ) ; selectors . add ( selector ) ; return selector ; }
Creates a new address selector .
20,251
public void resetAll ( MemberId leader , Collection < MemberId > members ) { MemberId oldLeader = this . leader ; this . leader = leader ; this . members = Lists . newLinkedList ( members ) ; selectors . forEach ( s -> s . reset ( leader , this . members ) ) ; if ( ! Objects . equals ( oldLeader , leader ) ) { leaderChangeListeners . forEach ( l -> l . accept ( leader ) ) ; } }
Resets all child selectors .
20,252
public static < T > AtomixFuture < T > wrap ( CompletableFuture < T > future ) { AtomixFuture < T > newFuture = new AtomixFuture < > ( ) ; future . whenComplete ( ( result , error ) -> { if ( error == null ) { newFuture . complete ( result ) ; } else { newFuture . completeExceptionally ( error ) ; } } ) ; return newFuture ; }
Wraps the given future in a new blockable future .
20,253
public static < T > CompletableFuture < T > completedFuture ( T result ) { CompletableFuture < T > future = new AtomixFuture < > ( ) ; future . complete ( result ) ; return future ; }
Returns a new completed Atomix future .
20,254
public static < T > CompletableFuture < T > exceptionalFuture ( Throwable t ) { CompletableFuture < T > future = new AtomixFuture < > ( ) ; future . completeExceptionally ( t ) ; return future ; }
Returns a new exceptionally completed Atomix future .
20,255
public T acquire ( ) { if ( closed ) { throw new IllegalStateException ( "pool closed" ) ; } T reference = pool . poll ( ) ; if ( reference == null ) { reference = factory . createReference ( this ) ; } reference . acquire ( ) ; return reference ; }
Acquires a reference .
20,256
public LogSession . Builder sessionBuilder ( ) { return new DistributedLogSession . Builder ( ) { public LogSession build ( ) { return new DistributedLogSession ( partitionId , sessionIdProvider . get ( ) . join ( ) , clusterMembershipService , protocol , primaryElection , threadContextFactory . createContext ( ) ) ; } } ; }
Returns a new distributed log session builder .
20,257
protected int checkRead ( int length ) { checkRead ( position , length ) ; int previousPosition = this . position ; this . position = previousPosition + length ; return offset ( previousPosition ) ; }
Checks bounds for a read for the given length .
20,258
protected int checkWrite ( int length ) { checkWrite ( position , length ) ; int previousPosition = this . position ; this . position = previousPosition + length ; return offset ( previousPosition ) ; }
Checks bounds for a write of the given length .
20,259
private int calculateCapacity ( int minimumCapacity ) { int newCapacity = Math . min ( Math . max ( capacity , 2 ) , minimumCapacity ) ; while ( newCapacity < Math . min ( minimumCapacity , maxCapacity ) ) { newCapacity <<= 1 ; } return Math . min ( newCapacity , maxCapacity ) ; }
Calculates the next capacity that meets the given minimum capacity .
20,260
@ SuppressWarnings ( "unchecked" ) public CompletableFuture < A > connect ( ) { return registry . createPrimitive ( name ( ) , type ( ) ) . thenApply ( v -> ( A ) this ) ; }
Connects the primitive .
20,261
public MemberConfig setProperties ( Map < String , String > map ) { Properties properties = new Properties ( ) ; properties . putAll ( map ) ; return setProperties ( properties ) ; }
Sets the member properties .
20,262
public boolean isFull ( ) { return size ( ) >= segment . descriptor ( ) . maxSegmentSize ( ) || getNextIndex ( ) - firstIndex >= segment . descriptor ( ) . maxEntries ( ) ; }
Returns a boolean indicating whether the segment is full .
20,263
private ByteBuffer zero ( ) { memory . clear ( ) ; for ( int i = 0 ; i < memory . limit ( ) ; i ++ ) { memory . put ( i , ( byte ) 0 ) ; } return memory ; }
Returns a zeroed out byte buffer .
20,264
private void bootstrap ( ) { List < MemberId > activePeers = bootstrapPeersSupplier . get ( ) ; if ( activePeers . isEmpty ( ) ) { return ; } try { requestBootstrapFromPeers ( activePeers ) . get ( DistributedPrimitive . DEFAULT_OPERATION_TIMEOUT_MILLIS , TimeUnit . MILLISECONDS ) ; } catch ( ExecutionException | InterruptedException | TimeoutException e ) { LOGGER . debug ( "Failed to bootstrap ec map {}: {}" , mapName , ExceptionUtils . getStackTrace ( e ) ) ; } }
Bootstraps the map to attempt to get in sync with existing instances of the same map on other nodes in the cluster . This is necessary to ensure that a read immediately after the map is created doesn t return a null value .
20,265
private CompletableFuture < Void > requestBootstrapFromPeer ( MemberId peer ) { LOGGER . trace ( "Sending bootstrap request to {} for {}" , peer , mapName ) ; return clusterCommunicator . < MemberId , Void > send ( bootstrapMessageSubject , localMemberId , serializer :: encode , serializer :: decode , peer ) . whenComplete ( ( updates , error ) -> { if ( error != null ) { LOGGER . debug ( "Bootstrap request to {} failed: {}" , peer , error . getMessage ( ) ) ; } } ) ; }
Requests a bootstrap from the given peer .
20,266
public void clearSecrets ( ) { if ( password != null ) { Arrays . fill ( password , ( byte ) '\0' ) ; password = null ; } nativeCredentials = null ; }
Wipe password and native credentials
20,267
public final void addAttributes ( final Map < String , String > attributes ) { if ( attributes != null ) { this . attributes . putAll ( attributes ) ; } }
Associate this user with a set of roles
20,268
public static boolean matchAny ( final Collection < String > pattern , final String [ ] candidate , boolean ignoreCase ) { for ( String string : pattern ) { if ( matchAny ( string , candidate , ignoreCase ) ) { return true ; } } return false ; }
returns true if at least one candidate match at least one pattern
20,269
public static boolean matchAny ( final String pattern , final String [ ] candidate , boolean ignoreCase ) { for ( int i = 0 ; i < candidate . length ; i ++ ) { final String string = candidate [ i ] ; if ( match ( pattern , string , ignoreCase ) ) { return true ; } } return false ; }
return true if at least one candidate matches the given pattern
20,270
private static Locale forEN ( ) { if ( "en" . equalsIgnoreCase ( Locale . getDefault ( ) . getLanguage ( ) ) ) { return Locale . getDefault ( ) ; } Locale [ ] locales = Locale . getAvailableLocales ( ) ; for ( int i = 0 ; i != locales . length ; i ++ ) { if ( "en" . equalsIgnoreCase ( locales [ i ] . getLanguage ( ) ) ) { return locales [ i ] ; } } return Locale . getDefault ( ) ; }
The Legion of the Bouncy Castle Inc
20,271
protected static String [ ] commaDelimitedListToStringArray ( String commaDelimitedStrings ) { return ( commaDelimitedStrings == null || commaDelimitedStrings . length ( ) == 0 ) ? new String [ 0 ] : commaSeparatedValuesPattern . split ( commaDelimitedStrings ) ; }
Convert a given comma delimited String into an array of String
20,272
protected static String listToCommaDelimitedString ( List < String > stringList ) { if ( stringList == null ) { return "" ; } StringBuilder result = new StringBuilder ( ) ; for ( Iterator < String > it = stringList . iterator ( ) ; it . hasNext ( ) ; ) { Object element = it . next ( ) ; if ( element != null ) { result . append ( element ) ; if ( it . hasNext ( ) ) { result . append ( ", " ) ; } } } return result . toString ( ) ; }
Convert an array of strings in a comma delimited string
20,273
public static String validateLicense ( String licenseText ) throws PGPException { licenseText = licenseText . trim ( ) . replaceAll ( "\\r|\\n" , "" ) ; licenseText = licenseText . replace ( "---- SCHNIPP (Armored PGP signed JSON as base64) ----" , "" ) ; licenseText = licenseText . replace ( "---- SCHNAPP ----" , "" ) ; try { final byte [ ] armoredPgp = BaseEncoding . base64 ( ) . decode ( licenseText ) ; final ArmoredInputStream in = new ArmoredInputStream ( new ByteArrayInputStream ( armoredPgp ) ) ; final ByteArrayOutputStream bout = new ByteArrayOutputStream ( ) ; int ch ; while ( ( ch = in . read ( ) ) >= 0 && in . isClearText ( ) ) { bout . write ( ( byte ) ch ) ; } final KeyFingerPrintCalculator c = new BcKeyFingerprintCalculator ( ) ; final PGPObjectFactory factory = new PGPObjectFactory ( in , c ) ; final PGPSignatureList sigL = ( PGPSignatureList ) factory . nextObject ( ) ; final PGPPublicKeyRingCollection pgpRings = new PGPPublicKeyRingCollection ( new ArmoredInputStream ( LicenseHelper . class . getResourceAsStream ( "/KEYS" ) ) , c ) ; if ( sigL == null || pgpRings == null || sigL . size ( ) == 0 || pgpRings . size ( ) == 0 ) { throw new PGPException ( "Cannot find license signature" ) ; } final PGPSignature sig = sigL . get ( 0 ) ; final PGPPublicKey publicKey = pgpRings . getPublicKey ( sig . getKeyID ( ) ) ; if ( publicKey == null || sig == null ) { throw new PGPException ( "license signature key mismatch" ) ; } sig . init ( new BcPGPContentVerifierBuilderProvider ( ) , publicKey ) ; final ByteArrayOutputStream lineOut = new ByteArrayOutputStream ( ) ; final InputStream sigIn = new ByteArrayInputStream ( bout . toByteArray ( ) ) ; int lookAhead = readInputLine ( lineOut , sigIn ) ; processLine ( sig , lineOut . toByteArray ( ) ) ; if ( lookAhead != - 1 ) { do { lookAhead = readInputLine ( lineOut , lookAhead , sigIn ) ; sig . update ( ( byte ) '\r' ) ; sig . update ( ( byte ) '\n' ) ; processLine ( sig , lineOut . toByteArray ( ) ) ; } while ( lookAhead != - 1 ) ; } if ( ! sig . verify ( ) ) { throw new PGPException ( "Invalid license signature" ) ; } return bout . toString ( ) ; } catch ( final Exception e ) { throw new PGPException ( e . toString ( ) , e ) ; } }
Validate pgp signature of license
20,274
public boolean writeHistoryEnabledForIndex ( String index ) { if ( index == null ) { return false ; } if ( searchguardIndex . equals ( index ) ) { return logInternalConfig ; } if ( auditLogIndex != null && auditLogIndex . equalsIgnoreCase ( index ) ) { return false ; } if ( auditLogPattern != null ) { if ( index . equalsIgnoreCase ( getExpandedIndexName ( auditLogPattern , null ) ) ) { return false ; } } return WildcardMatcher . matchAny ( watchedWriteIndices , index ) ; }
do not check for isEnabled
20,275
private static Map < Class < ? extends Throwable > , Boolean > getSqlRetryAbleExceptions ( ) { Map < Class < ? extends Throwable > , Boolean > retryableExceptions = new HashMap < > ( ) ; retryableExceptions . put ( SQLTransientException . class , true ) ; retryableExceptions . put ( SQLRecoverableException . class , true ) ; retryableExceptions . put ( TransientDataAccessException . class , true ) ; retryableExceptions . put ( SQLNonTransientConnectionException . class , true ) ; return retryableExceptions ; }
Returns all the exceptions for which a retry is useful .
20,276
protected DataSource createDataSourceInstance ( String identifier ) throws Exception { DBInstance instance = getDbInstance ( identifier ) ; return this . dataSourceFactory . createDataSource ( fromRdsInstance ( instance ) ) ; }
Creates a data source based in the instance name . The physical information for the data source is retrieved by the name passed as identifier . This method does distinguish between regular amazon rds instances and read - replicas because both meta - data is retrieved on the same way .
20,277
public String resolveToPhysicalResourceId ( String logicalResourceId ) { if ( this . stackResourceRegistry != null ) { String physicalResourceId = this . stackResourceRegistry . lookupPhysicalResourceId ( logicalResourceId ) ; if ( physicalResourceId != null ) { return physicalResourceId ; } } return logicalResourceId ; }
Resolves the provided logical resource id to the corresponding physical resource id . If the logical resource id refers to a resource part of any of the configured stacks the corresponding physical resource id from the stack is returned . If none of the configured stacks contain a resource with the provided logical resource id or no stacks are configured at all the logical resource id is returned as the physical resource id .
20,278
private String getDbInstanceResourceName ( ) { String userArn = this . identityManagement . getUser ( ) . getUser ( ) . getArn ( ) ; AmazonResourceName userResourceName = AmazonResourceName . fromString ( userArn ) ; AmazonResourceName dbResourceArn = new AmazonResourceName . Builder ( ) . withService ( "rds" ) . withRegion ( getRegion ( ) ) . withAccount ( userResourceName . getAccount ( ) ) . withResourceType ( "db" ) . withResourceName ( getDbInstanceIdentifier ( ) ) . withResourceTypeDelimiter ( ":" ) . build ( ) ; return dbResourceArn . toString ( ) ; }
Unfortunately Amazon AWS mandates to use ARN notation to get the tags . Therefore we first need to get the account number through the IAM service and then construct the ARN out of the account no and region
20,279
private static BeanDefinition getCredentials ( Element credentialsProviderElement , ParserContext parserContext ) { BeanDefinitionBuilder builder = BeanDefinitionBuilder . rootBeanDefinition ( "com.amazonaws.auth.BasicAWSCredentials" ) ; builder . addConstructorArgValue ( getAttributeValue ( ACCESS_KEY_ATTRIBUTE_NAME , credentialsProviderElement , parserContext ) ) ; builder . addConstructorArgValue ( getAttributeValue ( SECRET_KEY_ATTRIBUTE_NAME , credentialsProviderElement , parserContext ) ) ; return builder . getBeanDefinition ( ) ; }
Creates a bean definition for the credentials object . This methods creates a bean definition instead of the direct implementation to allow property place holder to change any place holder used for the access or secret key .
20,280
public String getDriverClassNameForDatabase ( DatabaseType databaseType ) { Assert . notNull ( databaseType , "databaseType must not be null" ) ; String candidate = this . getDriverClassNameMappings ( ) . get ( databaseType ) ; Assert . notNull ( candidate , String . format ( "No driver class name found for database :'%s'" , databaseType . name ( ) ) ) ; return candidate ; }
Returns the driver class for the database platform .
20,281
public int receive ( final MessageHandler handler ) { int messagesReceived = 0 ; final BroadcastReceiver receiver = this . receiver ; final long lastSeenLappedCount = receiver . lappedCount ( ) ; if ( receiver . receiveNext ( ) ) { if ( lastSeenLappedCount != receiver . lappedCount ( ) ) { throw new IllegalStateException ( "unable to keep up with broadcast" ) ; } final int length = receiver . length ( ) ; final int capacity = scratchBuffer . capacity ( ) ; if ( length > capacity && ! scratchBuffer . isExpandable ( ) ) { throw new IllegalStateException ( "buffer required length of " + length + " but only has " + capacity ) ; } final int msgTypeId = receiver . typeId ( ) ; scratchBuffer . putBytes ( 0 , receiver . buffer ( ) , receiver . offset ( ) , length ) ; if ( ! receiver . validate ( ) ) { throw new IllegalStateException ( "unable to keep up with broadcast" ) ; } handler . onMessage ( msgTypeId , scratchBuffer , 0 , length ) ; messagesReceived = 1 ; } return messagesReceived ; }
Receive one message from the broadcast buffer .
20,282
public static int parseIntOrDefault ( final String value , final int defaultValue ) { if ( null == value ) { return defaultValue ; } return Integer . parseInt ( value ) ; }
Parse an int from a String . If the String is null then return the defaultValue .
20,283
public static long epochMicros ( ) { final Instant now = Instant . now ( ) ; final long seconds = now . getEpochSecond ( ) ; final long nanosFromSecond = now . getNano ( ) ; return ( seconds * 1_000_000 ) + ( nanosFromSecond / 1_000 ) ; }
The number of microseconds since the 1 Jan 1970 UTC .
20,284
public static long epochNanos ( ) { final Instant now = Instant . now ( ) ; final long seconds = now . getEpochSecond ( ) ; final long nanosFromSecond = now . getNano ( ) ; return ( seconds * 1_000_000_000 ) + nanosFromSecond ; }
The number of nanoseconds since the 1 Jan 1970 UTC .
20,285
public static < T > boolean isReferringTo ( final Reference < T > ref , final T obj ) { return ref . get ( ) == obj ; }
Indicate whether a Reference refers to a given object .
20,286
public static boolean isDebuggerAttached ( ) { final RuntimeMXBean runtimeMXBean = ManagementFactory . getRuntimeMXBean ( ) ; for ( final String arg : runtimeMXBean . getInputArguments ( ) ) { if ( arg . contains ( "-agentlib:jdwp" ) ) { return true ; } } return false ; }
Is a debugger attached to the JVM?
20,287
public static String threadDump ( ) { final StringBuilder sb = new StringBuilder ( ) ; final ThreadMXBean threadMXBean = ManagementFactory . getThreadMXBean ( ) ; for ( final ThreadInfo info : threadMXBean . getThreadInfo ( threadMXBean . getAllThreadIds ( ) , Integer . MAX_VALUE ) ) { sb . append ( '"' ) . append ( info . getThreadName ( ) ) . append ( "\": " ) . append ( info . getThreadState ( ) ) ; for ( final StackTraceElement stackTraceElement : info . getStackTrace ( ) ) { sb . append ( "\n at " ) . append ( stackTraceElement . toString ( ) ) ; } sb . append ( "\n\n" ) ; } return sb . toString ( ) ; }
Get a formatted dump of all threads with associated state and stack traces .
20,288
public static int getSizeAsInt ( final String propertyName , final int defaultValue ) { final String propertyValue = getProperty ( propertyName ) ; if ( propertyValue != null ) { final long value = parseSize ( propertyName , propertyValue ) ; if ( value < 0 || value > Integer . MAX_VALUE ) { throw new NumberFormatException ( propertyName + " must positive and less than Integer.MAX_VALUE :" + value ) ; } return ( int ) value ; } return defaultValue ; }
Get a size value as an int from a system property . Supports a g m and k suffix to indicate gigabytes megabytes or kilobytes respectively .
20,289
public static long getSizeAsLong ( final String propertyName , final long defaultValue ) { final String propertyValue = getProperty ( propertyName ) ; if ( propertyValue != null ) { final long value = parseSize ( propertyName , propertyValue ) ; if ( value < 0 ) { throw new NumberFormatException ( propertyName + " must be positive: " + value ) ; } return value ; } return defaultValue ; }
Get a size value as a long from a system property . Supports a g m and k suffix to indicate gigabytes megabytes or kilobytes respectively .
20,290
public static long parseSize ( final String propertyName , final String propertyValue ) { final int lengthMinusSuffix = propertyValue . length ( ) - 1 ; final char lastCharacter = propertyValue . charAt ( lengthMinusSuffix ) ; if ( Character . isDigit ( lastCharacter ) ) { return Long . valueOf ( propertyValue ) ; } final long value = AsciiEncoding . parseLongAscii ( propertyValue , 0 , lengthMinusSuffix ) ; switch ( lastCharacter ) { case 'k' : case 'K' : if ( value > MAX_K_VALUE ) { throw new NumberFormatException ( propertyName + " would overflow long: " + propertyValue ) ; } return value * 1024 ; case 'm' : case 'M' : if ( value > MAX_M_VALUE ) { throw new NumberFormatException ( propertyName + " would overflow long: " + propertyValue ) ; } return value * 1024 * 1024 ; case 'g' : case 'G' : if ( value > MAX_G_VALUE ) { throw new NumberFormatException ( propertyName + " would overflow long: " + propertyValue ) ; } return value * 1024 * 1024 * 1024 ; default : throw new NumberFormatException ( propertyName + ": " + propertyValue + " should end with: k, m, or g." ) ; } }
Parse a string representation of a value with optional suffix of g m and k suffix to indicate gigabytes megabytes or kilobytes respectively .
20,291
public static void fill ( final FileChannel fileChannel , final long position , final long length , final byte value ) { try { final byte [ ] filler ; if ( 0 != value ) { filler = new byte [ BLOCK_SIZE ] ; Arrays . fill ( filler , value ) ; } else { filler = FILLER ; } final ByteBuffer byteBuffer = ByteBuffer . wrap ( filler ) ; fileChannel . position ( position ) ; final int blocks = ( int ) ( length / BLOCK_SIZE ) ; final int blockRemainder = ( int ) ( length % BLOCK_SIZE ) ; for ( int i = 0 ; i < blocks ; i ++ ) { byteBuffer . position ( 0 ) ; fileChannel . write ( byteBuffer ) ; } if ( blockRemainder > 0 ) { byteBuffer . position ( 0 ) ; byteBuffer . limit ( blockRemainder ) ; fileChannel . write ( byteBuffer ) ; } } catch ( final IOException ex ) { LangUtil . rethrowUnchecked ( ex ) ; } }
Fill a region of a file with a given byte value .
20,292
public static void delete ( final File file , final boolean ignoreFailures ) { if ( file . isDirectory ( ) ) { final File [ ] files = file . listFiles ( ) ; if ( null != files ) { for ( final File f : files ) { delete ( f , ignoreFailures ) ; } } } if ( ! file . delete ( ) && ! ignoreFailures ) { try { Files . delete ( file . toPath ( ) ) ; } catch ( final IOException ex ) { LangUtil . rethrowUnchecked ( ex ) ; } } }
Recursively delete a file or directory tree .
20,293
public static void ensureDirectoryExists ( final File directory , final String descriptionLabel ) { if ( ! directory . exists ( ) ) { if ( ! directory . mkdirs ( ) ) { throw new IllegalArgumentException ( "could not create " + descriptionLabel + " directory: " + directory ) ; } } }
Create a directory if it doesn t already exist .
20,294
public static void deleteIfExists ( final File file ) { if ( file . exists ( ) ) { try { Files . delete ( file . toPath ( ) ) ; } catch ( final IOException ex ) { LangUtil . rethrowUnchecked ( ex ) ; } } }
Delete file only if it already exists .
20,295
public static void checkFileExists ( final File file , final String name ) { if ( ! file . exists ( ) ) { final String msg = "missing file for " + name + " : " + file . getAbsolutePath ( ) ; throw new IllegalStateException ( msg ) ; } }
Check that a file exists and throw an exception if not .
20,296
public static long map ( final FileChannel fileChannel , final FileChannel . MapMode mode , final long offset , final long length ) { try { return ( long ) MappingMethods . MAP_ADDRESS . invoke ( fileChannel , getMode ( mode ) , offset , length ) ; } catch ( final IllegalAccessException | InvocationTargetException ex ) { LangUtil . rethrowUnchecked ( ex ) ; } return 0 ; }
Map a range of a file and return the address at which the range begins .
20,297
public static void unmap ( final FileChannel fileChannel , final long address , final long length ) { try { MappingMethods . UNMAP_ADDRESS . invoke ( fileChannel , address , length ) ; } catch ( final IllegalAccessException | InvocationTargetException ex ) { LangUtil . rethrowUnchecked ( ex ) ; } }
Unmap a region of a file .
20,298
public int allocate ( final String label , final int typeId ) { final int counterId = nextCounterId ( ) ; checkCountersCapacity ( counterId ) ; final int recordOffset = metaDataOffset ( counterId ) ; checkMetaDataCapacity ( recordOffset ) ; try { metaDataBuffer . putInt ( recordOffset + TYPE_ID_OFFSET , typeId ) ; metaDataBuffer . putLong ( recordOffset + FREE_FOR_REUSE_DEADLINE_OFFSET , NOT_FREE_TO_REUSE ) ; putLabel ( recordOffset , label ) ; metaDataBuffer . putIntOrdered ( recordOffset , RECORD_ALLOCATED ) ; } catch ( final Exception ex ) { freeList . pushInt ( counterId ) ; LangUtil . rethrowUnchecked ( ex ) ; } return counterId ; }
Allocate a new counter with a given label and type .
20,299
public void free ( final int counterId ) { final int recordOffset = metaDataOffset ( counterId ) ; metaDataBuffer . putLong ( recordOffset + FREE_FOR_REUSE_DEADLINE_OFFSET , epochClock . time ( ) + freeToReuseTimeoutMs ) ; metaDataBuffer . putIntOrdered ( recordOffset , RECORD_RECLAIMED ) ; freeList . addInt ( counterId ) ; }
Free the counter identified by counterId .