idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
26,400
public void performCompletion ( String s ) { int selStart = getSelectionStart ( ) ; int selEnd = getSelectionEnd ( ) ; if ( selStart != selEnd ) return ; Editable text = getText ( ) ; HintSpan [ ] spans = text . getSpans ( 0 , length ( ) , HintSpan . class ) ; if ( spans . length > 1 ) throw new IllegalStateException (...
Replaces the current word with s . Used by Adapter to set the selected item as text .
26,401
public Iterator iterator ( ) { processQueue ( ) ; final Iterator i = super . iterator ( ) ; return new Iterator ( ) { public boolean hasNext ( ) { return i . hasNext ( ) ; } public Object next ( ) { return getReferenceObject ( ( WeakReference ) i . next ( ) ) ; } public void remove ( ) { i . remove ( ) ; } } ; }
Returns an iterator over the elements in this set . The elements are returned in no particular order .
26,402
public void inflate ( Resources r , XmlPullParser parser , AttributeSet attrs , Resources . Theme theme ) throws XmlPullParserException , IOException { }
Inflate this Drawable from an XML resource optionally styled by a theme .
26,403
public void getBounds ( Rect bounds ) { final int outerX = ( int ) mTargetX ; final int outerY = ( int ) mTargetY ; final int r = ( int ) mTargetRadius + 1 ; bounds . set ( outerX - r , outerY - r , outerX + r , outerY + r ) ; }
Returns the maximum bounds of the ripple relative to the ripple center .
26,404
private void computeBoundedTargetValues ( ) { mTargetX = ( mClampedStartingX - mBounds . exactCenterX ( ) ) * .7f ; mTargetY = ( mClampedStartingY - mBounds . exactCenterY ( ) ) * .7f ; mTargetRadius = mBoundedRadius ; }
Compute target values that are dependent on bounding .
26,405
private void clampStartingPosition ( ) { final float cX = mBounds . exactCenterX ( ) ; final float cY = mBounds . exactCenterY ( ) ; final float dX = mStartingX - cX ; final float dY = mStartingY - cY ; final float r = mTargetRadius ; if ( dX * dX + dY * dY > r * r ) { final double angle = Math . atan2 ( dY , dX ) ; mC...
Clamps the starting position to fit within the ripple bounds .
26,406
public void setAllCorners ( CornerTreatment cornerTreatment ) { topLeftCorner = cornerTreatment . clone ( ) ; topRightCorner = cornerTreatment . clone ( ) ; bottomRightCorner = cornerTreatment . clone ( ) ; bottomLeftCorner = cornerTreatment . clone ( ) ; }
Sets all corner treatments .
26,407
public void setAllEdges ( EdgeTreatment edgeTreatment ) { leftEdge = edgeTreatment . clone ( ) ; topEdge = edgeTreatment . clone ( ) ; rightEdge = edgeTreatment . clone ( ) ; bottomEdge = edgeTreatment . clone ( ) ; }
Sets all edge treatments .
26,408
public void setCornerTreatments ( CornerTreatment topLeftCorner , CornerTreatment topRightCorner , CornerTreatment bottomRightCorner , CornerTreatment bottomLeftCorner ) { this . topLeftCorner = topLeftCorner ; this . topRightCorner = topRightCorner ; this . bottomRightCorner = bottomRightCorner ; this . bottomLeftCorn...
Sets corner treatments .
26,409
public void setEdgeTreatments ( EdgeTreatment leftEdge , EdgeTreatment topEdge , EdgeTreatment rightEdge , EdgeTreatment bottomEdge ) { this . leftEdge = leftEdge ; this . topEdge = topEdge ; this . rightEdge = rightEdge ; this . bottomEdge = bottomEdge ; }
Sets edge treatments .
26,410
boolean scrollIfNecessary ( ) { if ( mSelected == null ) { mDragScrollStartTimeInMs = Long . MIN_VALUE ; return false ; } final long now = System . currentTimeMillis ( ) ; final long scrollDuration = mDragScrollStartTimeInMs == Long . MIN_VALUE ? 0 : now - mDragScrollStartTimeInMs ; RecyclerView . LayoutManager lm = mR...
If user drags the view to the edge trigger a scroll if necessary .
26,411
int endRecoverAnimation ( ViewHolder viewHolder , boolean override ) { final int recoverAnimSize = mRecoverAnimations . size ( ) ; for ( int i = recoverAnimSize - 1 ; i >= 0 ; i -- ) { final RecoverAnimation anim = mRecoverAnimations . get ( i ) ; if ( anim . mViewHolder == viewHolder ) { anim . mOverridden |= override...
Returns the animation type or 0 if cannot be found .
26,412
boolean checkSelectForSwipe ( int action , MotionEvent motionEvent , int pointerIndex ) { if ( mSelected != null || action != MotionEvent . ACTION_MOVE || mActionState == ACTION_STATE_DRAG || ! mCallback . isItemViewSwipeEnabled ( ) ) { return false ; } if ( mRecyclerView . getScrollState ( ) == RecyclerView . SCROLL_S...
Checks whether we should select a View for swiping .
26,413
private void inflateLayers ( Resources r , XmlPullParser parser , AttributeSet attrs , Resources . Theme theme ) throws XmlPullParserException , IOException { final LayerState state = mLayerState ; final int innerDepth = parser . getDepth ( ) + 1 ; int type ; int depth ; while ( ( type = parser . next ( ) ) != XmlPullP...
Inflates child layers using the specified parser .
26,414
int addLayer ( ChildDrawable layer ) { final LayerState st = mLayerState ; final int N = st . mChildren != null ? st . mChildren . length : 0 ; final int i = st . mNum ; if ( i >= N ) { final ChildDrawable [ ] nu = new ChildDrawable [ N + 10 ] ; if ( i > 0 ) { System . arraycopy ( st . mChildren , 0 , nu , 0 , i ) ; } ...
Adds a new layer at the end of list of layers and returns its index .
26,415
ChildDrawable addLayer ( Drawable dr , int [ ] themeAttrs , int id , int left , int top , int right , int bottom ) { final ChildDrawable childDrawable = createLayer ( dr ) ; childDrawable . mId = id ; childDrawable . mThemeAttrs = themeAttrs ; if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . KITKAT ) childDraw...
Add a new layer to this drawable . The new layer is identified by an id .
26,416
public int getId ( int index ) { if ( index >= mLayerState . mNum ) { throw new IndexOutOfBoundsException ( ) ; } return mLayerState . mChildren [ index ] . mId ; }
Returns the ID of the specified layer .
26,417
public void setDrawable ( int index , Drawable drawable ) { if ( index >= mLayerState . mNum ) { throw new IndexOutOfBoundsException ( ) ; } final ChildDrawable [ ] layers = mLayerState . mChildren ; final ChildDrawable childDrawable = layers [ index ] ; if ( childDrawable . mDrawable != null ) { if ( drawable != null ...
Sets the drawable for the layer at the specified index .
26,418
public Drawable getDrawable ( int index ) { if ( index >= mLayerState . mNum ) { throw new IndexOutOfBoundsException ( ) ; } return mLayerState . mChildren [ index ] . mDrawable ; }
Returns the drawable for the layer at the specified index .
26,419
public void setLayerInset ( int index , int l , int t , int r , int b ) { setLayerInsetInternal ( index , l , t , r , b , UNDEFINED_INSET , UNDEFINED_INSET ) ; }
Specifies the insets in pixels for the drawable at the specified index .
26,420
public void setLayerInsetRelative ( int index , int s , int t , int e , int b ) { setLayerInsetInternal ( index , 0 , t , 0 , b , s , e ) ; }
Specifies the relative insets in pixels for the drawable at the specified index .
26,421
private boolean refreshChildPadding ( int i , ChildDrawable r ) { if ( r . mDrawable != null ) { final Rect rect = mTmpRect ; r . mDrawable . getPadding ( rect ) ; if ( rect . left != mPaddingL [ i ] || rect . top != mPaddingT [ i ] || rect . right != mPaddingR [ i ] || rect . bottom != mPaddingB [ i ] ) { mPaddingL [ ...
Refreshes the cached padding values for the specified child .
26,422
void ensurePadding ( ) { final int N = mLayerState . mNum ; if ( mPaddingL != null && mPaddingL . length >= N ) { return ; } mPaddingL = new int [ N ] ; mPaddingT = new int [ N ] ; mPaddingR = new int [ N ] ; mPaddingB = new int [ N ] ; }
Ensures the child padding caches are large enough .
26,423
public static Properties getResourceAsProperties ( ClassLoader loader , String resource ) throws IOException { Properties props = new Properties ( ) ; InputStream in = null ; String propfile = resource ; in = getResourceAsStream ( loader , propfile ) ; props . load ( in ) ; in . close ( ) ; return props ; }
Returns a resource on the classpath as a Properties object
26,424
public static Reader getResourceAsReader ( ClassLoader loader , String resource ) throws IOException { return new InputStreamReader ( getResourceAsStream ( loader , resource ) ) ; }
Returns a resource on the classpath as a Reader object
26,425
public static File getResourceAsFile ( ClassLoader loader , String resource ) throws IOException { return new File ( getResourceURL ( loader , resource ) . getFile ( ) ) ; }
Returns a resource on the classpath as a File object
26,426
public synchronized String generateId ( ) { final StringBuilder sb = new StringBuilder ( this . length ) ; sb . append ( this . seed ) ; sb . append ( this . sequence . getAndIncrement ( ) ) ; return sb . toString ( ) ; }
Generate a unqiue id
26,427
public String generateSanitizedId ( ) { String result = this . generateId ( ) ; result = result . replace ( ':' , '-' ) ; result = result . replace ( '_' , '-' ) ; result = result . replace ( '.' , '-' ) ; return result ; }
Generate a unique ID - that is friendly for a URL or file system
26,428
protected void doResponseHeaders ( final HttpServletResponse response , final String mimeType ) { if ( mimeType != null ) { response . setContentType ( mimeType ) ; } }
Set the response headers . This method is called to set the response headers such as content type and content length . May be extended to add additional headers .
26,429
public MessageProducer getOrCreateProducer ( final String topic ) { if ( ! this . shareProducer ) { FutureTask < MessageProducer > task = this . producers . get ( topic ) ; if ( task == null ) { task = new FutureTask < MessageProducer > ( new Callable < MessageProducer > ( ) { public MessageProducer call ( ) throws Exc...
Returns or create a message producer for topic .
26,430
public SendResult send ( MessageBuilder builder , long timeout , TimeUnit unit ) throws InterruptedException { Message msg = builder . build ( this . messageBodyConverter ) ; final String topic = msg . getTopic ( ) ; MessageProducer producer = this . getOrCreateProducer ( topic ) ; try { return producer . sendMessage (...
Send message built by message builder . Returns the sent result .
26,431
public void send ( MessageBuilder builder , SendMessageCallback cb , long timeout , TimeUnit unit ) { Message msg = builder . build ( this . messageBodyConverter ) ; final String topic = msg . getTopic ( ) ; MessageProducer producer = this . getOrCreateProducer ( topic ) ; producer . sendMessage ( msg , cb , timeout , ...
Send message asynchronously with callback .
26,432
public < T > Message build ( MessageBodyConverter < T > converter ) { if ( StringUtils . isBlank ( this . topic ) ) { throw new IllegalArgumentException ( "Blank topic" ) ; } if ( this . body == null && this . payload == null ) { throw new IllegalArgumentException ( "Empty payload" ) ; } byte [ ] payload = this . paylo...
Build message by message body converter .
26,433
public boolean acquireProcessLock ( ) throws MongobeeConnectionException , MongobeeLockException { verifyDbConnection ( ) ; boolean acquired = lockDao . acquireLock ( getMongoDatabase ( ) ) ; if ( ! acquired && waitForLock ) { long timeToGiveUp = new Date ( ) . getTime ( ) + ( changeLogLockWaitTime * 1000 * 60 ) ; whil...
Try to acquire process lock
26,434
public boolean waitForCompletion ( long duration , TimeUnit timeUnit ) throws InterruptedException { synchronized ( lock ) { if ( ! isCompleted ( ) ) { lock . wait ( timeUnit . toMillis ( duration ) ) ; } return isCompleted ( ) ; } }
Blocks until the task is complete or times out .
26,435
@ SuppressWarnings ( "unchecked" ) public static < TResult > Task < TResult > forResult ( TResult value ) { if ( value == null ) { return ( Task < TResult > ) TASK_NULL ; } if ( value instanceof Boolean ) { return ( Task < TResult > ) ( ( Boolean ) value ? TASK_TRUE : TASK_FALSE ) ; } bolts . TaskCompletionSource < TRe...
Creates a completed task with the given value .
26,436
public static < TResult > Task < TResult > forError ( Exception error ) { bolts . TaskCompletionSource < TResult > tcs = new bolts . TaskCompletionSource < > ( ) ; tcs . setError ( error ) ; return tcs . getTask ( ) ; }
Creates a faulted task with the given error .
26,437
public static Task < Void > delay ( long delay , CancellationToken cancellationToken ) { return delay ( delay , BoltsExecutors . scheduled ( ) , cancellationToken ) ; }
Creates a task that completes after a time delay .
26,438
public < TOut > Task < TOut > cast ( ) { @ SuppressWarnings ( "unchecked" ) Task < TOut > task = ( Task < TOut > ) this ; return task ; }
Makes a fluent cast of a Task s result possible avoiding an extra continuation just to cast the type of the result .
26,439
public < TContinuationResult > Task < TContinuationResult > continueWith ( Continuation < TResult , TContinuationResult > continuation ) { return continueWith ( continuation , IMMEDIATE_EXECUTOR , null ) ; }
Adds a synchronous continuation to this task returning a new task that completes after the continuation has finished running .
26,440
public < TContinuationResult > Task < TContinuationResult > continueWithTask ( final Continuation < TResult , Task < TContinuationResult > > continuation , final Executor executor , final CancellationToken ct ) { boolean completed ; final bolts . TaskCompletionSource < TContinuationResult > tcs = new bolts . TaskComple...
Adds an Task - based continuation to this task that will be scheduled using the executor returning a new task that completes after the task returned by the continuation has completed .
26,441
public < TContinuationResult > Task < TContinuationResult > continueWithTask ( Continuation < TResult , Task < TContinuationResult > > continuation ) { return continueWithTask ( continuation , IMMEDIATE_EXECUTOR , null ) ; }
Adds an asynchronous continuation to this task returning a new task that completes after the task returned by the continuation has completed .
26,442
private static Map < String , Object > parseAlData ( JSONArray dataArray ) throws JSONException { HashMap < String , Object > al = new HashMap < String , Object > ( ) ; for ( int i = 0 ; i < dataArray . length ( ) ; i ++ ) { JSONObject tag = dataArray . getJSONObject ( i ) ; String name = tag . getString ( "property" )...
Builds up a data structure filled with the app link data from the meta tags on a page . The structure of this object is a dictionary where each key holds an array of app link data dictionaries . Values are stored in a key called _value .
26,443
public void cancel ( ) { List < CancellationTokenRegistration > registrations ; synchronized ( lock ) { throwIfClosed ( ) ; if ( cancellationRequested ) { return ; } cancelScheduledCancellation ( ) ; cancellationRequested = true ; registrations = new ArrayList < > ( this . registrations ) ; } notifyListeners ( registra...
Cancels the token if it has not already been cancelled .
26,444
public void close ( ) { synchronized ( lock ) { if ( closed ) { return ; } closed = true ; tokenSource . unregister ( this ) ; tokenSource = null ; action = null ; } }
Unregisters the callback runnable from the cancellation token .
26,445
public static ExecutorService newCachedThreadPool ( ) { ThreadPoolExecutor executor = new ThreadPoolExecutor ( CORE_POOL_SIZE , MAX_POOL_SIZE , KEEP_ALIVE_TIME , TimeUnit . SECONDS , new LinkedBlockingQueue < Runnable > ( ) ) ; allowCoreThreadTimeout ( executor , true ) ; return executor ; }
Creates a proper Cached Thread Pool . Tasks will reuse cached threads if available or create new threads until the core pool is full . tasks will then be queued . If an task cannot be queued a new thread will be created unless this would exceed max pool size then the task will be rejected . Threads will time out after ...
26,446
public static Bundle getAppLinkExtras ( Intent intent ) { Bundle appLinkData = getAppLinkData ( intent ) ; if ( appLinkData == null ) { return null ; } return appLinkData . getBundle ( KEY_NAME_EXTRAS ) ; }
Gets the App Link extras for an intent if there is any .
26,447
public static Uri getTargetUrl ( Intent intent ) { Bundle appLinkData = getAppLinkData ( intent ) ; if ( appLinkData != null ) { String targetString = appLinkData . getString ( KEY_NAME_TARGET ) ; if ( targetString != null ) { return Uri . parse ( targetString ) ; } } return intent . getData ( ) ; }
Gets the target URL for an intent regardless of whether the intent is from an App Link . If the intent is from an App Link this will be the App Link target . Otherwise it will be the data Uri from the intent itself .
26,448
public static Uri getTargetUrlFromInboundIntent ( Context context , Intent intent ) { Bundle appLinkData = getAppLinkData ( intent ) ; if ( appLinkData != null ) { String targetString = appLinkData . getString ( KEY_NAME_TARGET ) ; if ( targetString != null ) { MeasurementEvent . sendBroadcastEvent ( context , Measurem...
Gets the target URL for an intent . If the intent is from an App Link this will be the App Link target . Otherwise it return null ; For app link intent this function will broadcast APP_LINK_NAVIGATE_IN_EVENT_NAME event .
26,449
private Bundle buildAppLinkDataForNavigation ( Context context ) { Bundle data = new Bundle ( ) ; Bundle refererAppLinkData = new Bundle ( ) ; if ( context != null ) { String refererAppPackage = context . getPackageName ( ) ; if ( refererAppPackage != null ) { refererAppLinkData . putString ( KEY_NAME_REFERER_APP_LINK_...
Creates a bundle containing the final constructed App Link data to be used in navigation .
26,450
private JSONObject getJSONForBundle ( Bundle bundle ) throws JSONException { JSONObject root = new JSONObject ( ) ; for ( String key : bundle . keySet ( ) ) { root . put ( key , getJSONValue ( bundle . get ( key ) ) ) ; } return root ; }
Gets a JSONObject equivalent to the input bundle for use when falling back to a web navigation .
26,451
public NavigationResult navigate ( Context context ) { PackageManager pm = context . getPackageManager ( ) ; Bundle finalAppLinkData = buildAppLinkDataForNavigation ( context ) ; Intent eligibleTargetIntent = null ; for ( AppLink . Target target : getAppLink ( ) . getTargets ( ) ) { Intent targetIntent = new Intent ( I...
Performs the navigation .
26,452
public static void setRegistry ( Registry registry ) { SpectatorContext . registry = registry ; if ( registry instanceof NoopRegistry ) { initStacktrace = null ; } else { Exception cause = initStacktrace ; Exception e = new IllegalStateException ( "called SpectatorContext.setRegistry(" + registry . getClass ( ) . getNa...
Set the registry to use . By default it will use the NoopRegistry .
26,453
public static LazyGauge gauge ( MonitorConfig config ) { return new LazyGauge ( Registry :: gauge , registry , createId ( config ) ) ; }
Create a gauge based on the config .
26,454
public static LazyGauge maxGauge ( MonitorConfig config ) { return new LazyGauge ( Registry :: maxGauge , registry , createId ( config ) ) ; }
Create a max gauge based on the config .
26,455
public static Id createId ( MonitorConfig config ) { Map < String , String > tags = new HashMap < > ( config . getTags ( ) . asMap ( ) ) ; tags . remove ( "type" ) ; return registry . createId ( config . getName ( ) ) . withTags ( tags ) ; }
Convert servo config to spectator id .
26,456
public static PolledMeter . Builder polledGauge ( MonitorConfig config ) { long delayMillis = Math . max ( Pollers . getPollingIntervals ( ) . get ( 0 ) - 1000 , 5000 ) ; Id id = createId ( config ) ; PolledMeter . remove ( registry , id ) ; return PolledMeter . using ( registry ) . withId ( id ) . withDelay ( Duration...
Create builder for a polled gauge based on the config .
26,457
public static void register ( Monitor < ? > monitor ) { if ( monitor instanceof SpectatorMonitor ) { ( ( SpectatorMonitor ) monitor ) . initializeSpectator ( BasicTagList . EMPTY ) ; } else if ( ! isEmptyComposite ( monitor ) ) { ServoMeter m = new ServoMeter ( monitor ) ; PolledMeter . remove ( registry , m . id ( ) )...
Register a custom monitor .
26,458
public static AmazonCloudWatch cloudWatch ( AWSCredentialsProvider credentials ) { AmazonCloudWatch client = new AmazonCloudWatchClient ( credentials ) ; client . setEndpoint ( System . getProperty ( AwsPropertyKeys . AWS_CLOUD_WATCH_END_POINT . getBundle ( ) , "monitoring.amazonaws.com" ) ) ; return client ; }
Get a CloudWatch client whose endpoint is configured based on properties .
26,459
public static AmazonAutoScaling autoScaling ( AWSCredentials credentials ) { AmazonAutoScaling client = new AmazonAutoScalingClient ( credentials ) ; client . setEndpoint ( System . getProperty ( AwsPropertyKeys . AWS_AUTO_SCALING_END_POINT . getBundle ( ) , "autoscaling.amazonaws.com" ) ) ; return client ; }
Get an AutoScaling client whose endpoint is configured based on properties .
26,460
public static Stopwatch start ( MonitorConfig config , TimeUnit unit ) { return INSTANCE . get ( config , unit ) . start ( ) ; }
Returns a stopwatch that has been started and will automatically record its result to the dynamic timer specified by the given config .
26,461
public static Stopwatch start ( MonitorConfig config ) { return INSTANCE . get ( config , TimeUnit . MILLISECONDS ) . start ( ) ; }
Returns a stopwatch that has been started and will automatically record its result to the dynamic timer specified by the given config . The timer will report the times in milliseconds to observers .
26,462
public static void record ( MonitorConfig config , long duration ) { INSTANCE . get ( config , TimeUnit . MILLISECONDS ) . record ( duration , TimeUnit . MILLISECONDS ) ; }
Record result to the dynamic timer indicated by the provided config with a TimeUnit of milliseconds .
26,463
public static void record ( MonitorConfig config , long duration , TimeUnit unit ) { INSTANCE . get ( config , unit ) . record ( duration , unit ) ; }
Record a duration to the dynamic timer indicated by the provided config . The units in which the timer is reported and the duration unit are the same .
26,464
public static Stopwatch start ( String name , TagList list , TimeUnit unit ) { final MonitorConfig config = new MonitorConfig . Builder ( name ) . withTags ( list ) . build ( ) ; return INSTANCE . get ( config , unit ) . start ( ) ; }
Returns a stopwatch that has been started and will automatically record its result to the dynamic timer specified by the given config . The timer uses a TimeUnit of milliseconds .
26,465
public long getDuration ( ) { final long end = running . get ( ) ? System . nanoTime ( ) : endTime . get ( ) ; return end - startTime . get ( ) ; }
Returns the duration in nanoseconds . No checks are performed to ensure that the stopwatch has been properly started and stopped before executing this method . If called before stop it will return the current duration .
26,466
public static < T > Memoizer < T > create ( Callable < T > getter , long duration , TimeUnit unit ) { return new Memoizer < > ( getter , duration , unit ) ; }
Create a memoizer that caches the value produced by getter for a given duration .
26,467
public T get ( ) { long expiration = whenItExpires ; long now = System . nanoTime ( ) ; if ( expiration == 0 || now >= expiration ) { synchronized ( this ) { if ( whenItExpires == expiration ) { whenItExpires = now + durationNanos ; try { value = getter . call ( ) ; } catch ( Exception e ) { throw Throwables . propagat...
Get or refresh and return the latest value .
26,468
public void push ( List < Metric > rawMetrics ) { List < Metric > validMetrics = ValidCharacters . toValidValues ( filter ( rawMetrics ) ) ; List < Metric > metrics = transformMetrics ( validMetrics ) ; LOGGER . debug ( "Scheduling push of {} metrics" , metrics . size ( ) ) ; final UpdateTasks tasks = getUpdateTasks ( ...
Immediately send metrics to the backend .
26,469
protected Func1 < HttpClientResponse < ByteBuf > , Integer > withBookkeeping ( final int batchSize ) { return response -> { boolean ok = response . getStatus ( ) . code ( ) == 200 ; if ( ok ) { numMetricsSent . increment ( batchSize ) ; } else { LOGGER . info ( "Status code: {} - Lost {} metrics" , response . getStatus...
Utility function to map an Observable&lt ; ByteBuf > to an Observable&lt ; Integer > while also updating our counters for metrics sent and errors .
26,470
public static ServoAtlasConfig getAtlasConfig ( ) { return new ServoAtlasConfig ( ) { public String getAtlasUri ( ) { return getAtlasObserverUri ( ) ; } public int getPushQueueSize ( ) { return 1000 ; } public boolean shouldSendMetrics ( ) { return isAtlasObserverEnabled ( ) ; } public int batchSize ( ) { return 10000 ...
Get config for the atlas observer .
26,471
public static Set < Field > getAllFields ( Class < ? > classs ) { Set < Field > set = new HashSet < > ( ) ; Class < ? > c = classs ; while ( c != null ) { set . addAll ( Arrays . asList ( c . getDeclaredFields ( ) ) ) ; c = c . getSuperclass ( ) ; } return set ; }
Gets all fields from class and its super classes .
26,472
public static Set < Method > getAllMethods ( Class < ? > classs ) { Set < Method > set = new HashSet < > ( ) ; Class < ? > c = classs ; while ( c != null ) { set . addAll ( Arrays . asList ( c . getDeclaredMethods ( ) ) ) ; c = c . getSuperclass ( ) ; } return set ; }
Gets all methods from class and its super classes .
26,473
public static Set < Field > getFieldsAnnotatedBy ( Class < ? > classs , Class < ? extends Annotation > ann ) { Set < Field > set = new HashSet < > ( ) ; for ( Field field : getAllFields ( classs ) ) { if ( field . isAnnotationPresent ( ann ) ) { set . add ( field ) ; } } return set ; }
Gets all fields annotated by annotation .
26,474
public static Set < Method > getMethodsAnnotatedBy ( Class < ? > classs , Class < ? extends Annotation > ann ) { Set < Method > set = new HashSet < > ( ) ; for ( Method method : getAllMethods ( classs ) ) { if ( method . isAnnotationPresent ( ann ) ) { set . add ( method ) ; } } return set ; }
Gets all methods annotated by annotation .
26,475
protected M getMonitorForCurrentContext ( ) { MonitorConfig contextConfig = getConfig ( ) ; M monitor = monitors . get ( contextConfig ) ; if ( monitor == null ) { M newMon = newMonitor . apply ( contextConfig ) ; if ( newMon instanceof SpectatorMonitor ) { ( ( SpectatorMonitor ) newMon ) . initializeSpectator ( specta...
Returns a monitor instance for the current context . If no monitor exists for the current context then a new one will be created .
26,476
static Tag internCustom ( Tag t ) { return ( t instanceof BasicTag ) ? t : newTag ( t . getKey ( ) , t . getValue ( ) ) ; }
Interns custom tag types assumes that basic tags are already interned . This is used to ensure that we have a common view of tags internally . In particular different subclasses of Tag may not be equal even if they have the same key and value . Tag lists should use this to ensure the equality will work as expected .
26,477
public static Tag newTag ( String key , String value ) { Tag newTag = new BasicTag ( intern ( key ) , intern ( value ) ) ; return intern ( newTag ) ; }
Create a new tag instance .
26,478
public String getTimeUnitAbbreviation ( ) { switch ( timeUnit ) { case DAYS : return "day" ; case HOURS : return "hr" ; case MICROSECONDS : return "\u00B5s" ; case MILLISECONDS : return "ms" ; case MINUTES : return "min" ; case NANOSECONDS : return "ns" ; case SECONDS : return "s" ; default : return "unkwn" ; } }
Returns an abbreviation for the Bucket s TimeUnit .
26,479
public synchronized void start ( ) { if ( ! running ) { running = true ; Thread t = new Thread ( new CpuStatRunnable ( ) , "ThreadCpuStatsCollector" ) ; t . setDaemon ( true ) ; t . start ( ) ; } }
Start collecting cpu stats for the threads .
26,480
public static String toDuration ( long inputTime ) { final long second = 1000000000L ; final long minute = 60 * second ; final long hour = 60 * minute ; final long day = 24 * hour ; final long week = 7 * day ; long time = inputTime ; final StringBuilder buf = new StringBuilder ( ) ; buf . append ( 'P' ) ; time = append...
Convert time in nanoseconds to a duration string . This is used to provide a more human readable order of magnitude for the duration . We assume standard fixed size quantities for all units .
26,481
public void printThreadCpuUsages ( OutputStream out , CpuUsageComparator cmp ) { final PrintWriter writer = getPrintWriter ( out ) ; final Map < String , Object > threadCpuUsages = getThreadCpuUsages ( cmp ) ; writer . printf ( "Time: %s%n%n" , new Date ( ( Long ) threadCpuUsages . get ( CURRENT_TIME ) ) ) ; final long...
Utility function that dumps the cpu usages for the threads to stdout . Output will be sorted based on the 1 - minute usage from highest to lowest .
26,482
private void updateStats ( ) { final ThreadMXBean bean = ManagementFactory . getThreadMXBean ( ) ; if ( bean . isThreadCpuTimeEnabled ( ) ) { final long [ ] ids = bean . getAllThreadIds ( ) ; Arrays . sort ( ids ) ; long totalCpuTime = 0L ; for ( long id : ids ) { long cpuTime = bean . getThreadCpuTime ( id ) ; if ( cp...
Update the stats for all threads and the jvm .
26,483
public < T > T callWithTimeout ( Callable < T > callable , long duration , TimeUnit unit ) throws Exception { Future < T > future = executor . submit ( callable ) ; try { return future . get ( duration , unit ) ; } catch ( InterruptedException e ) { future . cancel ( true ) ; throw e ; } catch ( ExecutionException e ) ...
Invokes a specified Callable timing out after the specified time limit . If the target method call finished before the limit is reached the return value or exception is propagated to the caller exactly as - is . If on the other hand the time limit is reached we attempt to abort the call to the Callable and throw an exc...
26,484
public static Timer newTimer ( String name , TimeUnit unit ) { return new BasicTimer ( MonitorConfig . builder ( name ) . build ( ) , unit ) ; }
Create a new timer with only the name specified .
26,485
public static Counter newCounter ( String name , TaggingContext context ) { final MonitorConfig config = MonitorConfig . builder ( name ) . build ( ) ; return new ContextualCounter ( config , context , COUNTER_FUNCTION ) ; }
Create a new counter with a name and context . The returned counter will maintain separate sub - monitors for each distinct set of tags returned from the context on an update operation .
26,486
public static CompositeMonitor < ? > newObjectMonitor ( String id , Object obj ) { final TagList tags = getMonitorTags ( obj ) ; List < Monitor < ? > > monitors = new ArrayList < > ( ) ; addMonitors ( monitors , id , tags , obj ) ; final Class < ? > c = obj . getClass ( ) ; final String objectId = ( id == null ) ? DEFA...
Helper function to easily create a composite for all monitor fields and annotated attributes of a given object .
26,487
public static CompositeMonitor < ? > newThreadPoolMonitor ( String id , ThreadPoolExecutor pool ) { return newObjectMonitor ( id , new MonitoredThreadPool ( pool ) ) ; }
Creates a new monitor for a thread pool with standard metrics for the pool size queue size task counts etc .
26,488
public static CompositeMonitor < ? > newCacheMonitor ( String id , Cache < ? , ? > cache ) { return newObjectMonitor ( id , new MonitoredCache ( cache ) ) ; }
Creates a new monitor for a cache with standard metrics for the hits misses and loads .
26,489
public static boolean isObjectRegistered ( String id , Object obj ) { return DefaultMonitorRegistry . getInstance ( ) . isRegistered ( newObjectMonitor ( id , obj ) ) ; }
Check whether an object is currently registered with the default registry .
26,490
@ SuppressWarnings ( "unchecked" ) static < T > Monitor < T > wrap ( TagList tags , Monitor < T > monitor ) { Monitor < T > m ; if ( monitor instanceof CompositeMonitor < ? > ) { m = new CompositeMonitorWrapper < > ( tags , ( CompositeMonitor < T > ) monitor ) ; } else { m = MonitorWrapper . create ( tags , monitor ) ;...
Returns a new monitor that adds the provided tags to the configuration returned by the wrapped monitor .
26,491
static void addMonitors ( List < Monitor < ? > > monitors , String id , TagList tags , Object obj ) { addMonitorFields ( monitors , id , tags , obj ) ; addAnnotatedFields ( monitors , id , tags , obj ) ; }
Extract all monitors across class hierarchy .
26,492
private static TagList getMonitorTags ( Object obj ) { try { Set < Field > fields = getFieldsAnnotatedBy ( obj . getClass ( ) , MonitorTags . class ) ; for ( Field field : fields ) { field . setAccessible ( true ) ; return ( TagList ) field . get ( obj ) ; } Set < Method > methods = getMethodsAnnotatedBy ( obj . getCla...
Get tags from annotation .
26,493
private static void checkType ( com . netflix . servo . annotations . Monitor anno , Class < ? > type , Class < ? > container ) { if ( ! isNumericType ( type ) ) { final String msg = "annotation of type " + anno . type ( ) . name ( ) + " can only be used" + " with numeric values, " + anno . name ( ) + " in class " + co...
Verify that the type for the annotated field is numeric .
26,494
private static MonitorConfig newObjectConfig ( Class < ? > c , String id , TagList tags ) { final MonitorConfig . Builder builder = MonitorConfig . builder ( id ) ; final String className = className ( c ) ; if ( ! className . isEmpty ( ) ) { builder . withTag ( "class" , className ) ; } if ( tags != null ) { builder ....
Creates a monitor config for a composite object .
26,495
private static MonitorConfig newConfig ( Class < ? > c , String defaultName , String id , com . netflix . servo . annotations . Monitor anno , TagList tags ) { String name = anno . name ( ) ; if ( name . isEmpty ( ) ) { name = defaultName ; } MonitorConfig . Builder builder = MonitorConfig . builder ( name ) ; builder ...
Creates a monitor config based on an annotation .
26,496
public void stop ( ) { try { if ( socket != null ) { socket . close ( ) ; socket = null ; LOGGER . info ( "Disconnected from graphite server: {}" , graphiteServerURI ) ; } } catch ( IOException e ) { LOGGER . warn ( "Error Stopping" , e ) ; } }
Stop sending metrics to the graphite server .
26,497
public Tag get ( String key ) { int idx = binarySearch ( tagArray , key ) ; if ( idx < 0 ) { return null ; } else { return tagArray [ idx ] ; } }
Get the tag associated with a given key .
26,498
public void record ( long n ) { values [ Integer . remainderUnsigned ( pos ++ , size ) ] = n ; if ( curSize < size ) { ++ curSize ; } }
Record a new value for this buffer .
26,499
public void computeStats ( ) { if ( statsComputed . getAndSet ( true ) ) { return ; } if ( curSize == 0 ) { return ; } Arrays . sort ( values , 0 , curSize ) ; min = values [ 0 ] ; max = values [ curSize - 1 ] ; total = 0L ; double sumSquares = 0.0 ; for ( int i = 0 ; i < curSize ; ++ i ) { total += values [ i ] ; sumS...
Compute stats for the current set of values .