idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
1,700
public static Managed registerInjector ( final Application application , final Injector injector ) { Preconditions . checkNotNull ( application , "Application instance required" ) ; Preconditions . checkArgument ( ! INJECTORS . containsKey ( application ) , "Injector already registered for application %s" , application...
Used internally to register application specific injector .
1,701
@ SuppressWarnings ( "unchecked" ) public static < T > Class < T > getInstanceClass ( final T object ) { final Class cls = object . getClass ( ) ; return cls . getName ( ) . contains ( "$$EnhancerByGuice" ) ? ( Class < T > ) cls . getSuperclass ( ) : cls ; }
Used to get correct object type even if it s guice proxy .
1,702
public void scan ( final ClassVisitor visitor ) { if ( scanned == null ) { performScan ( ) ; } for ( Class < ? > cls : scanned ) { visitor . visit ( cls ) ; } }
Scan configured classpath packages .
1,703
public static < T > List < T > removeTypes ( final List < T > list , final List < Class < ? extends T > > filter ) { final Iterator it = list . iterator ( ) ; while ( it . hasNext ( ) ) { final Class type = it . next ( ) . getClass ( ) ; if ( filter . contains ( type ) ) { it . remove ( ) ; } } return list ; }
Filter list from objects of type present in filter list .
1,704
public ConfigPath findByPath ( final String path ) { return paths . stream ( ) . filter ( it -> it . getPath ( ) . equalsIgnoreCase ( path ) ) . findFirst ( ) . orElse ( null ) ; }
Case insensitive exact match .
1,705
public List < ConfigPath > findAllRootPaths ( ) { return paths . stream ( ) . filter ( it -> ! it . getPath ( ) . contains ( DOT ) ) . collect ( Collectors . toList ( ) ) ; }
For example it would always contain logging metrics and server paths from dropwizard configuration .
1,706
public void hkManage ( final Class < ? > type ) { if ( ! JerseyBinding . isHK2Managed ( type , options . get ( JerseyExtensionsManagedByGuice ) ) ) { throw new WrongContextException ( "HK2 creates service %s which must be managed by guice." , type . getName ( ) ) ; } hkManaged . add ( type ) ; }
Called by specific HK2 lifecycle listener to check if bean is properly instantiated by HK2 .
1,707
public void guiceManage ( final Class < ? > type ) { if ( JerseyBinding . isHK2Managed ( type , options . get ( JerseyExtensionsManagedByGuice ) ) ) { throw new WrongContextException ( "Guice creates service %s which must be managed by HK2." , type . getName ( ) ) ; } guiceManaged . add ( type ) ; }
Called by specific guice provision listener to check if bean is properly instantiated by guice .
1,708
private void checkHkFirstMode ( ) { final boolean guiceyFirstMode = context . option ( JerseyExtensionsManagedByGuice ) ; if ( ! guiceyFirstMode ) { Preconditions . checkState ( context . option ( UseHkBridge ) , "HK2 management for jersey extensions is enabled by default " + "(InstallersOptions.JerseyExtensionsManaged...
When HK2 management for jersey extensions is enabled by default then guice bridge must be enabled . Without it guice beans could not be used in resources and other jersey extensions . If this is expected then guice support is not needed at all .
1,709
public static void register ( final GuiceyConfigurationHook hook ) { if ( HOOKS . get ( ) == null ) { HOOKS . set ( new LinkedHashSet < > ( ) ) ; } HOOKS . get ( ) . add ( hook ) ; }
Register hook for current thread . Must be called before application initialization otherwise will not be used at all .
1,710
@ SuppressWarnings ( "unchecked" ) public static void configureModules ( final ConfigurationContext context ) { final Options options = new Options ( context . options ( ) ) ; for ( Module mod : context . getEnabledModules ( ) ) { if ( mod instanceof BootstrapAwareModule ) { ( ( BootstrapAwareModule ) mod ) . setBootst...
Post - process registered modules by injecting bootstrap configuration environment and options objects .
1,711
public void activate ( ) { GuiceBridge . getGuiceBridge ( ) . initializeGuiceBridge ( locator ) ; final GuiceIntoHK2Bridge guiceBridge = locator . getService ( GuiceIntoHK2Bridge . class ) ; guiceBridge . bridgeGuiceInjector ( injector ) ; }
Activate HK2 guice bridge .
1,712
protected boolean isForceSingleton ( final Class < ? > type , final boolean hkManaged ) { return ( ( Boolean ) option ( ForceSingletonForJerseyExtensions ) ) && ! hasScopeAnnotation ( type , hkManaged ) ; }
Singleton binding should not be forced if bean has explicit scope declaration .
1,713
private boolean hasScopeAnnotation ( final Class < ? > type , final boolean hkManaged ) { boolean found = false ; for ( Annotation ann : type . getAnnotations ( ) ) { final Class < ? extends Annotation > annType = ann . annotationType ( ) ; if ( annType . isAnnotationPresent ( Scope . class ) ) { found = true ; break ;...
Checks scope annotation presence directly on bean . Base classes are not checked as scope is not inheritable .
1,714
public void registerCommands ( final List < Class < Command > > commands ) { setScope ( ConfigScope . ClasspathScan . getType ( ) ) ; for ( Class < Command > cmd : commands ) { register ( ConfigItem . Command , cmd ) ; } closeScope ( ) ; }
Register commands resolved with classpath scan .
1,715
private void applyPredicatesForRegisteredItems ( final List < PredicateHandler > predicates ) { ImmutableList . builder ( ) . addAll ( getEnabledModules ( ) ) . addAll ( getEnabledBundles ( ) ) . addAll ( getEnabledExtensions ( ) ) . addAll ( getEnabledInstallers ( ) ) . build ( ) . stream ( ) . < ItemInfo > map ( this...
Disable predicate could be registered after some items registration and to make sure that predicate affects all these items - apply to all currenlty registered items .
1,716
@ SuppressWarnings ( "unchecked" ) private < T extends ItemInfoImpl > T getOrCreateInfo ( final ConfigItem type , final Object item ) { final Class < ? > itemType = getType ( item ) ; final T info ; if ( detailsHolder . containsKey ( itemType ) ) { info = ( T ) detailsHolder . get ( itemType ) ; } else { itemsHolder . ...
Disabled items may not be actually registered . In order to register disable info in uniform way dummy container is created .
1,717
public final OptionsConfig hideGroups ( final Class < Enum > ... groups ) { hiddenGroups . addAll ( Arrays . asList ( groups ) ) ; return this ; }
Hide option groups from reporting .
1,718
public static void overrideScope ( final Runnable action ) { override . set ( true ) ; try { action . run ( ) ; } finally { override . remove ( ) ; } }
Use to register overriding modules . Such complex approach was used because overriding modules is the only item that require additional parameter during registration . This parameter may be used in disable predicate to differentiate overriding modules from normal modules .
1,719
public final Reporter line ( final String line , final Object ... args ) { counter ++ ; wasEmptyLine = false ; message . append ( TAB ) . append ( String . format ( line , args ) ) . append ( NEWLINE ) ; return this ; }
Prints formatted line .
1,720
public String renderReport ( final ContextTreeConfig config ) { final Set < Class < ? > > scopes = service . getActiveScopes ( ! config . isHideDisables ( ) ) ; final TreeNode root = new TreeNode ( "APPLICATION" ) ; if ( ! config . getHiddenScopes ( ) . contains ( Application . getType ( ) ) ) { renderScopeContent ( co...
Renders configuration tree report according to provided config . By default report padded left with one tab . Subtrees are always padded with empty lines for better visibility .
1,721
private void renderBundle ( final ContextTreeConfig config , final TreeNode root , final Class < ? > scope , final Class < Object > bundle ) { final BundleItemInfo info = service . getData ( ) . getInfo ( bundle ) ; if ( isHidden ( config , info , scope ) ) { return ; } final List < String > markers = Lists . newArrayL...
Renders bundle if allowed .
1,722
@ SuppressWarnings ( "checkstyle:BooleanExpressionComplexity" ) private boolean isHidden ( final ContextTreeConfig config , final ItemInfo info , final Class < ? > scope ) { final boolean hidden = config . getHiddenItems ( ) . contains ( info . getItemType ( ) ) ; final boolean disabled = config . isHideDisables ( ) &&...
Checks element visibility according to config . Universal place to check visibility for either simple config items or bundles and special scopes .
1,723
public static ConfigurationTree build ( final Bootstrap bootstrap , final Configuration configuration , final boolean introspect ) { final List < Class > roots = resolveRootTypes ( new ArrayList < > ( ) , configuration . getClass ( ) ) ; if ( introspect ) { final List < ConfigPath > content = resolvePaths ( bootstrap ....
Analyze configuration object to extract bindable parts .
1,724
public String renderReport ( final OptionsConfig config ) { final StringBuilder res = new StringBuilder ( ) ; render ( config , res ) ; return res . toString ( ) ; }
Renders options report .
1,725
public void count ( final Stat name , final int count ) { Integer value = counters . get ( name ) ; value = value == null ? count : value + count ; counters . put ( name , value ) ; }
Inserts value for first call and sum values for consequent calls .
1,726
public void startHkTimer ( final Stat name ) { timer ( GuiceyTime ) ; if ( ! HKTime . equals ( name ) ) { timer ( HKTime ) ; } timer ( name ) ; }
Special methods for tracking time in HK2 scope . Such complication used to avoid using 3 different trackers in code . HK2 initialization is performed after bundles run and so out of scope of GuiceBundle .
1,727
private List < FeatureInstaller > prepareInstallers ( final List < Class < ? extends FeatureInstaller > > installerClasses ) { final List < FeatureInstaller > installers = Lists . newArrayList ( ) ; final Options options = new Options ( context . options ( ) ) ; for ( Class < ? extends FeatureInstaller > installerClass...
Instantiate all found installers using default constructor .
1,728
@ SuppressWarnings ( "PMD.PrematureDeclaration" ) private void resolveExtensions ( final ExtensionsHolder holder ) { final Stopwatch timer = context . stat ( ) . timer ( Stat . ExtensionsRecognitionTime ) ; final boolean guiceFirstMode = context . option ( JerseyExtensionsManagedByGuice ) ; final List < Class < ? > > m...
Performs one more classpath scan to search for extensions or simply install manually provided extension classes .
1,729
@ SuppressWarnings ( "unchecked" ) private void bindExtension ( final ExtensionItemInfo item , final FeatureInstaller installer , final ExtensionsHolder holder ) { final Class < ? extends FeatureInstaller > installerClass = installer . getClass ( ) ; final Class < ? > type = item . getType ( ) ; holder . register ( ins...
Bind extension to guice context .
1,730
public static String renderDisabledInstaller ( final Class < FeatureInstaller > type ) { return String . format ( "-%-19s %-38s" , FeatureUtils . getInstallerExtName ( type ) , brackets ( renderClass ( type ) ) ) ; }
Renders disabled installer line . The same as installer line but with - before installer name and without markers .
1,731
public static String renderPackage ( final Class < ? > type ) { return PACKAGE_FORMATTER . abbreviate ( type . isMemberClass ( ) && ! type . isAnonymousClass ( ) ? type . getDeclaringClass ( ) . getName ( ) : type . getPackage ( ) . getName ( ) ) ; }
If provided type is inner class then declaring class will be rendered instead of package .
1,732
public String renderReport ( final DiagnosticConfig config ) { final StringBuilder res = new StringBuilder ( ) ; printCommands ( config , res ) ; printBundles ( config , res ) ; if ( config . isPrintInstallers ( ) ) { printInstallers ( config , res ) ; printDisabledExtensions ( config , res , true ) ; } else { printExt...
Renders diagnostic report according to config .
1,733
private void configureFromBundles ( ) { context . lifecycle ( ) . runPhase ( context . getConfiguration ( ) , context . getConfigurationTree ( ) , context . getEnvironment ( ) ) ; final Stopwatch timer = context . stat ( ) . timer ( BundleTime ) ; final Stopwatch resolutionTimer = context . stat ( ) . timer ( BundleRes...
Apply configuration from registered bundles . If dropwizard bundles support is enabled lookup them too .
1,734
@ SuppressWarnings ( "deprecation" ) private void bindEnvironment ( ) { bind ( Bootstrap . class ) . toInstance ( bootstrap ( ) ) ; bind ( Environment . class ) . toInstance ( environment ( ) ) ; install ( new ConfigBindingModule ( configuration ( ) , configurationTree ( ) , context . option ( BindConfigurationInterfac...
Bind bootstrap configuration and environment objects to be able to use them as injectable .
1,735
public static void enableBundles ( final Class < ? extends GuiceyBundle > ... bundles ) { final String prop = Joiner . on ( ',' ) . join ( toStrings ( Lists . newArrayList ( bundles ) ) ) ; System . setProperty ( BUNDLES_PROPERTY , prop ) ; }
Sets system property value to provided classes . Shortcut is useful to set property from code for example in unit tests .
1,736
public boolean cancel ( boolean ign ) { assert op != null : "No operation" ; op . cancel ( ) ; notifyListeners ( ) ; return op . getState ( ) == OperationState . WRITE_QUEUED ; }
Cancel this operation if possible .
1,737
public Long getCas ( ) { if ( cas == null ) { try { get ( ) ; } catch ( InterruptedException e ) { status = new OperationStatus ( false , "Interrupted" , StatusCode . INTERRUPTED ) ; } catch ( ExecutionException e ) { getLogger ( ) . warn ( "Error getting cas of operation" , e ) ; } } if ( cas == null && status . isSuc...
Get the CAS for this operation .
1,738
public OperationStatus getStatus ( ) { if ( status == null ) { try { get ( ) ; } catch ( InterruptedException e ) { status = new OperationStatus ( false , "Interrupted" , StatusCode . INTERRUPTED ) ; } catch ( ExecutionException e ) { getLogger ( ) . warn ( "Error getting status of operation" , e ) ; } } return status ...
Get the current status of this operation .
1,739
public void set ( T o , OperationStatus s ) { objRef . set ( o ) ; status = s ; }
Set the Operation associated with this OperationFuture .
1,740
public static Logger getLogger ( String name ) { if ( name == null ) { throw new NullPointerException ( "Logger name may not be null." ) ; } init ( ) ; return ( instance . internalGetLogger ( name ) ) ; }
Get a logger by name .
1,741
private Logger internalGetLogger ( String name ) { assert name != null : "Name was null" ; Logger rv = instances . get ( name ) ; if ( rv == null ) { Logger newLogger = null ; try { newLogger = getNewInstance ( name ) ; } catch ( Exception e ) { throw new RuntimeException ( "Problem getting logger" , e ) ; } Logger tmp...
Get an instance of Logger from internal mechanisms .
1,742
@ SuppressWarnings ( "unchecked" ) private void getConstructor ( ) { Class < ? extends Logger > c = DefaultLogger . class ; String className = System . getProperty ( "net.spy.log.LoggerImpl" ) ; if ( className != null ) { try { c = ( Class < ? extends Logger > ) Class . forName ( className ) ; } catch ( NoClassDefFound...
Find the appropriate constructor
1,743
public Throwable getThrowable ( Object [ ] args ) { Throwable rv = null ; if ( args . length > 0 ) { if ( args [ args . length - 1 ] instanceof Throwable ) { rv = ( Throwable ) args [ args . length - 1 ] ; } } return rv ; }
Get the throwable from the last element of this array if it is Throwable else null .
1,744
public void trace ( Object message , Throwable exception ) { log ( Level . TRACE , message , exception ) ; }
Log a message at trace level .
1,745
public void trace ( String message , Object ... args ) { if ( isDebugEnabled ( ) ) { trace ( String . format ( message , args ) , getThrowable ( args ) ) ; } }
Log a formatted message at trace level .
1,746
public void debug ( Object message , Throwable exception ) { log ( Level . DEBUG , message , exception ) ; }
Log a message at debug level .
1,747
public void info ( String message , Object ... args ) { if ( isInfoEnabled ( ) ) { info ( String . format ( message , args ) , getThrowable ( args ) ) ; } }
Log a formatted message at info level .
1,748
public void warn ( Object message , Throwable exception ) { log ( Level . WARN , message , exception ) ; }
Log a message at warning level .
1,749
public void error ( Object message , Throwable exception ) { log ( Level . ERROR , message , exception ) ; }
Log a message at error level .
1,750
public void fatal ( Object message , Throwable exception ) { log ( Level . FATAL , message , exception ) ; }
Log a message at fatal level .
1,751
public void log ( Level level , Object message , Throwable e ) { if ( level == null ) { level = Level . FATAL ; } switch ( level ) { case TRACE : logger . trace ( message . toString ( ) , e ) ; break ; case DEBUG : logger . debug ( message . toString ( ) , e ) ; break ; case INFO : logger . info ( message . toString ( ...
Wrapper around SLF4J logger facade .
1,752
public synchronized void authConnection ( MemcachedConnection conn , OperationFactory opFact , AuthDescriptor authDescriptor , MemcachedNode node ) { interruptOldAuth ( node ) ; AuthThread newSASLAuthenticator = new AuthThread ( conn , opFact , authDescriptor , node ) ; nodeMap . put ( node , newSASLAuthenticator ) ; }
Authenticate a new connection . This is typically used by a MemcachedNode in order to authenticate a connection right after it has been established .
1,753
private void parseHeaderFromBuffer ( ) { int magic = header [ 0 ] ; assert magic == RES_MAGIC : "Invalid magic: " + magic ; responseCmd = header [ 1 ] ; assert cmd == DUMMY_OPCODE || responseCmd == cmd : "Unexpected response command value" ; keyLen = decodeShort ( header , 2 ) ; errorCode = decodeShort ( header , 6 ) ...
Parse the header info out of the buffer .
1,754
private void readPayloadFromBuffer ( final ByteBuffer buffer ) throws IOException { int toRead = payload . length - payloadOffset ; int available = buffer . remaining ( ) ; toRead = Math . min ( toRead , available ) ; getLogger ( ) . debug ( "Reading %d payload bytes" , toRead ) ; buffer . get ( payload , payloadOffset...
Read the payload from the buffer .
1,755
protected OperationStatus getStatusForErrorCode ( int errCode , byte [ ] errPl ) throws IOException { if ( errCode == SUCCESS ) { return STATUS_OK ; } else { StatusCode statusCode = StatusCode . fromBinaryCode ( errCode ) ; errorMsg = errPl . clone ( ) ; switch ( errCode ) { case ERR_NOT_FOUND : return new CASOperation...
Get the OperationStatus object for the given error code .
1,756
protected void prepareBuffer ( final String key , final long cas , final byte [ ] val , final Object ... extraHeaders ) { int extraLen = 0 ; int extraHeadersLength = extraHeaders . length ; if ( extraHeadersLength > 0 ) { extraLen = calculateExtraLength ( extraHeaders ) ; } final byte [ ] keyBytes = KeyUtil . getKeyByt...
Prepare the buffer for sending .
1,757
private void initReporter ( ) { String reporterType = System . getProperty ( "net.spy.metrics.reporter.type" , DEFAULT_REPORTER_TYPE ) ; String reporterInterval = System . getProperty ( "net.spy.metrics.reporter.interval" , DEFAULT_REPORTER_INTERVAL ) ; String reporterDir = System . getProperty ( "net.spy.metrics.repor...
Initialize the proper metrics Reporter .
1,758
public ResponseMessage getNextMessage ( long time , TimeUnit timeunit ) { try { Object m = rqueue . poll ( time , timeunit ) ; if ( m == null ) { return null ; } else if ( m instanceof ResponseMessage ) { return ( ResponseMessage ) m ; } else if ( m instanceof TapAck ) { TapAck ack = ( TapAck ) m ; tapAck ( ack . getCo...
Gets the next tap message from the queue of received tap messages .
1,759
public boolean hasMoreMessages ( ) { if ( ! rqueue . isEmpty ( ) ) { return true ; } else { synchronized ( omap ) { Iterator < TapStream > itr = omap . keySet ( ) . iterator ( ) ; while ( itr . hasNext ( ) ) { TapStream ts = itr . next ( ) ; if ( ts . isCompleted ( ) || ts . isCancelled ( ) || ts . hasErrored ( ) ) { o...
Decides whether the client has received tap messages or will receive more messages in the future .
1,760
public TapStream tapCustom ( final String id , final RequestMessage message ) throws ConfigurationException , IOException { final TapConnectionProvider conn = new TapConnectionProvider ( addrs ) ; final TapStream ts = new TapStream ( ) ; conn . broadcastOp ( new BroadcastOpFactory ( ) { public Operation newOp ( final M...
Allows the user to specify a custom tap message .
1,761
public void shutdown ( ) { synchronized ( omap ) { for ( Map . Entry < TapStream , TapConnectionProvider > me : omap . entrySet ( ) ) { me . getValue ( ) . shutdown ( ) ; } } }
Shuts down all tap streams that are currently running .
1,762
public static long fieldToValue ( byte [ ] buffer , int offset , int length ) { long total = 0 ; long val = 0 ; for ( int i = 0 ; i < length ; i ++ ) { val = buffer [ offset + i ] ; if ( val < 0 ) { val = val + 256 ; } total += ( long ) Math . pow ( 256.0 , ( double ) ( length - 1 - i ) ) * val ; } return total ; }
Converts a field in a byte array into a value .
1,763
public static void valueToFieldOffest ( byte [ ] buffer , int offset , int length , long l ) { long divisor ; for ( int i = 0 ; i < length ; i ++ ) { divisor = ( long ) Math . pow ( 256.0 , ( double ) ( length - 1 - i ) ) ; buffer [ offset + i ] = ( byte ) ( l / divisor ) ; l = l % divisor ; } }
Puts a value into a specific location in a byte buffer .
1,764
protected final synchronized void transitionState ( OperationState newState ) { getLogger ( ) . debug ( "Transitioned state from %s to %s" , state , newState ) ; state = newState ; if ( state != OperationState . WRITE_QUEUED && state != OperationState . WRITING ) { cmd = null ; } if ( state == OperationState . COMPLETE...
Transition the state of this operation to the given state .
1,765
public boolean isCompleted ( ) { for ( TapOperation op : ops ) { if ( ! op . getState ( ) . equals ( OperationState . COMPLETE ) ) { return false ; } } return true ; }
Check if all operations in the TapStream are completed .
1,766
public void setFlags ( TapRequestFlag f ) { if ( ! flagList . contains ( f ) ) { if ( ! hasFlags ) { hasFlags = true ; extralength += 4 ; totalbody += 4 ; } if ( f . equals ( TapRequestFlag . BACKFILL ) ) { hasBackfill = true ; totalbody += 8 ; } if ( f . equals ( TapRequestFlag . LIST_VBUCKETS ) || f . equals ( TapReq...
Sets the flags for the tap stream . These flags decide what kind of tap stream will be received .
1,767
public void setVbucketlist ( short [ ] vbs ) { int oldSize = ( vblist . length + 1 ) * 2 ; int newSize = ( vbs . length + 1 ) * 2 ; totalbody += newSize - oldSize ; vblist = vbs ; }
Sets a list of vbuckets to stream keys from .
1,768
public void setvBucketCheckpoints ( Map < Short , Long > vbchkpnts ) { int oldSize = ( vBucketCheckpoints . size ( ) ) * 10 ; int newSize = ( vbchkpnts . size ( ) ) * 10 ; totalbody += newSize - oldSize ; vBucketCheckpoints = vbchkpnts ; }
Sets a map of vbucket checkpoints .
1,769
public void setName ( String n ) { if ( n . length ( ) > 65535 ) { throw new IllegalArgumentException ( "Tap name too long" ) ; } totalbody += n . length ( ) - name . length ( ) ; keylength = ( short ) n . length ( ) ; name = n ; }
Sets a name for this tap stream . If the tap stream fails this name can be used to try to restart the tap stream from where it last left off .
1,770
public ByteBuffer getBytes ( ) { ByteBuffer bb = ByteBuffer . allocate ( HEADER_LENGTH + getTotalbody ( ) ) ; bb . put ( magic . getMagic ( ) ) ; bb . put ( opcode . getOpcode ( ) ) ; bb . putShort ( keylength ) ; bb . put ( extralength ) ; bb . put ( datatype ) ; bb . putShort ( vbucket ) ; bb . putInt ( totalbody ) ;...
Encodes the message into binary .
1,771
protected Future < T > addToListeners ( final GenericCompletionListener < ? extends Future < T > > listener ) { if ( listener == null ) { throw new IllegalArgumentException ( "The listener can't be null." ) ; } synchronized ( this ) { listeners . add ( listener ) ; } if ( isDone ( ) ) { notifyListeners ( ) ; } return t...
Add the given listener to the total list of listeners to be notified .
1,772
protected void notifyListener ( final ExecutorService executor , final Future < ? > future , final GenericCompletionListener listener ) { executor . submit ( new Runnable ( ) { public void run ( ) { try { listener . onComplete ( future ) ; } catch ( Throwable t ) { getLogger ( ) . warn ( "Exception thrown wile executin...
Notify a specific listener of completion .
1,773
protected void notifyListeners ( final Future < ? > future ) { final List < GenericCompletionListener < ? extends Future < T > > > copy = new ArrayList < GenericCompletionListener < ? extends Future < T > > > ( ) ; synchronized ( this ) { copy . addAll ( listeners ) ; listeners = new ArrayList < GenericCompletionListen...
Notify all registered listeners with a special future on completion .
1,774
protected Future < T > removeFromListeners ( GenericCompletionListener < ? extends Future < T > > listener ) { if ( listener == null ) { throw new IllegalArgumentException ( "The listener can't be null." ) ; } if ( ! isDone ( ) ) { synchronized ( this ) { listeners . remove ( listener ) ; } } return this ; }
Remove a listener from the list of registered listeners .
1,775
protected void registerMetrics ( ) { if ( metricType . equals ( MetricType . DEBUG ) || metricType . equals ( MetricType . PERFORMANCE ) ) { metrics . addHistogram ( OVERALL_AVG_BYTES_READ_METRIC ) ; metrics . addHistogram ( OVERALL_AVG_BYTES_WRITE_METRIC ) ; metrics . addHistogram ( OVERALL_AVG_TIME_ON_WIRE_METRIC ) ;...
Register Metrics for collection .
1,776
protected List < MemcachedNode > createConnections ( final Collection < InetSocketAddress > addrs ) throws IOException { List < MemcachedNode > connections = new ArrayList < MemcachedNode > ( addrs . size ( ) ) ; for ( SocketAddress sa : addrs ) { SocketChannel ch = SocketChannel . open ( ) ; ch . configureBlocking ( f...
Create connections for the given list of addresses .
1,777
private boolean selectorsMakeSense ( ) { for ( MemcachedNode qa : locator . getAll ( ) ) { if ( qa . getSk ( ) != null && qa . getSk ( ) . isValid ( ) ) { if ( qa . getChannel ( ) . isConnected ( ) ) { int sops = qa . getSk ( ) . interestOps ( ) ; int expected = 0 ; if ( qa . hasReadOp ( ) ) { expected |= SelectionKey ...
Make sure that the current selectors make sense .
1,778
public void handleIO ( ) throws IOException { if ( shutDown ) { getLogger ( ) . debug ( "No IO while shut down." ) ; return ; } handleInputQueue ( ) ; getLogger ( ) . debug ( "Done dealing with queue." ) ; long delay = wakeupDelay ; if ( ! reconnectQueue . isEmpty ( ) ) { long now = System . currentTimeMillis ( ) ; lon...
Handle all IO that flows through the connection .
1,779
private void handleShutdownQueue ( ) throws IOException { for ( MemcachedNode qa : nodesToShutdown ) { if ( ! addedQueue . contains ( qa ) ) { nodesToShutdown . remove ( qa ) ; metrics . decrementCounter ( SHUTD_QUEUE_METRIC ) ; Collection < Operation > notCompletedOperations = qa . destroyInputQueue ( ) ; if ( qa . ge...
Check if nodes need to be shut down and do so if needed .
1,780
private void checkPotentiallyTimedOutConnection ( ) { boolean stillCheckingTimeouts = true ; while ( stillCheckingTimeouts ) { try { for ( SelectionKey sk : selector . keys ( ) ) { MemcachedNode mn = ( MemcachedNode ) sk . attachment ( ) ; if ( mn . getContinuousTimeout ( ) > timeoutExceptionThreshold ) { getLogger ( )...
Check if one or more nodes exceeded the timeout Threshold .
1,781
private void handleInputQueue ( ) { if ( ! addedQueue . isEmpty ( ) ) { getLogger ( ) . debug ( "Handling queue" ) ; Collection < MemcachedNode > toAdd = new HashSet < MemcachedNode > ( ) ; Collection < MemcachedNode > todo = new HashSet < MemcachedNode > ( ) ; MemcachedNode qaNode ; while ( ( qaNode = addedQueue . pol...
Handle any requests that have been made against the client .
1,782
private void connected ( final MemcachedNode node ) { assert node . getChannel ( ) . isConnected ( ) : "Not connected." ; int rt = node . getReconnectCount ( ) ; node . connected ( ) ; for ( ConnectionObserver observer : connObservers ) { observer . connectionEstablished ( node . getSocketAddress ( ) , rt ) ; } }
Indicate a successful connect to the given node .
1,783
private void lostConnection ( final MemcachedNode node ) { queueReconnect ( node ) ; for ( ConnectionObserver observer : connObservers ) { observer . connectionLost ( node . getSocketAddress ( ) ) ; } }
Indicate a lost connection to the given node .
1,784
boolean belongsToCluster ( final MemcachedNode node ) { for ( MemcachedNode n : locator . getAll ( ) ) { if ( n . getSocketAddress ( ) . equals ( node . getSocketAddress ( ) ) ) { return true ; } } return false ; }
Makes sure that the given node belongs to the current cluster .
1,785
private void handleIO ( final SelectionKey sk ) { MemcachedNode node = ( MemcachedNode ) sk . attachment ( ) ; try { getLogger ( ) . debug ( "Handling IO for: %s (r=%s, w=%s, c=%s, op=%s)" , sk , sk . isReadable ( ) , sk . isWritable ( ) , sk . isConnectable ( ) , sk . attachment ( ) ) ; if ( sk . isConnectable ( ) &&...
Handle IO for a specific selector .
1,786
private void finishConnect ( final SelectionKey sk , final MemcachedNode node ) throws IOException { if ( verifyAliveOnConnect ) { final CountDownLatch latch = new CountDownLatch ( 1 ) ; final OperationFuture < Boolean > rv = new OperationFuture < Boolean > ( "noop" , latch , 2500 , listenerExecutorService ) ; NoopOper...
Finish the connect phase and potentially verify its liveness .
1,787
private void handleWrites ( final MemcachedNode node ) throws IOException { node . fillWriteBuffer ( shouldOptimize ) ; boolean canWriteMore = node . getBytesRemainingToWrite ( ) > 0 ; while ( canWriteMore ) { int wrote = node . writeSome ( ) ; metrics . updateHistogram ( OVERALL_AVG_BYTES_WRITE_METRIC , wrote ) ; node...
Handle pending writes for the given node .
1,788
private void handleReads ( final MemcachedNode node ) throws IOException { Operation currentOp = node . getCurrentReadOp ( ) ; if ( currentOp instanceof TapAckOperationImpl ) { node . removeCurrentReadOp ( ) ; return ; } ByteBuffer rbuf = node . getRbuf ( ) ; final SocketChannel channel = node . getChannel ( ) ; int re...
Handle pending reads for the given node .
1,789
private void readBufferAndLogMetrics ( final Operation currentOp , final ByteBuffer rbuf , final MemcachedNode node ) throws IOException { currentOp . readFromBuffer ( rbuf ) ; if ( currentOp . getState ( ) == OperationState . COMPLETE ) { getLogger ( ) . debug ( "Completed read op: %s and giving the next %d " + "bytes...
Read from the buffer and add metrics information .
1,790
private Operation handleReadsWhenChannelEndOfStream ( final Operation currentOp , final MemcachedNode node , final ByteBuffer rbuf ) throws IOException { if ( currentOp instanceof TapOperation ) { currentOp . getCallback ( ) . complete ( ) ; ( ( TapOperation ) currentOp ) . streamClosed ( OperationState . COMPLETE ) ; ...
Deal with an operation where the channel reached the end of a stream .
1,791
private void potentiallyCloseLeakingChannel ( final SocketChannel ch , final MemcachedNode node ) { if ( ch != null && ! ch . isConnected ( ) && ! ch . isConnectionPending ( ) ) { try { ch . close ( ) ; } catch ( IOException e ) { getLogger ( ) . error ( "Exception closing channel: %s" , node , e ) ; } } }
Make sure channel connections are not leaked and properly close under faulty reconnect cirumstances .
1,792
protected void addOperation ( final String key , final Operation o ) { MemcachedNode placeIn = null ; MemcachedNode primary = locator . getPrimary ( key ) ; if ( primary . isActive ( ) || failureMode == FailureMode . Retry ) { placeIn = primary ; } else if ( failureMode == FailureMode . Cancel ) { o . cancel ( ) ; } el...
Add an operation to a connection identified by the given key .
1,793
public void insertOperation ( final MemcachedNode node , final Operation o ) { o . setHandlingNode ( node ) ; o . initialize ( ) ; node . insertOp ( o ) ; addedQueue . offer ( node ) ; metrics . markMeter ( OVERALL_REQUEST_METRIC ) ; Selector s = selector . wakeup ( ) ; assert s == selector : "Wakeup returned the wrong...
Insert an operation on the given node to the beginning of the queue .
1,794
protected void addOperation ( final MemcachedNode node , final Operation o ) { if ( ! node . isAuthenticated ( ) ) { retryOperation ( o ) ; return ; } o . setHandlingNode ( node ) ; o . initialize ( ) ; node . addOp ( o ) ; addedQueue . offer ( node ) ; metrics . markMeter ( OVERALL_REQUEST_METRIC ) ; Selector s = sele...
Enqueue an operation on the given node .
1,795
public void addOperations ( final Map < MemcachedNode , Operation > ops ) { for ( Map . Entry < MemcachedNode , Operation > me : ops . entrySet ( ) ) { addOperation ( me . getKey ( ) , me . getValue ( ) ) ; } }
Enqueue the given list of operations on each handling node .
1,796
public CountDownLatch broadcastOperation ( final BroadcastOpFactory of , final Collection < MemcachedNode > nodes ) { final CountDownLatch latch = new CountDownLatch ( nodes . size ( ) ) ; for ( MemcachedNode node : nodes ) { getLogger ( ) . debug ( "broadcast Operation: node = " + node ) ; Operation op = of . newOp ( ...
Broadcast an operation to a collection of nodes .
1,797
public void shutdown ( ) throws IOException { shutDown = true ; try { Selector s = selector . wakeup ( ) ; assert s == selector : "Wakeup returned the wrong selector." ; for ( MemcachedNode node : locator . getAll ( ) ) { if ( node . getChannel ( ) != null ) { node . getChannel ( ) . close ( ) ; node . setSk ( null ) ;...
Shut down all connections and do not accept further incoming ops .
1,798
public String connectionsStatus ( ) { StringBuilder connStatus = new StringBuilder ( ) ; connStatus . append ( "Connection Status {" ) ; for ( MemcachedNode node : locator . getAll ( ) ) { connStatus . append ( " " ) . append ( node . getSocketAddress ( ) ) . append ( " active: " ) . append ( node . isActive ( ) ) . ap...
Construct a String containing information about all nodes and their state .
1,799
private static void setTimeout ( final Operation op , final boolean isTimeout ) { Logger logger = LoggerFactory . getLogger ( MemcachedConnection . class ) ; try { if ( op == null || op . isTimedOutUnsent ( ) ) { return ; } MemcachedNode node = op . getHandlingNode ( ) ; if ( node != null ) { node . setContinuousTimeou...
Set the continuous timeout on an operation .