idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
22,000
public GroupsConfigurationBuilder clearGroupers ( ) { List < Grouper < ? > > groupers = attributes . attribute ( GROUPERS ) . get ( ) ; groupers . clear ( ) ; attributes . attribute ( GROUPERS ) . set ( groupers ) ; return this ; }
Clear the groupers
22,001
public GroupsConfigurationBuilder addGrouper ( Grouper < ? > grouper ) { List < Grouper < ? > > groupers = attributes . attribute ( GROUPERS ) . get ( ) ; groupers . add ( grouper ) ; attributes . attribute ( GROUPERS ) . set ( groupers ) ; return this ; }
Add a grouper
22,002
private Cache < QueryCacheKey , Object > getCache ( ) { final Cache < QueryCacheKey , Object > cache = lazyCache ; if ( cache != null ) { return cache ; } synchronized ( this ) { if ( lazyCache == null ) { internalCacheRegistry . registerInternalCache ( QUERY_CACHE_NAME , getQueryCacheConfig ( ) . build ( ) , EnumSet . noneOf ( InternalCacheRegistry . Flag . class ) ) ; lazyCache = cacheManager . getCache ( QUERY_CACHE_NAME ) ; } return lazyCache ; } }
Obtain the cache . Start it lazily when needed .
22,003
private ConfigurationBuilder getQueryCacheConfig ( ) { ConfigurationBuilder cfgBuilder = new ConfigurationBuilder ( ) ; cfgBuilder . clustering ( ) . cacheMode ( CacheMode . LOCAL ) . transaction ( ) . transactionMode ( TransactionMode . NON_TRANSACTIONAL ) . expiration ( ) . maxIdle ( ENTRY_LIFESPAN , TimeUnit . SECONDS ) . memory ( ) . evictionType ( EvictionType . COUNT ) . size ( MAX_ENTRIES ) ; return cfgBuilder ; }
Create the configuration of the internal query cache .
22,004
public Class < ? > getClass ( int id ) throws IOException { if ( id < 0 || id > internalIdToClass . length ) { throw new IOException ( "Unknown class id " + id ) ; } Class < ? > clazz = internalIdToClass [ id ] ; if ( clazz == null ) { throw new IOException ( "Unknown class id " + id ) ; } return clazz ; }
This method throws IOException because it is assumed that we got the id from network .
22,005
private < R > boolean requiresFinalizer ( boolean parallelPublisher , Set < K > keysToInclude , DeliveryGuarantee deliveryGuarantee ) { return parallelPublisher || keysToInclude == null && deliveryGuarantee == DeliveryGuarantee . EXACTLY_ONCE ; }
This method is used to determine if a finalizer is required to be sent remotely . For cases we don t have to we don t want to serialize it for nothing
22,006
private long performGet ( long bucketHeadAddress , WrappedBytes k ) { long address = bucketHeadAddress ; while ( address != 0 ) { long nextAddress = offHeapEntryFactory . getNext ( address ) ; if ( offHeapEntryFactory . equalsKey ( address , k ) ) { break ; } else { address = nextAddress ; } } return address ; }
Gets the actual address for the given key in the given bucket or 0 if it isn t present or expired
22,007
public void dataRehashed ( DataRehashedEvent < K , V > event ) { ConsistentHash startHash = event . getConsistentHashAtStart ( ) ; ConsistentHash endHash = event . getConsistentHashAtEnd ( ) ; boolean trace = log . isTraceEnabled ( ) ; if ( startHash != null && endHash != null ) { if ( trace ) { log . tracef ( "Data rehash occurred startHash: %s and endHash: %s with new topology %s and was pre %s" , startHash , endHash , event . getNewTopologyId ( ) , event . isPre ( ) ) ; } if ( ! changeListener . isEmpty ( ) ) { if ( trace ) { log . tracef ( "Previous segments %s " , startHash . getSegmentsForOwner ( localAddress ) ) ; log . tracef ( "After segments %s " , endHash . getSegmentsForOwner ( localAddress ) ) ; } IntSet beforeSegments = IntSets . mutableFrom ( startHash . getSegmentsForOwner ( localAddress ) ) ; beforeSegments . removeAll ( endHash . getSegmentsForOwner ( localAddress ) ) ; if ( ! beforeSegments . isEmpty ( ) ) { for ( Map . Entry < Object , SegmentListener > entry : changeListener . entrySet ( ) ) { if ( trace ) { log . tracef ( "Notifying %s through SegmentChangeListener" , entry . getKey ( ) ) ; } entry . getValue ( ) . lostSegments ( beforeSegments ) ; } } else if ( trace ) { log . tracef ( "No segments have been removed from data rehash, no notification required" ) ; } } else if ( trace ) { log . tracef ( "No change listeners present!" ) ; } } }
We need to listen to data rehash events in case if data moves while we are iterating over it . If a rehash occurs causing this node to lose a segment and there is something iterating over the stream looking for values of that segment we can t guarantee that the data has all been seen correctly so we must therefore suspect that node by sending it back to the owner .
22,008
private void handleSuspectSegmentsBeforeStream ( Object requestId , SegmentListener listener , IntSet segments ) { LocalizedCacheTopology topology = dm . getCacheTopology ( ) ; if ( trace ) { log . tracef ( "Topology for supplier is %s for id %s" , topology , requestId ) ; } ConsistentHash readCH = topology . getCurrentCH ( ) ; ConsistentHash pendingCH = topology . getPendingCH ( ) ; if ( pendingCH != null ) { IntSet lostSegments = IntSets . mutableEmptySet ( topology . getCurrentCH ( ) . getNumSegments ( ) ) ; PrimitiveIterator . OfInt iterator = segments . iterator ( ) ; while ( iterator . hasNext ( ) ) { int segment = iterator . nextInt ( ) ; if ( ! pendingCH . isSegmentLocalToNode ( localAddress , segment ) || ! readCH . isSegmentLocalToNode ( localAddress , segment ) ) { iterator . remove ( ) ; lostSegments . set ( segment ) ; } } if ( ! lostSegments . isEmpty ( ) ) { if ( trace ) { log . tracef ( "Lost segments %s during rehash for id %s" , lostSegments , requestId ) ; } listener . lostSegments ( lostSegments ) ; } else if ( trace ) { log . tracef ( "Currently in the middle of a rehash for id %s" , requestId ) ; } } else { IntSet ourSegments = topology . getLocalReadSegments ( ) ; if ( segments . retainAll ( ourSegments ) ) { if ( trace ) { log . tracef ( "We found to be missing some segments requested for id %s" , requestId ) ; } listener . localSegments ( ourSegments ) ; } else if ( trace ) { log . tracef ( "Hash %s for id %s" , readCH , requestId ) ; } } }
that we allow backup owners to respond even though it was thought to be a primary owner .
22,009
public void addUser ( String userName , String userRealm , char [ ] password , String ... groups ) { if ( userName == null ) { throw new IllegalArgumentException ( "userName is null" ) ; } if ( userRealm == null ) { throw new IllegalArgumentException ( "userRealm is null" ) ; } if ( password == null ) { throw new IllegalArgumentException ( "password is null" ) ; } final String canonUserRealm = userRealm . toLowerCase ( ) . trim ( ) ; final String canonUserName = userName . toLowerCase ( ) . trim ( ) ; synchronized ( map ) { Map < String , Entry > realmMap = map . get ( canonUserRealm ) ; if ( realmMap == null ) { realmMap = new HashMap < String , Entry > ( ) ; map . put ( canonUserRealm , realmMap ) ; } realmMap . put ( canonUserName , new Entry ( canonUserName , canonUserRealm , password , groups != null ? groups : new String [ 0 ] ) ) ; } }
Add a user to the authentication table .
22,010
protected < C extends FlagAffectedCommand & TopologyAffectedCommand > CompletionStage < Void > remoteGetSingleKey ( InvocationContext ctx , C command , Object key , boolean isWrite ) { LocalizedCacheTopology cacheTopology = checkTopologyId ( command ) ; int topologyId = cacheTopology . getTopologyId ( ) ; DistributionInfo info = retrieveDistributionInfo ( cacheTopology , command , key ) ; if ( info . isReadOwner ( ) ) { if ( trace ) { log . tracef ( "Key %s became local after wrapping, retrying command. Command topology is %d, current topology is %d" , key , command . getTopologyId ( ) , topologyId ) ; } if ( command . getTopologyId ( ) == topologyId ) { throw new IllegalStateException ( ) ; } throw OutdatedTopologyException . RETRY_NEXT_TOPOLOGY ; } if ( trace ) { log . tracef ( "Perform remote get for key %s. currentTopologyId=%s, owners=%s" , key , topologyId , info . readOwners ( ) ) ; } ClusteredGetCommand getCommand = cf . buildClusteredGetCommand ( key , info . segmentId ( ) , command . getFlagsBitSet ( ) ) ; getCommand . setTopologyId ( topologyId ) ; getCommand . setWrite ( isWrite ) ; return rpcManager . invokeCommandStaggered ( info . readOwners ( ) , getCommand , new RemoteGetSingleKeyCollector ( ) , rpcManager . getSyncRpcOptions ( ) ) . thenAccept ( response -> { Object responseValue = response . getResponseValue ( ) ; if ( responseValue == null ) { if ( rvrl != null ) { rvrl . remoteValueNotFound ( key ) ; } wrapRemoteEntry ( ctx , key , NullCacheEntry . getInstance ( ) , isWrite ) ; return ; } InternalCacheEntry ice = ( ( InternalCacheValue ) responseValue ) . toInternalCacheEntry ( key ) ; if ( rvrl != null ) { rvrl . remoteValueFound ( ice ) ; } wrapRemoteEntry ( ctx , key , ice , isWrite ) ; } ) ; }
Fetch a key from its remote owners and store it in the context .
22,011
public TransportConfigurationBuilder initialClusterTimeout ( long initialClusterTimeout , TimeUnit unit ) { attributes . attribute ( INITIAL_CLUSTER_TIMEOUT ) . set ( unit . toMillis ( initialClusterTimeout ) ) ; return this ; }
Sets the timeout for the initial cluster to form . Defaults to 1 minute
22,012
@ Start ( priority = 50 ) public void start ( ) { timeout = configuration . clustering ( ) . stateTransfer ( ) . timeout ( ) ; chunkSize = configuration . clustering ( ) . stateTransfer ( ) . chunkSize ( ) ; }
Must start before StateTransferManager sends the join request
22,013
public static < X > String createParameterId ( Type type , Set < Annotation > annotations ) { StringBuilder builder = new StringBuilder ( ) ; if ( type instanceof Class < ? > ) { Class < ? > c = ( Class < ? > ) type ; builder . append ( c . getName ( ) ) ; } else { builder . append ( type . toString ( ) ) ; } builder . append ( createAnnotationCollectionId ( annotations ) ) ; return builder . toString ( ) ; }
Creates a string representation of a given type and set of annotations .
22,014
private < T > List < T > immutableAdd ( List < T > list , T element ) { List < T > result = new ArrayList < T > ( list ) ; result . add ( element ) ; return Collections . unmodifiableList ( result ) ; }
Helpers for working with immutable lists
22,015
public static String getCacheName ( Method method , String methodCacheName , CacheDefaults cacheDefaultsAnnotation , boolean generate ) { assertNotNull ( method , "method parameter must not be null" ) ; assertNotNull ( methodCacheName , "methodCacheName parameter must not be null" ) ; String cacheName = methodCacheName . trim ( ) ; if ( cacheName . isEmpty ( ) && cacheDefaultsAnnotation != null ) { cacheName = cacheDefaultsAnnotation . cacheName ( ) . trim ( ) ; } if ( cacheName . isEmpty ( ) && generate ) { cacheName = getDefaultMethodCacheName ( method ) ; } return cacheName ; }
Resolves the cache name of a method annotated with a JCACHE annotation .
22,016
private static String getDefaultMethodCacheName ( Method method ) { int i = 0 ; int nbParameters = method . getParameterTypes ( ) . length ; StringBuilder cacheName = new StringBuilder ( ) . append ( method . getDeclaringClass ( ) . getName ( ) ) . append ( "." ) . append ( method . getName ( ) ) . append ( "(" ) ; for ( Class < ? > oneParameterType : method . getParameterTypes ( ) ) { cacheName . append ( oneParameterType . getName ( ) ) ; if ( i < ( nbParameters - 1 ) ) { cacheName . append ( "," ) ; } i ++ ; } return cacheName . append ( ")" ) . toString ( ) ; }
Returns the default cache name associated to the given method according to JSR - 107 .
22,017
public < K , V > RemoteCache < K , V > getRemoteCache ( InjectionPoint injectionPoint ) { final Set < Annotation > qualifiers = injectionPoint . getQualifiers ( ) ; final RemoteCacheManager cacheManager = getRemoteCacheManager ( qualifiers . toArray ( new Annotation [ 0 ] ) ) ; final Remote remote = getRemoteAnnotation ( injectionPoint . getAnnotated ( ) ) ; if ( remote != null && ! remote . value ( ) . isEmpty ( ) ) { return cacheManager . getCache ( remote . value ( ) ) ; } return cacheManager . getCache ( ) ; }
Produces the remote cache .
22,018
protected Object convert ( Object instance ) { try { return ProtobufUtil . toWrappedByteArray ( serializationContext , instance ) ; } catch ( IOException e ) { throw new CacheException ( e ) ; } }
Marshals the instance using Protobuf .
22,019
public AnnotatedTypeBuilder < X > addToMethodParameter ( Method method , int position , Annotation annotation ) { if ( ! methods . containsKey ( method ) ) { methods . put ( method , new AnnotationBuilder ( ) ) ; } if ( methodParameters . get ( method ) == null ) { methodParameters . put ( method , new HashMap < Integer , AnnotationBuilder > ( ) ) ; } if ( methodParameters . get ( method ) . get ( position ) == null ) { methodParameters . get ( method ) . put ( position , new AnnotationBuilder ( ) ) ; } methodParameters . get ( method ) . get ( position ) . add ( annotation ) ; return this ; }
Add an annotation to the specified method parameter . If the method is not already present it will be added . If the method parameter is not already present it will be added .
22,020
public AnnotatedTypeBuilder < X > removeFromMethodParameter ( Method method , int position , Class < ? extends Annotation > annotationType ) { if ( methods . get ( method ) == null ) { throw new IllegalArgumentException ( "Method not present " + method + " on " + javaClass ) ; } else { if ( methodParameters . get ( method ) . get ( position ) == null ) { throw new IllegalArgumentException ( "Method parameter " + position + " not present on " + method + " on " + javaClass ) ; } else { methodParameters . get ( method ) . get ( position ) . remove ( annotationType ) ; } } return this ; }
Remove an annotation from the specified method parameter .
22,021
public MapSession getSession ( String id , boolean updateTTL ) { return Optional . ofNullable ( cache . get ( id ) ) . map ( v -> ( MapSession ) v . get ( ) ) . map ( v -> updateTTL ( v , updateTTL ) ) . orElse ( null ) ; }
Returns session with optional parameter whether or not update time accessed .
22,022
@ ManagedAttribute ( description = "Number of seconds since cache started" , displayName = "Seconds since cache started" , units = Units . SECONDS , measurementType = MeasurementType . TRENDSUP , displayType = DisplayType . SUMMARY ) public long getElapsedTime ( ) { return getTimeSinceStart ( ) ; }
Returns number of seconds since cache started
22,023
private boolean parentIsNotOfClass ( BaseCondition condition , Class < ? extends BooleanCondition > expectedParentClass ) { BaseCondition parent = condition . getParent ( ) ; return parent != null && parent . getClass ( ) != expectedParentClass ; }
We check if the parent if of the expected class hoping that if it is then we can avoid wrapping this condition in parentheses and still maintain the same logic .
22,024
public HashConfigurationBuilder consistentHashFactory ( ConsistentHashFactory < ? extends ConsistentHash > consistentHashFactory ) { attributes . attribute ( CONSISTENT_HASH_FACTORY ) . set ( consistentHashFactory ) ; return this ; }
The consistent hash factory in use .
22,025
public HashConfigurationBuilder numOwners ( int numOwners ) { if ( numOwners < 1 ) throw new IllegalArgumentException ( "numOwners cannot be less than 1" ) ; attributes . attribute ( NUM_OWNERS ) . set ( numOwners ) ; return this ; }
Number of cluster - wide replicas for each cache entry .
22,026
private Object handleTxCommand ( TxInvocationContext ctx , TransactionBoundaryCommand command ) { if ( trace ) log . tracef ( "handleTxCommand for command %s, origin %s" , command , getOrigin ( ctx ) ) ; updateTopologyId ( command ) ; return invokeNextAndHandle ( ctx , command , handleTxReturn ) ; }
Special processing required for transaction commands .
22,027
public DataContainerConfigurationBuilder dataContainer ( DataContainer dataContainer ) { attributes . attribute ( DATA_CONTAINER ) . set ( dataContainer ) ; return this ; }
Specify the data container in use
22,028
public < Original , E > OnCloseIterator < E > start ( Address origin , Supplier < Stream < Original > > streamSupplier , Iterable < IntermediateOperation > intOps , Object requestId ) { if ( trace ) { log . tracef ( "Iterator requested from %s using requestId %s" , origin , requestId ) ; } BaseStream stream = streamSupplier . get ( ) ; for ( IntermediateOperation intOp : intOps ) { stream = intOp . perform ( stream ) ; } OnCloseIterator < E > iter = new IteratorCloser < > ( ( CloseableIterator < E > ) Closeables . iterator ( stream ) ) ; iter . onClose ( ( ) -> closeIterator ( origin , requestId ) ) ; currentRequests . put ( requestId , iter ) ; Set < Object > ids = ownerRequests . computeIfAbsent ( origin , k -> ConcurrentHashMap . newKeySet ( ) ) ; ids . add ( requestId ) ; return iter ; }
Starts an iteration process from the given stream that converts the stream to a subsequent stream using the given intermediate operations and then creates a managed iterator for the caller to subsequently retrieve .
22,029
public boolean equalsKey ( long address , WrappedBytes wrappedBytes ) { int headerOffset = evictionEnabled ? 24 : 8 ; byte type = MEMORY . getByte ( address , headerOffset ) ; headerOffset ++ ; int hashCode = wrappedBytes . hashCode ( ) ; if ( hashCode != MEMORY . getInt ( address , headerOffset ) ) { return false ; } headerOffset += 4 ; int keyLength = MEMORY . getInt ( address , headerOffset ) ; if ( keyLength != wrappedBytes . getLength ( ) ) { return false ; } headerOffset += 4 ; if ( requiresMetadataSize ( type ) ) { headerOffset += 4 ; } headerOffset += 4 ; for ( int i = 0 ; i < keyLength ; i ++ ) { byte b = MEMORY . getByte ( address , headerOffset + i ) ; if ( b != wrappedBytes . getByte ( i ) ) return false ; } return true ; }
Assumes the address points to the entry excluding the pointer reference at the beginning
22,030
public boolean isExpired ( long address ) { int offset = evictionEnabled ? 24 : 8 ; byte metadataType = MEMORY . getByte ( address , offset ) ; if ( ( metadataType & IMMORTAL ) != 0 ) { return false ; } offset += 1 ; offset += 4 ; int keyLength = MEMORY . getInt ( address , offset ) ; offset += 4 ; long now = timeService . wallClockTime ( ) ; byte [ ] metadataBytes ; if ( ( metadataType & CUSTOM ) == CUSTOM ) { return false ; } else { offset += 4 + keyLength ; if ( ( metadataType & HAS_VERSION ) != 0 ) { offset += 4 ; } switch ( metadataType & 0xFC ) { case MORTAL : metadataBytes = new byte [ 16 ] ; MEMORY . getBytes ( address , offset , metadataBytes , 0 , metadataBytes . length ) ; return ExpiryHelper . isExpiredMortal ( Bits . getLong ( metadataBytes , 0 ) , Bits . getLong ( metadataBytes , 8 ) , now ) ; case TRANSIENT : metadataBytes = new byte [ 16 ] ; MEMORY . getBytes ( address , offset , metadataBytes , 0 , metadataBytes . length ) ; return ExpiryHelper . isExpiredTransient ( Bits . getLong ( metadataBytes , 0 ) , Bits . getLong ( metadataBytes , 8 ) , now ) ; case TRANSIENT_MORTAL : metadataBytes = new byte [ 32 ] ; MEMORY . getBytes ( address , offset , metadataBytes , 0 , metadataBytes . length ) ; long lifespan = Bits . getLong ( metadataBytes , 0 ) ; long maxIdle = Bits . getLong ( metadataBytes , 8 ) ; long created = Bits . getLong ( metadataBytes , 16 ) ; long lastUsed = Bits . getLong ( metadataBytes , 24 ) ; return ExpiryHelper . isExpiredTransientMortal ( maxIdle , lastUsed , lifespan , created , now ) ; default : return false ; } } }
Returns whether entry is expired .
22,031
public void cleanupLeaverTransactions ( List < Address > members ) { Iterator < RemoteTransaction > it = getRemoteTransactions ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { RecoveryAwareRemoteTransaction recTx = ( RecoveryAwareRemoteTransaction ) it . next ( ) ; recTx . computeOrphan ( members ) ; if ( recTx . isInDoubt ( ) ) { recoveryManager . registerInDoubtTransaction ( recTx ) ; it . remove ( ) ; } } super . cleanupLeaverTransactions ( members ) ; }
First moves the prepared transactions originated on the leavers into the recovery cache and then cleans up the transactions that are not yet prepared .
22,032
public Xid getRemoteTransactionXid ( Long internalId ) { for ( RemoteTransaction rTx : getRemoteTransactions ( ) ) { RecoverableTransactionIdentifier gtx = ( RecoverableTransactionIdentifier ) rTx . getGlobalTransaction ( ) ; if ( gtx . getInternalId ( ) == internalId ) { if ( trace ) log . tracef ( "Found xid %s matching internal id %s" , gtx . getXid ( ) , internalId ) ; return gtx . getXid ( ) ; } } if ( trace ) log . tracef ( "Could not find remote transactions matching internal id %s" , internalId ) ; return null ; }
Iterates over the remote transactions and returns the XID of the one that has an internal id equal with the supplied internal Id .
22,033
@ Start ( priority = 14 ) public void start ( ) { initMBeanServer ( globalConfig ) ; if ( mBeanServer != null ) { Collection < ComponentRef < ? > > components = basicComponentRegistry . getRegisteredComponents ( ) ; Collection < ResourceDMBean > resourceDMBeans = getResourceDMBeansFromComponents ( components ) ; nonCacheDMBeans = getNonCacheComponents ( resourceDMBeans ) ; registrar . registerMBeans ( resourceDMBeans ) ; needToUnregister = true ; log . mbeansSuccessfullyRegistered ( ) ; } }
Here is where the registration is being performed .
22,034
public void stop ( ) { if ( needToUnregister ) { try { unregisterMBeans ( nonCacheDMBeans ) ; needToUnregister = false ; } catch ( Exception e ) { log . problemsUnregisteringMBeans ( e ) ; } } if ( unregisterCacheMBean ) globalJmxRegistration . unregisterCacheMBean ( this . cacheName , this . cacheConfiguration . clustering ( ) . cacheModeString ( ) ) ; }
Unregister when the cache is being stopped .
22,035
public int estimateSize ( Codec codec ) { int size = key . length + 1 ; if ( ! ControlByte . NON_EXISTING . hasFlag ( control ) && ! ControlByte . NOT_READ . hasFlag ( control ) ) { size += 8 ; } if ( ! ControlByte . REMOVE_OP . hasFlag ( control ) ) { size += value . length ; size += codec . estimateExpirationSize ( lifespan , lifespanTimeUnit , maxIdle , maxIdleTimeUnit ) ; } return size ; }
The estimated size .
22,036
public static String readString ( ByteBuf bf ) { byte [ ] bytes = readRangedBytes ( bf ) ; return bytes . length > 0 ? new String ( bytes , CharsetUtil . UTF_8 ) : "" ; }
Reads length of String and then returns an UTF - 8 formatted String of such length . If the length is 0 an empty String is returned .
22,037
CompletableFuture < CounterConfiguration > getConfiguration ( String name ) { return stateCache . getAsync ( stateKey ( name ) ) . thenCompose ( existingConfiguration -> { if ( existingConfiguration == null ) { return checkGlobalConfiguration ( name ) ; } else { return CompletableFuture . completedFuture ( existingConfiguration ) ; } } ) ; }
Returns the counter s configuration .
22,038
private CompletableFuture < CounterConfiguration > checkGlobalConfiguration ( String name ) { for ( AbstractCounterConfiguration config : configuredCounters ) { if ( config . name ( ) . equals ( name ) ) { CounterConfiguration cConfig = parsedConfigToConfig ( config ) ; return stateCache . putIfAbsentAsync ( stateKey ( name ) , cConfig ) . thenApply ( configuration -> { if ( configuration == null ) { storage . store ( name , cConfig ) ; return cConfig ; } return configuration ; } ) ; } } return CompletableFutures . completedNull ( ) ; }
Checks if the counter is defined in the Infinispan s configuration file .
22,039
private void validateConfiguration ( CounterConfiguration configuration ) { storage . validatePersistence ( configuration ) ; switch ( configuration . type ( ) ) { case BOUNDED_STRONG : validateStrongCounterBounds ( configuration . lowerBound ( ) , configuration . initialValue ( ) , configuration . upperBound ( ) ) ; break ; case WEAK : if ( configuration . concurrencyLevel ( ) < 1 ) { throw log . invalidConcurrencyLevel ( configuration . concurrencyLevel ( ) ) ; } break ; } }
Validates the counter s configuration .
22,040
QueryResponse unicast ( Address address , ClusteredQueryCommand clusteredQueryCommand ) { if ( address . equals ( myAddress ) ) { Future < QueryResponse > localResponse = localInvoke ( clusteredQueryCommand ) ; try { return localResponse . get ( ) ; } catch ( InterruptedException e ) { throw new SearchException ( "Interrupted while searching locally" , e ) ; } catch ( ExecutionException e ) { throw new SearchException ( "Exception while searching locally" , e ) ; } } else { Map < Address , Response > responses = rpcManager . invokeRemotely ( Collections . singletonList ( address ) , clusteredQueryCommand , rpcOptions ) ; List < QueryResponse > queryResponses = cast ( responses ) ; return queryResponses . get ( 0 ) ; } }
Send this ClusteredQueryCommand to a node .
22,041
List < QueryResponse > broadcast ( ClusteredQueryCommand clusteredQueryCommand ) { Future < QueryResponse > localResponse = localInvoke ( clusteredQueryCommand ) ; Map < Address , Response > responses = rpcManager . invokeRemotely ( null , clusteredQueryCommand , rpcOptions ) ; List < QueryResponse > queryResponses = cast ( responses ) ; try { queryResponses . add ( localResponse . get ( ) ) ; } catch ( InterruptedException e ) { throw new SearchException ( "Interrupted while searching locally" , e ) ; } catch ( ExecutionException e ) { throw new SearchException ( "Exception while searching locally" , e ) ; } return queryResponses ; }
Broadcast this ClusteredQueryCommand to all cluster nodes . The command will be also invoked on local node .
22,042
public void runL1UpdateIfPossible ( InternalCacheEntry ice ) { try { if ( ice != null ) { Object key ; if ( sync . attemptUpdateToRunning ( ) && ! dc . containsKey ( ( key = ice . getKey ( ) ) ) ) { stateTransferLock . acquireSharedTopologyLock ( ) ; try { if ( ! dc . containsKey ( key ) && ! cdl . getCacheTopology ( ) . isWriteOwner ( key ) ) { log . tracef ( "Caching remotely retrieved entry for key %s in L1" , toStr ( key ) ) ; long lifespan = ice . getLifespan ( ) < 0 ? l1Lifespan : Math . min ( ice . getLifespan ( ) , l1Lifespan ) ; Metadata newMetadata = ice . getMetadata ( ) . builder ( ) . lifespan ( lifespan ) . maxIdle ( - 1 ) . build ( ) ; dc . put ( key , ice . getValue ( ) , new L1Metadata ( newMetadata ) ) ; } else { log . tracef ( "Data container contained value after rehash for key %s" , key ) ; } } finally { stateTransferLock . releaseSharedTopologyLock ( ) ; } } } } finally { sync . innerSet ( ice ) ; } }
Attempts to the L1 update and set the value . If the L1 update was marked as being skipped this will instead just set the value to release blockers . A null value can be provided which will not run the L1 update but will just alert other waiters that a null was given .
22,043
public ConnectionPoolConfigurationBuilder withPoolProperties ( Properties properties ) { TypedProperties typed = TypedProperties . toTypedProperties ( properties ) ; exhaustedAction ( typed . getEnumProperty ( ConfigurationProperties . CONNECTION_POOL_EXHAUSTED_ACTION , ExhaustedAction . class , ExhaustedAction . values ( ) [ typed . getIntProperty ( "whenExhaustedAction" , exhaustedAction . ordinal ( ) , true ) ] , true ) ) ; maxActive ( typed . getIntProperty ( ConfigurationProperties . CONNECTION_POOL_MAX_ACTIVE , typed . getIntProperty ( "maxActive" , maxActive , true ) , true ) ) ; maxWait ( typed . getLongProperty ( ConfigurationProperties . CONNECTION_POOL_MAX_WAIT , typed . getLongProperty ( "maxWait" , maxWait , true ) , true ) ) ; minIdle ( typed . getIntProperty ( ConfigurationProperties . CONNECTION_POOL_MIN_IDLE , typed . getIntProperty ( "minIdle" , minIdle , true ) , true ) ) ; minEvictableIdleTime ( typed . getLongProperty ( ConfigurationProperties . CONNECTION_POOL_MIN_EVICTABLE_IDLE_TIME , typed . getLongProperty ( "minEvictableIdleTimeMillis" , minEvictableIdleTime , true ) , true ) ) ; maxPendingRequests ( typed . getIntProperty ( ConfigurationProperties . CONNECTION_POOL_MAX_PENDING_REQUESTS , typed . getIntProperty ( "maxPendingRequests" , maxPendingRequests , true ) , true ) ) ; lifo ( typed . getBooleanProperty ( "lifo" , lifo , true ) ) ; maxTotal ( typed . getIntProperty ( "maxTotal" , maxTotal , true ) ) ; maxIdle ( typed . getIntProperty ( "maxIdle" , maxIdle , true ) ) ; numTestsPerEvictionRun ( typed . getIntProperty ( "numTestsPerEvictionRun" , numTestsPerEvictionRun , true ) ) ; timeBetweenEvictionRuns ( typed . getLongProperty ( "timeBetweenEvictionRunsMillis" , timeBetweenEvictionRuns , true ) ) ; testOnBorrow ( typed . getBooleanProperty ( "testOnBorrow" , testOnBorrow , true ) ) ; testOnReturn ( typed . getBooleanProperty ( "testOnReturn" , testOnReturn , true ) ) ; testWhileIdle ( typed . getBooleanProperty ( "testWhileIdle" , testWhileIdle , true ) ) ; return this ; }
Configures the connection pool parameter according to properties
22,044
CompletableFuture < Void > handleLifespanExpireEntry ( K key , V value , long lifespan , boolean skipLocking ) { if ( expiring . putIfAbsent ( key , key ) == null ) { if ( trace ) { log . tracef ( "Submitting expiration removal for key %s which had lifespan of %s" , toStr ( key ) , lifespan ) ; } AdvancedCache < K , V > cacheToUse = skipLocking ? cache . withFlags ( Flag . SKIP_LOCKING ) : cache ; CompletableFuture < Void > future = cacheToUse . removeLifespanExpired ( key , value , lifespan ) ; return future . whenComplete ( ( v , t ) -> expiring . remove ( key , key ) ) ; } return CompletableFutures . completedNull ( ) ; }
holds the lock until this CompletableFuture completes . Without lock skipping this would deadlock .
22,045
CompletableFuture < Boolean > handleMaxIdleExpireEntry ( K key , V value , long maxIdle , boolean skipLocking ) { return actualRemoveMaxIdleExpireEntry ( key , value , maxIdle , skipLocking ) ; }
Method invoked when an entry is found to be expired via get
22,046
CompletableFuture < Boolean > actualRemoveMaxIdleExpireEntry ( K key , V value , long maxIdle , boolean skipLocking ) { CompletableFuture < Boolean > completableFuture = new CompletableFuture < > ( ) ; Object expiringObject = expiring . putIfAbsent ( key , completableFuture ) ; if ( expiringObject == null ) { if ( trace ) { log . tracef ( "Submitting expiration removal for key %s which had maxIdle of %s" , toStr ( key ) , maxIdle ) ; } completableFuture . whenComplete ( ( b , t ) -> expiring . remove ( key , completableFuture ) ) ; try { AdvancedCache < K , V > cacheToUse = skipLocking ? cache . withFlags ( Flag . SKIP_LOCKING ) : cache ; CompletableFuture < Boolean > expired = cacheToUse . removeMaxIdleExpired ( key , value ) ; expired . whenComplete ( ( b , t ) -> { if ( t != null ) { completableFuture . completeExceptionally ( t ) ; } else { completableFuture . complete ( b ) ; } } ) ; return completableFuture ; } catch ( Throwable t ) { completableFuture . completeExceptionally ( t ) ; throw t ; } } else if ( expiringObject instanceof CompletableFuture ) { return ( CompletableFuture < Boolean > ) expiringObject ; } else { return CompletableFutures . completedTrue ( ) ; } }
Method invoked when entry should be attempted to be removed via max idle
22,047
public S purgeOnStartup ( boolean b ) { attributes . attribute ( PURGE_ON_STARTUP ) . set ( b ) ; purgeOnStartup = b ; return self ( ) ; }
If true purges this cache store when it starts up .
22,048
public < T extends StoreConfigurationBuilder < ? , ? > > T addStore ( Class < T > klass ) { try { Constructor < T > constructor = klass . getDeclaredConstructor ( PersistenceConfigurationBuilder . class ) ; T builder = constructor . newInstance ( this ) ; this . stores . add ( builder ) ; return builder ; } catch ( Exception e ) { throw new CacheConfigurationException ( "Could not instantiate loader configuration builder '" + klass . getName ( ) + "'" , e ) ; } }
Adds a cache loader that uses the specified builder class to build its configuration .
22,049
public static SmallIntSet from ( Set < Integer > set ) { if ( set instanceof SmallIntSet ) { return ( SmallIntSet ) set ; } else { return new SmallIntSet ( set ) ; } }
Either converts the given set to an IntSet if it is one or creates a new IntSet and copies the contents
22,050
public boolean add ( int i ) { boolean wasSet = bitSet . get ( i ) ; if ( ! wasSet ) { bitSet . set ( i ) ; return true ; } return false ; }
Add an integer to the set without boxing the parameter .
22,051
public boolean remove ( int i ) { boolean wasSet = bitSet . get ( i ) ; if ( wasSet ) { bitSet . clear ( i ) ; return true ; } return false ; }
Remove an integer from the set without boxing .
22,052
public static Object fromStorage ( Object stored , Encoder encoder , Wrapper wrapper ) { if ( encoder == null || wrapper == null ) { throw new IllegalArgumentException ( "Both Encoder and Wrapper must be provided!" ) ; } if ( stored == null ) return null ; return encoder . fromStorage ( wrapper . unwrap ( stored ) ) ; }
Decode object from storage format .
22,053
public static Object toStorage ( Object toStore , Encoder encoder , Wrapper wrapper ) { if ( encoder == null || wrapper == null ) { throw new IllegalArgumentException ( "Both Encoder and Wrapper must be provided!" ) ; } if ( toStore == null ) return null ; return wrapper . wrap ( encoder . toStorage ( toStore ) ) ; }
Encode object to storage format .
22,054
public static String requireSingleAttribute ( final XMLStreamReader reader , final String attributeName ) throws XMLStreamException { final int count = reader . getAttributeCount ( ) ; if ( count == 0 ) { throw missingRequired ( reader , Collections . singleton ( attributeName ) ) ; } requireNoNamespaceAttribute ( reader , 0 ) ; if ( ! attributeName . equals ( reader . getAttributeLocalName ( 0 ) ) ) { throw unexpectedAttribute ( reader , 0 ) ; } if ( count > 1 ) { throw unexpectedAttribute ( reader , 1 ) ; } return reader . getAttributeValue ( 0 ) ; }
Require that the current element have only a single attribute with the given name .
22,055
private void configureEvent ( CacheEntryListenerInvocation listenerInvocation , EventImpl < K , V > e , K key , V value , Metadata metadata , boolean pre , InvocationContext ctx , FlagAffectedCommand command , V previousValue , Metadata previousMetadata ) { key = convertKey ( listenerInvocation , key ) ; value = convertValue ( listenerInvocation , value ) ; previousValue = convertValue ( listenerInvocation , previousValue ) ; e . setOriginLocal ( ctx . isOriginLocal ( ) ) ; e . setValue ( pre ? previousValue : value ) ; e . setPre ( pre ) ; e . setOldValue ( previousValue ) ; e . setOldMetadata ( previousMetadata ) ; e . setMetadata ( metadata ) ; if ( command != null && command . hasAnyFlag ( FlagBitSets . COMMAND_RETRY ) ) { e . setCommandRetried ( true ) ; } e . setKey ( key ) ; setTx ( ctx , e ) ; }
Configure event data . Currently used for created modified removed invalidated events .
22,056
private void configureEvent ( CacheEntryListenerInvocation listenerInvocation , EventImpl < K , V > e , K key , V value , boolean pre , InvocationContext ctx ) { e . setPre ( pre ) ; e . setKey ( convertKey ( listenerInvocation , key ) ) ; e . setValue ( convertValue ( listenerInvocation , value ) ) ; e . setOriginLocal ( ctx . isOriginLocal ( ) ) ; setTx ( ctx , e ) ; }
Configure event data . Currently used for activated loaded visited events .
22,057
private void configureEvent ( CacheEntryListenerInvocation listenerInvocation , EventImpl < K , V > e , K key , V value , Metadata metadata ) { e . setKey ( convertKey ( listenerInvocation , key ) ) ; e . setValue ( convertValue ( listenerInvocation , value ) ) ; e . setMetadata ( metadata ) ; e . setOriginLocal ( true ) ; e . setPre ( false ) ; }
Configure event data . Currently used for expired events .
22,058
private FilterIndexingServiceProvider findIndexingServiceProvider ( IndexedFilter indexedFilter ) { if ( filterIndexingServiceProviders != null ) { for ( FilterIndexingServiceProvider provider : filterIndexingServiceProviders ) { if ( provider . supportsFilter ( indexedFilter ) ) { return provider ; } } } log . noFilterIndexingServiceProviderFound ( indexedFilter . getClass ( ) . getName ( ) ) ; return null ; }
Gets a suitable indexing provider for the given indexed filter .
22,059
public void shutdownNow ( ) { log . tracef ( "Stopping limited executor %s" , name ) ; running = false ; lock . lock ( ) ; try { queue . clear ( ) ; for ( Thread t : threads . keySet ( ) ) { t . interrupt ( ) ; } } finally { lock . unlock ( ) ; } }
Stops the executor and cancels any queued tasks .
22,060
void notifyCacheCollected ( ) { int result = expectedCaches . decrementAndGet ( ) ; if ( isTraceEnabled ( ) ) { log ( ) . tracef ( "[%s] Cache collected. Missing=%s." , xid , result ) ; } if ( result == 0 ) { onCachesCollected ( ) ; } }
Invoked every time a cache is found to be involved in a transaction .
22,061
private void onCachesCollected ( ) { if ( isTraceEnabled ( ) ) { log ( ) . tracef ( "[%s] All caches collected: %s" , xid , cacheNames ) ; } int size = cacheNames . size ( ) ; if ( size == 0 ) { sendReply ( ) ; return ; } List < CompletableFuture < Void > > futures = new ArrayList < > ( size ) ; for ( ByteString cacheName : cacheNames ) { try { futures . add ( completeCache ( cacheName ) ) ; } catch ( Throwable t ) { hasErrors = true ; } } CompletableFuture . allOf ( futures . toArray ( new CompletableFuture [ 0 ] ) ) . thenRun ( this :: sendReply ) ; }
Invoked when all caches are ready to complete the transaction .
22,062
private CompletableFuture < Void > completeCache ( ByteString cacheName ) throws Throwable { TxState state = globalTxTable . getState ( new CacheXid ( cacheName , xid ) ) ; HotRodServer . CacheInfo cacheInfo = server . getCacheInfo ( cacheName . toString ( ) , header . getVersion ( ) , header . getMessageId ( ) , true ) ; AdvancedCache < ? , ? > cache = server . cache ( cacheInfo , header , subject ) ; RpcManager rpcManager = cache . getRpcManager ( ) ; if ( rpcManager == null || rpcManager . getAddress ( ) . equals ( state . getOriginator ( ) ) ) { if ( isTraceEnabled ( ) ) { log ( ) . tracef ( "[%s] Completing local executed transaction." , xid ) ; } return asyncCompleteLocalTransaction ( cache , state . getTimeout ( ) ) ; } else if ( rpcManager . getMembers ( ) . contains ( state . getOriginator ( ) ) ) { if ( isTraceEnabled ( ) ) { log ( ) . tracef ( "[%s] Forward remotely executed transaction to %s." , xid , state . getOriginator ( ) ) ; } return forwardCompleteCommand ( cacheName , rpcManager , state ) ; } else { if ( isTraceEnabled ( ) ) { log ( ) . tracef ( "[%s] Originator, %s, left the cluster." , xid , state . getOriginator ( ) ) ; } return completeWithRemoteCommand ( cache , rpcManager , state ) ; } }
Completes the transaction for a specific cache .
22,063
private CompletableFuture < Void > completeWithRemoteCommand ( AdvancedCache < ? , ? > cache , RpcManager rpcManager , TxState state ) throws Throwable { CommandsFactory commandsFactory = cache . getComponentRegistry ( ) . getCommandsFactory ( ) ; CacheRpcCommand command = buildRemoteCommand ( cache . getCacheConfiguration ( ) , commandsFactory , state ) ; CompletableFuture < Void > remote = rpcManager . invokeCommandOnAll ( command , validOnly ( ) , rpcManager . getSyncRpcOptions ( ) ) . handle ( handler ( ) ) . toCompletableFuture ( ) ; commandsFactory . initializeReplicableCommand ( command , false ) ; CompletableFuture < Void > local = command . invokeAsync ( ) . handle ( handler ( ) ) ; return CompletableFuture . allOf ( remote , local ) ; }
Completes the transaction in the cache when the originator no longer belongs to the cache topology .
22,064
private CompletableFuture < Void > forwardCompleteCommand ( ByteString cacheName , RpcManager rpcManager , TxState state ) { Address originator = state . getOriginator ( ) ; CacheRpcCommand command = buildForwardCommand ( cacheName , state . getTimeout ( ) ) ; return rpcManager . invokeCommand ( originator , command , validOnly ( ) , rpcManager . getSyncRpcOptions ( ) ) . handle ( handler ( ) ) . toCompletableFuture ( ) ; }
Completes the transaction in the cache when the originator is still in the cache topology .
22,065
public final void addValue ( ExtendedStatistic stat , double value ) { container . addValue ( stat , value ) ; if ( trace ) { log . tracef ( "Add %s to %s" , value , stat ) ; } }
Adds a value to a statistic collected for this transaction .
22,066
public final void terminateTransaction ( ) { if ( trace ) { log . tracef ( "Terminating transaction. Is read only? %s. Is commit? %s" , readOnly , committed ) ; } long execTime = timeService . timeDuration ( initTime , NANOSECONDS ) ; if ( readOnly ) { if ( committed ) { incrementValue ( NUM_COMMITTED_RO_TX ) ; addValue ( RO_TX_SUCCESSFUL_EXECUTION_TIME , execTime ) ; } else { incrementValue ( NUM_ABORTED_RO_TX ) ; addValue ( RO_TX_ABORTED_EXECUTION_TIME , execTime ) ; } } else { if ( committed ) { incrementValue ( NUM_COMMITTED_WR_TX ) ; addValue ( WR_TX_SUCCESSFUL_EXECUTION_TIME , execTime ) ; } else { incrementValue ( NUM_ABORTED_WR_TX ) ; addValue ( WR_TX_ABORTED_EXECUTION_TIME , execTime ) ; } } terminate ( ) ; }
Signals this transaction as completed and updates the statistics to the final values ready to be merged in the cache statistics .
22,067
public final void flushTo ( ConcurrentGlobalContainer globalContainer ) { if ( trace ) { log . tracef ( "Flush this [%s] to %s" , this , globalContainer ) ; } container . mergeTo ( globalContainer ) ; }
Merges this statistics in the global container .
22,068
protected final void copyValue ( ExtendedStatistic from , ExtendedStatistic to ) { try { double value = container . getValue ( from ) ; container . addValue ( to , value ) ; if ( log . isDebugEnabled ( ) ) { log . debugf ( "Copy value [%s] from [%s] to [%s]" , value , from , to ) ; } } catch ( ExtendedStatisticNotFoundException e ) { log . unableToCopyValue ( from , to , e ) ; } }
Copies a statistic value and adds it to another statistic .
22,069
void writeLock ( int count ) { if ( count > 0 && counter != null ) counter . acquireShared ( count ) ; sync . acquireShared ( 1 ) ; }
Acquires the write lock and consumes the specified amount of buffer space . Blocks if the object is currently locked for reading or if the buffer is full and count is greater than 0 .
22,070
void reset ( int count ) { if ( counter != null ) counter . releaseShared ( count ) ; available . releaseShared ( count ) ; }
Resets the buffer counter to the specified number .
22,071
public void forceUnlock ( String lockName ) { Cache < Object , Integer > lockCache = getDistLockCache ( ) . getAdvancedCache ( ) . withFlags ( Flag . SKIP_CACHE_STORE , Flag . SKIP_CACHE_LOAD ) ; FileCacheKey fileCacheKey = new FileCacheKey ( indexName , lockName , affinitySegmentId ) ; Object previousValue = lockCache . remove ( fileCacheKey ) ; if ( previousValue != null && trace ) { log . tracef ( "Lock forcibly removed for index: %s" , indexName ) ; } }
Force release of the lock in this directory . Make sure to understand the consequences
22,072
public static < K , V > CacheEventFilterConverter < K , V , ObjectFilter . FilterResult > makeFilter ( Query query ) { return makeFilter ( query . getQueryString ( ) , query . getParameters ( ) ) ; }
Create an event filter out of an Ickle query .
22,073
public static QueryFactory getQueryFactory ( Cache < ? , ? > cache ) { if ( cache == null || cache . getAdvancedCache ( ) == null ) { throw new IllegalArgumentException ( "cache parameter shall not be null" ) ; } AdvancedCache < ? , ? > advancedCache = cache . getAdvancedCache ( ) ; ensureAccessPermissions ( advancedCache ) ; EmbeddedQueryEngine queryEngine = SecurityActions . getCacheComponentRegistry ( advancedCache ) . getComponent ( EmbeddedQueryEngine . class ) ; if ( queryEngine == null ) { throw log . queryModuleNotInitialised ( ) ; } return new EmbeddedQueryFactory ( queryEngine ) ; }
Obtain the query factory for building DSL based Ickle queries .
22,074
public LongStream toStream ( ) { return LongStream . iterate ( memory , l -> l + 8 ) . limit ( pointerCount ) . map ( UNSAFE :: getLong ) . filter ( l -> l != 0 ) ; }
Returns a stream of longs that are all of the various memory locations
22,075
public void start ( ) { initMBeanServer ( globalConfig ) ; if ( mBeanServer != null ) { Collection < ComponentRef < ? > > components = basicComponentRegistry . getRegisteredComponents ( ) ; resourceDMBeans = Collections . synchronizedCollection ( getResourceDMBeansFromComponents ( components ) ) ; registrar . registerMBeans ( resourceDMBeans ) ; needToUnregister = true ; } stopped = false ; }
On start the mbeans are registered .
22,076
public void stop ( ) { if ( stopped ) return ; if ( needToUnregister ) { try { unregisterMBeans ( resourceDMBeans ) ; needToUnregister = false ; } catch ( Exception e ) { log . problemsUnregisteringMBeans ( e ) ; } } stopped = true ; }
On stop the mbeans are unregistered .
22,077
public < C extends ConnectionFactoryConfigurationBuilder < ? > > C connectionFactory ( Class < C > klass ) { if ( connectionFactory != null ) { throw new IllegalStateException ( "A ConnectionFactory has already been configured for this store" ) ; } try { Constructor < C > constructor = klass . getDeclaredConstructor ( AbstractJdbcStoreConfigurationBuilder . class ) ; C builder = constructor . newInstance ( this ) ; this . connectionFactory = ( ConnectionFactoryConfigurationBuilder < ConnectionFactoryConfiguration > ) builder ; return builder ; } catch ( Exception e ) { throw new CacheConfigurationException ( "Could not instantiate loader configuration builder '" + klass . getName ( ) + "'" , e ) ; } }
Use the specified ConnectionFactory to handle connection to the database
22,078
private boolean stoppingAndNotAllowed ( ComponentStatus status , InvocationContext ctx ) throws Exception { return status . isStopping ( ) && ( ! ctx . isInTxScope ( ) || ! isOngoingTransaction ( ctx ) ) ; }
If the cache is STOPPING non - transaction invocations or transactional invocations for transaction others than the ongoing ones are no allowed . This method returns true if under this circumstances meet . Otherwise it returns false .
22,079
private KeyValuePair < CacheTransaction , Object > waitForTransactionsToComplete ( Collection < PendingTransaction > transactionsToCheck , long expectedEndTime ) throws InterruptedException { if ( transactionsToCheck . isEmpty ( ) ) { return null ; } for ( PendingTransaction tx : transactionsToCheck ) { for ( Map . Entry < Object , CompletableFuture < Void > > entry : tx . keyReleased . entrySet ( ) ) { long remaining = timeService . remainingTime ( expectedEndTime , TimeUnit . MILLISECONDS ) ; if ( ! CompletableFutures . await ( entry . getValue ( ) , remaining , TimeUnit . MILLISECONDS ) ) { return new KeyValuePair < > ( tx . cacheTransaction , entry . getKey ( ) ) ; } } } return null ; }
cache - tx and key if it timed out otherwise null
22,080
private int compareIntervals ( Interval < K > i1 , Interval < K > i2 ) { int res1 = compare ( i1 . up , i2 . low ) ; if ( res1 < 0 || res1 <= 0 && ( ! i1 . includeUpper || ! i2 . includeLower ) ) { return - 1 ; } int res2 = compare ( i2 . up , i1 . low ) ; if ( res2 < 0 || res2 <= 0 && ( ! i2 . includeUpper || ! i1 . includeLower ) ) { return 1 ; } return 0 ; }
Compare two Intervals .
22,081
public boolean remove ( Interval < K > i ) { checkValidInterval ( i ) ; return remove ( root . left , i ) ; }
Removes the Interval .
22,082
public List < Node < K , V > > stab ( K k ) { Interval < K > i = new Interval < K > ( k , true , k , true ) ; final List < Node < K , V > > nodes = new ArrayList < Node < K , V > > ( ) ; findOverlap ( root . left , i , new NodeCallback < K , V > ( ) { public void handle ( Node < K , V > node ) { nodes . add ( node ) ; } } ) ; return nodes ; }
Find all Intervals that contain a given value .
22,083
InvocationCallback queuePoll ( ) { InvocationCallback element ; synchronized ( this ) { if ( tail != head ) { element = elements [ head & mask ] ; head ++ ; } else { element = null ; frozen = true ; } } return element ; }
Remove one handler from the deque or freeze the deque if there are no more elements .
22,084
private BeanManagerInfo getBeanManagerInfo ( ClassLoader cl ) { BeanManagerInfo bmi = bmpSingleton . bmInfos . get ( cl ) ; if ( bmi == null ) { synchronized ( this ) { bmi = bmpSingleton . bmInfos . get ( cl ) ; if ( bmi == null ) { bmi = new BeanManagerInfo ( ) ; bmpSingleton . bmInfos . put ( cl , bmi ) ; } } } return bmi ; }
Get or create the BeanManagerInfo for the given ClassLoader
22,085
public void addGet ( Object key , boolean remote ) { if ( ! isEnabled ( ) ) { return ; } syncOffer ( remote ? Stat . REMOTE_GET : Stat . LOCAL_GET , key ) ; }
Adds the key to the read top - key .
22,086
public void addPut ( Object key , boolean remote ) { if ( ! isEnabled ( ) ) { return ; } syncOffer ( remote ? Stat . REMOTE_PUT : Stat . LOCAL_PUT , key ) ; }
Adds the key to the put top - key .
22,087
public void addLockInformation ( Object key , boolean contention , boolean failLock ) { if ( ! isEnabled ( ) ) { return ; } syncOffer ( Stat . MOST_LOCKED_KEYS , key ) ; if ( contention ) { syncOffer ( Stat . MOST_CONTENDED_KEYS , key ) ; } if ( failLock ) { syncOffer ( Stat . MOST_FAILED_KEYS , key ) ; } }
Adds the lock information about the key namely if the key suffer some contention and if the keys was locked or not .
22,088
public final void tryFlushAll ( ) { if ( flushing . compareAndSet ( false , true ) ) { if ( reset ) { for ( Stat stat : Stat . values ( ) ) { topKeyWrapper . get ( stat ) . reset ( this , capacity ) ; } reset = false ; } else { for ( Stat stat : Stat . values ( ) ) { topKeyWrapper . get ( stat ) . flush ( ) ; } } flushing . set ( false ) ; } }
Tries to flush all the enqueue offers to be visible globally .
22,089
protected < K , V > Map < K , V > allocMap ( int size ) { return size == 0 ? Collections . emptyMap ( ) : new HashMap < > ( size * 4 / 3 , 0.75f ) ; }
We usually know the size of the map ahead and we want to return static empty map if we re not going to add anything .
22,090
public void validateNamedParameters ( ) { if ( namedParameters != null ) { for ( Map . Entry < String , Object > e : namedParameters . entrySet ( ) ) { if ( e . getValue ( ) == null ) { throw log . queryParameterNotSet ( e . getKey ( ) ) ; } } } }
Ensure all named parameters have non - null values .
22,091
public void visitCollection ( InvocationContext ctx , Collection < ? extends VisitableCommand > toVisit ) throws Throwable { for ( VisitableCommand command : toVisit ) { command . acceptVisitor ( ctx , this ) ; } }
Helper method to visit a collection of VisitableCommands .
22,092
public static boolean isLegacyIndexingEnabled ( Descriptor messageDescriptor ) { boolean isLegacyIndexingEnabled = true ; for ( Option o : messageDescriptor . getFileDescriptor ( ) . getOptions ( ) ) { if ( o . getName ( ) . equals ( INDEXED_BY_DEFAULT_OPTION ) ) { isLegacyIndexingEnabled = Boolean . valueOf ( ( String ) o . getValue ( ) ) ; break ; } } return isLegacyIndexingEnabled ; }
Retrieves the value of the indexed_by_default protobuf option from the schema file defining the given message descriptor .
22,093
public static String getterName ( Class < ? > componentClass ) { if ( componentClass == null ) return null ; StringBuilder sb = new StringBuilder ( "get" ) ; sb . append ( componentClass . getSimpleName ( ) ) ; return sb . toString ( ) ; }
Returns a getter for a given class
22,094
public static Method getterMethod ( Class < ? > target , Class < ? > componentClass ) { try { return target . getMethod ( getterName ( componentClass ) ) ; } catch ( NoSuchMethodException e ) { return null ; } catch ( NullPointerException e ) { return null ; } }
Returns a Method object corresponding to a getter that retrieves an instance of componentClass from target .
22,095
public static Method setterMethod ( Class < ? > target , Class < ? > componentClass ) { try { return target . getMethod ( setterName ( componentClass ) , componentClass ) ; } catch ( NoSuchMethodException e ) { return null ; } catch ( NullPointerException e ) { return null ; } }
Returns a Method object corresponding to a setter that sets an instance of componentClass from target .
22,096
private Properties extractIndexingProperties ( OperationContext context , ModelNode operation , String cacheConfiguration ) { Properties properties = new Properties ( ) ; PathAddress cacheAddress = getCacheAddressFromOperation ( operation ) ; Resource cacheConfigResource = context . readResourceFromRoot ( cacheAddress . subAddress ( 0 , 2 ) , true ) . getChild ( PathElement . pathElement ( ModelKeys . CONFIGURATIONS , ModelKeys . CONFIGURATIONS_NAME ) ) . getChild ( PathElement . pathElement ( getConfigurationKey ( ) , cacheConfiguration ) ) ; PathElement indexingPathElement = PathElement . pathElement ( ModelKeys . INDEXING , ModelKeys . INDEXING_NAME ) ; if ( cacheConfigResource == null || ! cacheConfigResource . hasChild ( indexingPathElement ) ) { return properties ; } Resource indexingResource = cacheConfigResource . getChild ( indexingPathElement ) ; if ( indexingResource == null ) return properties ; ModelNode indexingModel = indexingResource . getModel ( ) ; boolean hasProperties = indexingModel . hasDefined ( ModelKeys . INDEXING_PROPERTIES ) ; if ( ! hasProperties ) return properties ; ModelNode modelNode = indexingResource . getModel ( ) . get ( ModelKeys . INDEXING_PROPERTIES ) ; List < Property > modelProperties = modelNode . asPropertyList ( ) ; modelProperties . forEach ( p -> properties . put ( p . getName ( ) , p . getValue ( ) . asString ( ) ) ) ; return properties ; }
Extract indexing information for the cache from the model .
22,097
void populate ( ModelNode fromModel , ModelNode toModel ) throws OperationFailedException { for ( AttributeDefinition attr : CacheResource . CACHE_ATTRIBUTES ) { attr . validateAndSet ( fromModel , toModel ) ; } }
Transfer elements common to both operations and models
22,098
public static List < Method > getAllMethodsShallow ( Class < ? > c , Class < ? extends Annotation > annotationType ) { List < Method > annotated = new ArrayList < > ( ) ; for ( Method m : c . getDeclaredMethods ( ) ) { if ( m . isAnnotationPresent ( annotationType ) ) annotated . add ( m ) ; } return annotated ; }
Returns a set of Methods that contain the given method annotation . This includes all public protected package and private methods but not those of superclasses and interfaces .
22,099
private static boolean notFound ( Method m , Collection < Method > s ) { for ( Method found : s ) { if ( m . getName ( ) . equals ( found . getName ( ) ) && Arrays . equals ( m . getParameterTypes ( ) , found . getParameterTypes ( ) ) ) return false ; } return true ; }
Tests whether a method has already been found i . e . overridden .